●
A
Admin
`); win.document.close(); win.focus(); setTimeout(()=>{ try{ win.print(); win.onafterprint=()=>win.close(); }catch(e){ console.error('Day Book print error:',e); } },300); } function balanceSheetReport(){return `
Transaction Report

Balance Sheet

Assets, liabilities and capital position based on records available in MVIApps.

${reportPeriodControls('bs')}
₹

Balance Sheet

Select the period and click View Report.

The Balance Sheet is presented as on the selected To Date.
`;} function printBalanceSheet(){ const el=document.getElementById('balanceSheetResult'); if(!el || !el.classList.contains('professional-report')){ alert('Please click View Report first, then click Print / Save PDF.'); return; } const source=el.cloneNode(true); source.querySelectorAll('button,.pl-pdf-actions').forEach(x=>x.remove()); const win=window.open('','_blank'); if(!win){ alert('Please allow pop-ups to print the report.'); return; } win.document.write('Balance Sheet' + source.outerHTML + ''); win.document.close(); win.focus(); setTimeout(()=>{try{win.print();win.onafterprint=()=>win.close();}catch(e){console.error('Balance Sheet print error:',e);}},300); } function balanceSheetStockAtDate(item,to){ const bounds=getFinancialYearBounds(getActiveFinancialYear()); const fyFrom=bounds.from||''; const base=stockTotals(item)||{}; let qty=Number(base.opening)||0; let value=Number(base.openingValue)||0; const defaultRate=Number(item.purchase)||0; const purchases=JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]'); const purchaseRateForMove=m=>{ if(Number(m.rate)>0)return Number(m.rate); const inv=purchases.find(x=>String(x.invoiceNo||x.number||'')===String(m.ref||'')); const it=(inv?.items||[]).find(x=>String(x.itemId)===String(item.id)); return Number(it?.rate||it?.purchaseRate||0)||defaultRate; }; getStockMovements().filter(m=>String(m.itemId)===String(item.id)).slice().sort((a,b)=>String(a.date||'').localeCompare(String(b.date||''))||(Number(a.id)||0)-(Number(b.id)||0)).forEach(m=>{ const d=String(m.date||'').slice(0,10), q=Math.max(0,Number(m.qty)||0); if(!q || (fyFrom&&dto))return; const rate=purchaseRateForMove(m); if(m.type==='purchase'){qty+=q;value+=q*rate;} else if(m.type==='sale'||m.type==='return'){ const avg=qty>0?value/qty:(m.type==='return'?rate:defaultRate),used=Math.min(q,Math.max(0,qty)); qty-=q;value=Math.max(0,value-used*avg); }else if(m.type==='adjustment'){ if(m.adjustmentType==='increase'){qty+=q;value+=q*rate;} else{const avg=qty>0?value/qty:defaultRate,used=Math.min(q,Math.max(0,qty));qty-=q;value=Math.max(0,value-used*avg);} } }); return {qty:Math.max(0,qty),value:Math.max(0,value)}; } function balanceSheetCashAtDate(to){ let balance=getCashBalanceForActiveFinancialYear(); getCashTransactions().forEach(x=>{const d=String(x.date||'');if(d&&to&&d>to)balance-=Number(x.amount)||0;}); return Number(balance)||0; } function balanceSheetBankAtDate(to){ return getBankAccounts().reduce((total,bank)=>{ let balance=getBankFYOpeningBalance(bank.id); getBankDisplayTransactions(bank.id).forEach(x=>{const d=String(x.date||'');if(d&&(!to||d<=to))balance+=Number(x.amount)||0;}); return total+balance; },0); } function generateBalanceSheet(){ const r=document.getElementById('balanceSheetResult');if(!r)return; const p=reportPeriodFilter('bs'),to=p.to; const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); let stock=0;items.forEach(i=>{stock+=balanceSheetStockAtDate(i,to).value;}); const outstanding=getPartyOutstandingTotals('',to),receivable=outstanding.receivable,payable=outstanding.payable; const cash=balanceSheetCashAtDate(to),bank=balanceSheetBankAtDate(to); const assets=stock+receivable+cash+bank,liabilities=payable,capital=assets-liabilities; r.className='panel professional-report'; r.innerHTML=`

Balance Sheet

As on ${escapeHtml(to.split('-').reverse().join('/'))}   |   ${escapeHtml(p.fy)}

Liabilities & Capital
Creditors / Payables${plMoney(payable)}
Capital / Balancing Figure${plMoney(capital)}
Total Liabilities & Capital${plMoney(assets)}
Assets
Closing Stock${plMoney(stock)}
Debtors / Receivables${plMoney(receivable)}
Cash Balance${plMoney(cash)}
Bank Balance${plMoney(bank)}
Total Assets${plMoney(assets)}

This statement uses the balances and stock data currently available in MVIApps as on the selected To Date. Capital is shown as the balancing figure; additional fixed assets, loans and tax balances will be included when those ledgers are available in the app.

`; } function partyReportParties(){return JSON.parse(localStorage.getItem('mviapps_parties')||'[]');} function partyIdOf(x){return String(x?.partyId||x?.customerId||x?.supplierId||x?.party||x?.customer||x?.supplier||'');} function partyNameOf(x,parties){const id=partyIdOf(x);const p=parties.find(z=>String(z.id)===id);return p?.name||x?.partyName||x?.customerName||x?.supplierName||x?.customer||x?.supplier||(id?'Party #'+id:'Cash / General');} function partyReportData(from,to){ const parties=partyReportParties(), out=[]; const norm=v=>String(v??'').trim().toLowerCase(); const inRange=x=>{const d=partyLedgerISODate(x?.date);return d&&d>=from&&d<=to;}; // Resolve records saved by older app versions using party name instead of ID. // This matches Party Ledger's alias matching so the statement doesn't omit // sales/purchases that should offset Payment-In/Payment-Out balances. const resolvePartyId=x=>{ const raw=[x?.partyId,x?.customerId,x?.supplierId,x?.party,x?.customer,x?.supplier, x?.partyName,x?.customerName,x?.supplierName].map(norm).filter(Boolean); const found=parties.find(p=>raw.some(v=>v===norm(p.id)||v===norm(p.name)||v===norm(p.partyName))); return found?String(found.id):String(partyIdOf(x)||''); }; const add=(key,type,fn)=>JSON.parse(localStorage.getItem(key)||'[]').filter(inRange).forEach(x=>{ const id=resolvePartyId(x);if(id)out.push({date:partyLedgerISODate(x.date),partyId:id,party:partyNameOf(x,parties),type,...fn(x)}); }); add('mviapps_sales_invoices','Sale',x=>({ref:x.invoiceNo||x.number||'',amount:plAmount(x),record:x})); add('mviapps_sales_returns','Credit Note',x=>({ref:x.number||x.invoiceNo||'',amount:plAmount(x),record:x})); add('mviapps_purchase_invoices','Purchase',x=>({ref:x.invoiceNo||x.number||'',amount:plAmount(x),record:x})); add('mviapps_purchase_returns','Debit Note',x=>({ref:x.number||x.invoiceNo||'',amount:plAmount(x),record:x})); add('mviapps_payment_in','Payment-In',x=>({ref:x.number||x.receiptNo||'',amount:parseMoney(x.amount),record:x})); add('mviapps_payment_out','Payment-Out',x=>({ref:x.number||x.paymentNo||'',amount:parseMoney(x.amount),record:x})); add('mviapps_expenses','Expense',x=>({ref:x.number||'',amount:parseMoney(x.amount),record:x})); add('mviapps_other_income','Other Income',x=>({ref:x.number||x.receiptNo||'',amount:plAmount(x),record:x})); return out.sort((a,b)=>String(a.date).localeCompare(String(b.date))); } function partyStatementReport(){ const parties=partyReportParties(),opts=parties.map(p=>``).join(''); return `
Party Report

Party Statement

Detailed party-wise ledger statement for the selected accounting period.

${reportPeriodControls('ps', 'generatePartyStatement')}
▤

Party Statement

Select Financial Year, Month/Date Range and Party, then click View Report.

`; } function generatePartyStatement(){ const r=document.getElementById('partyStatementResult');if(!r)return; const pid=document.getElementById('psParty')?.value||''; if(!pid){r.innerHTML='
▤

Select a Party

Please select a party to generate the statement.

';return;} const p=reportPeriodFilter('ps'), parties=partyReportParties(), party=parties.find(x=>String(x.id)===String(pid)); const openingDate=String(party?.openingDate||'').trim(); const rows=partyReportData(p.from,p.to).filter(x=>String(x.partyId)===String(pid) && (!openingDate || partyLedgerISODate(x.date)>=partyLedgerISODate(openingDate))); // Use the same carry-forward opening balance as Party Ledger. Do not // replace it with the Party Master opening on default FY reports, because // that drops transactions from earlier periods and causes balances to differ. let bal=getPartyLedgerOpening(party,p.from); // If the party's saved opening-balance date falls inside the requested // period, the visible statement rows start at that opening date (earlier // rows are intentionally excluded above). Start the running balance from // that effective opening amount so the first Payment-In doesn't incorrectly // appear as a payable balance simply because the period began earlier. const openingISO=partyLedgerISODate(openingDate); const fromISO=partyLedgerISODate(p.from); const toISO=partyLedgerISODate(p.to); if(openingISO && fromISO && toISO && openingISO>fromISO && openingISO<=toISO){ const base=parseMoney(party?.opening); bal=String(party?.balanceType||'Debit').toLowerCase()==='credit'?-Math.abs(base):Math.abs(base); } // Receivable/Payable columns are derived from the same net running balance // used by Party Ledger: positive = debit/receivable, negative = credit/payable. let receivable=Math.max(0,bal); let payable=Math.max(0,-bal); let debit=0,credit=0,html=''; const allByKey=(key)=>JSON.parse(localStorage.getItem(key)||'[]'); const findRecord=(x)=>x.record||( x.type==='Sale'?allByKey('mviapps_sales_invoices').find(z=>String(z.invoiceNo||z.number||'')===String(x.ref)): x.type==='Purchase'?allByKey('mviapps_purchase_invoices').find(z=>String(z.invoiceNo||z.number||'')===String(x.ref)): x.type==='Payment-In'?allByKey('mviapps_payment_in').find(z=>String(z.number||z.receiptNo||'')===String(x.ref)): x.type==='Payment-Out'?allByKey('mviapps_payment_out').find(z=>String(z.number||z.paymentNo||'')===String(x.ref)): x.type==='Expense'?allByKey('mviapps_expenses').find(z=>String(z.number||'')===String(x.ref)): x.type==='Credit Note'?allByKey('mviapps_sales_returns').find(z=>String(z.number||z.invoiceNo||'')===String(x.ref)): x.type==='Debit Note'?allByKey('mviapps_purchase_returns').find(z=>String(z.number||z.invoiceNo||'')===String(x.ref)): allByKey('mviapps_other_income').find(z=>String(z.number||z.receiptNo||'')===String(x.ref)) ); rows.forEach(x=>{ const rec=findRecord(x)||{}; let d=0,c=0; const mode=String(rec.paymentMode||'').toLowerCase(); // Party balance sign convention: debit/receivable is positive; // credit/payable is negative. Keep cash transactions from creating // an outstanding balance, and apply payments/returns against the right side. if(x.type==='Sale'){ if(mode==='credit') d=x.amount; }else if(x.type==='Purchase'){ if(mode==='credit') c=x.amount; }else if(x.type==='Expense'){ if(mode==='credit') c=x.amount; }else if(x.type==='Payment-In'){ c=x.amount; }else if(x.type==='Payment-Out'){ d=x.amount; }else if(x.type==='Credit Note'){ c=x.amount; }else if(x.type==='Debit Note'){ d=x.amount; }else if(x.type==='Other Income'){ if(mode==='credit') d=x.amount; }else{ d=x.amount; } debit+=d;credit+=c;bal+=d-c; // Recalculate both sides from net balance after each transaction, so // transactions offset the opening balance consistently for every party. receivable=Math.max(0,bal); payable=Math.max(0,-bal); const status=(x.type==='Purchase'||x.type==='Sale'||x.type==='Expense')?(mode==='credit'?'Unpaid':'Paid'):(x.type==='Payment-In'||x.type==='Payment-Out'?'Used':'—'); const receivedPaid=(x.type==='Payment-In'||x.type==='Payment-Out')?x.amount:0; const txnBalance=(x.type==='Payment-In'||x.type==='Payment-Out')?'':(mode==='credit'||x.type==='Purchase'||x.type==='Debit Note'?x.amount:(x.type==='Sale'||x.type==='Expense'?x.amount:0)); const running=bal; const items=Array.isArray(rec.items)?rec.items:[]; const itemRows=items.map((it,i)=>{ const item=JSON.parse(localStorage.getItem('mviapps_items')||'[]').find(z=>String(z.id)===String(it.itemId)); const qty=Number(it.qty)||0, rate=Number(it.rate)||0; const amount=qty*rate*(1-Number(it.discount||0)/100)*(1+Number(it.gst||0)/100); return `${i+1}${escapeHtml(item?.name||'Item')}${qty}${escapeHtml(item?.unit||'Pcs')}${plMoney(rate)}${plMoney(amount)}`; }).join(''); const itemBlock=items.length?`#   Item nameQuantityUnitPrice/ UnitAmount${itemRows}Sub Total${plMoney(x.amount)}`:''; const details=(x.type==='Payment-In'||x.type==='Payment-Out'||x.type==='Expense'||x.type==='Other Income')?`${x.type==='Expense'?`Payment Type: ${escapeHtml(rec.paymentMode||'—')}${rec.reference?`   Payment Ref No.: ${escapeHtml(rec.reference)}`:''}${rec.notes?`
Description: ${escapeHtml(rec.notes)}`:''}`:x.type==='Other Income'?`Description: ${escapeHtml(rec.notes||rec.paymentMode||'—')}${rec.reference?`   Payment Ref No.: ${escapeHtml(rec.reference)}`:''}`:`Payment Type: ${escapeHtml(rec.paymentMode||((String(rec.paymentMode||'').toLowerCase()==='bank'||String(rec.paymentMode||'').toLowerCase()==='bank transfer')?mviappsBankDisplay(rec.account||rec.bankAccount||''):rec.account||'—'))}${rec.reference?`   Payment Ref No.: ${escapeHtml(rec.reference)}`:''}${rec.notes?`
Description: ${escapeHtml(rec.notes)}`:''}`}`:''; html+=`${escapeHtml(x.date.split('-').reverse().join('/'))}${escapeHtml(x.type)}${escapeHtml(x.ref||'')}${escapeHtml(status)}${plMoney(x.amount)}${receivedPaid?plMoney(receivedPaid):''}${txnBalance?plMoney(txnBalance):''}${receivable?plMoney(receivable):''}${payable?plMoney(payable):''}${itemBlock}${details}`; }); const c=getCompanyDetails(), companyName=c.name||'Company Name'; const address=[c.address,c.city,c.state,c.pin].filter(Boolean).join(', '), contact=[c.mobile?`Phone no.: ${c.mobile}`:'',c.email?`Email: ${c.email}`:''].filter(Boolean).join(' '); const logo=c.logo?``:''; r.className='panel professional-report'; r.innerHTML=`
${logo}
${escapeHtml(companyName)}
${c.trade?`
${escapeHtml(c.trade)}
`:''}${address?`
${escapeHtml(address)}
`:''}${contact?`
${escapeHtml(contact)}
`:''}

Party statement

Party name: ${escapeHtml(party?.name||'')}
${html||''}
DateTxn TypeRef No.Payment StatusTotalReceived / PaidTxn BalanceReceivable BalancePayable Balance
No transactions found for the selected period.
${escapeHtml(reportPeriodLabel('ps'))}
`; } function printPartyStatement(){ const result=document.getElementById('partyStatementResult'); if(!result || !result.classList.contains('professional-report')){alert('Please generate the Party Statement first.');return;} const source=result.querySelector('.ps-report'); if(!source){alert('Party Statement data is not available.');return;} const table=source.querySelector('.ps-table'); const rows=table ? Array.from(table.querySelectorAll('tbody tr')) : []; const transactions=[]; let current=null; rows.forEach(row=>{ if(row.classList.contains('ps-txn')){ current={txn:row, items:[], subtotal:null, detail:null}; transactions.push(current); }else if(current){ if(row.classList.contains('ps-items-head')) current.itemsHead=row; else if(row.classList.contains('ps-item-row')) current.items.push(row); else if(row.classList.contains('ps-subtotal')) current.subtotal=row; else if(row.classList.contains('ps-detail')) current.detail=row; } }); const cellHTML=(row,index)=>row?.cells?.[index]?.innerHTML||''; const transactionHTML=transactions.map((t)=>{ const txnCells=Array.from(t.txn.cells).map((c,i)=>`
${i===3 && /^(Payment-In|Payment-Out)$/i.test(t.txn.cells[1]?.textContent?.trim()||'')?'':c.innerHTML}
`).join(''); let itemHTML=''; if(t.items.length){ const head=t.itemsHead; itemHTML=`${[0,1,2,3,4,5].map(i=>``).join('')}`; itemHTML+=t.items.map(r=>`${[0,1,2,3,4,5].map(i=>``).join('')}`).join(''); if(t.subtotal){ itemHTML+=``; } itemHTML+='
${cellHTML(head,i)}
${cellHTML(r,i)}
${cellHTML(t.subtotal,0)}${cellHTML(t.subtotal,1)}
'; } const detailHTML=t.detail?`
${t.detail.cells[0]?.innerHTML||t.detail.innerHTML}
`:''; return `
${txnCells}
${itemHTML}${detailHTML}
`; }).join(''); const company=source.querySelector('.ps-company-head')?.outerHTML||''; const title=source.querySelector('.ps-title')?.outerHTML||'

Party statement

'; const party=source.querySelector('.ps-party-name')?.outerHTML||''; const period=source.querySelector('.ps-period')?.outerHTML||''; const printHead='
Date
Txn Type
Ref No.
Payment Status
Total
Received / Paid
Txn Balance
Receivable Balance
Payable Balance
'; const w=window.open('','_blank');if(!w)return; w.document.write(`Party Statement
${company}${title}${party}${printHead}${transactionHTML}${period}
`); w.document.close();w.focus(); setTimeout(()=>{w.print();setTimeout(()=>w.close(),500);},300); } function allPartiesReport(){return `
Party Report

All Parties

All saved parties, using the same Party Details list.

Party List

View and manage all saved customer and supplier details.

`;} function printAllParties(){ const result=document.getElementById('all-parties-list'); if(!result || !result.querySelector('.table-wrap')){alert('Please open the All Parties report first.');return;} const tableWrap=result.querySelector('.table-wrap'); const table=tableWrap.querySelector('table'); if(!table){alert('All Parties data is not available to print.');return;} const cleanTable=table.cloneNode(true); cleanTable.querySelectorAll('button,[onclick]').forEach(el=>el.remove()); const companyName=(typeof getCompanyName==='function'?getCompanyName():'MVIApps') || 'MVIApps'; const w=window.open('','_blank'); if(!w){alert('Please allow pop-ups to print the All Parties report.');return;} w.document.write(`All Parties Report
${escapeHtml(companyName)}
MVIApps · Inventory & Accounts Management
All Parties Report
All saved customers and suppliers
${cleanTable.outerHTML}
Generated from MVIApps
`); w.document.close(); w.focus(); setTimeout(()=>w.print(),250); } function renderAllPartiesList(){ const list=document.getElementById('all-parties-list'); if(!list)return; const q=(document.getElementById('all-parties-search')?.value||'').toLowerCase().trim(); const parties=Array.isArray(window._mviPOSCloudContext?.parties)?window._mviPOSCloudContext.parties:[]; const filtered=parties.filter(x=>[x.name,x.type,x.mobile,x.email,x.gstin,x.pan,x.city,x.state,x.pin].some(v=>String(v||'').toLowerCase().includes(q))); if(!filtered.length){list.innerHTML='
No parties found.
';return;} list.innerHTML=`
${filtered.map(x=>``).join('')}
PartyTypeMobileGSTINOpeningBalanceAction
${escapeHtml(x.name||'')}
${escapeHtml(x.city||'')}
${escapeHtml(x.type||'Customer')}${escapeHtml(x.mobile||'—')}${escapeHtml(x.gstin||'—')}₹ ${escapeHtml(x.opening||'0')}${escapeHtml(x.balanceType||'Debit')}
`; } function salePurchasePartyReport(){ return `
Party Report

Sale / Purchase by Party

Party-wise sale and purchase summary for the selected period.

This Month
Between
To
#PARTY NAMESALE AMOUNTPURCHASE AMOUNT
`; } function reportDateISO(v){ if(!v)return ''; const d=new Date(v); return isNaN(d)?'':d.toISOString().slice(0,10); } function getReportTxDate(x){ return reportDateISO(x.date||x.invoiceDate||x.transactionDate||x.createdAt||x.paymentDate||''); } function getPartyReportName(x){ return String(x.partyName||x.customerName||x.supplierName||x.party||x.customer||x.supplier||'').trim(); } function renderSalePurchasePartyReport(){ const rows=document.getElementById('spRows'); if(!rows)return; const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const sales=filterByActiveFinancialYear(JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]')); const purchases=filterByActiveFinancialYear(JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]')); const from=document.getElementById('spFrom')?.value||''; const to=document.getElementById('spTo')?.value||''; const q=(document.getElementById('spSearch')?.value||'').toLowerCase().trim(); const map={}; parties.forEach(p=>{ const name=String(p.name||'').trim(); if(name)map[name.toLowerCase()]={name,sale:0,purchase:0}; }); const inRange=x=>{ const d=getReportTxDate(x); return (!from||!d||d>=from)&&(!to||!d||d<=to); }; sales.filter(inRange).forEach(x=>{ const n=getPartyReportName(x); if(!n)return; const k=n.toLowerCase(); if(!map[k])map[k]={name:n,sale:0,purchase:0}; map[k].sale += plAmount(x); }); purchases.filter(inRange).forEach(x=>{ const n=getPartyReportName(x); if(!n)return; const k=n.toLowerCase(); if(!map[k])map[k]={name:n,sale:0,purchase:0}; map[k].purchase += plAmount(x); }); const data=Object.values(map) .filter(x=>!q||x.name.toLowerCase().includes(q)) .sort((a,b)=>a.name.localeCompare(b.name)); document.getElementById('spCount').textContent=`${data.length} parties`; rows.innerHTML=data.length ?data.map((x,i)=>`${i+1}${escapeHtml(x.name)}${x.sale?'₹ '+x.sale.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}):'---'}${x.purchase?'₹ '+x.purchase.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}):'---'}`).join('') :`No party transactions found.`; } function printSalePurchaseParty(){ const table=document.querySelector('#report-sale-purchase-party #spRows')?.closest('table') || document.getElementById('spRows')?.closest('table'); if(!table){alert('Sale / Purchase by Party data is not available.');return;} const rows=table.querySelectorAll('tbody tr'); if(!rows.length){alert('Please generate the Sale / Purchase by Party report first.');return;} const cleanTable=table.cloneNode(true); cleanTable.querySelectorAll('button,.print-pdf-btn,.pl-pdf-actions').forEach(x=>x.remove()); const from=document.getElementById('spFrom')?.value||''; const to=document.getElementById('spTo')?.value||''; const fmt=v=>v?String(v).split('-').reverse().join('/'):''; const period=from&&to?`From ${fmt(from)} to ${fmt(to)}`:(from?`From ${fmt(from)}`:(to?`Up to ${fmt(to)}`:'Selected Period')); const company=(typeof getCompanyDetails==='function'?getCompanyDetails():{})||{}; const companyName=company.name||'MVIApps'; const address=[company.address,company.city,company.state,company.pin].filter(Boolean).join(', '); const contact=[company.mobile?`Phone: ${company.mobile}`:'',company.email?`Email: ${company.email}`:''].filter(Boolean).join(' '); const win=window.open('','_blank'); if(!win){alert('Please allow pop-ups to print the report.');return;} win.document.write(`Sale / Purchase by Party
${escapeHtml(companyName)}
MVIApps · Inventory & Accounts Management
${escapeHtml(address)}${contact?`
${escapeHtml(contact)}`:''}
Sale / Purchase by Party
Party-wise sale and purchase summary
Report Period:   ${escapeHtml(period)}
${cleanTable.outerHTML}
MVIAppsGenerated from MVIApps
`); win.document.close();win.focus(); setTimeout(()=>{try{win.print();setTimeout(()=>win.close(),500);}catch(e){console.error('Sale / Purchase by Party print error:',e);}},300); } function exportSalePurchasePartyCSV(){ const rows=[['#','PARTY NAME','SALE AMOUNT','PURCHASE AMOUNT']]; document.querySelectorAll('#spRows tr').forEach((tr,i)=>{const c=[...tr.children].map(x=>x.innerText.trim()); if(c.length===4)rows.push(c);}); const csv=rows.map(r=>r.map(v=>`"${String(v).replaceAll('"','""')}"`).join(',')).join('\n'); const a=document.createElement('a'); a.href='data:text/csv;charset=utf-8,'+encodeURIComponent(csv); a.download='Sale_Purchase_By_Party.csv'; a.click(); } function generateSalePurchaseParty(){const r=document.getElementById('salePurchasePartyResult');if(!r)return;const p=reportPeriodFilter('spp'),parties=partyReportParties(),rows=partyReportData(p.from,p.to);const body=parties.map(pt=>{const tx=rows.filter(x=>String(x.partyId)===String(pt.id));let sale=0,purchase=0,credit=0,debit=0;tx.forEach(x=>{if(x.type==='Sale')sale+=x.amount;else if(x.type==='Purchase')purchase+=x.amount;else if(x.type==='Credit Note')credit+=x.amount;else if(x.type==='Debit Note')debit+=x.amount;});return `${escapeHtml(pt.name||'Unnamed Party')}${escapeHtml(pt.type||'')}${plMoney(sale)}${plMoney(credit)}${plMoney(purchase)}${plMoney(debit)}${plMoney(sale-credit-purchase+debit)}`;}).join('');r.className='panel professional-report';r.innerHTML=`

Sale / Purchase by Party

${escapeHtml(reportPeriodLabel('spp'))}

${body||''}
PartyTypeSaleCredit NotePurchaseDebit NoteNet Difference
No party transactions found.
`;} function bankAccountsPage(){ const banks=getBankAccounts(); const selectedId=String(window._selectedBankId||banks[0]?.id||''); if(!window._selectedBankId && selectedId)window._selectedBankId=selectedId; const selected=banks.find(b=>String(b.id)===selectedId)||banks[0]; const search=escapeHtml(''); const rows=banks.map(b=>`
${escapeHtml(b.name||'Unnamed Bank')}
${(()=>{const bt=getBankTransactionTotals(b.id);const net=Number(bt.net)||0;return `
${net<0?'−':'+'} ₹ ${Math.abs(net).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2})}
`})()}
`).join(''); const tx=selected?getBankTransactions(selected.id):[]; return `
Bank & Cash

Banks

Manage bank accounts, balances and bank transactions.

${selected?escapeHtml(selected.name||'Unnamed Bank'):'Select a bank account'}
All Bank-mode transactions linked to this account are shown below.
${selected?`
`:''}
${selected?`${(()=>{const t=getBankTransactionTotals(selected.id);return `
Total Transactions
${t.count}
Total Transaction Amount
₹ ${t.total.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2})}
Net Bank Movement
₹ ${Math.abs(t.net).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2})}
`})()}

Transactions

${renderBankTransactionRows(selected.id)}
TypeNameDateIn/OutAmountReference⋮
`:`
Add a bank account to start managing bank transactions.
`}
`; } function cleanupDuplicateICICIBank(){ try{ const banks=getBankAccounts(); const matches=banks.filter(b=>String(b.name||'').trim().toLowerCase()==='icici'); if(matches.length<=1)return; const txAll=getAllBankTransactions(); // Keep the ICICI account with the most transaction history; if tied, keep the first. matches.sort((a,b)=>{ const ta=txAll.filter(x=>String(x.bankId)===String(a.id)).length; const tb=txAll.filter(x=>String(x.bankId)===String(b.id)).length; return tb-ta; }); const keepId=matches[0].id; const removeIds=new Set(matches.slice(1).map(b=>String(b.id))); saveBankAccounts(banks.filter(b=>!removeIds.has(String(b.id)))); saveBankTransactions(txAll.filter(x=>!removeIds.has(String(x.bankId)))); if(removeIds.has(String(window._selectedBankId)))window._selectedBankId=keepId; }catch(e){console.warn('Duplicate ICICI cleanup failed',e);} } function mviappsBankDisplay(value){ const raw=String(value??'').trim(); if(!raw)return '—'; try{ const banks=typeof getBankAccounts==='function'?getBankAccounts():JSON.parse(localStorage.getItem('mviapps_bank_accounts')||'[]'); const list=Array.isArray(banks)?banks:[]; const key=raw.toLowerCase(); const bank=list.find(b=>{ const vals=[ b?.id,b?.accountId,b?.name,b?.accountName,b?.bankName,b?.institution, b?.accountNumber,b?.accountNo ].map(v=>String(v??'').trim().toLowerCase()).filter(Boolean); return vals.includes(key); }); if(!bank)return raw; const name=String(bank?.bankName??bank?.institution??bank?.name??bank?.accountName??'').trim(); const no=String(bank?.accountNumber??bank?.accountNo??'').trim(); if(name&&no)return `${name} (A/c ${no})`; return name||no||raw; }catch(e){return raw;} } function getBankAccounts(){return JSON.parse(localStorage.getItem('mviapps_bank_accounts')||'[]');} function saveBankAccounts(a){localStorage.setItem('mviapps_bank_accounts',JSON.stringify(a));} function getBankTransactions(id){return JSON.parse(localStorage.getItem('mviapps_bank_transactions')||'[]').filter(x=>String(x.bankId)===String(id)).sort((a,b)=>String(b.date||'').localeCompare(String(a.date||''))||(Number(b.id)||0)-(Number(a.id)||0));} function saveBankTransactions(a){localStorage.setItem('mviapps_bank_transactions',JSON.stringify(a));} function getLinkedBankTransactions(bankId){ const banks=getBankAccounts(), bank=banks.find(b=>String(b.id)===String(bankId)); if(!bank)return []; const bankKeys=new Set([String(bank.id||'').trim().toLowerCase(),String(bank.name||'').trim().toLowerCase(),String(bank.accountName||'').trim().toLowerCase(),String(bank.bankName||'').trim().toLowerCase(),String(bank.institution||'').trim().toLowerCase()].filter(Boolean)); const out=[]; const money=v=>{if(typeof v==='number')return v;const n=Number(String(v??'').replace(/[^0-9.-]/g,''));return isFinite(n)?n:0;}; const add=(arr,type,amountSign,nameField)=>{ (arr||[]).forEach(x=>{ const mode=String(x.paymentMode||x.mode||'').trim().toLowerCase(); if(mode!=='bank' && mode!=='bank transfer')return; const refs=[x.bankAccount,x.account,x.bankName,x.bankId].map(v=>String(v??'').trim().toLowerCase()).filter(Boolean); if(!refs.some(r=>bankKeys.has(r)))return; const rawAmount=(type==='Sale'||type==='Purchase')?(x.total??x.grandTotal??x.netAmount??x.amount):(x.amount??x.total??x.grandTotal??x.netAmount); const amount=money(rawAmount); if(amount<=0)return; const name=x[nameField]||x.partyName||x.customerName||x.supplierName||x.category||x.incomeHead||x.number||'—'; out.push({id:'linked-'+type+'-'+x.id,type,name,date:x.date||'',amount:amount*amountSign,source:type,reference:x.number||x.invoiceNo||x.reference||''}); }); }; add(JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]'),'Sale',1,'customerName'); add(JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]'),'Purchase',-1,'supplierName'); add(JSON.parse(localStorage.getItem('mviapps_expenses')||'[]'),'Expense',-1,'category'); add(JSON.parse(localStorage.getItem('mviapps_payment_in')||'[]'),'Payment-In',1,'partyName'); add(JSON.parse(localStorage.getItem('mviapps_payment_out')||'[]'),'Payment-Out',-1,'partyName'); add(JSON.parse(localStorage.getItem('mviapps_other_income')||'[]'),'Other Income',1,'incomeHead'); return out; } function getBankDisplayTransactions(id){ const fyb=getFinancialYearBounds(getActiveFinancialYear()); const all=getBankTransactions(id).map(x=>({...x,source:'Bank'})).concat(getLinkedBankTransactions(id)); return all.filter(x=>{ const d=String(x.date||''); if(String(x.type||'').toLowerCase()==='opening balance')return false; return (!fyb.from||d>=fyb.from)&&(!fyb.to||d<=fyb.to); }).sort((a,b)=>String(b.date||'').localeCompare(String(a.date||''))||(Number(b.id)||0)-(Number(a.id)||0)); } function getBankFYOpeningBalance(id){ const bank=getBankAccounts().find(b=>String(b.id)===String(id)); if(!bank)return 0; const fyb=getFinancialYearBounds(getActiveFinancialYear()); let opening=Number(bank.openingBalance)||0; const all=getBankTransactions(id).map(x=>({...x,source:'Bank'})).concat(getLinkedBankTransactions(id)); all.forEach(x=>{ const d=String(x.date||''); if(!d||!fyb.from||d>=fyb.from||String(x.type||'').toLowerCase()==='opening balance')return; opening+=Number(x.amount)||0; }); return opening; } function getBankTransactionTotals(id){ const tx=getBankDisplayTransactions(id);let inflow=0,outflow=0; tx.forEach(x=>{const n=Number(x.amount)||0;if(n>=0)inflow+=n;else outflow+=Math.abs(n);}); const opening=getBankFYOpeningBalance(id); return {inflow,outflow,total:inflow+outflow,net:opening+inflow-outflow,count:tx.length,opening}; } function renderBankTransactionRows(id){ const tx=getBankDisplayTransactions(id); return tx.length?tx.map(x=>{const n=Number(x.amount)||0;const dir=n>=0?'In':'Out';return `${escapeHtml(x.type||'')}${escapeHtml(x.name||'—')}${escapeHtml(x.date||'')}${dir}₹ ${Math.abs(n).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2})}${escapeHtml(x.reference||'')}⋮`;}).join(''):`No transactions found for this bank account.`; } function selectBankAccount(id){window._selectedBankId=id;show('bank-accounts');} function closeBankAccountEdit(){ document.getElementById('bankEditOverlay')?.remove(); } function openBankAccountEdit(id){ const bank=getBankAccounts().find(b=>String(b.id)===String(id)); if(!bank)return; closeBankAccountEdit(); const esc=v=>escapeHtml(String(v??'')); const date=bank.openingBalanceDate||bank.asOfDate||''; const accountNumber=bank.accountNumber||bank.accountNo||''; const ifsc=bank.ifsc||bank.ifscCode||''; const upi=bank.upiId||bank.upi||''; const bankName=bank.bankName||bank.institution||''; const holder=bank.accountHolderName||bank.holderName||''; const overlay=document.createElement('div'); overlay.id='bankEditOverlay'; overlay.className='bank-edit-overlay open'; overlay.innerHTML=``; overlay.addEventListener('click',e=>{if(e.target===overlay)closeBankAccountEdit();}); document.body.appendChild(overlay); setTimeout(()=>document.getElementById('editBankDisplayName')?.focus(),0); } function saveBankAccountEdit(id){ const banks=getBankAccounts(); const bank=banks.find(b=>String(b.id)===String(id)); if(!bank){closeBankAccountEdit();return;} const name=document.getElementById('editBankDisplayName')?.value.trim()||''; if(!name){alert('Please enter the Account Display Name.');return;} const oldOpening=Number(bank.openingBalance)||0; const newOpening=Number(document.getElementById('editBankOpening')?.value)||0; const openingDate=document.getElementById('editBankOpeningDate')?.value||bank.openingBalanceDate||new Date().toISOString().slice(0,10); bank.name=name; bank.accountName=name; bank.institution=document.getElementById('editBankName')?.value.trim()||''; bank.bankName=bank.institution; bank.accountNumber=document.getElementById('editBankAccountNumber')?.value.trim()||''; bank.ifsc=document.getElementById('editBankIfsc')?.value.trim()||''; bank.ifscCode=bank.ifsc; bank.upiId=document.getElementById('editBankUpi')?.value.trim()||''; bank.accountHolderName=document.getElementById('editBankHolder')?.value.trim()||''; bank.openingBalance=newOpening; bank.openingBalanceDate=openingDate; if(newOpening!==oldOpening)bank.balance=(Number(bank.balance)||0)+(newOpening-oldOpening); saveBankAccounts(banks); const allTx=getAllBankTransactions(); const openingIndex=allTx.findIndex(x=>String(x.bankId)===String(bank.id)&&String(x.type||'').toLowerCase()==='opening balance'); if(openingIndex>=0){ if(newOpening===0)allTx.splice(openingIndex,1); else{ allTx[openingIndex].amount=newOpening; allTx[openingIndex].date=openingDate; allTx[openingIndex].name='Opening Balance'; } }else if(newOpening!==0){ allTx.push({id:Date.now()+Math.random(),bankId:bank.id,type:'Opening Balance',name:'Opening Balance',date:openingDate,amount:newOpening}); } saveBankTransactions(allTx); window._selectedBankId=bank.id; closeBankAccountEdit(); show('bank-accounts'); alert('Bank account details updated successfully.'); } function renderBankAccounts(){const el=document.getElementById('bankList');if(!el)return;const q=(document.getElementById('bankSearch')?.value||'').toLowerCase().trim();const banks=getBankAccounts().filter(b=>!q||String(b.name||'').toLowerCase().includes(q)||String(b.balance||'').includes(q));el.innerHTML=banks.length?banks.map(b=>`
${escapeHtml(b.name||'Unnamed Bank')}
${(()=>{const bt=getBankTransactionTotals(b.id);const net=Number(bt.net)||0;return `
${net<0?'−':'+'} ₹ ${Math.abs(net).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2})}
`})()}
`).join(''):'
No matching bank accounts.
';} function toggleBankAddForm(force){const e=document.getElementById('bankAddForm');if(!e)return;e.classList.toggle('open',force===undefined?!e.classList.contains('open'):!!force);if(e.classList.contains('open'))setTimeout(()=>document.getElementById('newBankName')?.focus(),0);} function addBankAccount(){const name=document.getElementById('newBankName')?.value.trim()||'',institution=document.getElementById('newBankInstitution')?.value.trim()||'',opening=Number(document.getElementById('newBankOpening')?.value)||0,openingDate=document.getElementById('newBankOpeningDate')?.value||new Date().toISOString().slice(0,10);if(!name){alert('Please enter the Account Name.');return;}const banks=getBankAccounts();const bank={id:Date.now()+Math.random(),name,institution,balance:opening,openingBalance:opening,openingBalanceDate:openingDate,createdAt:new Date().toISOString()};banks.push(bank);saveBankAccounts(banks);window._selectedBankId=bank.id;if(opening!==0){const tx=getBankTransactions(bank.id);tx.push({id:Date.now(),bankId:bank.id,type:'Opening Balance',name:'Opening Balance',date:openingDate,amount:opening});saveBankTransactions([...getAllBankTransactions(),...tx]);}alert('Bank account added successfully.');show('bank-accounts');} function getAllBankTransactions(){return filterByActiveFinancialYear(JSON.parse(localStorage.getItem('mviapps_bank_transactions')||'[]'));} function toggleBankActionMenu(e){if(e)e.stopPropagation();document.getElementById('bankActionMenu')?.classList.toggle('open');} function openBankTransaction(type){document.getElementById('bankActionMenu')?.classList.remove('open');const bank=getBankAccounts().find(b=>String(b.id)===String(window._selectedBankId));if(!bank)return;const title=type==='bank-cash'?'Bank to Cash Transfer':type==='cash-bank'?'Cash to Bank Transfer':type==='bank-bank'?'Bank to Bank Transfer':'Adjust Bank Balance';const body=type==='bank-bank'?`
`:'';const sign=type==='cash-bank'?'Deposit':'Withdrawal';const adjust=type==='adjust'?`
`:'';const box=document.getElementById('bankTxnForm');if(!box)return;box.style.display='block';box.innerHTML=`

${title}

Account: ${escapeHtml(bank.name)}

${body}${adjust}
`;} function saveBankTransaction(type){const banks=getBankAccounts(),bank=banks.find(b=>String(b.id)===String(window._selectedBankId)),amount=Number(document.getElementById('bankTxnAmount')?.value)||0;if(!bank||amount<=0){alert('Please enter a valid amount.');return;}const date=document.getElementById('bankTxnDate')?.value||new Date().toISOString().slice(0,10);if(!ensureEntryDateInActiveFY(date,'Date'))return;const name=document.getElementById('bankTxnName')?.value.trim()||'';let delta=0,label='',target=null;if(type==='cash-bank'){delta=amount;label='Cash to Bank Transfer';}else if(type==='bank-cash'){delta=-amount;label='Bank to Cash Transfer';}else if(type==='bank-bank'){target=banks.find(b=>String(b.id)===String(document.getElementById('bankTxnTarget')?.value));if(!target){alert('Please select the destination bank.');return;}delta=-amount;label='Bank to Bank Transfer';}else{const inc=document.getElementById('bankAdjustType')?.value==='increase';delta=inc?amount:-amount;label='Bank Balance Adjustment';}if(delta<0 && (Number(bank.balance)||0)+delta<0){if(!confirm('This transaction will make the bank balance negative. Continue?'))return;}bank.balance=(Number(bank.balance)||0)+delta;saveBankAccounts(banks);const tx=getAllBankTransactions();tx.push({id:Date.now()+Math.random(),bankId:bank.id,type:label,name:name||label,date,amount:delta});if(target){target.balance=(Number(target.balance)||0)+amount;tx.push({id:Date.now()+Math.random(),bankId:target.id,type:'Bank to Bank Transfer',name:`From ${bank.name}`,date,amount});}saveBankTransactions(tx); if(type==='cash-bank' || type==='bank-cash'){ const cashDelta=type==='cash-bank'?-amount:amount; const currentCash=getCashBalance(); saveCashBalance(currentCash+cashDelta); const cashTx=getCashTransactions(); cashTx.push({id:Date.now()+Math.random(),type:label,description:target?`To ${target.name}`:name||label,date,amount:cashDelta}); saveCashTransactions(cashTx); } show('bank-accounts'); } function stockSummaryReport(){ const cats=[...new Set(JSON.parse(localStorage.getItem('mviapps_items')||'[]').map(x=>String(x.category||'').trim()).filter(Boolean))].sort((a,b)=>a.localeCompare(b)); const gs=typeof getGodowns==='function'?getGodowns():[]; const godownOptions=gs.map(g=>``).join(''); return `
Stock / Item Report

Stock Summary

Item-wise stock position with quantity, availability and stock value.

FILTERS
Show items in stock
STOCK SUMMARY
Stock Qty and stock value are calculated from the inventory records currently saved in MVIApps. Godown filtering uses the saved godown stock balances.
`; } function getReportStockCustomFields(){ return [...document.querySelectorAll('.rs-stock-custom:checked')].map(x=>x.value); } function toggleReportStockCustomFields(){ document.getElementById('rsStockCustomMenu')?.classList.toggle('open'); } function toggleAllReportStockCustomFields(checked){ document.querySelectorAll('.rs-stock-custom').forEach(x=>x.checked=checked); renderReportStockSummary(); } document.addEventListener('click',function(e){ const wrap=e.target.closest('.stock-custom-wrap'); if(!wrap)document.getElementById('rsStockCustomMenu')?.classList.remove('open'); }); function reportStockRows(){ const items=typeof getSortedItems==='function'?getSortedItems():JSON.parse(localStorage.getItem('mviapps_items')||'[]').sort((a,b)=>String(a.name||'').localeCompare(String(b.name||''))); const category=document.getElementById('rsStockCategory')?.value||''; const godownId=document.getElementById('rsStockGodown')?.value||''; const onlyStock=!!document.getElementById('rsStockOnly')?.checked; return items.filter(x=>{ if(category && String(x.category||'')!==category)return false; const t=typeof stockTotals==='function'?stockTotals(x):{closing:Number(x.qty)||0,stockValue:(Number(x.qty)||0)*(Number(x.purchase)||0)}; let qty=t.closing, value=t.stockValue; if(godownId && typeof getItemGodownQty==='function')qty=getItemGodownQty(x.id,godownId); if(onlyStock && qty<=0)return false; return true; }).map(x=>{ const t=typeof stockTotals==='function'?stockTotals(x):{closing:Number(x.qty)||0,stockValue:(Number(x.qty)||0)*(Number(x.purchase)||0)}; const godownId=document.getElementById('rsStockGodown')?.value||''; const qty=godownId&&typeof getItemGodownQty==='function'?getItemGodownQty(x.id,godownId):t.closing; const rate=Number(x.purchase)||0; return {item:x,stockQty:qty,availableQty:qty,reservedQty:0,stockValue:godownId?qty*rate:t.stockValue,purchasePrice:rate}; }); } function renderReportStockSummary(){ const head=document.getElementById('rsStockHead'),body=document.getElementById('rsStockRows'),foot=document.getElementById('rsStockFoot'); if(!head||!body)return; const fields=getReportStockCustomFields(), rows=reportStockRows(); const cols=[['Item Name','left'],['Purchase Price','right'],['Stock Qty','right'],['Available Qty For Sale','right'],['Reserved Qty','right'],['Stock Value','right']]; fields.forEach(f=>cols.push([f==='sku'?'SKU':f==='weight'?'Weight':f==='dimension'?'Dimension':'Source','right'])); head.innerHTML=''+cols.map(c=>`${c[0]}`).join('')+''; body.innerHTML=rows.length?rows.map(r=>{ const x=r.item,custom=fields.map(f=>f==='sku'?x.code||x.sku||'':f==='weight'?x.weight||'':f==='dimension'?x.dimension||x.dimensions||'':x.source||''); return `${escapeHtml(x.name||'')}${x.code?`${escapeHtml(x.code)}`:''}₹ ${r.purchasePrice.toFixed(2)}${r.stockQty}${r.availableQty}0₹ ${r.stockValue.toFixed(2)}${custom.map(v=>`${escapeHtml(v)}`).join('')}`; }).join(''):`No stock items found for the selected filters.`; const totalQty=rows.reduce((a,r)=>a+r.stockQty,0), totalAvail=rows.reduce((a,r)=>a+r.availableQty,0), totalReserved=rows.reduce((a,r)=>a+r.reservedQty,0), totalValue=rows.reduce((a,r)=>a+r.stockValue,0); foot.innerHTML=rows.length?`Total${totalQty}${totalAvail}${totalReserved}₹ ${totalValue.toFixed(2)}${fields.map(()=>'').join('')}`:''; } function printReportStockSummary(){ let table=document.querySelector('.stock-summary-report-table'); if(!table){renderReportStockSummary();table=document.querySelector('.stock-summary-report-table');} if(!table){alert('Stock Summary data is not available for printing.');return;} const category=document.getElementById('rsStockCategory')?.value||'All Categories'; const godown=document.getElementById('rsStockGodown'); const godownName=godown?.selectedOptions?.[0]?.textContent||'All Godown'; const onlyStock=document.getElementById('rsStockOnly')?.checked?'Yes':'No'; const custom=getReportStockCustomFields(); const win=window.open('','_blank');if(!win){alert('Please allow pop-ups to print the Stock Summary report.');return;} const safeTable=table.outerHTML; win.document.open(); win.document.write(`Stock Summary

Stock Summary

Item-wise stock position with quantity, availability and stock value

Category: ${escapeHtml(category)}
Godown: ${escapeHtml(godownName)}
Show items in stock: ${onlyStock}
Custom fields: ${custom.length?escapeHtml(custom.join(', ')):'None'}
${table.innerHTML}
`); win.document.close();win.focus();setTimeout(()=>{win.print();setTimeout(()=>win.close(),500)},300); } function mviappsExcelXmlEscape(v){ return String(v??'').replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"').replace(/'/g,'''); } function exportReportStockSummary(){ let table=document.querySelector('.stock-summary-report-table'); if(!table){renderReportStockSummary();table=document.querySelector('.stock-summary-report-table');} if(!table){alert('Stock Summary data is not available for export.');return;} const category=document.getElementById('rsStockCategory')?.value||'All Categories'; const godown=document.getElementById('rsStockGodown'); const godownName=godown?.selectedOptions?.[0]?.textContent||'All Godown'; const onlyStock=document.getElementById('rsStockOnly')?.checked?'Yes':'No'; const rows=[...table.querySelectorAll('tr')]; const sheetRows=rows.map(tr=>{ const cells=[...tr.children]; const isTotal=tr.parentElement?.tagName==='TFOOT'; const isHead=tr.parentElement?.tagName==='THEAD'; const out=[]; cells.forEach((cell,idx)=>{ const raw=String(cell.textContent||'').replace(/\s+/g,' ').trim(); if(idx===0 && !isHead){ const code=cell.querySelector('.item-code')?.textContent?.trim()||''; const name=code?raw.replace(code,'').trim():raw; out.push(`${mviappsExcelXmlEscape(name)}`); out.push(`${mviappsExcelXmlEscape(code)}`); return; } if(idx===0 && isHead){ out.push(`Item Name`); out.push(`Item Code`); return; } const text=raw; const isNumber=idx>0 && /^₹?\s*-?[\d,]+(?:\.\d+)?$/.test(text); const numeric=isNumber?Number(text.replace(/₹|,/g,'')):NaN; out.push(`${mviappsExcelXmlEscape(Number.isFinite(numeric)?numeric:text)}`); }); return `${out.join('')}`; }).join(''); const xml=` Stock SummaryCategory${mviappsExcelXmlEscape(category)}Godown${mviappsExcelXmlEscape(godownName)}Show items in stock${onlyStock} ${sheetRows}
`; const blob=new Blob([xml],{type:'application/vnd.ms-excel'}); const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='stock-summary-report.xls';document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(a.href),1000); } function stockDetailsReport(){ const cats=[...new Set(JSON.parse(localStorage.getItem('mviapps_items')||'[]').map(x=>String(x.category||'').trim()).filter(Boolean))].sort((a,b)=>a.localeCompare(b)); const gs=typeof getGodowns==='function'?getGodowns():[]; const godownOptions=gs.map(g=>``).join(''); const fy=mviappsActiveFYReportRange(); const iso=d=>d; const first=fy.from, last=fy.to; return `
Stock / Item Report

Stock Details

Item-wise stock movement details for the selected period.

To
DETAILS
`; } function stockDetailsDateInRange(date,from,to){const d=String(date||'');return d>=from&&d<=to;} function getStockDetailsRows(){ const items=typeof getSortedItems==='function'?getSortedItems():JSON.parse(localStorage.getItem('mviapps_items')||'[]').sort((a,b)=>String(a.name||'').localeCompare(String(b.name||''))); let from=document.getElementById('rsDetailsFrom')?.value||''; let to=document.getElementById('rsDetailsTo')?.value||''; ({from,to}=mviappsConstrainReportRange(from,to)); const category=document.getElementById('rsDetailsCategory')?.value||''; const godownId=document.getElementById('rsDetailsGodown')?.value||''; const gs=typeof getGodowns==='function'?getGodowns():[]; const main=gs.find(g=>String(g.name||'').trim().toLowerCase()==='main godown')||gs[0]; const moves=typeof getStockMovements==='function'?getStockMovements():[]; const inScope=(m)=>!godownId||!m.godownId||String(m.godownId)===String(godownId)||(!m.godownId&&main&&String(main.id)===String(godownId)); return items.filter(x=>!category||String(x.category||'')===category).map(item=>{ const im=moves.filter(m=>String(m.itemId)===String(item.id)&&inScope(m)); const fyb=getFinancialYearBounds(getActiveFinancialYear()); const baseTotals=typeof stockTotals==='function'?stockTotals(item):{opening:Number(item.qty)||0}; let beginning=Number(baseTotals.opening)||0; const created=String(item.createdAt||'').slice(0,10); const fyFrom=String(fyb.from||''); const createdDuringFY=!!created&&!!fyFrom&&created>fyFrom&&(!fyb.to||created<=fyb.to); const baseQty=createdDuringFY?(Number(item.qty)||0):0; // Items created after the FY began have their initial quantity stored on the // item record rather than as a stock movement. Carry it into the report at // the creation date so Stock Details agrees with Stock Summary. if(createdDuringFY&&(!from||created{ const d=String(m.date||'').slice(0,10); if(!d||!from||d=from)return; if(createdDuringFY&&created&&d=from)&&(!to||created<=to)&&(!godownId||!main||String(main.id)===String(godownId))){ qtyIn+=baseQty; purchaseAmount+=baseQty*(Number(item.purchase||item.purchaseRate||item.rate)||0); } im.forEach(m=>{ const d=String(m.date||'').slice(0,10); if(!stockDetailsDateInRange(d,from,to))return; if(createdDuringFY&&created&&dto){const tmp=from;from=to;to=tmp;document.getElementById('rsDetailsFrom').value=from;document.getElementById('rsDetailsTo').value=to;} const rows=getStockDetailsRows(); const cols=['Item Name','Beginning Quantity','Quantity In','Purchase Amount','Quantity Out','Sale Amount','Closing Quantity']; head.innerHTML=''+cols.map((c,i)=>`${c}`).join('')+''; body.innerHTML=rows.length?rows.map(r=>`${escapeHtml(r.item.name||'')}${r.beginning}${r.qtyIn}₹ ${r.purchaseAmount.toFixed(2)}${r.qtyOut}₹ ${r.saleAmount.toFixed(2)}${r.closing}`).join(''):`No stock details found for the selected filters.`; const sums=rows.reduce((a,r)=>{a.b+=r.beginning;a.i+=r.qtyIn;a.pa+=r.purchaseAmount;a.o+=r.qtyOut;a.sa+=r.saleAmount;a.c+=r.closing;return a;},{b:0,i:0,pa:0,o:0,sa:0,c:0}); foot.innerHTML=rows.length?`Total${sums.b}${sums.i}₹ ${sums.pa.toFixed(2)}${sums.o}₹ ${sums.sa.toFixed(2)}${sums.c}`:''; } function printStockDetailsReport(){ const table=document.querySelector('.stock-details-table');if(!table)return;const from=document.getElementById('rsDetailsFrom')?.value||'',to=document.getElementById('rsDetailsTo')?.value||'';const win=window.open('','_blank');if(!win)return; win.document.write(`Stock Details

Stock Details

Item-wise stock movement details

From: ${escapeHtml(from)}   To: ${escapeHtml(to)}
${table.outerHTML}`);win.document.close();win.focus();setTimeout(()=>{win.print();setTimeout(()=>win.close(),300)},250); } function exportStockDetailsReport(){ const rows=getStockDetailsRows();let csv='Item Name,Beginning Quantity,Quantity In,Purchase Amount,Quantity Out,Sale Amount,Closing Quantity\n';rows.forEach(r=>{const v=[r.item.name||'',r.beginning,r.qtyIn,r.purchaseAmount.toFixed(2),r.qtyOut,r.saleAmount.toFixed(2),r.closing];csv+=v.map(x=>`"${String(x).replace(/"/g,'""')}"`).join(',')+'\n';});if(typeof downloadCSV==='function')downloadCSV(csv,'stock-details-report.csv'); } function itemDetailsReport(){ const cats=[...new Set(JSON.parse(localStorage.getItem('mviapps_items')||'[]').map(x=>String(x.category||'').trim()).filter(Boolean))].sort((a,b)=>a.localeCompare(b)); const gs=typeof getGodowns==='function'?getGodowns():[]; const godownOptions=gs.map(g=>``).join(''); return `
Stock / Item Report

Item Details

Complete item master details with pricing, stock and source information.

ITEM DETAILS
`; } function getItemDetailsReportRows(){ const items=typeof getSortedItems==='function'?getSortedItems():JSON.parse(localStorage.getItem('mviapps_items')||'[]').sort((a,b)=>String(a.name||'').localeCompare(String(b.name||''))); const category=document.getElementById('riDetailsCategory')?.value||''; const godownId=document.getElementById('riDetailsGodown')?.value||''; return items.filter(x=>!category||String(x.category||'')===category).map(x=>{ const t=typeof stockTotals==='function'?stockTotals(x):{closing:Number(x.qty)||0,stockValue:(Number(x.qty)||0)*(Number(x.purchase)||0)}; const qty=godownId&&typeof getItemGodownQty==='function'?getItemGodownQty(x.id,godownId):t.closing; const rate=Number(x.purchase)||0; return {item:x,qty,stockValue:godownId?qty*rate:t.stockValue}; }); } function renderItemDetailsReport(){ const head=document.getElementById('riDetailsHead'),body=document.getElementById('riDetailsRows'),foot=document.getElementById('riDetailsFoot');if(!head||!body)return; const rows=getItemDetailsReportRows(); const cols=['Item Name','Item Code','Category','Brand','Unit','HSN/SAC','Purchase Rate','Sale Rate','Quantity','Stock Value','Source']; head.innerHTML=''+cols.map((c,i)=>`${c}`).join('')+''; body.innerHTML=rows.length?rows.map(r=>{const x=r.item;return `${escapeHtml(x.name||'')}${escapeHtml(x.code||x.sku||'')}${escapeHtml(x.category||'')}${escapeHtml(x.brand||'')}${escapeHtml(x.unit||'')}${escapeHtml(x.hsn||'')}₹ ${Number(x.purchase||0).toFixed(2)}₹ ${Number(x.sale||0).toFixed(2)}${r.qty}₹ ${r.stockValue.toFixed(2)}${escapeHtml(x.source||'')}`}).join(''):`No items found for the selected filters.`; const qty=rows.reduce((a,r)=>a+r.qty,0),value=rows.reduce((a,r)=>a+r.stockValue,0); foot.innerHTML=rows.length?`Total${qty}₹ ${value.toFixed(2)}`:''; } function printItemDetailsReport(){ const table=document.querySelector('.item-details-report-table');if(!table)return;const win=window.open('','_blank');if(!win)return; win.document.write(`Item Details

Item Details

Complete item master details

${table.outerHTML}`);win.document.close();win.focus();setTimeout(()=>{win.print();setTimeout(()=>win.close(),300)},250); } function exportItemDetailsReport(){ const rows=getItemDetailsReportRows();let csv='Item Name,Item Code,Category,Brand,Unit,HSN/SAC,Purchase Rate,Sale Rate,Quantity,Stock Value,Source\n'; rows.forEach(r=>{const x=r.item,v=[x.name||'',x.code||x.sku||'',x.category||'',x.brand||'',x.unit||'',x.hsn||'',Number(x.purchase||0).toFixed(2),Number(x.sale||0).toFixed(2),r.qty,r.stockValue.toFixed(2),x.source||''];csv+=v.map(z=>`"${String(z).replace(/"/g,'""')}"`).join(',')+'\n';}); if(typeof downloadCSV==='function')downloadCSV(csv,'item-details-report.csv'); } function stockTransferReport(){ return `
Stock / Item Report

Stock Transfer Details

Item-wise details of stock transferred between godowns.

⇄

Stock Transfer Details

Loading transfer details...

`; } function initStockTransferReport(){ const items=getSortedItems(), gs=getGodowns(); const itemSel=document.getElementById('strItem'); const fromSel=document.getElementById('strFromGodown'); const toSel=document.getElementById('strToGodown'); if(itemSel) itemSel.innerHTML=''+ items.map(i=>``).join(''); const godownOpts=gs.map(g=>``).join(''); if(fromSel) fromSel.innerHTML=''+godownOpts; if(toSel) toSel.innerHTML=''+godownOpts; const fy=mviappsActiveFYReportRange(); const f=document.getElementById('strFrom'), t=document.getElementById('strTo'); if(f) f.value=fy.from; if(t) t.value=fy.to; syncReportDateDisplay('str','from'); syncReportDateDisplay('str','to'); renderStockTransferReport(); } function renderStockTransferReport(){ const result=document.getElementById('stockTransferReportResult'); if(!result)return; const rawFrom=document.getElementById('strFrom')?.value||''; const rawTo=document.getElementById('strTo')?.value||''; const constrained=mviappsConstrainReportRange(rawFrom,rawTo); const from=constrained.from||rawFrom; const to=constrained.to||rawTo; const fromEl=document.getElementById('strFrom'), toEl=document.getElementById('strTo'); if(fromEl && fromEl.value!==from){fromEl.value=from;syncReportDateDisplay('str','from');} if(toEl && toEl.value!==to){toEl.value=to;syncReportDateDisplay('str','to');} const itemId=document.getElementById('strItem')?.value||''; const fromGodown=document.getElementById('strFromGodown')?.value||''; const toGodown=document.getElementById('strToGodown')?.value||''; const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); const gs=getGodowns(); const transfers=filterByActiveFinancialYear(JSON.parse(localStorage.getItem('mviapps_godown_transfers')||'[]')); const itemMap=new Map(items.map(i=>[String(i.id),i])); const godownMap=new Map(gs.map(g=>[String(g.id),g])); const rows=transfers.filter(x=>{ const d=String(x.date||''); return (!from||d>=from)&&(!to||d<=to)&& (!itemId||String(x.itemId)===String(itemId))&& (!fromGodown||String(x.fromGodownId)===String(fromGodown))&& (!toGodown||String(x.toGodownId)===String(toGodown)); }).sort((a,b)=>String(a.date||'').localeCompare(String(b.date||''))||(Number(a.id)||0)-(Number(b.id)||0)); const totalQty=rows.reduce((s,x)=>s+(Number(x.qty)||0),0); const body=rows.length?rows.map(x=>{ const item=itemMap.get(String(x.itemId)); const fg=godownMap.get(String(x.fromGodownId)); const tg=godownMap.get(String(x.toGodownId)); return ` ${escapeHtml(String(x.date||'').split('-').reverse().join('/'))} ${escapeHtml(x.itemName||item?.name||'')}${item?.code?`${escapeHtml(item.code)}`:''} ${escapeHtml(fg?.name||x.fromGodownName||'—')} ${escapeHtml(tg?.name||x.toGodownName||'—')} ${Number(x.qty||0).toLocaleString('en-IN')} ${escapeHtml(item?.unit||'Nos')} ${escapeHtml(x.note||'—')} `; }).join(''):`No stock transfers found for the selected filters.`; const period=(from&&to)?`From ${from.split('-').reverse().join('/')} to ${to.split('-').reverse().join('/')}`:'All available dates'; result.innerHTML=`
Stock Transfer Details ${escapeHtml(period)}
${body} ${rows.length?``:''}
DateItemFrom GodownTo GodownQuantityUnitReference / Note
Total Transfers: ${rows.length}${totalQty.toLocaleString('en-IN')}
`; } function printStockTransferReport(){ const el=document.getElementById('stockTransferReportResult'); const table=el?.querySelector('.stock-transfer-report-table'); if(!table){ alert('Please click View Report first, then click Print / Save PDF.'); return; } const win=window.open('','_blank'); if(!win){alert('Please allow pop-ups to print the report.');return;} const heading=el.querySelector('.stock-transfer-report-heading')?.textContent?.replace(/\s+/g,' ').trim()||'Stock Transfer Details'; win.document.write(`Stock Transfer Details

Stock Transfer Details

Item-wise details of stock transferred between godowns.

${heading}
${table.outerHTML}
MVIApps • Stock / Item Report
`); win.document.close();win.focus();setTimeout(()=>{win.print();setTimeout(()=>win.close(),300)},250); } function purchaseReport(){ return `
↗
Sale / Purchase Report
Purchase Report
View and analyse purchase invoices and item-wise purchases for the selected period.
Invoices
0
Items Purchased
0
Total Purchase
₹ 0.00
Purchase Transactions
DateInvoice No.SupplierItemGodownQtyRateDiscountGSTPayment ModeAmount
Total Purchase₹ 0.00
`; } function purchaseReportMoney(v){return '₹ '+Number(v||0).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2});} function purchaseReportNumber(v){const n=Number(String(v??0).replace(/[^0-9.-]/g,''));return isFinite(n)?n:0;} function purchaseReportInit(){ const fy=mviappsActiveFYReportRange(); const f=document.getElementById('purchaseReportFrom'),t=document.getElementById('purchaseReportTo');if(f)f.value=fy.from;if(t)t.value=fy.to; syncReportDateDisplay('purchaseReport','from'); syncReportDateDisplay('purchaseReport','to'); const purchases=JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]'),sel=document.getElementById('purchaseReportSupplier'); if(sel){const names=[...new Set(purchases.map(x=>String(x.supplierName||x.supplier||'').trim()).filter(Boolean))].sort((a,b)=>a.localeCompare(b));sel.innerHTML=''+names.map(n=>``).join('');} mviappsRunPurchaseReport(); } function mviappsRunPurchaseReport(){ const rows=document.getElementById('purchaseReportRows');if(!rows)return; const purchases=JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]'); let {from,to}=mviappsConstrainReportRange(document.getElementById('purchaseReportFrom')?.value||'',document.getElementById('purchaseReportTo')?.value||''); const supplier=(document.getElementById('purchaseReportSupplier')?.value||'').toLowerCase(),mode=(document.getElementById('purchaseReportMode')?.value||'').toLowerCase(),q=(document.getElementById('purchaseReportSearch')?.value||'').toLowerCase().trim(); const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'),godowns=getGodowns();const itemName=id=>items.find(i=>String(i.id)===String(id))?.name||'Item';const godownName=id=>godowns.find(g=>String(g.id)===String(id))?.name||'—'; const inRange=x=>{const d=String(x.date||'').slice(0,10);return (!from||d>=from)&&(!to||d<=to);}; const filtered=purchases.filter(x=>{const cn=String(x.supplierName||x.supplier||'').toLowerCase(),pm=String(x.paymentMode||'').toLowerCase();const itemText=(x.items||[]).map(it=>itemName(it.itemId)).join(' ').toLowerCase();return inRange(x)&&(!supplier||cn===supplier)&&(!mode||pm===mode)&&(!q||String(x.invoiceNo||'').toLowerCase().includes(q)||cn.includes(q)||itemText.includes(q));}).sort((a,b)=>(String(a.date||'')).localeCompare(String(b.date||''))||(Number(a.id)||0)-(Number(b.id)||0)); let total=0,itemCount=0;const out=[]; filtered.forEach(x=>(x.items||[]).forEach(it=>{const qty=purchaseReportNumber(it.qty),rate=purchaseReportNumber(it.rate),disc=purchaseReportNumber(it.discount),gst=purchaseReportNumber(it.gst),base=qty*rate,discount=base*disc/100,taxable=base-discount,tax=taxable*gst/100,amount=taxable+tax;total+=amount;itemCount+=qty;out.push({date:x.date||'',invoice:x.invoiceNo||'',supplier:x.supplierName||x.supplier||'',item:itemName(it.itemId),godown:godownName(it.godownId),qty,rate,disc,gst,mode:x.paymentMode||'',amount});})); const esc=escapeHtml,fmt=purchaseReportMoney;rows.innerHTML=out.length?out.map(x=>`${esc(x.date)}${esc(x.invoice)}${esc(x.supplier)}${esc(x.item)}${esc(x.godown)}${x.qty.toLocaleString('en-IN')}${fmt(x.rate)}${x.disc.toFixed(2)}%${x.gst.toFixed(2)}%${esc(x.mode)}${fmt(x.amount)}`).join(''):`No purchase transactions found for the selected filters.`; const invEl=document.getElementById('purchaseReportInvoices'),itemsEl=document.getElementById('purchaseReportItems'),totEl=document.getElementById('purchaseReportTotal'),foot=document.getElementById('purchaseReportFootTotal'),badge=document.getElementById('purchaseReportBadge'),period=document.getElementById('purchaseReportPeriod');if(invEl)invEl.textContent=filtered.length;if(itemsEl)itemsEl.textContent=itemCount.toLocaleString('en-IN');if(totEl)totEl.textContent=fmt(total);if(foot)foot.textContent=fmt(total);if(badge)badge.textContent=out.length+' line'+(out.length===1?'':'s')+' · '+fmt(total);if(period)period.textContent=(from||'Start')+' to '+(to||'End'); } function mviappsPrintPurchaseReport(){const table=document.getElementById('purchaseReportTable');if(!table)return;const period=document.getElementById('purchaseReportPeriod')?.textContent||'';const w=window.open('','_blank');if(!w){alert('Please allow pop-ups to print the report.');return;}w.document.write(`Purchase Report

Purchase Report

${escapeHtml(period)}

${table.outerHTML}`);w.document.close();w.focus();setTimeout(()=>w.print(),250);} function saleReport(){ return `
↗
Sale / Purchase Report
Sale Report
View and analyse sales invoices and item-wise sales for the selected period.
Invoices
0
Items Sold
0
Total Sale
₹ 0.00
Sales Transactions
DateInvoice No.CustomerItemGodownQtyRateDiscountGSTPayment ModeAmount
Total Sale₹ 0.00
`; } function saleReportMoney(v){return '₹ '+Number(v||0).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2});} function saleReportNumber(v){const n=Number(String(v??0).replace(/[^0-9.-]/g,''));return isFinite(n)?n:0;} function saleReportInit(){ const fy=mviappsActiveFYReportRange(); const f=document.getElementById('saleReportFrom'),t=document.getElementById('saleReportTo');if(f)f.value=fy.from;if(t)t.value=fy.to; syncReportDateDisplay('saleReport','from'); syncReportDateDisplay('saleReport','to'); const sales=JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]'),sel=document.getElementById('saleReportCustomer'); if(sel){const names=[...new Set(sales.map(x=>String(x.customerName||x.customer||'').trim()).filter(Boolean))].sort((a,b)=>a.localeCompare(b));sel.innerHTML=''+names.map(n=>``).join('');} mviappsRunSaleReport(); } function mviappsRunSaleReport(){ const rows=document.getElementById('saleReportRows');if(!rows)return; const sales=JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]'); let {from,to}=mviappsConstrainReportRange(document.getElementById('saleReportFrom')?.value||'',document.getElementById('saleReportTo')?.value||''); const customer=(document.getElementById('saleReportCustomer')?.value||'').toLowerCase(),mode=(document.getElementById('saleReportMode')?.value||'').toLowerCase(),q=(document.getElementById('saleReportSearch')?.value||'').toLowerCase().trim(); const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'),godowns=getGodowns();const itemName=id=>items.find(i=>String(i.id)===String(id))?.name||'Item';const godownName=id=>godowns.find(g=>String(g.id)===String(id))?.name||'—'; const inRange=x=>{const d=String(x.date||'').slice(0,10);return (!from||d>=from)&&(!to||d<=to);}; const filtered=sales.filter(x=>{const cn=String(x.customerName||x.customer||'').toLowerCase(),pm=String(x.paymentMode||'').toLowerCase();const itemText=(x.items||[]).map(it=>itemName(it.itemId)).join(' ').toLowerCase();return inRange(x)&&(!customer||cn===customer)&&(!mode||pm===mode)&&(!q||String(x.invoiceNo||'').toLowerCase().includes(q)||cn.includes(q)||itemText.includes(q));}).sort((a,b)=>(String(a.date||'')).localeCompare(String(b.date||''))||(Number(a.id)||0)-(Number(b.id)||0)); let total=0,itemCount=0;const out=[]; filtered.forEach(x=>(x.items||[]).forEach(it=>{const qty=saleReportNumber(it.qty),rate=saleReportNumber(it.rate),disc=saleReportNumber(it.discount),gst=saleReportNumber(it.gst),base=qty*rate,discount=base*disc/100,taxable=base-discount,tax=taxable*gst/100,amount=taxable+tax;total+=amount;itemCount+=qty;out.push({date:x.date||'',invoice:x.invoiceNo||'',customer:x.customerName||x.customer||'',item:itemName(it.itemId),godown:godownName(it.godownId),qty,rate,disc,gst,mode:x.paymentMode||'',amount});})); const esc=escapeHtml,fmt=saleReportMoney;rows.innerHTML=out.length?out.map(x=>`${esc(x.date)}${esc(x.invoice)}${esc(x.customer)}${esc(x.item)}${esc(x.godown)}${x.qty.toLocaleString('en-IN')}${fmt(x.rate)}${x.disc.toFixed(2)}%${x.gst.toFixed(2)}%${esc(x.mode)}${fmt(x.amount)}`).join(''):`No sales transactions found for the selected filters.`; const invEl=document.getElementById('saleReportInvoices'),itemsEl=document.getElementById('saleReportItems'),totEl=document.getElementById('saleReportTotal'),foot=document.getElementById('saleReportFootTotal'),badge=document.getElementById('saleReportBadge'),period=document.getElementById('saleReportPeriod');if(invEl)invEl.textContent=filtered.length;if(itemsEl)itemsEl.textContent=itemCount.toLocaleString('en-IN');if(totEl)totEl.textContent=fmt(total);if(foot)foot.textContent=fmt(total);if(badge)badge.textContent=out.length+' line'+(out.length===1?'':'s')+' · '+fmt(total);if(period)period.textContent=(from||'Start')+' to '+(to||'End'); } function mviappsPrintSaleReport(){const table=document.getElementById('saleReportTable');if(!table)return;const period=document.getElementById('saleReportPeriod')?.textContent||'';const w=window.open('','_blank');if(!w){alert('Please allow pop-ups to print the report.');return;}w.document.write(`Sale Report

Sale Report

${escapeHtml(period)}

${table.outerHTML}`);w.document.close();w.focus();setTimeout(()=>w.print(),250);} function reportSubPage(category,title,description,filterLabel){ return `
${escapeHtml(category)}

${escapeHtml(title)}

${escapeHtml(description)}

▤

${escapeHtml(title)}

${escapeHtml(description)}

This report section is ready for detailed report configuration.
`; } function mviappsBankAccountOptions(selectedId=''){ try{ const banks=typeof getBankAccounts==='function'?getBankAccounts():JSON.parse(localStorage.getItem('mviapps_bank_accounts')||'[]'); return banks.map((b,i)=>{const id=String(b.id??b.accountId??i);const name=String(b.name??b.accountName??b.bankName??'').trim();return name?``:''}).join(''); }catch(e){return '';} } function mviappsRefreshBankSelect(selectId, selectedId=''){ const el=document.getElementById(selectId); if(!el)return; const opts=mviappsBankAccountOptions(selectedId); el.innerHTML=''+(opts||''); } function mviappsToggleBankAccount(modeId, groupId, selectId){ const mode=document.getElementById(modeId), group=document.getElementById(groupId); if(!mode||!group)return; const modeValue=String(mode.value||'').toLowerCase(); const isBank=modeValue!=='cash' && modeValue!=='credit' && modeValue!==''; group.style.display=isBank?'':'none'; if(isBank)mviappsRefreshBankSelect(selectId, document.getElementById(selectId)?.value||''); } function otherIncomeReport(){ return `
↗
Reports
Other Income Report
View and analyse other income transactions for the selected period.
Other Income Transactions
DateIncome No.Income HeadPayment ModeBank AccountReference No.DescriptionAmount
Total Other Income₹0.00
`; } const MVIAPPS_SHIPPING_KEY='mviapps_shipping_rates'; function getShippingRateSheets(){ try{const v=JSON.parse(localStorage.getItem(MVIAPPS_SHIPPING_KEY)||'[]');return Array.isArray(v)?v:[];}catch(e){return []} } function saveShippingRateSheets(v){localStorage.setItem(MVIAPPS_SHIPPING_KEY,JSON.stringify(v));} function shippingMoney(v){return '₹ '+Number(v||0).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2});} function shippingDateDisplay(v){if(!v)return '';const p=String(v).split('-');return p.length===3?p[2]+'/'+p[1]+'/'+p[0]:v;} function shippingToday(){return new Date().toISOString().slice(0,10);} function shippingRateRow(weight='',rate=''){ return `
`; } function addShippingRateRow(){const root=document.getElementById('shippingRateRows');if(root)root.insertAdjacentHTML('beforeend',shippingRateRow());} function clearShippingRateSheet(){ const root=document.getElementById('shippingRateRows'); if(root)root.innerHTML=shippingRateRow(); const sh=document.getElementById('shippingShipper');if(sh)sh.value=''; const dt=document.getElementById('shippingEffectiveFrom'),dd=document.getElementById('shippingEffectiveFromDisplay'),dp=document.getElementById('shippingEffectiveFromPicker');if(dt)dt.value=shippingToday();if(dd)dd.value=shippingDateDisplay(shippingToday());if(dp)dp.value=shippingToday(); window._editingShippingRateSheetId=null; const saveBtn=document.querySelector('.shipping-plugin .ship-sheet-actions .btn:not(.secondary)'); if(saveBtn)saveBtn.textContent='Save Rate Sheet'; } function formatShippingEffectiveDate(el){ if(!el)return; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits; if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2); if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4); el.value=out; } function openShippingEffectiveCalendar(){ const picker=document.getElementById('shippingEffectiveFromPicker'); if(!picker)return; const hidden=document.getElementById('shippingEffectiveFrom'); if(hidden?.value)picker.value=hidden.value; try{if(typeof picker.showPicker==='function')picker.showPicker();else{picker.focus();picker.click();}}catch(e){picker.focus();picker.click();} } function selectShippingEffectiveCalendar(picker){ if(!picker?.value)return; const display=document.getElementById('shippingEffectiveFromDisplay'); if(display){const p=picker.value.split('-');if(p.length===3)display.value=p[2]+'/'+p[1]+'/'+p[0];} const hidden=document.getElementById('shippingEffectiveFrom'); if(hidden)hidden.value=picker.value; } function syncShippingEffectiveDate(){ const display=document.getElementById('shippingEffectiveFromDisplay'); const hidden=document.getElementById('shippingEffectiveFrom'); const picker=document.getElementById('shippingEffectiveFromPicker'); if(!display||!hidden)return; const m=String(display.value||'').match(/^(\d{2})\/(\d{2})\/(\d{4})$/); if(m){ const day=Number(m[1]),month=Number(m[2]),year=Number(m[3]); const d=new Date(year,month-1,day); if(d.getFullYear()===year&&d.getMonth()===month-1&&d.getDate()===day){ hidden.value=year+'-'+String(month).padStart(2,'0')+'-'+String(day).padStart(2,'0'); if(picker)picker.value=hidden.value; display.value=String(day).padStart(2,'0')+'/'+String(month).padStart(2,'0')+'/'+year; return; } } if(hidden.value){display.value=shippingDateDisplay(hidden.value);if(picker)picker.value=hidden.value;} } function saveShippingRateSheet(){ const shipper=(document.getElementById('shippingShipper')?.value||'').trim(); const effectiveFrom=document.getElementById('shippingEffectiveFrom')?.value||''; const rows=[...document.querySelectorAll('#shippingRateRows .ship-rate-row')].map(r=>({weight:Number(r.querySelector('.ship-weight')?.value),rate:Number(r.querySelector('.ship-rate')?.value)})).filter(x=>Number.isFinite(x.weight)&&x.weight>0&&Number.isFinite(x.rate)&&x.rate>=0); if(!shipper){alert('Please enter shipper / courier name.');return;} if(!effectiveFrom){alert('Please select the effective date.');return;} if(!rows.length){alert('Please enter at least one weight and fixed rate.');return;} const duplicateRow=rows.find((x,i)=>rows.findIndex(y=>y.weight===x.weight)!==i); if(duplicateRow){alert('Weight slab '+duplicateRow.weight.toFixed(2)+' kg already exists in this rate sheet. Please enter each weight only once.');return;} // Entry can be in any order; normalize saved slabs to ascending weight order. rows.sort((a,b)=>a.weight-b.weight); const all=getShippingRateSheets(); const existing=all.find(x=>String(x.shipper).trim().toLowerCase()===shipper.toLowerCase()&&String(x.effectiveFrom)===String(effectiveFrom)); if(existing && !confirm('A rate sheet for this shipper and effective date already exists. Replace that rate sheet?'))return; const editingId=window._editingShippingRateSheetId; const editingSheet=editingId?all.find(x=>String(x.id)===String(editingId)):null; const sheet={id:editingSheet?.id||existing?.id||('ship-'+Date.now()+'-'+Math.random().toString(36).slice(2,8)),shipper,effectiveFrom,rates:rows}; const next=all.filter(x=>x.id!==sheet.id);next.push(sheet);next.sort((a,b)=>String(b.effectiveFrom).localeCompare(String(a.effectiveFrom))||String(a.shipper).localeCompare(String(b.shipper))); saveShippingRateSheets(next); clearShippingRateSheet(); renderShippingPlugin(); alert(editingId?'Shipping rate sheet updated successfully.':'Shipping rate sheet saved successfully.'); } function editShippingRateSheet(id){ const sheet=getShippingRateSheets().find(x=>String(x.id)===String(id)); if(!sheet)return; const sh=document.getElementById('shippingShipper'),dt=document.getElementById('shippingEffectiveFrom'),root=document.getElementById('shippingRateRows'); if(!sh||!dt||!root)return; sh.value=sheet.shipper||''; dt.value=sheet.effectiveFrom||''; const dd=document.getElementById('shippingEffectiveFromDisplay'),dp=document.getElementById('shippingEffectiveFromPicker');if(dd)dd.value=shippingDateDisplay(sheet.effectiveFrom||'');if(dp)dp.value=sheet.effectiveFrom||''; root.innerHTML=(Array.isArray(sheet.rates)&&sheet.rates.length?sheet.rates.slice().sort((a,b)=>Number(a.weight)-Number(b.weight)):[{weight:'',rate:''}]).map(r=>shippingRateRow(r.weight,r.rate)).join(''); window._editingShippingRateSheetId=sheet.id; const saveBtn=document.querySelector('.shipping-plugin .ship-sheet-actions .btn:not(.secondary)'); if(saveBtn)saveBtn.textContent='Update Rate Sheet'; document.getElementById('shippingShipper')?.scrollIntoView({behavior:'smooth',block:'center'}); } function deleteShippingRateSheet(id){ const all=getShippingRateSheets(),sheet=all.find(x=>String(x.id)===String(id)); if(!sheet)return; if(!confirm('Delete the complete rate sheet for '+sheet.shipper+' effective '+shippingDateDisplay(sheet.effectiveFrom)+'?'))return; saveShippingRateSheets(all.filter(x=>String(x.id)!==String(id)));renderShippingPlugin(); } function getApplicableShippingRate(sheet,actualWeight){ const w=Number(actualWeight);if(!Number.isFinite(w)||w<=0)return null; const rates=Array.isArray(sheet.rates)?sheet.rates.slice().sort((a,b)=>Number(a.weight)-Number(b.weight)):[]; return rates.find(r=>Number(r.weight)>=w)||null; } function openShippingComparisonPopup(){ document.getElementById('shippingComparisonPopup')?.remove(); const modal=document.createElement('div'); modal.id='shippingComparisonPopup'; modal.className='shipping-compare-modal'; modal.innerHTML=``; modal.addEventListener('click',e=>{if(e.target===modal)closeShippingComparisonPopup();}); document.body.appendChild(modal); } function closeShippingComparisonPopup(){document.getElementById('shippingComparisonPopup')?.remove();} function formatShippingCompareDate(input){ let v=String(input.value||'').replace(/\D/g,'').slice(0,8); if(v.length>4)v=v.slice(0,2)+'/'+v.slice(2,4)+'/'+v.slice(4); else if(v.length>2)v=v.slice(0,2)+'/'+v.slice(2); input.value=v; if(v.length===10) syncShippingCompareDate(); } function openShippingCompareCalendar(){ const picker=document.getElementById('shippingCompareDatePicker'); if(!picker)return; const hidden=document.getElementById('shippingCompareDate'); if(hidden?.value)picker.value=hidden.value; if(typeof picker.showPicker==='function') picker.showPicker(); else { picker.focus(); picker.click(); } } function selectShippingCompareCalendar(picker){ if(!picker?.value)return; const display=document.getElementById('shippingCompareDateDisplay'); if(display){ const p=picker.value.split('-'); if(p.length===3)display.value=p[2]+'/'+p[1]+'/'+p[0]; } const hidden=document.getElementById('shippingCompareDate'); if(hidden)hidden.value=picker.value; compareShippingRates(); } function syncShippingCompareDate(){ const display=document.getElementById('shippingCompareDateDisplay'); const hidden=document.getElementById('shippingCompareDate'); if(!display||!hidden)return; const m=String(display.value||'').match(/^(\d{2})\/(\d{2})\/(\d{4})$/); if(m){ const day=Number(m[1]),month=Number(m[2]),year=Number(m[3]); const d=new Date(year,month-1,day); if(d.getFullYear()===year&&d.getMonth()===month-1&&d.getDate()===day){ hidden.value=year+'-'+String(month).padStart(2,'0')+'-'+String(day).padStart(2,'0'); compareShippingRates(); return; } } hidden.value=''; const out=document.getElementById('shippingComparisonResult'); if(out)out.innerHTML='
Please enter a valid shipment date in DD/MM/YYYY format.
'; } function compareShippingRates(){ const date=document.getElementById('shippingCompareDate')?.value||shippingToday(); const weight=Number(document.getElementById('shippingCompareWeight')?.value); const out=document.getElementById('shippingComparisonResult');if(!out)return; if(!date||!Number.isFinite(weight)||weight<=0){out.innerHTML='
Enter shipment date and actual weight to compare shipping costs.
';return;} const all=getShippingRateSheets(); const byShipper={}; all.filter(s=>String(s.effectiveFrom)<=String(date)).forEach(s=>{ const key=String(s.shipper).trim().toLowerCase(); if(!byShipper[key]||String(s.effectiveFrom)>String(byShipper[key].effectiveFrom))byShipper[key]=s; }); const sheets=Object.values(byShipper).sort((a,b)=>String(a.shipper).localeCompare(String(b.shipper))); if(!sheets.length){out.innerHTML='
No shipping rate sheets are available for the selected date.
';return;} const rows=sheets.map(s=>{const r=getApplicableShippingRate(s,weight);return `${escapeHtml(s.shipper)}${shippingDateDisplay(s.effectiveFrom)}${r?Number(r.weight).toFixed(2):'—'}${r?shippingMoney(r.rate):'No slab'}`}).join(''); out.innerHTML=`
${rows}
ShipperRate Effective FromApplicable Weight (kg)Shipping Cost
The applicable slab is the smallest manually entered weight that is equal to or above the actual shipment weight. Rates are fixed shipment charges, not per-kg rates.
`; } function selectShippingShipper(shipper,rate,weight){ const el=document.getElementById('shippingSelected');if(el)el.innerHTML=`Selected Shipper: ${escapeHtml(shipper)} · Applicable Weight: ${Number(weight).toFixed(2)} kg · Shipping Cost: ${shippingMoney(rate)}`; } document.addEventListener('click',function(e){ const editBtn=e.target.closest('.shipping-sheet-edit'); if(editBtn){ e.preventDefault(); editShippingRateSheet(editBtn.getAttribute('data-shipping-id')); return; } const deleteBtn=e.target.closest('.shipping-sheet-delete'); if(deleteBtn){ e.preventDefault(); deleteShippingRateSheet(deleteBtn.getAttribute('data-shipping-id')); } }); function renderShippingPlugin(){ const root=document.getElementById('shippingPluginRoot');if(!root)return; const sheets=getShippingRateSheets(); const grouped={};sheets.forEach(s=>{const k=String(s.shipper).trim().toLowerCase();(grouped[k]??=[]).push(s);}); const cards=Object.values(grouped).sort((a,b)=>String(a[0].shipper).localeCompare(String(b[0].shipper))).map(group=>group.sort((a,b)=>String(b.effectiveFrom).localeCompare(String(a.effectiveFrom))).map(s=>`
${escapeHtml(s.shipper)}
Effective ${shippingDateDisplay(s.effectiveFrom)}
${(Array.isArray(s.rates)?s.rates.slice():[]).sort((a,b)=>Number(a.weight)-Number(b.weight)).map(r=>``).join('')}
Weight (kg)Fixed Rate
${Number(r.weight).toFixed(2)}${shippingMoney(r.rate)}
`).join('')).join('')||'
No shipping rate sheets saved yet.
'; const list=document.getElementById('shippingSavedSheets');if(list)list.innerHTML=cards; } function shippingRatesPage(){ return `
Plugins

Shipping Rates & Comparison

Enter each shipper's fixed weight-slab rates once, keep effective-date history, and compare shipping cost before dispatch.

Add / Update Shipping Rate Sheet
Enter the actual weight points and their fixed shipment charges manually. Example: 1.00 kg = ₹2100, 1.50 kg = ₹2300. These are not per-kg rates.
${shippingRateRow()}

Compare Shipping Cost

For the selected shipment date, MVIApps uses the latest effective rate sheet for each shipper.

Enter actual shipment weight to compare shipping costs.

Saved Rate Sheets

Older effective-date sheets are retained so historical rates are not overwritten.

`; } function bankStatementReport(){ const banks=getBankAccounts(); const opts=banks.map(b=>``).join(''); return `
Bank

Bank Statement

Bank-account-wise statement for the selected accounting period.

${reportPeriodControls('bankStmt','generateBankStatement')}
▤

Bank Statement

Select Financial Year, Month/Date Range and Bank Account, then click View Report.

`; } function generateBankStatement(){ const r=document.getElementById('bankStatementResult'); if(!r)return; const bankId=document.getElementById('bankStmtBank')?.value||''; if(!bankId){r.innerHTML='
▤

Select a Bank Account

Please select a bank account to generate the statement.

';return;} const p=reportPeriodFilter('bankStmt'), banks=getBankAccounts(), bank=banks.find(b=>String(b.id)===String(bankId)); if(!bank){r.innerHTML='
▤

Bank Account Not Found

The selected bank account is no longer available.

';return;} const fyOpening=getBankFYOpeningBalance(bankId); const tx=getBankDisplayTransactions(bankId).filter(x=>{const d=String(x.date||'');return d&&d>=p.from&&d<=p.to;}).sort((a,b)=>String(a.date).localeCompare(String(b.date))||(Number(a.id)||0)-(Number(b.id)||0)); const allTx=getBankDisplayTransactions(bankId).sort((a,b)=>String(a.date||'').localeCompare(String(b.date||''))||(Number(a.id)||0)-(Number(b.id)||0)); let balance=fyOpening; allTx.filter(x=>{const d=String(x.date||'');return d&&d{balance+=Number(x.amount)||0;}); const openingForPeriod=balance; const rows=tx.map(x=>{const n=Number(x.amount)||0;const debit=n<0?Math.abs(n):0,credit=n>=0?n:0;balance+=n;const displayDate=String(x.date||'').split('-').reverse().join('/');return `${escapeHtml(displayDate)}${escapeHtml(x.type||'')}${escapeHtml(x.name||'—')}${escapeHtml(x.reference||'')}${debit?plMoney(debit):'—'}${credit?plMoney(credit):'—'}${plMoney(balance)}`;}).join(''); r.className='panel professional-report'; r.innerHTML=`

Bank Statement — ${escapeHtml(bank.name||bank.accountName||'Unnamed Bank')}

${escapeHtml(reportPeriodLabel('bankStmt'))}

Opening Balance: ${plMoney(openingForPeriod)}
${rows||''}
DateTypeParticularsReferenceDebitCreditBalance
No bank transactions found for the selected period.
`; } function printBankStatement(){ const el=document.getElementById('bankStatementResult'); if(!el || !el.classList.contains('professional-report')){alert('Please click View Report first, then click Print / Save PDF.');return;} const source=el.cloneNode(true); source.querySelectorAll('button,.pl-pdf-actions').forEach(x=>x.remove()); const win=window.open('','_blank'); if(!win){alert('Please allow pop-ups to print the report.');return;} win.document.write(`Bank Statement${source.innerHTML}`); win.document.close(); setTimeout(()=>{win.focus();win.print();win.onafterprint=()=>win.close();},300); } function posReportPage(){ return `
▣
Reports
POS Sales Report
Analyse POS billing, collections and payment-mode performance.
Report FiltersSelect period and optional filters
Loading POS Sales from Production Cloud…
POS Sales Summary
Payment Mode SummaryTotal POS bill value by payment mode
POS TransactionsInvoice-wise transaction details
DateInvoice No.CustomerPayment ModeBill AmountAmount ReceivedChange
`; } async function mviappsRunPOSReport(){ const status=document.getElementById('posReportCloudStatus'); const setStatus=(message,isError=false)=>{if(status){status.textContent=message;status.style.color=isError?'#b91c1c':'#64748b';}}; const from=document.getElementById('posReportFrom')?.value||''; const to=document.getElementById('posReportTo')?.value||''; const mode=document.getElementById('posReportMode')?.value||''; const search=String(document.getElementById('posReportSearch')?.value||'').trim().toLowerCase(); try{ const bridge=window.mviappsCloudBusinessData; if(!bridge?.readAll)throw new Error('Production Cloud data adapter is unavailable.'); setStatus('Loading complete POS invoice history from Production Cloud…'); const result=await bridge.readAll('salesInvoices',{pageSize:100,maxPages:100}); if(result?.complete!==true)throw new Error('Cloud Sales Invoice history is incomplete. Report totals are withheld until all pages are loaded.'); let rows=(result.records||[]).map(x=>({...x.record,id:String(x.id),updatedAt:x.updatedAt||null})).filter(x=>x&&String(x.notes||'').trim().toUpperCase()==='POS SALE'); rows=rows.filter(x=>{const d=String(x.date||'');if(from&&dto)return false;if(mode&&String(x.paymentMode||'')!==mode)return false;if(search&&!(`${x.invoiceNo||''} ${x.customerName||x.partyName||''}`.toLowerCase().includes(search)))return false;return true;}); rows.sort((a,b)=>String(b.date||'').localeCompare(String(a.date||''))||String(b.invoiceNo||'').localeCompare(String(a.invoiceNo||''))); const total=rows.reduce((s,x)=>s+(Number(x.totalAmount??x.total)||0),0); const received=rows.reduce((s,x)=>s+(Number(x.amountReceived)||0),0); const change=rows.reduce((s,x)=>s+(Number(x.changeAmount)||0),0); const modeTotal=m=>rows.filter(x=>String(x.paymentMode||'')===m).reduce((s,x)=>s+(Number(x.totalAmount??x.total)||0),0); const summary=document.getElementById('posReportSummary'); if(summary)summary.innerHTML=`
Total Bills${rows.length}
Total POS Sales${plMoney(total)}
Amount Received${plMoney(received)}
Change Given${plMoney(change)}
Average Bill${plMoney(rows.length?total/rows.length:0)}
`; const ps=document.getElementById('posReportPaymentSummary'); if(ps)ps.innerHTML=['Cash','UPI','Card','Bank','Credit'].map(m=>`
${m}${plMoney(modeTotal(m))}
`).join(''); const tbody=document.querySelector('#posReportTable tbody'); const tfoot=document.querySelector('#posReportTable tfoot'); if(tbody)tbody.innerHTML=rows.map(x=>`${escapeHtml(String(x.date||'').split('-').reverse().join('/'))}${escapeHtml(x.invoiceNo||'')}${escapeHtml(x.customerName||x.partyName||'Walk-in / Cash Customer')}${escapeHtml(x.paymentMode||'')}${plMoney(x.totalAmount??x.total)}${plMoney(x.amountReceived)}${plMoney(x.changeAmount)}`).join('')||'No POS transactions found in Production Cloud for the selected filters.'; if(tfoot)tfoot.innerHTML=rows.length?`Total${plMoney(total)}${plMoney(received)}${plMoney(change)}`:''; const period=document.getElementById('posReportPeriod');if(period)period.textContent=reportPeriodLabel('posReport'); const totalEl=document.getElementById('posReportTotal');if(totalEl)totalEl.innerHTML=`${rows.length} Bill${rows.length===1?'':'s'} • ${plMoney(total)}`; setStatus(`Production Cloud · ${result.records?.length||0} sales invoices read completely · ${rows.length} POS bills matched. No LocalStorage data used.`); }catch(error){ const message=error?.message||String(error);setStatus('Cloud POS report unavailable — totals withheld. '+message,true); const summary=document.getElementById('posReportSummary');if(summary)summary.innerHTML='
Report StatusUnavailable
'; const ps=document.getElementById('posReportPaymentSummary');if(ps)ps.innerHTML=''; const tbody=document.querySelector('#posReportTable tbody');if(tbody)tbody.innerHTML=`${escapeHtml(message)}`; const tfoot=document.querySelector('#posReportTable tfoot');if(tfoot)tfoot.innerHTML=''; const totalEl=document.getElementById('posReportTotal');if(totalEl)totalEl.textContent='Cloud data unavailable'; } } function initPOSReport(){ const fy=getSelectedFinancialYear(); const start=Number(String(fy).split('-')[0])||new Date().getFullYear(); setReportDateValues('posReport',start+'-04-01',(start+1)+'-03-31'); if(document.getElementById('posReportMode'))document.getElementById('posReportMode').value=''; if(document.getElementById('posReportSearch'))document.getElementById('posReportSearch').value=''; return mviappsRunPOSReport(); } function mviappsPrintPOSReport(){ const el=document.getElementById('posReportCard'); if(!el){alert('Please open the POS report first.');return;} const source=el.cloneNode(true); const win=window.open('','_blank'); if(!win){alert('Please allow pop-ups to print the report.');return;} win.document.write(`POS Sales Report${source.innerHTML}`); win.document.close();setTimeout(()=>{win.focus();win.print();win.onafterprint=()=>win.close();},300); } function helpCenterPage(){ return `

MVIApps Help Center

Quick, practical instructions for the features available in this version of MVIApps. Choose a topic or search for a term such as “service”, “shipping”, “stock”, “payment” or “sync”.

Parties & Balances

Add or update a party
  1. Open Parties → Party Details.
  2. Add the party’s name and available contact, party type and opening-balance details, then save.
  3. Use the available Edit/Modify action to correct saved details.
Review a party ledger
  1. Open Parties → Party Ledger and select the party.
  2. Check the Financial Year and any date range before reviewing the opening balance, entries and closing balance.
  3. If a balance looks unexpected, verify the opening balance and transactions for the selected period before changing records.

Items & Inventory

Add or edit an item
  1. Open Items → Item Details.
  2. Enter the item name and applicable item code, category, unit, rates and opening stock details.
  3. Save and review the item in the item list. Check the item code before saving to avoid assigning a duplicate code.
Check stock or godown quantity
  1. Use Items → Stock Summary for an overview or Items → Godown Management for godown-wise stock.
  2. For a transfer, carefully select the date, source and destination godowns, item and quantity.
  3. Review the resulting quantities before entering another transaction.

Sales & Receipts

Create a sale invoice
  1. Open Sale → Sale Invoices and start a new sale.
  2. Select the party, check the invoice date, add items and select a godown where applicable.
  3. Review quantities, rates, discounts, tax and total, then save and confirm the invoice appears in the list.
Record money received
  1. Open Sale → Payment-In.
  2. Enter the relevant party, date, amount and payment details requested on the screen.
  3. Check the amount, payment mode and reference details before saving.

Point of Sale (POS)

Make a POS sale
  1. Open POS from the sidebar.
  2. Choose the customer or use the available Walk in/Cash customer, then search for or scan an item.
  3. Confirm item, quantity, price and discount, review the total and received amount, then complete the sale using the on-screen controls.
Barcode and credit payments

A USB/Bluetooth scanner that types a barcode can work when the correct barcode/search field is focused. Scanner behaviour on a phone depends on the device and available scanning setup. For a credit payment, use the POS credit-payment controls and verify the customer and outstanding amount before confirming.

Purchases, Services & Expenses

Enter a goods purchase
  1. Open Purchase & Expense → Purchase Invoices.
  2. Select the supplier and add stock items with their quantities, rates and other required details.
  3. Review the invoice and save it.
How Service Purchase is recorded

When a service item is added to a supplier purchase, the service amount is automatically recorded under Expenses using the selected Service Expense Head. Service items do not create stock quantities or a goods-purchase entry. Supplier bill/reference details are retained with the related entry. Check the expense and supplier ledger after saving.

Record an expense or payment

Use Expenses to record an expense and Payment-Out to record money paid. Check the date, party/category, payment mode, account, reference and amount before saving.

Reports & Printing

Select a report period
  1. Open Reports and choose the required report.
  2. Check the Financial Year and use the available Month or From/To date controls where provided.
  3. Run or refresh the report, then confirm that the displayed period and figures are correct.
Print or save as PDF

Use the report’s Print / Save PDF control when available. In the browser print window, choose a printer or “Save as PDF”, check the preview and page orientation, then save.

Tip: If an opening or closing balance looks incorrect, verify the selected period and source entries before editing financial data.

Bank & Cash

Manage a bank account
  1. Open Bank & Cash → Bank Accounts.
  2. Review the account details and opening balance before saving any changes.
  3. Use Reports → Bank Statement to choose an account and period and review the opening balance and transactions.
Check cash records

Open Bank & Cash → Cash to review the available cash controls. Verify the date and amount carefully before making an adjustment.

Shipping Rates & Comparison

Save a shipping rate sheet
  1. Open Plugins → Shipping Rates & Comparison.
  2. Enter the shipper and rate details, including the effective-from date and applicable weight slabs.
  3. Save the rate sheet and check that it appears in the saved rate sheets list.
Compare a shipment
  1. Enter the shipment date and weight.
  2. Review the comparison using rate sheets effective for the shipment date.
  3. Confirm the weight slab and quoted cost before choosing a shipper. Edit or delete saved rate sheets only when the details need correction.

Backup & Restore

Create a backup
  1. Open Sync, Share & Backup → Backup / Restore.
  2. Use the available backup/export control and save the file somewhere safe.
  3. Keep a separate full backup before major changes or restoring data; label backups clearly so the correct file can be identified later.
Restore a backup

Use the restore/import option on the same page, select the intended backup and read the confirmation carefully. Restoring can replace data on this device. Do not proceed until you have a current backup of the data you want to keep.

Google Drive Sync

Connect and sync devices
  1. Open Sync, Share & Backup → Drive Sync.
  2. Follow the page’s connection instructions and authorize the Google account when prompted.
  3. Use the sync controls and wait for the status message before moving to another device.
Conflict or unexpected data

If a conflict warning appears, do not guess which copy to keep. Make a backup first, review the local/cloud choices shown by the app and select the correct source only after checking the data. Do not clear browser data as a troubleshooting shortcut.

Important: These Help instructions do not change or run Drive Sync.

Financial Year, Settings & Access

Select a financial year

Use the Financial Year selector in the top bar. Check the selected year before entering transactions or reviewing reports. A year selector changes the period being viewed; it is not a substitute for a backup.

Company and application settings

Open Settings to review company details, invoice/tax settings, item and expense categories, accounts, appearance and security options. Change only the settings you intend to update.

Protect access

Keep login details private and use the available security controls. Before changing important settings, ensure that you have a recent backup.

No matching Help topics. Try another search word.
Need more help? Screen labels can vary by the selected module. Follow the prompts in your current MVIApps version. Always back up important data before restoring or making major data changes.
`; } function filterMviHelp(query){ const root=document.getElementById('mviHelpPage');if(!root)return; const q=String(query||'').toLowerCase().trim();let visible=0; root.querySelectorAll('.help-topic').forEach(card=>{ const match=!q||(card.innerText+' '+(card.getAttribute('data-help-terms')||'')).toLowerCase().includes(q); card.style.display=match?'':'none';if(match)visible++; }); const empty=root.querySelector('#mviHelpEmpty');if(empty)empty.style.display=visible?'none':'block'; } /* MVIApps Barcode Printing — isolated add-on; does not alter item records or POS logic. */ function barcodePrintingPage(){ return `

Barcode Printing

Choose items and print barcode labels to paste on products.

Barcode uses the saved Barcode/SKU field. If it is empty, the existing Item Code is used. Item data is not changed.

0 selected
SelectItem NameItem CodeBarcode ValueLabels
Loading items…

Print layout: 4 columns × 10 rows on a 21 × 30 cm sheet. Each row uses cell widths of 5.1, 5.2, 5.3 and 5.4 cm respectively; every cell is 3 cm high.

`; } function getMVIBarcodePrintItems(){ return JSON.parse(localStorage.getItem('mviapps_items')||'[]'); } function getMVIBarcodeValue(item){ return String(item?.barcode ?? item?.barCode ?? item?.Barcode ?? item?.itemBarcode ?? item?.sku ?? item?.code ?? item?.itemCode ?? '').trim(); } function renderMVIBarcodeItems(){ const body=document.getElementById('mviBarcodeItemsBody'); if(!body)return; const all=getMVIBarcodePrintItems(); const q=String(document.getElementById('mviBarcodeSearch')?.value||'').trim().toLowerCase(); const items=all.filter(x=>!q||[x.name,x.code,x.itemCode,getMVIBarcodeValue(x)].some(v=>String(v??'').toLowerCase().includes(q))); body.innerHTML=items.map(item=>{ const id=String(item.id??''); const value=getMVIBarcodeValue(item); const safeId=id.replace(/&/g,'&').replace(/"/g,'"').replace(/${escapeMVIBarcodeText(item.name||'Unnamed item')}${escapeMVIBarcodeText(item.code||item.itemCode||'—')}${escapeMVIBarcodeText(value||'No code')}`; }).join('')||'No matching items found.'; const selected=Object.keys(window._mviBarcodeSelected||{}).filter(id=>window._mviBarcodeSelected[id]&&all.some(x=>String(x.id??'')===id)); const count=document.getElementById('mviBarcodeSelectionCount'); if(count)count.textContent=`${selected.length} item(s) selected`; } function escapeMVIBarcodeText(v){ return String(v??'').replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"').replace(/'/g,'''); } function setMVIBarcodeSelected(id,on){ window._mviBarcodeSelected=window._mviBarcodeSelected||{}; window._mviBarcodeSelected[String(id)]=!!on; renderMVIBarcodeItems(); } function setMVIBarcodeQty(id,value){ window._mviBarcodeQty=window._mviBarcodeQty||{}; window._mviBarcodeQty[String(id)]=Math.max(1,Math.min(500,parseInt(value,10)||1)); } function toggleAllMVIBarcodeItems(on){ window._mviBarcodeSelected=window._mviBarcodeSelected||{}; const q=String(document.getElementById('mviBarcodeSearch')?.value||'').trim().toLowerCase(); getMVIBarcodePrintItems().filter(x=>!q||[x.name,x.code,x.itemCode,getMVIBarcodeValue(x)].some(v=>String(v??'').toLowerCase().includes(q))) .forEach(x=>window._mviBarcodeSelected[String(x.id??'')]=!!on); renderMVIBarcodeItems(); } const MVI_CODE128_PATTERNS=[ '212222','222122','222221','121223','121322','131222','122213','122312','132212','221213','221312','231212', '112232','122132','122231','113222','123122','123221','223211','221132','221231','213212','223112','312131', '311222','321122','321221','312212','322112','322211','212123','212321','232121','111323','131123','131321', '112313','132113','132311','211313','231113','231311','112133','112331','132131','113123','113321','133121', '313121','211331','231131','213113','213311','213131','311123','311321','331121','312113','312311','332111', '314111','221411','431111','111224','111422','121124','121421','141122','141221','112214','112412','122114', '122411','142112','142211','241211','221114','413111','241112','134111','111242','121142','121241','114212', '124112','124211','411212','421112','421211','212141','214121','412121','111143','111341','131141','114113', '114311','411113','411311','113141','114131','311141','411131','211412','211214','211232','2331112' ]; function mviCode128SVG(raw){ const text=String(raw??'').replace(/[^\x20-\x7E]/g,'?').slice(0,80); const vals=[104]; for(let i=0;i{ const pat=MVI_CODE128_PATTERNS[code]||'212222'; let black=true; for(const n of pat){ const w=Number(n)*2; if(black)bars+=``; x+=w;black=!black; } }); const width=x+8; return `${bars}`; } function getMVIBarcodeSelectedLabels(){ const selected=window._mviBarcodeSelected||{}, qtys=window._mviBarcodeQty||{}; const all=getMVIBarcodePrintItems(), out=[]; all.forEach(item=>{ const id=String(item.id??''); if(!selected[id])return; const code=getMVIBarcodeValue(item); if(!code)return; const qty=Math.max(1,Math.min(500,parseInt(qtys[id]||'1',10)||1)); for(let i=0;i`
${escapeMVIBarcodeText(item.name)}
${mviCode128SVG(item.code)}
${escapeMVIBarcodeText(item.code)}
${showPrice&&item.price!==''&&item.price!=null?`
₹ ${escapeMVIBarcodeText(item.price)}
`:''}
`).join(''); } function previewMVIBarcodeLabels(){ const labels=getMVIBarcodeSelectedLabels(), preview=document.getElementById('mviBarcodePreview'); if(!preview)return; if(!labels.length){alert('Please select at least one item with a barcode or item code.');return;} preview.style.display='block'; preview.innerHTML=`

Label Preview (${labels.length} labels)

${buildMVIBarcodeSheet(labels.slice(0,12))}
${labels.length>12?'

Preview shows the first 12 labels. Printing includes all selected labels.

':''} `; } function printMVIBarcodeLabels(){ const labels=getMVIBarcodeSelectedLabels(); if(!labels.length){alert('Please select at least one item with a barcode or item code.');return;} const w=window.open('','_blank','width=1000,height=800'); if(!w){alert('Please allow pop-ups to open barcode labels.');return;} const sheet=buildMVIBarcodeSheet(labels); w.document.open(); w.document.write(`MVIApps Barcode Labels
For PDF: click “Save as PDF”, then choose “Save as PDF” in the browser printer destination.
${sheet}
`); w.document.close(); w.focus(); } function cloudReportsPage(){ const b=getFinancialYearBounds(getSelectedFinancialYear()); const from=b.from||'',to=b.to||''; return `
Production Cloud

Cloud Reports — Read Only

Checks tenant-scoped Cloud report source records. Does not read LocalStorage or modify any record.

Production Cloud Report Source Check

One consolidated read-only check for Transactions, Parties, Stock, Bank/Cash and Accounting Journal.

Read Only

Not checked yet. Select a date range and run the consolidated Cloud read.

Cloud Source Results

No Cloud report source check has been run.

This is a source-availability diagnostic, not a financial statement. Existing report calculations remain unchanged and continue to use their current local data until each report is separately reconciled and approved for Cloud read-only rendering. POS Cloud reporting is not exposed by the current Worker API.

`; } const pages={ dashboard:{title:"Dashboard",sub:"Business overview and quick actions",html:dashboard()}, "party-details":{title:"Party Details",sub:"Manage customers and suppliers",html:partyDetails()}, "party-ledger":{title:"Party Ledger",sub:"Party-wise sales, purchases, receipts and payments",html:partyLedger()}, receivable:{title:"Receivable",sub:"Party-wise receivable balances",html:receivablePage()}, payable:{title:"Payable",sub:"Party-wise outstanding amounts after payments and purchase returns",html:payablePage()}, "add-item":{title:"Add Item",sub:"Create and store inventory items with images",html:itemManager()}, "item-details":{title:"Item Details",sub:"Manage your stored inventory items",html:itemDetails()}, "item-barcode-print":{title:"Barcode Printing",sub:"Print item barcode labels",html:barcodePrintingPage()}, "stock-summary":{title:"Stock Summary",sub:"Current inventory position",html:stockSummary()}, "stock-ledger":{title:"Stock Ledger",sub:"Item-wise stock movement",html:stockLedger()},"godown-management":{title:"Godown Management",sub:"Manage godowns and transfer stock between locations",html:godownManagement()}, "point-of-sale":{title:"Point of Sale (POS)",sub:"Fast counter billing",html:pointOfSalePage()}, "sale-invoices":{title:"Sale Invoices",sub:"View, print, modify and delete saved sales invoices",html:saleInvoices()}, "sales-returns":{title:"Sales Return",sub:"Record customer returns with or without an original invoice",html:salesReturnPage()}, "payment-in":{title:"Payment-In",sub:"Record customer receipts",html:payment("Payment-In")}, "other-income":{title:"Other Income",sub:"Record non-sales income",html:payment("Other Income")}, purchase:{title:"Purchase",sub:"Record supplier purchases",html:invoice("Purchase")}, "purchase-invoices":{title:"Purchase Invoices",sub:"View, print and modify saved purchase invoices",html:purchaseInvoices()}, expenses:{title:"Expenses",sub:"Record and manage business expenses",html:expensePage()}, "purchase-returns":{title:"Purchase Returns",sub:"Manage purchase returns",html:invoice("Purchase Return")},"bank-accounts":{title:"Bank Accounts",sub:"Manage bank accounts and transactions",html:bankAccountsPage()},"payment-out":{title:"Payment-Out",sub:"Record supplier payments",html:payment("Payment-Out")}, "payment-out":{title:"Payment-Out",sub:"Record supplier payments",html:payment("Payment-Out")}, "report-cloud-readonly":{title:"Cloud Reports — Read Only",sub:"Production Cloud report source diagnostics",html:cloudReportsPage()}, "report-profit-loss":{title:"Profit & Loss",sub:"Transaction Report",html:profitLossReport()}, "report-all-transactions":{title:"All Transactions",sub:"Transaction Report",html:allTransactionsReport()}, "report-day-book":{title:"Day Book",sub:"Transaction Report",html:dayBookReport()}, "report-balance-sheet":{title:"Balance Sheet",sub:"Transaction Report",html:balanceSheetReport()}, "report-party-statement":{title:"Party Statement",sub:"Party Report",html:partyStatementReport()}, "report-all-parties":{title:"All Parties",sub:"Party Report",html:allPartiesReport()}, "report-sale-purchase-party":{title:"Sale / Purchase by Party",sub:"Party Report",html:salePurchasePartyReport()}, "report-stock-summary":{title:"Stock Summary",sub:"Stock / Item Report",html:stockSummaryReport()}, "report-stock-details":{title:"Stock Details",sub:"Stock / Item Report",html:stockDetailsReport()}, "report-item-details":{title:"Item Details",sub:"Stock / Item Report",html:itemDetailsReport()}, "report-stock-transfer-details":{title:"Stock Transfer Details",sub:"Stock / Item Report",html:stockTransferReport()}, "report-bank-statement":{title:"Bank Statement",sub:"Bank Report",html:bankStatementReport()}, "report-pos":{title:"POS Sales",sub:"POS Report",html:posReportPage()}, "report-expense":{ title:"Expense", sub:"Expense Report", html:`
₹
Reports
Expense Report
View and analyse expenses for the selected period.
Expense Transactions
DateExpense No.CategoryPartyPayment ModeReference No.Amount
Total Expense₹0.00
` }, "report-sale":{title:"Sale",sub:"Sale / Purchase Report",html:saleReport()}, "report-purchase":{title:"Purchase",sub:"Sale / Purchase Report",html:purchaseReport()}, "report-other-income":{title:"Other Income",sub:"Other Income Report",html:otherIncomeReport()}, "drive-sync":{title:"Drive Sync",sub:"Safe multi-device Google Drive synchronization",html:driveSyncTestPage()},utilities:{title:"Backup / Restore",sub:"Protect your business data",html:utility()}, "shipping-rates":{title:"Shipping Rates & Comparison",sub:"Manage shipping rate sheets and compare courier costs",html:shippingRatesPage()}, "data-safety":{title:"System & Data Safety",sub:"Backup reminders, browser guidance and data protection",html:dataSafetyPage()}, "delete-all-data":{title:"Delete All App Data",sub:"Permanently remove all saved app data on this browser",html:deleteAllDataPage()}, "reset-production-cloud":{title:"Reset Production Cloud Data",sub:"Owner-only one-time reset of Production business records",html:resetProductionCloudDataPage()}, company:{title:"Company Details",sub:"Business identity, contact, tax and address information",html:companySettings()}, "invoice-settings":{title:"Invoice Settings",sub:"Control invoice numbering, format, bank details and terms",html:invoiceSettings()}, "tax-settings":{title:"Tax Settings",sub:"Configure GST registration, rates and tax behavior",html:taxSettings()}, "item-settings":{title:"Item Settings",sub:"Organize item defaults, units, pricing and stock behavior",html:itemSettings()}, "item-categories":{title:"Item Categories",sub:"Add, modify and delete item categories",html:itemCategories()}, "expense-categories":{title:"Expense Categories",sub:"Add, modify and delete expense categories",html:expenseCategories()}, "income-heads":{title:"Other Income Heads",sub:"Add, modify and delete other income heads",html:incomeHeads()}, "account-settings":{title:"Accounts",sub:"Manage cash, bank and other business accounts",html:accountSettings()}, appearance:{title:"Appearance",sub:"Customize application branding, layout and print preferences",html:appearanceSettings()}, security:{title:"Security",sub:"Protect the application and control access",html:securitySettings()}, help:{title:"Help Center",sub:"Quick instructions for using MVIApps",html:helpCenterPage()} }; function getCompanyBranding(){ const name=localStorage.getItem('mviapps_companyName')||localStorage.getItem('mviapps_tradeName')||'mviapps'; const logo=localStorage.getItem('mviapps_company_logo')||''; return `
${logo?`Company Logo`:''}
${escapeHtml(name)}
Business Management Dashboard
`; } function getCreditPayableTotal(){ const purchases=JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]'); const returns=JSON.parse(localStorage.getItem('mviapps_purchase_returns')||'[]'); const expenses=JSON.parse(localStorage.getItem('mviapps_expenses')||'[]'); const payments=JSON.parse(localStorage.getItem('mviapps_payment_out')||'[]'); const money=v=>Number(String(v??'').replace(/[^0-9.-]/g,''))||0; const byParty={}; const add=(id,v)=>{const k=String(id||'');if(!k)return;byParty[k]=(byParty[k]||0)+v;}; purchases.forEach(x=>{if(String(x.paymentMode||'').toLowerCase()==='credit')add(x.partyId||x.supplier||x.party,money(x.total));}); expenses.forEach(x=>{if(String(x.paymentMode||'').toLowerCase()==='credit'&&x.partyId)add(x.partyId,money(x.amount));}); returns.forEach(x=>{const k=String(x.partyId||x.supplier||x.party||'');if(k)byParty[k]=(byParty[k]||0)-money(x.total);}); payments.forEach(x=>{const k=String(x.partyId||x.supplier||x.party||'');if(k)byParty[k]=(byParty[k]||0)-money(x.amount);}); return Object.values(byParty).reduce((n,v)=>n+Math.max(0,v),0); } function checkItemAvailabilityPage(){ return `
Quick Action

Check Item Availability

Check current available quantity of any item, including godown-wise stock.

Select Item
▣

Item Availability

Select an item to view its current available quantity.

`; } function initQuickItemAvailability(){ const sel=document.getElementById('quickAvailabilityItem'); if(!sel)return; const items=typeof getSortedItems==='function'?getSortedItems():JSON.parse(localStorage.getItem('mviapps_items')||'[]'); sel.innerHTML=''+items.map(i=>``).join(''); } function renderQuickItemAvailability(){ const result=document.getElementById('quickAvailabilityResult'); const itemId=document.getElementById('quickAvailabilityItem')?.value||''; if(!result)return; if(!itemId){ result.className='report-placeholder'; result.innerHTML='
▣

Item Availability

Select an item to view its current available quantity.

'; return; } const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); const item=items.find(i=>String(i.id)===String(itemId)); if(!item)return; const gs=typeof getGodowns==='function'?getGodowns():[]; if(typeof syncGodownStockWithClosing==='function' && gs.length)syncGodownStockWithClosing(item,gs); const unit=item.unit||'Nos'; let total=0; const rows=gs.map(g=>{ const q=typeof getItemGodownQty==='function'?getItemGodownQty(itemId,g.id):0; total+=q; return `${escapeHtml(g.name||'Godown')}${q}${escapeHtml(unit)}`; }).join(''); if(!gs.length){ const qty=typeof stockTotals==='function'?Number(stockTotals(item).closing)||0:Number(item.qty)||0; total=qty; } result.className='panel'; result.innerHTML=`
Selected Item
${escapeHtml(item.name||'')}
${item.code?`
Code: ${escapeHtml(item.code)}
`:''}
Total Available
${total} ${escapeHtml(unit)}
${gs.length?`
Godown-wise Availability
${rows}
GodownAvailable QuantityUnit
Total Available${total}${escapeHtml(unit)}
`:'
Availability
No godown is configured. The current item quantity is shown above.
'}`; } function dashboard(){ /* Safe dashboard data reader: a malformed saved key must never prevent Dashboard rendering. */ const dashArray=(key)=>{try{const v=JSON.parse(localStorage.getItem(key)||'[]');return Array.isArray(v)?v:[];}catch(e){return [];}}; const sales=filterByActiveFinancialYear(dashArray('mviapps_sales_invoices')); const purchases=filterByActiveFinancialYear(dashArray('mviapps_purchase_invoices')); const returns=filterByActiveFinancialYear(dashArray('mviapps_purchase_returns')); const paymentsIn=filterByActiveFinancialYear(dashArray('mviapps_payment_in')); const paymentsOut=filterByActiveFinancialYear(dashArray('mviapps_payment_out')); const expenses=filterByActiveFinancialYear(dashArray('mviapps_expenses')); const income=filterByActiveFinancialYear(dashArray('mviapps_other_income')); const money=v=>Number(String(v??'').replace(/[^0-9.-]/g,''))||0; const total=arr=>arr.reduce((n,x)=>n+money(x.total??x.amount),0); const now=new Date(); const currentMonthKey=now.getFullYear()+'-'+String(now.getMonth()+1).padStart(2,'0'); const monthTotal=(arr)=>arr.filter(x=>{const d=String(x.date||''); return d.slice(0,7)===currentMonthKey;}).reduce((n,x)=>n+money(x.total??x.amount),0); const todayPad=n=>String(n).padStart(2,'0'); const todayKey=now.getFullYear()+'-'+todayPad(now.getMonth()+1)+'-'+todayPad(now.getDate()); const todayTotal=(arr)=>arr.filter(x=>String(x.date||'').slice(0,10)===todayKey).reduce((n,x)=>n+money(x.total??x.amount),0); const salesTotal=total(sales), purchaseTotal=total(purchases), returnTotal=total(returns); const receivedTotal=total(paymentsIn), paidTotal=total(paymentsOut); const expenseTotal=total(expenses), otherIncomeTotal=total(income); const outstanding=getPartyOutstandingTotals(); const receivable=outstanding.receivable; const payable=outstanding.payable; const creditPurchases=purchases.filter(x=>String(x.paymentMode||'').toLowerCase()==='credit'); const creditExpenses=expenses.filter(x=>String(x.paymentMode||'').toLowerCase()==='credit' && x.partyId); const creditPurchaseTotal=total(creditPurchases), creditExpenseTotal=total(creditExpenses); const fmt=v=>'₹ '+Number(v||0).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}); const allTx=[]; sales.forEach(x=>allTx.push({date:x.date||'',label:'Sale Invoice',ref:x.invoiceNo||'',party:x.customerName||x.customer||'',amount:money(x.total),kind:'Sale'})); purchases.forEach(x=>allTx.push({date:x.date||'',label:'Purchase Invoice',ref:x.invoiceNo||'',party:x.supplierName||x.supplier||'',amount:money(x.total),kind:'Purchase'})); paymentsIn.forEach(x=>allTx.push({date:x.date||'',label:'Payment-In',ref:x.number||'',party:x.partyName||'',amount:money(x.amount),kind:'Receipt'})); paymentsOut.forEach(x=>allTx.push({date:x.date||'',label:'Payment-Out',ref:x.number||'',party:x.partyName||'',amount:money(x.amount),kind:'Payment'})); expenses.forEach(x=>allTx.push({date:x.date||'',label:'Expense',ref:x.number||'',party:x.partyName||x.category||'',amount:money(x.amount),kind:'Expense'})); income.forEach(x=>allTx.push({date:x.date||'',label:'Other Income',ref:x.number||'',party:x.incomeHead||'',amount:money(x.amount),kind:'Income'})); allTx.sort((a,b)=>String(b.date).localeCompare(String(a.date))); const recent=allTx.slice(0,8); const recentHtml=recent.length?`
${recent.map(x=>``).join('')}
DateTypeReferenceParty / HeadAmount
${escapeHtml(x.date)}${escapeHtml(x.kind)}${escapeHtml(x.ref||'—')}${escapeHtml(x.party||'—')}${fmt(x.amount)}
`:`
No transactions yet. Start by adding a Party, Item, Sale or Purchase.
`; const days=[]; for(let i=6;i>=0;i--){const d=new Date();d.setDate(d.getDate()-i);const ds=d.toISOString().slice(0,10);const st=todayTotal;days.push({date:ds,sales:st(sales.filter(x=>x.date===ds)),purchases:st(purchases.filter(x=>x.date===ds))});} const max=Math.max(1,...days.flatMap(x=>[x.sales,x.purchases])); const chart=days.map(x=>`
${x.date.slice(5)}
`).join(''); return `
${getCompanyBranding().replace('margin-bottom:22px','margin-bottom:10px')}
Today's Sale
${fmt(todayTotal(sales))}
Current Month
${fmt(monthTotal(sales)).replace(/\.00$/,'')}
Total Sale
${fmt(salesTotal).replace(/\.00$/,'')}
Today's Purchase
${fmt(todayTotal(purchases))}
Current Month
${fmt(monthTotal(purchases)).replace(/\.00$/,'')}
Total Purchase
${fmt(purchaseTotal).replace(/\.00$/,'')}
Receivable
${fmt(receivable)}
Payable
${fmt(payable)}

Financial Performance Overview

■ Sales■ Purchase
${chart}

Quick Actions

Recent Transactions

${recentHtml}

Production Cloud — Remaining Modules Read Only

Checks Sales, Purchase, Returns, Stock Adjustments, Transfers, Payments, Expenses, Income and Bank/Cash routes. No records are created, edited, deleted or migrated.

Not checked yet. Run this after Owner sign-in.
Module / RouteResultRecords checked
No checks run yet.

Production Cloud — Dashboard Preview (Read Only)

Compares Cloud and browser record counts only. It does not replace Dashboard amounts or calculate balances.

Not checked yet. Run after Owner or authorized Staff sign-in.
Data SourceCloud RecordsLocal RecordsRead Status
No Cloud reads have been run.

Receivable / Payable and monetary totals are intentionally withheld until Cloud ledger field mapping and accounting rules are reconciled. No Cloud or local records are written, imported, merged or deleted.

`; } function list(title,cols,button){return `

${title}

Search, filter and manage records.

${cols.map(c=>``).join('')}
${c}Action
No records found.
`} function partyLedger(){ const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]').slice().sort((a,b)=>String(a.name||'').localeCompare(String(b.name||''),undefined,{sensitivity:'base',numeric:true})); const opts=parties.map(p=>``).join(''); return `

Party Ledger

View complete party-wise transaction history and running balance.

Production Cloud Party Ledger Reconciliation

Compares independently calculated Cloud Party balances with the authoritative read-only Worker ledger for the same date range.

Run reconciliation to compare every active Cloud Party. LocalStorage and Ver 4.5 data are not used.
PartyTypeCloud Source NetWorker Ledger ClosingDifferenceResultAction
No reconciliation has been run.

Both Parties: a net match does not prove separate gross Receivable and Payable. Party Master currently stores one signed opening balance; separate AR/AP opening balances need a later accounting design decision.

Opening Balance
₹ 0.00
Total Debit
₹ 0.00
Total Credit
₹ 0.00
Closing Balance
₹ 0.00
DateParticularsReferenceDebitCreditBalance
Select a party to view its ledger.
`; } function partyLedgerISODate(value){ const v=String(value||'').trim(); if(/^\d{4}-\d{2}-\d{2}$/.test(v))return v; let m=v.match(/^(\d{1,2})[\/.-](\d{1,2})[\/.-](\d{4})$/); if(m){ const dd=String(m[1]).padStart(2,'0'),mm=String(m[2]).padStart(2,'0'),yy=m[3]; const d=new Date(Number(yy),Number(mm)-1,Number(dd)); if(d.getFullYear()===Number(yy)&&d.getMonth()===Number(mm)-1&&d.getDate()===Number(dd))return yy+'-'+mm+'-'+dd; } const dt=new Date(v+'T00:00:00'); return isNaN(dt.getTime())?'':dt.toISOString().slice(0,10); } function getPartyLedgerEntryData(pid){ const entries=[]; const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const party=parties.find(p=>String(p.id)===String(pid)); const partyName=String(party?.name||'').trim().toLowerCase(); const norm=v=>String(v??'').trim().toLowerCase(); const partyAliases=[norm(pid),norm(party?.name),norm(party?.partyName)].filter(Boolean); const add=(key,fn)=>JSON.parse(localStorage.getItem(key)||'[]').forEach(x=>{ // Different generations of MVIApps stored the party as ID, customer/supplier // name, or a separate partyName/customerName/supplierName field. Match all. const candidates=[ x.partyId,x.customerId,x.supplierId,x.party,x.customer,x.supplier, x.partyName,x.customerName,x.supplierName ].map(norm).filter(Boolean); const matched=candidates.some(v=>partyAliases.includes(v)); if(!matched)return; const d=partyLedgerISODate(x.date); if(!d)return; const v=fn(x); if(v)entries.push({date:d,...v}); }); add('mviapps_sales_invoices',x=>({particulars:'Sales Invoice',ref:x.invoiceNo||x.number||'',debit:String(x.paymentMode||'').toLowerCase()==='credit'?parseMoney(x.total):0,credit:0})); add('mviapps_sales_returns',x=>({particulars:'Sales Return',ref:x.invoiceNo||x.number||'',debit:0,credit:parseMoney(x.total)})); add('mviapps_purchase_invoices',x=>({particulars:'Purchase Invoice',ref:x.invoiceNo||x.number||'',debit:0,credit:String(x.paymentMode||'').toLowerCase()==='credit'?parseMoney(x.total):0})); add('mviapps_purchase_returns',x=>({particulars:'Purchase Return',ref:x.invoiceNo||x.number||'',debit:parseMoney(x.total),credit:0})); add('mviapps_payment_in',x=>({particulars:'Payment-In',ref:x.number||x.receiptNo||'',debit:0,credit:parseMoney(x.amount)})); add('mviapps_payment_out',x=>({particulars:'Payment-Out',ref:x.number||x.paymentNo||'',debit:parseMoney(x.amount),credit:0})); add('mviapps_expenses',x=>({particulars:'Expense - '+(x.category||''),ref:x.number||'',debit:0,credit:String(x.paymentMode||'').toLowerCase()==='credit'?parseMoney(x.amount):0})); return entries.sort((a,b)=>String(a.date).localeCompare(String(b.date))); } function getPartyLedgerOpening(party, beforeDate){ /* Opening is the balance immediately before the displayed period. The selected Financial Year is the default period when no manual dates are entered. A saved Opening Balance Date controls when the opening amount starts; legacy parties without a saved date retain their opening amount at the active FY start while all old ledger transactions are still carried forward. */ const rawOpeningDate=String(party?.openingDate||'').trim(); const savedOpeningDate=partyLedgerISODate(rawOpeningDate); const cutoff=String(beforeDate||''); const base=parseMoney(party?.opening); let balance=String(party?.balanceType||'Debit').toLowerCase()==='credit'?-Math.abs(base):Math.abs(base); // If the saved opening date is after the period start, the opening // amount has not yet come into effect at the opening of this period. if(savedOpeningDate && cutoff && savedOpeningDate>cutoff) balance=0; const entries=getPartyLedgerEntryData(party.id); entries.forEach(x=>{ // Do not count transactions before an explicitly saved opening date. // For legacy parties with no saved date, retain all historical entries // so their previous balance is carried into the selected FY. if(savedOpeningDate && x.date=cutoff)return; balance+=Number(x.debit||0)-Number(x.credit||0); }); return balance; } function renderPartyLedger(){ const pid=document.getElementById('ledgerParty')?.value, rowsEl=document.getElementById('partyLedgerRows'); if(!rowsEl)return; if(!pid){rowsEl.innerHTML='Select a party to view its ledger.';return;} const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'), party=parties.find(p=>String(p.id)===String(pid)); if(!party){rowsEl.innerHTML='Party not found.';return;} const selectedFY=getActiveFinancialYear(); const fyb=getFinancialYearBounds(selectedFY); let from=document.getElementById('ledgerFrom')?.value||''; let to=document.getElementById('ledgerTo')?.value||''; const noManualDates=!from&&!to; // If both manual dates are blank, ALWAYS use the complete selected FY. // This keeps Party Ledger independent of the browser's current date. if(noManualDates){from=fyb.from;to=fyb.to;} // Party Ledger always stays inside the selected Financial Year. // When no manual dates are selected, the complete FY is shown. if(from && fromfyb.to) to=fyb.to; if(from && from>fyb.to) from=fyb.to; if(to && toto){ const badFrom=from; from=to; to=badFrom; } const effectiveFrom=from||fyb.from; const effectiveTo=to||fyb.to; // Opening = exact balance immediately before From Date. // Closing = Opening + only the transactions between From and To. // This preserves carry-forward while respecting the selected FY. // In default FY mode, the Party Master's Opening Balance is the opening // figure for the selected Financial Year. The Opening Balance Date is // still used for manual From/To periods, but it must not make an existing // FY opening disappear merely because that date was entered later. // Always carry forward transactions dated before the selected period. // This keeps Party Ledger closing balance consistent with the Receivable/ // Payable summaries and avoids dropping prior-period collections/payments. let openingBefore=getPartyLedgerOpening(party,effectiveFrom); const openingDate=String(party?.openingDate||'').trim(); const openingDateISO=partyLedgerISODate(openingDate); // Party Ledger default-FY view: when a saved opening balance date falls // inside the selected FY, show the Party Master's opening amount in the // Opening Balance card. Transactions before that date remain excluded. // Manual date-range views continue to use the exact before-date balance. if(noManualDates && openingDateISO && openingDateISO>effectiveFrom && openingDateISO<=effectiveTo){ const base=parseMoney(party?.opening); openingBefore=String(party?.balanceType||'Debit').toLowerCase()==='credit'?-Math.abs(base):Math.abs(base); } const all=getPartyLedgerEntryData(pid).filter(x=>!openingDateISO||x.date>=openingDateISO); const tx=all.filter(x=>x.date>=effectiveFrom && x.date<=effectiveTo); let balance=openingBefore, debit=0,credit=0; tx.forEach(x=>{ debit+=Number(x.debit||0); credit+=Number(x.credit||0); balance+=Number(x.debit||0)-Number(x.credit||0); x.balance=balance; }); const openingLabel=openingBefore>=0?'Dr':'Cr'; const openingText='₹ '+Math.abs(openingBefore).toFixed(2); const closingText=(balance>=0?'Dr':'Cr')+' ₹ '+Math.abs(balance).toFixed(2); rowsEl.innerHTML=tx.length?tx.map(x=>`${escapeHtml(formatPartyLedgerDate(x.date)||'')}${escapeHtml(x.particulars)}${escapeHtml(x.ref||'')}${x.debit?'₹ '+Number(x.debit).toFixed(2):'—'}${x.credit?'₹ '+Number(x.credit).toFixed(2):'—'}${x.balance>=0?'Dr':'Cr'} ₹ ${Math.abs(x.balance).toFixed(2)}`).join(''):`No transactions found for the selected period.`; const summary=document.getElementById('partyLedgerSummary'); if(summary)summary.innerHTML=`
Opening Balance
${openingLabel} ${openingText}
Total Debit
₹ ${debit.toFixed(2)}
Total Credit
₹ ${credit.toFixed(2)}
Closing Balance
${closingText}
`; } function showPartyLedgerById(id){ const pid=String(id||'').trim(); if(!pid){alert('Party could not be identified.');return;} const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const party=parties.find(p=>String(p.id)===pid); if(!party){alert('Party not found.');return;} show('party-ledger'); setTimeout(()=>{ const sel=document.getElementById('ledgerParty'); if(!sel){alert('Party Ledger could not be opened.');return;} sel.value=pid; renderPartyLedger(); },0); } async function previewProductionCloudPartyLedger(partyIdOverride=''){ const partyId=String(partyIdOverride||document.getElementById('ledgerParty')?.value||''); if(!partyId){alert('Please select a Party first.');return;} const rawFrom=document.getElementById('ledgerFrom')?.value||'',rawTo=document.getElementById('ledgerTo')?.value||''; const defaultFY=!rawFrom&&!rawTo; const fyBounds=getFinancialYearBounds(); const from=rawFrom||fyBounds.from,to=rawTo||fyBounds.to; if(!from||!to||from>to){alert('Please select a valid date range.');return;} const old=document.getElementById('mviappsCloudPartyLedgerModal');if(old)old.remove(); const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); document.body.insertAdjacentHTML('beforeend',`

Cloud Party Ledger

Loading tenant-scoped Cloud entries…

Loading…
`); try{ const cloud=window.mviappsProductionCloud; if(!cloud?.businessDataRequest)throw new Error('Production Cloud identity is not available. Please sign in again.'); const result=await cloud.businessDataRequest('/business/data/party-ledger?partyId='+encodeURIComponent(partyId)+'&from='+encodeURIComponent(from)+'&to='+encodeURIComponent(to)+'&defaultFY='+(defaultFY?'1':'0'),{method:'GET'}); const body=document.getElementById('mviappsCloudPartyLedgerBody'),status=document.getElementById('mviappsCloudPartyLedgerStatus'); if(!body||!status)return; const fmt=n=>'₹ '+Math.abs(Number(n)||0).toFixed(2), drcr=n=>(Number(n)>=0?'Dr ':'Cr ')+fmt(n); status.textContent=(result.party?.name||'Party')+' · '+from.split('-').reverse().join('/')+' to '+to.split('-').reverse().join('/')+' · Read-only Cloud data'; body.innerHTML=`
Opening Balance
${drcr(result.openingBalance)}
Total Debit
${fmt(result.totalDebit)}
Total Credit
${fmt(result.totalCredit)}
Closing Balance
${drcr(result.closingBalance)}
${(result.entries||[]).map(x=>``).join('')||''}
DateParticularsReferenceDebitCreditBalance
${esc(x.date?.split('-').reverse().join('/')||'')}${esc(x.particulars)}${esc(x.reference||'')}${x.debit?fmt(x.debit):'—'}${x.credit?fmt(x.credit):'—'}${drcr(x.balance)}
No Cloud transactions found for this period.

Read-only projection. This does not post journals or modify local data, Party balances, Cash or Bank.

`; }catch(error){ const status=document.getElementById('mviappsCloudPartyLedgerStatus'),body=document.getElementById('mviappsCloudPartyLedgerBody'); if(status)status.textContent='Cloud Ledger could not be loaded.'; if(body)body.innerHTML=`
${esc(error?.message||error||'Unknown error')}
`; } } function printPartyLedger(){ const result=document.getElementById('partyLedgerRows'); const partySel=document.getElementById('ledgerParty'); const partyName=partySel?.selectedOptions?.[0]?.textContent||''; if(!partySel?.value){alert('Please select a party first.');return;} const summary=document.getElementById('partyLedgerSummary'); const table=result?.closest('table'); if(!table){alert('Party Ledger data is not available.');return;} const from=document.getElementById('ledgerFrom')?.value||''; const to=document.getElementById('ledgerTo')?.value||''; const company=JSON.parse(localStorage.getItem('mviapps_company')||localStorage.getItem('mviapps_company_details')||'{}'); const companyName=company.companyName||company.name||'MVIApps'; const logo=company.logo?``:''; const period=from||to?`Period: ${formatPartyLedgerDate(from)||'Beginning'} to ${formatPartyLedgerDate(to)||'Present'}`:'All Transactions'; const w=window.open('','_blank'); if(!w){alert('Please allow pop-ups to print the Party Ledger.');return;} w.document.write(`Party Ledger - ${escapeHtml(partyName)}
${logo}
${escapeHtml(companyName)}
Party Ledger
${escapeHtml(partyName)}
${escapeHtml(period)}
${summary?.innerHTML||''}
${table.outerHTML}
Generated from MVIApps
`); w.document.close();w.focus();setTimeout(()=>{w.print();setTimeout(()=>w.close(),500);},300); } function printReceivable(){ printOutstandingReport('receivable'); } function printPayable(){ printOutstandingReport('payable'); } function printOutstandingReport(type){ const isReceivable=type==='receivable'; const prefix=isReceivable?'receivable':'payable'; const table=document.getElementById(prefix+'Rows')?.closest('table'); if(!table){alert((isReceivable?'Receivable':'Payable')+' data is not available.');return;} const search=document.getElementById(prefix+'Search')?.value||''; const from=document.getElementById(prefix+'From')?.value||''; const to=document.getElementById(prefix+'To')?.value||''; const rows=table.querySelectorAll('tbody tr'); const clone=table.cloneNode(true); clone.querySelectorAll('tr').forEach(tr=>{if(tr.lastElementChild)tr.removeChild(tr.lastElementChild);}); const q=search.toLowerCase().trim(); const fyBounds=getFinancialYearBounds(),expectedFrom=from||fyBounds.from,expectedTo=to||fyBounds.to; const cache=isReceivable?window._mviappsCloudReceivableRows:window._mviappsCloudPayableRows,period=isReceivable?window._mviappsCloudReceivablePeriod:window._mviappsCloudPayablePeriod; if(!Array.isArray(cache)){alert('Load the complete Production Cloud '+(isReceivable?'Receivable':'Payable')+' report before printing.');return;} if(period?.from!==expectedFrom||period?.to!==expectedTo){alert((isReceivable?'Receivable':'Payable')+' date range has changed. Wait for the Cloud report to refresh, then print again.');return;} const data=cache.filter(r=>!q||String(r.name).toLowerCase().includes(q)); const total=data.reduce((sum,r)=>sum+(isReceivable?Number(r.receivable)||0:Number(r.payable)||0),0); const company=JSON.parse(localStorage.getItem('mviapps_company')||localStorage.getItem('mviapps_company_details')||'{}'); const companyName=company.companyName||company.name||'MVIApps'; const logo=company.logo?``:''; const periodLabel=`Period: ${expectedFrom.split('-').reverse().join('/')} to ${expectedTo.split('-').reverse().join('/')}`; const reportTitle=isReceivable?'Receivable Report':'Payable Report'; const reportDescription=isReceivable?'Party-wise outstanding receivable balances.':'Party-wise outstanding payable balances.'; const totalLabel=isReceivable?'Total Receivable':'Total Payable'; const w=window.open('','_blank'); if(!w){alert('Please allow pop-ups to print the '+reportTitle+'.');return;} w.document.write(`${reportTitle}
${logo}
${escapeHtml(companyName)}
${reportTitle}
${reportDescription}
${escapeHtml(periodLabel)}${search?`   |   Search: ${escapeHtml(search)}`:''}
${totalLabel}
₹ ${total.toFixed(2)}
${clone.outerHTML}
Generated from MVIApps
`); w.document.close();w.focus();setTimeout(()=>{w.print();setTimeout(()=>w.close(),500);},300); } function parseMoney(v){return Number(String(v??'').replace(/,/g,'').replace(/[^0-9.-]/g,''))||0;} function formatPartyLedgerDate(value){const v=String(value||'');return /^\d{4}-\d{2}-\d{2}$/.test(v)?v.split('-').reverse().join('/'):v;} function syncPartyLedgerDateDisplay(which){const picker=document.getElementById(which==='from'?'ledgerFrom':'ledgerTo'),display=document.getElementById(which==='from'?'ledgerFromDisplay':'ledgerToDisplay');if(display)display.value=picker?.value?formatPartyLedgerDate(picker.value):'';} function formatPartyLedgerDateInput(el){if(!el)return;const digits=(el.value||'').replace(/\D/g,'').slice(0,8);let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out;} function syncPartyLedgerManualDate(which){const display=document.getElementById(which==='from'?'ledgerFromDisplay':'ledgerToDisplay'),picker=document.getElementById(which==='from'?'ledgerFrom':'ledgerTo');if(!display||!picker)return;let value=(display.value||'').trim().replace(/[.\-]/g,'/');if(!value){picker.value='';display.value='';renderPartyLedger();return;}const parts=value.split('/');if(parts.length===3){const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2];if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){const test=new Date(Number(yyyy),Number(mm)-1,Number(dd));if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;renderPartyLedger();return;}}}syncPartyLedgerDateDisplay(which);renderPartyLedger();} function openPartyLedgerDatePicker(which){const picker=document.getElementById(which==='from'?'ledgerFrom':'ledgerTo');if(!picker)return;try{if(typeof picker.showPicker==='function')picker.showPicker();else{picker.focus();picker.click();}}catch(e){picker.focus();picker.click();}} async function runCloudPartyLedgerReconciliation(){ const btn=document.getElementById('runCloudPartyLedgerReconciliationBtn'),status=document.getElementById('cloudPartyLedgerReconStatus'),rows=document.getElementById('cloudPartyLedgerReconRows'),summary=document.getElementById('cloudPartyLedgerReconSummary'); if(!rows||!status)return; const cloud=window.mviappsProductionCloud,bridge=window.mviappsCloudBusinessData; if(!cloud?.getIdentity?.()||!cloud?.businessDataRequest||!bridge?.readAll){status.textContent='Production Owner/Staff login and Cloud data adapter are required.';return;} const rawFrom=document.getElementById('ledgerFrom')?.value||'',rawTo=document.getElementById('ledgerTo')?.value||'',fy=getFinancialYearBounds(),from=rawFrom||fy.from,to=rawTo||fy.to,defaultFY=!rawFrom&&!rawTo; if(!from||!to||from>to){status.textContent='Select a valid date range before reconciliation.';return;} const fmtPaise=n=>'₹ '+(Number(n||0)/100).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}); const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const norm=v=>String(v??'').trim().toLowerCase(); const isoDate=v=>{const x=String(v??'').trim();if(/^\d{4}-\d{2}-\d{2}$/.test(x)){const d=new Date(x+'T00:00:00.000Z');return Number.isFinite(d.getTime())&&d.toISOString().slice(0,10)===x?x:'';}const m=x.match(/^(\d{1,2})[\/.-](\d{1,2})[\/.-](\d{4})$/);if(!m)return '';const c=`${m[3]}-${m[2].padStart(2,'0')}-${m[1].padStart(2,'0')}`,d=new Date(c+'T00:00:00.000Z');return Number.isFinite(d.getTime())&&d.toISOString().slice(0,10)===c?c:'';}; const moneyPaise=v=>{if(v===null||v===undefined||String(v).trim()==='')return 0;const c=String(v).replace(/,/g,'').replace(/[^0-9.-]/g,'');if(!c||!/^-?(?:\d+\.?\d*|\.\d+)$/.test(c))return NaN;const n=Number(c);return Number.isFinite(n)&&Math.abs(n)<=90000000000000?Math.round(n*100):NaN;}; const setBusy=v=>{if(btn){btn.disabled=v;btn.textContent=v?'Reconciling…':'Run Cloud Reconciliation';}}; setBusy(true);status.textContent='Reading complete Production Cloud collections…';rows.innerHTML='Reconciliation is running. Please wait…';if(summary)summary.innerHTML=''; try{ const kinds=['parties','salesInvoices','salesReturns','purchaseInvoices','purchaseReturns','paymentIn','paymentOut','expenses']; const results=await Promise.all(kinds.map(k=>bridge.readAll(k,{pageSize:100,maxPages:100}))); const incomplete=kinds.filter((k,i)=>!results[i]?.complete); if(incomplete.length)throw new Error('Incomplete Cloud collection(s): '+incomplete.join(', ')+'. No partial reconciliation is accepted.'); const data=Object.fromEntries(kinds.map((k,i)=>[k,results[i].records||[]])); const parties=data.parties.map(x=>({...x.record,id:String(x.id)})).filter(p=>String(p.id||'').trim()); const txRows=[]; const append=(kind,rowsIn)=>{for(const item of rowsIn){const r=item.record||{},date=isoDate(r.date);if(!date)continue;let amount=0,debit=0,credit=0;const mode=norm(r.paymentMode); if(kind==='salesInvoices'){amount=moneyPaise(r.total??0);if(mode==='credit')debit=amount;} else if(kind==='salesReturns'){amount=moneyPaise(r.total??0);credit=amount;} else if(kind==='purchaseInvoices'){amount=moneyPaise(r.total??0);if(mode==='credit')credit=amount;} else if(kind==='purchaseReturns'){amount=moneyPaise(r.total??0);debit=amount;} else if(kind==='paymentIn'){amount=moneyPaise(r.amount??0);credit=amount;} else if(kind==='paymentOut'){amount=moneyPaise(r.amount??0);debit=amount;} else if(kind==='expenses'){amount=moneyPaise(r.amount??0);if(mode==='credit')credit=amount;} if(!Number.isSafeInteger(amount)||!Number.isSafeInteger(debit)||!Number.isSafeInteger(credit))throw new Error('Invalid amount in '+kind+' Cloud record '+String(item.id)+'.'); const aliases=[r.partyId,r.customerId,r.supplierId,r.party,r.customer,r.supplier,r.partyName,r.customerName,r.supplierName].map(norm).filter(Boolean); if(debit||credit)txRows.push({date,debit,credit,aliases,kind,id:String(r.id??item.id)}); }}; append('salesInvoices',data.salesInvoices);append('salesReturns',data.salesReturns);append('purchaseInvoices',data.purchaseInvoices);append('purchaseReturns',data.purchaseReturns);append('paymentIn',data.paymentIn);append('paymentOut',data.paymentOut);append('expenses',data.expenses); const aliasOwners=new Map();for(const p of parties){for(const a of [p.id,p.name,p.partyName].map(norm).filter(Boolean)){const set=aliasOwners.get(a)||new Set();set.add(p.id);aliasOwners.set(a,set);}} const checks=[]; for(const p of parties){ const id=String(p.id),aliases=new Set([id,p.name,p.partyName].map(norm).filter(Boolean)); const ambiguous=[...aliases].some(a=>(aliasOwners.get(a)?.size||0)>1); const opening=moneyPaise(p.opening??0);if(!Number.isSafeInteger(opening))throw new Error('Invalid opening balance for Party '+String(p.name||id)+'.'); const openingDate=isoDate(p.openingDate||'');const signedOpening=norm(p.balanceType)==='credit'?-Math.abs(opening):Math.abs(opening); let sourceOpening=openingDate&&openingDate>from?0:signedOpening;if(defaultFY&&openingDate&&openingDate>from&&openingDate<=to)sourceOpening=signedOpening; let sourceClosing=sourceOpening;const linked=txRows.filter(t=>t.aliases.some(a=>aliases.has(a))); linked.sort((a,b)=>a.date.localeCompare(b.date)||a.kind.localeCompare(b.kind)||a.id.localeCompare(b.id)); for(const t of linked){if(openingDate&&t.dateto)continue;if(t.datea.name.localeCompare(b.name,undefined,{sensitivity:'base',numeric:true})); const matched=checks.filter(x=>x.result.startsWith('MATCH')).length,mismatched=checks.filter(x=>x.result==='MISMATCH').length,review=checks.filter(x=>x.result.startsWith('REVIEW')||x.result.includes('BOTH REVIEW')).length,totalSource=checks.reduce((n,x)=>n+x.sourceClosing,0),totalWorker=checks.reduce((n,x)=>n+x.workerClosing,0); if(summary)summary.innerHTML=`
Parties Checked
${checks.length}
Matched
${matched}
Mismatches
${mismatched}
Review Required
${review}
Source Net Total
${fmtPaise(totalSource)}
Worker Ledger Net Total
${fmtPaise(totalWorker)}
`; rows.innerHTML=checks.length?checks.map(x=>`${esc(x.name)}${esc(x.type)}${fmtPaise(x.sourceClosing)}${fmtPaise(x.workerClosing)}${fmtPaise(x.difference)}${esc(x.result)}`).join(''):'No active Cloud Parties found.'; status.textContent='Completed · '+from.split('-').reverse().join('/')+' to '+to.split('-').reverse().join('/')+' · '+checks.length+' Party(ies) checked · read-only'; window._mviappsCloudPartyLedgerReconciliation={from,to,checks,matched,mismatched,review,sourceNetPaise:totalSource,workerNetPaise:totalWorker,createdAt:new Date().toISOString()}; }catch(error){rows.innerHTML=`Reconciliation stopped safely: ${esc(error?.message||'Unknown error')}`;if(summary)summary.innerHTML='';status.textContent='Not reconciled — no partial result displayed.';window._mviappsCloudPartyLedgerReconciliation=null;} finally{setBusy(false);} } function clearPartyLedger(){['ledgerParty','ledgerFrom','ledgerTo','ledgerFromDisplay','ledgerToDisplay'].forEach(id=>{const e=document.getElementById(id);if(e)e.value='';});renderPartyLedger();} function getFinancialYears(){ const now=new Date(), y=now.getFullYear(), m=now.getMonth()+1, current=m>=4?y:y-1, out=[]; for(let i=0;i<6;i++){const a=current-i;out.push({value:a+'-'+String(a+1).slice(-2),label:a+'–'+String(a+1).slice(-2)});} return out; } function getSelectedFinancialYear(){ const years=getFinancialYears(), current=years[0]?.value||''; const saved=localStorage.getItem('mviapps_selected_financial_year')||''; return years.some(x=>x.value===saved)?saved:current; } function getFinancialYearForDate(dateValue){const d=new Date(String(dateValue||'')+'T00:00:00');if(isNaN(d.getTime()))return '';const y=d.getFullYear(),m=d.getMonth()+1,start=m>=4?y:y-1;return start+'-'+String(start+1).slice(-2);} function getActiveFinancialYear(){return getSelectedFinancialYear();} function isDateInFinancialYear(dateValue,fy=getActiveFinancialYear()){return !!dateValue&&getFinancialYearForDate(dateValue)===fy;} function getFinancialYearBounds(fy=getActiveFinancialYear()){const start=Number(String(fy||'').split('-')[0]);return start?{from:start+'-04-01',to:(start+1)+'-03-31'}:{from:'',to:''};} function filterByActiveFinancialYear(arr,dateField='date'){return Array.isArray(arr)?arr.filter(x=>isDateInFinancialYear(x?.[dateField])):[];} function getPartyOpeningDate(p){ const saved=String(p?.openingDate||'').trim(); if(/^\d{4}-\d{2}-\d{2}$/.test(saved)) return saved; const opening=Number(p?.opening||0); if(!opening) return ''; const fy=getActiveFinancialYear(); const b=getFinancialYearBounds(fy); return b.from||''; } function ensureEntryDateInActiveFY(dateValue,label='Date'){if(!dateValue){alert(label+' is required.');return false;}if(!isDateInFinancialYear(dateValue)){const b=getFinancialYearBounds();alert(label+' must be within the selected Financial Year ('+getActiveFinancialYear()+').\nAllowed period: '+b.from+' to '+b.to+'.');return false;}return true;} function setGlobalFinancialYear(value){ const years=getFinancialYears();if(!years.some(x=>x.value===value))return; localStorage.setItem('mviapps_selected_financial_year',value); const top=document.getElementById('globalFinancialYear');if(top)top.value=value; document.querySelectorAll('select[id$="FinancialYear"]').forEach(el=>{if([...el.options].some(o=>o.value===value))el.value=value;}); window._mviappsSelectedFY=value; if(typeof show==='function'&&window._mviappsCurrentPage)setTimeout(()=>show(window._mviappsCurrentPage,window._mviappsCurrentBtn||null),0); } function initGlobalFinancialYear(){ const el=document.getElementById('globalFinancialYear'); if(!el)return; const years=getFinancialYears(), selected=getSelectedFinancialYear(); el.innerHTML=years.map(f=>``).join(''); el.value=selected; document.querySelectorAll('select[id$="FinancialYear"]').forEach(x=>{ if([...x.options].some(o=>o.value===selected))x.value=selected; }); } document.addEventListener('DOMContentLoaded',initGlobalFinancialYear); function profitLossReport(){ const fys=getFinancialYears(), currentFY=getSelectedFinancialYear(); return `
Transaction Report

Profit & Loss Account

Professional income statement with stock valuation, gross profit and net profit.

Report Period

Select financial year, month or an exact date range.

₹

Profit & Loss Account

Select the reporting period and click View Report.

The report uses opening stock, net purchases, closing stock, other income and expenses.
`; } function openProfitLossDatePicker(which){const picker=document.getElementById(which==='from'?'plFrom':'plTo');if(!picker)return;try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();}catch(e){try{picker.click();}catch(ignore){}}} function syncProfitLossDateDisplay(which){const picker=document.getElementById(which==='from'?'plFrom':'plTo'),display=document.getElementById(which==='from'?'plFromDisplay':'plToDisplay');if(display)display.value=picker?.value?picker.value.split('-').reverse().join('/') : '';} function prepareProfitLossDateManual(which){const display=document.getElementById(which==='from'?'plFromDisplay':'plToDisplay');if(display&&!display.dataset.manualReady){display.value='';display.dataset.manualReady='1';}} function formatProfitLossDateInput(el){if(!el)return;el.dataset.manualReady='1';const digits=(el.value||'').replace(/\D/g,'').slice(0,8);let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out;} function syncProfitLossDateManual(which){const display=document.getElementById(which==='from'?'plFromDisplay':'plToDisplay'),picker=document.getElementById(which==='from'?'plFrom':'plTo');if(!display||!picker)return;let value=(display.value||'').trim().replace(/[.\-]/g,'/');if(!value){delete display.dataset.manualReady;picker.value='';return;}const parts=value.split('/');if(parts.length===3){const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2];if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){const test=new Date(Number(yyyy),Number(mm)-1,Number(dd));if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;return;}}}syncProfitLossDateDisplay(which);} function setProfitLossDateValues(from,to){const f=document.getElementById('plFrom'),t=document.getElementById('plTo');if(f)f.value=from||'';if(t)t.value=to||'';syncProfitLossDateDisplay('from');syncProfitLossDateDisplay('to');} function profitLossDateFilter(){ const fy=getActiveFinancialYear()||document.getElementById('plFinancialYear')?.value||'', month=document.getElementById('plMonth')?.value||'all', from=document.getElementById('plFrom')?.value||'', to=document.getElementById('plTo')?.value||''; const bounds=getFinancialYearBounds(fy); const parts=String(fy||'').split('-'), start=Number(parts[0])||new Date().getFullYear(), fyStart=bounds.from||start+'-04-01', fyEnd=bounds.to||(start+1)+'-03-31'; let f=from||fyStart, t=to||fyEnd; if(month!=='all'){const mo=Number(month), yr=mo>=4?start:start+1, last=new Date(yr,mo,0).getDate();f=yr+'-'+String(mo).padStart(2,'0')+'-01';t=yr+'-'+String(mo).padStart(2,'0')+'-'+String(last).padStart(2,'0');} // Profit & Loss must never read outside the selected Financial Year. if(ffyEnd)t=fyEnd; if(f>fyEnd)f=fyEnd; if(tt){const z=f;f=t;t=z;if(ffyEnd)t=fyEnd;} return {from:f,to:t}; } function plAmount(x){return parseMoney(x?.total??x?.amount??0);} function plStockValuation(from,to){ const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); const purchases=JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]'); const purchaseReturns=JSON.parse(localStorage.getItem('mviapps_purchase_returns')||'[]'); const sales=JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]'); const movements=getStockMovements(); const dayBefore=new Date(new Date(from+'T00:00:00').getTime()-86400000).toISOString().slice(0,10); const inRange=(d,a,b)=>String(d||'')>=a&&String(d||'')<=b; const rows=[]; let openingTotal=0,closingTotal=0,cogsTotal=0,purchaseCost=0,purchaseReturnCost=0; const movementRate=(m)=>{ if(Number(m.rate)>0)return Number(m.rate); const inv=[...purchases,...purchaseReturns].find(x=>String(x.invoiceNo||x.number||'')===String(m.ref||'')); const it=(inv?.items||[]).find(x=>String(x.itemId)===String(m.itemId)); return Number(it?.rate||it?.purchaseRate||0); }; items.forEach(item=>{ let qty=Number(item.qty)||0, value=Number(item.value)||0; if(qty>0 && value<=0)value=qty*(Number(item.purchase)||0); let avg=qty>0?value/qty:(Number(item.purchase)||0); let openingQty=qty,openingValue=value; const events=[]; movements.filter(m=>String(m.itemId)===String(item.id)).forEach(m=>events.push({date:m.date||'',type:m.type,qty:Number(m.qty)||0,rate:movementRate(m),adj:m.adjustmentType})); // Rebuild invoice-based purchase/return events when older stock movements do not carry rates. purchases.forEach(inv=>(inv.items||[]).filter(it=>String(it.itemId)===String(item.id)&&!isServiceSaleItem(item)).forEach(it=>{ if(!events.some(e=>e.type==='purchase'&&e.date===inv.date&&Math.abs(e.qty-(Number(it.qty)||0))<1e-9))events.push({date:inv.date||'',type:'purchase',qty:Number(it.qty)||0,rate:Number(it.rate||it.purchaseRate||0)}); })); purchaseReturns.forEach(inv=>(inv.items||[]).filter(it=>String(it.itemId)===String(item.id)&&!isServiceSaleItem(item)).forEach(it=>{ if(!events.some(e=>e.type==='return'&&e.date===inv.date&&Math.abs(e.qty-(Number(it.qty)||0))<1e-9))events.push({date:inv.date||'',type:'return',qty:Number(it.qty)||0,rate:Number(it.rate||it.purchaseRate||0)}); })); sales.forEach(inv=>(inv.items||[]).filter(it=>String(it.itemId)===String(item.id)&&!isServiceSaleItem(item)).forEach(it=>{ if(!events.some(e=>e.type==='sale'&&e.date===inv.date&&Math.abs(e.qty-(Number(it.qty)||0))<1e-9))events.push({date:inv.date||'',type:'sale',qty:Number(it.qty)||0,rate:0}); })); events.sort((a,b)=>String(a.date).localeCompare(String(b.date))); let periodOpeningQty=qty,periodOpeningValue=value,periodCogs=0; events.forEach(e=>{ const q=Math.max(0,e.qty||0), rate=Number(e.rate)||avg; if(e.date<=dayBefore){ if(e.type==='purchase'){value+=q*rate;qty+=q;avg=qty>0?value/qty:avg;} else if(e.type==='return'){const cost=Math.min(value, q*avg);value=Math.max(0,value-cost);qty=Math.max(0,qty-q);avg=qty>0?value/qty:rate;} else if(e.type==='sale'){const cost=Math.min(value,q*avg);value=Math.max(0,value-cost);qty=Math.max(0,qty-q);periodOpeningQty=qty;periodOpeningValue=value;avg=qty>0?value/qty:avg;} else if(e.type==='adjustment'){if(e.adj==='increase'){value+=q*rate;qty+=q;avg=qty>0?value/qty:rate;}else{const cost=Math.min(value,q*avg);value=Math.max(0,value-cost);qty=Math.max(0,qty-q);avg=qty>0?value/qty:avg;}} } }); periodOpeningQty=qty; periodOpeningValue=value; events.filter(e=>e.date>=from&&e.date<=to).forEach(e=>{ const q=Math.max(0,e.qty||0), rate=Number(e.rate)||avg; if(e.type==='purchase'){const cost=q*rate;purchaseCost+=cost;value+=cost;qty+=q;avg=qty>0?value/qty:rate;} else if(e.type==='return'){const cost=Math.min(value,q*avg);purchaseReturnCost+=cost;value=Math.max(0,value-cost);qty=Math.max(0,qty-q);avg=qty>0?value/qty:rate;} else if(e.type==='sale'){const cost=Math.min(value,q*avg);periodCogs+=cost;cogsTotal+=cost;value=Math.max(0,value-cost);qty=Math.max(0,qty-q);avg=qty>0?value/qty:avg;} else if(e.type==='adjustment'){if(e.adj==='increase'){value+=q*rate;qty+=q;avg=qty>0?value/qty:rate;}else{const cost=Math.min(value,q*avg);value=Math.max(0,value-cost);qty=Math.max(0,qty-q);avg=qty>0?value/qty:avg;}} }); openingTotal+=periodOpeningValue; closingTotal+=value; if(periodOpeningQty||periodOpeningValue||qty||value||periodCogs)rows.push({name:item.name||item.itemName||'Item',openingQty:periodOpeningQty,openingValue:periodOpeningValue,closingQty:qty,closingValue:value,cogs:periodCogs}); }); return {rows,openingTotal,closingTotal,cogsTotal,purchaseCost,purchaseReturnCost}; } function plStockAtDate(item,date){ const v=plStockValuation('0000-01-01',date); const row=v.rows.find(x=>x.name===String(item.name||item.itemName||'Item')); return row||{qty:Number(item.qty)||0,value:Number(item.value)||0,openingQty:Number(item.qty)||0,openingValue:Number(item.value)||0}; } function plCategoryTotals(arr,field){const out={};arr.forEach(x=>{let raw=x?.[field];if((raw===undefined||raw===null||String(raw).trim()==='')&&field==='category')raw=x?.incomeHead||x?.incomeCategory||x?.head||x?.expenseCategory||x?.expenseHead||'';const key=String(raw||'Uncategorised').trim()||'Uncategorised';out[key]=(out[key]||0)+plAmount(x);});return out;} function plIncomeHead(x){return String(x?.incomeHead||x?.incomeCategory||x?.head||x?.category||'Uncategorised').trim()||'Uncategorised';} function plMoney(v){ const n=Number(v||0); const text='₹ '+n.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}); return `${text}`; } function plSignedRow(label,value,cls=''){return `${label}${plMoney(value)}`;} function generateProfitLoss(){ const r=document.getElementById('profitLossResult');if(!r)return; const {from,to}=profitLossDateFilter(); const inRange=x=>{const d=String(x?.date||'');return d&&d>=from&&d<=to;}; const sales=JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]').filter(inRange); const purchases=JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]').filter(inRange); const returns=JSON.parse(localStorage.getItem('mviapps_purchase_returns')||'[]').filter(inRange); const expenses=JSON.parse(localStorage.getItem('mviapps_expenses')||'[]').filter(inRange); const income=JSON.parse(localStorage.getItem('mviapps_other_income')||'[]').filter(inRange); const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const partyName=id=>{const p=parties.find(x=>String(x.id)===String(id));return p?.name||p?.partyName||'Cash / General';}; const stockValuation=plStockValuation(from,to); const openingStock=stockValuation.openingTotal, closingStock=stockValuation.closingTotal; const stockRows=stockValuation.rows; const saleTotal=sales.reduce((a,x)=>a+plAmount(x),0); const purchaseTotal=purchases.reduce((a,x)=>a+plAmount(x),0); const returnTotal=returns.reduce((a,x)=>a+plAmount(x),0); const expenseTotal=expenses.reduce((a,x)=>a+plAmount(x),0); const incomeTotal=income.reduce((a,x)=>a+plAmount(x),0); const fy=document.getElementById('plFinancialYear')?.value||''; const month=document.getElementById('plMonth')?.value||'all'; const monthName=month==='all'?'All Months':document.getElementById('plMonth')?.selectedOptions?.[0]?.text||''; const expenseCats=plCategoryTotals(expenses,'category'), incomeCats=plCategoryTotals(income,'category'); const invoiceRows=(arr,type)=>arr.length?arr.map(x=>`${escapeHtml(x.date||'')}${escapeHtml(x.invoiceNo||x.number||'')}${escapeHtml(partyName(x.customer||x.partyId||x.supplier))}${plMoney(plAmount(x))}`).join(''):`No ${type.toLowerCase()} transactions in this period.`; const catRows=obj=>Object.keys(obj).length?Object.entries(obj).map(([k,v])=>`${escapeHtml(k)}${plMoney(v)}`).join(''):'No entries.'; const stockDetailRows=stockRows.length?stockRows.map(x=>`${escapeHtml(x.name)}${Number(x.openingQty||0).toLocaleString('en-IN')}${plMoney(x.openingValue)}${Number(x.closingQty||0).toLocaleString('en-IN')}${plMoney(x.closingValue)}`).join(''):'No stock details available.'; // PDF-reference style: a clean Particulars / Amount statement with detailed break-up below. const salesReturns=JSON.parse(localStorage.getItem('mviapps_sales_returns')||'[]').filter(inRange); const creditNote= salesReturns.reduce((a,x)=>a+plAmount(x),0); const debitNote= returnTotal; const saleFA=JSON.parse(localStorage.getItem('mviapps_sale_fa')||'[]').filter(inRange).reduce((a,x)=>a+plAmount(x),0); const purchaseFA=JSON.parse(localStorage.getItem('mviapps_purchase_fa')||'[]').filter(inRange).reduce((a,x)=>a+plAmount(x),0); const splitExpenses=()=>{ const direct={}, indirect={}; expenses.forEach(x=>{ const k=String(x?.category||'Other Expense').trim()||'Other Expense'; const isDirect=/direct/i.test(k); const target=isDirect?direct:indirect; target[k]=(target[k]||0)+plAmount(x); }); return {direct,indirect}; }; const expSplit=splitExpenses(); const directExpenseTotal=Object.values(expSplit.direct).reduce((a,v)=>a+v,0); const indirectExpenseTotal=Object.values(expSplit.indirect).reduce((a,v)=>a+v,0); const paymentInDiscount=JSON.parse(localStorage.getItem('mviapps_payment_in')||'[]').filter(inRange).reduce((a,x)=>a+parseMoney(x?.discount??x?.discountAmount??0),0); const taxSum=(arr,keys)=>arr.reduce((a,x)=>a+keys.reduce((n,k)=>n+parseMoney(x?.[k]),0),0); const gstPayable=taxSum(sales,['gstPayable','gstPayableAmount']), tcsPayable=taxSum(sales,['tcsPayable','tcsPayableAmount']), tdsPayable=taxSum(sales,['tdsPayable','tdsPayableAmount']); const gstReceivable=taxSum(purchases,['gstReceivable','gstReceivableAmount']), tcsReceivable=taxSum(purchases,['tcsReceivable','tcsReceivableAmount']), tdsReceivable=taxSum(purchases,['tdsReceivable','tdsReceivableAmount']); const openingStockFA=0, closingStockFA=0; const adjustedSales=saleTotal-creditNote+saleFA; // Stock is valued at cost using a moving weighted-average method. COGS is therefore the cost of stock actually sold, while closing stock remains on the balance sheet. const cogs=stockValuation.cogsTotal; const grossResult=adjustedSales-cogs+debitNote-purchaseFA-directExpenseTotal-paymentInDiscount-gstPayable-tcsPayable-tdsPayable+gstReceivable+tcsReceivable+tdsReceivable; const grossProfitPDF=grossResult; const netProfitPDF=grossProfitPDF+incomeTotal-indirectExpenseTotal; const grossMarginPDF=adjustedSales?grossProfitPDF/adjustedSales*100:0; const netMarginPDF=adjustedSales?netProfitPDF/adjustedSales*100:0; const pdfRow=(label,value,cls='')=>`${escapeHtml(label)}${plMoney(value)}`; const pdfSection=(label)=>`${escapeHtml(label)}`; const categoryRows=(obj)=>Object.entries(obj).map(([k,v])=>pdfRow(' '+k,v)).join(''); const company=getCompanyDetails(), companyName=company.name||'Company Name'; const address=[company.address,company.city,company.state,company.pin].filter(Boolean).join(', '); const stockNote=items.length?'Stock is valued at cost using a moving weighted-average rate. Opening stock is carried at opening cost; purchases add their actual item cost; purchase returns reduce stock at the prevailing average cost; sales reduce stock at the prevailing average cost.':'No items available for stock valuation.'; const contact=[company.phone?`Phone no.: ${company.phone}`:'',company.email?`Email: ${company.email}`:''].filter(Boolean).join(' '); const periodLabel=`From ${from.split('-').reverse().join('/')} to ${to.split('-').reverse().join('/')}`; const statement=`
${pdfRow('Sale (+)',saleTotal)} ${pdfRow('Credit Note (-)',creditNote)} ${pdfRow('Sale FA (+)',saleFA)} ${pdfRow('Purchase (-)',purchaseTotal)} ${pdfRow('Debit Note (+)',debitNote)} ${pdfRow('Purchase FA (-)',purchaseFA)} ${pdfRow('Cost of Goods Sold (-)',cogs,'pl-pdf-subtotal')} ${pdfSection('Direct Expenses')} ${categoryRows(expSplit.direct)} ${pdfRow('Other Direct Expenses (-)',directExpenseTotal)} ${pdfRow('Payment-in Discount (-)',paymentInDiscount)} ${pdfSection('Tax Payable')} ${pdfRow('GST Payable (-)',gstPayable)} ${pdfRow('TCS Payable (-)',tcsPayable)} ${pdfRow('TDS Payable (-)',tdsPayable)} ${pdfSection('Tax Receivable')} ${pdfRow('GST Receivable (+)',gstReceivable)} ${pdfRow('TCS Receivable (+)',tcsReceivable)} ${pdfRow('TDS Receivable (+)',tdsReceivable)} ${pdfRow('Opening Stock (-)',openingStock)} ${pdfRow('Closing Stock (+)',closingStock)} ${pdfRow('Opening Stock FA (-)',openingStockFA)} ${pdfRow('Closing Stock FA (+)',closingStockFA)} ${pdfRow(grossProfitPDF>=0?'Gross Profit':'Gross Loss',Math.abs(grossProfitPDF),grossProfitPDF<0?'pl-pdf-result pl-loss-red':'pl-pdf-result')} ${pdfSection('Other Income')} ${categoryRows(incomeCats)} ${pdfRow('Other Income (+)',incomeTotal,'pl-pdf-subtotal')} ${pdfSection('Indirect Expenses')} ${categoryRows(expSplit.indirect)} ${pdfRow('Total Indirect Expenses (-)',indirectExpenseTotal,'pl-pdf-subtotal')} ${pdfRow(netProfitPDF>=0?'Net Profit':'Net Loss',Math.abs(netProfitPDF),netProfitPDF<0?'pl-pdf-net pl-loss-red':'pl-pdf-net')}
ParticularsAmount
`; r.className='panel professional-pl'; r.innerHTML=`
${company.logo?`Company Logo`:''}
${escapeHtml(companyName)}
${company.trade?`
${escapeHtml(company.trade)}
`:''}${address?`
${escapeHtml(address)}
`:''}${contact?`
${escapeHtml(contact)}
`:''}${company.gstin?`
GSTIN: ${escapeHtml(company.gstin)}
`:''}
Profit And Loss Report
Duration: ${escapeHtml(periodLabel)}
Financial Year: ${escapeHtml(fy)}    |    ${escapeHtml(monthName)}
${statement}
Sales Register — Detail
${invoiceRows(sales,'Sales')}
DateInvoice No.PartyAmount
Total Sales${plMoney(saleTotal)}
Purchase Register — Detail
${invoiceRows(purchases,'Purchase')}
DateBill No.PartyAmount
Total Purchases${plMoney(purchaseTotal)}
Expense Category Break-up
${catRows(expenses.length?plCategoryTotals(expenses,'category'):{})}
Expense CategoryAmount
Total Expenses${plMoney(expenseTotal)}
Other Income Category Break-up
${catRows(incomeCats)}
Income CategoryAmount
Total Other Income${plMoney(incomeTotal)}
Stock Valuation — Opening vs Closing
${stockDetailRows}
ItemOpening QtyOpening ValueClosing QtyClosing Value
Total${plMoney(openingStock)}${plMoney(closingStock)}

${escapeHtml(stockNote)}

Prepared from transactions recorded in MVIApps.Report generated: ${new Date().toLocaleString('en-IN')}
`; } function printProfitLoss(){ const el=document.getElementById('profitLossResult'); if(!el)return; // The generated Profit & Loss class is applied to #profitLossResult itself. // Check the element itself as well as its descendants. const hasProfitLoss = () => el.classList.contains('professional-pl') || !!el.querySelector('.professional-pl'); if(!hasProfitLoss()){ generateProfitLoss(); } if(!hasProfitLoss()){ alert('Please click View Report first to generate the Profit & Loss Account.'); return; } const printStyle=document.createElement('style'); printStyle.id='mviapps-profit-loss-print-style'; printStyle.textContent=` @page{size:A4 portrait;margin:10mm} @media print{ html,body{background:#fff!important;margin:0!important;padding:0!important} body.pl-print-mode .sidebar, body.pl-print-mode .topbar, body.pl-print-mode .page-head, body.pl-print-mode .pl-filter-panel, body.pl-print-mode .report-placeholder:not(#profitLossResult){display:none!important} body.pl-print-mode .main{margin-left:0!important;width:100%!important} body.pl-print-mode .content{padding:0!important;max-width:none!important} body.pl-print-mode #profitLossResult{ display:block!important; border:0!important; box-shadow:none!important; border-radius:0!important; margin:0!important; padding:0!important; background:#fff!important; } body.pl-print-mode #profitLossResult .pl-pdf-wrap{ display:block!important; width:100%!important; max-width:none!important; margin:0!important; padding:0!important; border:0!important; box-shadow:none!important; } body.pl-print-mode #profitLossResult .pl-pdf-actions{display:none!important} /* Print-only: begin Stock Valuation on a fresh page. */ body.pl-print-mode #profitLossResult .pl-stock-detail{ break-before:page!important; page-break-before:always!important; } body.pl-print-mode #profitLossResult .pl-detail-card, body.pl-print-mode #profitLossResult .pl-pdf-statement{ break-inside:auto; page-break-inside:auto; } body.pl-print-mode #profitLossResult tr{ break-inside:avoid; page-break-inside:avoid; } } `; document.head.appendChild(printStyle); const cleanup=()=>{ document.body.classList.remove('pl-print-mode'); printStyle.remove(); window.removeEventListener('afterprint',cleanup); }; document.body.classList.add('pl-print-mode'); window.addEventListener('afterprint',cleanup); // Direct window.print() keeps the browser's print/save-PDF dialog // connected to the user's button click and avoids popup blocking. setTimeout(()=>{ try{ window.print(); }catch(e){ cleanup(); console.error('Profit & Loss print error:',e); alert('Unable to open the Print / Save PDF dialog.'); } },50); } function report(title,selector){return reportSubPage(title,title,`Generate a formatted ${title.toLowerCase()} for the selected period.`,selector)} function summary(){return reportSubPage("Stock / Item Report","Stock Summary","Current stock quantity and value summary.","Item")} function partyDetails(){ return `

Party Details

Manage customer and supplier information in one place.

Party List

Search and manage your saved parties.

Production Cloud Parties — Cloud Workspace Read-only check validates authenticated Business scope. Cloud CRUD opens separately; local Party records remain untouched.
`; } function mviappsRequireStaffPermission(module,action){ const identity=window.mviappsProductionCloud?.getIdentity?.(); if(identity?.mode!=='staff')return true; const allowed=window.mviappsProductionCloud?.hasStaffPermission?.(module,action)===true; if(!allowed){alert('Access denied: your Staff account does not have '+module+'.'+action+' permission.');return false;} return true; } function openPartyForm(){if(!mviappsRequireStaffPermission('parties','create'))return;document.getElementById('party-form-panel').style.display='block'} function closePartyForm(){document.getElementById('party-form-panel').style.display='none'} function togglePartyForm(){ if(!mviappsRequireStaffPermission('parties','create'))return; const panel=document.getElementById('party-form-panel'); if(!panel)return; panel.style.display = panel.style.display==='none' ? 'block' : 'none'; if(panel.style.display==='block') setTimeout(()=>panel.scrollIntoView({behavior:'smooth',block:'start'}),0); } function partyOpeningDateToDisplay(iso){ const v=String(iso||'').trim(); if(!/^\d{4}-\d{2}-\d{2}$/.test(v)) return ''; return v.slice(8,10)+'/'+v.slice(5,7)+'/'+v.slice(0,4); } function partyOpeningDateToISO(display){ const v=String(display||'').trim(); if(!v) return ''; const m=v.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/); if(!m) return ''; const dd=String(m[1]).padStart(2,'0'), mm=String(m[2]).padStart(2,'0'), yy=m[3]; const d=yy+'-'+mm+'-'+dd; const dt=new Date(d+'T00:00:00'); if(isNaN(dt.getTime()) || dt.getFullYear()!==Number(yy) || dt.getMonth()+1!==Number(mm) || dt.getDate()!==Number(dd)) return ''; return d; } function partyOpeningDateTextChanged(el,finalize=false){ if(!el)return; let v=String(el.value||'').replace(/[^\d/]/g,''); if(v.length===2 && !v.includes('/')) v+='/'; if(v.length===5 && v.split('/').length===2) v+='/'; el.value=v.slice(0,10); const iso=partyOpeningDateToISO(el.value); const hidden=document.getElementById('partyOpeningDate'); if(hidden && iso) hidden.value=iso; if(finalize && el.value && !iso){ alert('Please enter Opening Balance Date in dd/mm/yyyy format.'); el.focus(); } } function syncPartyOpeningDateDisplay(iso){ const hidden=document.getElementById('partyOpeningDate'); const display=document.getElementById('partyOpeningDateDisplay'); if(hidden && iso) hidden.value=iso; if(display) display.value=partyOpeningDateToDisplay(iso || hidden?.value || ''); } function openPartyOpeningDatePicker(){ const hidden=document.getElementById('partyOpeningDate'); if(!hidden)return; try{ if(typeof hidden.showPicker==='function') hidden.showPicker(); else hidden.click(); }catch(e){ hidden.click(); } hidden.onchange=()=>syncPartyOpeningDateDisplay(hidden.value); } function clearPartyForm(){ const panel=document.getElementById('party-form-panel'); if(!panel)return; const title=panel.querySelector('h3'); if(title) title.textContent='Add Party'; const saveBtn=panel.querySelector('.btn.primary'); if(saveBtn){saveBtn.textContent='Save Party'; saveBtn.onclick=saveParty;} panel.querySelectorAll('input,textarea').forEach(el=>el.value=''); const openingDateEl=document.getElementById('partyOpeningDate'); if(openingDateEl) openingDateEl.value=''; const openingDateDisplay=document.getElementById('partyOpeningDateDisplay'); if(openingDateDisplay) openingDateDisplay.value=''; panel.querySelectorAll('select').forEach((el,i)=>{ if(i===0) el.selectedIndex=0; else el.selectedIndex=0; }); } function saveParty(){if(!mviappsRequireStaffPermission('parties','create'))return; const panel=document.getElementById('party-form-panel'); if(!panel)return; const name=document.getElementById('partyName')?.value.trim(); if(!name){alert('Please enter Party Name.');return} const opening=document.getElementById('partyOpening')?.value||'0'; partyOpeningDateTextChanged(document.getElementById('partyOpeningDateDisplay')); const openingDate=document.getElementById('partyOpeningDate')?.value||''; if(Number(opening)!==0 && !openingDate){alert('Please select Opening Balance Date.');return;} if(openingDate && !/^\d{4}-\d{2}-\d{2}$/.test(openingDate)){alert('Please enter a valid Opening Balance Date.');return;} const party={id:Date.now(),name,type:document.getElementById('partyType')?.value||'Customer',mobile:document.getElementById('partyMobile')?.value.trim()||'',email:document.getElementById('partyEmail')?.value.trim()||'',gstin:document.getElementById('partyGstin')?.value.trim()||'',pan:document.getElementById('partyPan')?.value.trim()||'',address:document.getElementById('partyAddress')?.value.trim()||'',city:document.getElementById('partyCity')?.value.trim()||'',state:document.getElementById('partyState')?.value.trim()||'',pin:document.getElementById('partyPin')?.value.trim()||'',opening,openingDate,limit:document.getElementById('partyLimit')?.value||'',terms:document.getElementById('partyTerms')?.value.trim()||'',balanceType:document.getElementById('partyBalanceType')?.value||'Debit'}; const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); parties.push(party); localStorage.setItem('mviapps_parties',JSON.stringify(parties)); alert('Party saved successfully.'); clearPartyForm(); closePartyForm(); renderParties(); } function editParty(id){if(!mviappsRequireStaffPermission('parties','edit'))return; const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const p=parties.find(x=>String(x.id)===String(id)); if(!p)return; const panel=document.getElementById('party-form-panel'); if(!panel)return; panel.style.display='block'; panel.querySelector('h3').textContent='Modify Party'; document.getElementById('partyName').value=p.name||''; document.getElementById('partyType').value=p.type||'Customer'; document.getElementById('partyMobile').value=p.mobile||''; document.getElementById('partyEmail').value=p.email||''; document.getElementById('partyGstin').value=p.gstin||''; document.getElementById('partyPan').value=p.pan||''; document.getElementById('partyAddress').value=p.address||''; document.getElementById('partyCity').value=p.city||''; document.getElementById('partyState').value=p.state||''; document.getElementById('partyPin').value=p.pin||''; document.getElementById('partyOpening').value=p.opening||''; syncPartyOpeningDateDisplay(p.openingDate||''); document.getElementById('partyLimit').value=p.limit||''; document.getElementById('partyTerms').value=p.terms||''; document.getElementById('partyBalanceType').value=p.balanceType||'Debit'; panel.querySelector('.btn.primary').textContent='Update Party'; panel.querySelector('.btn.primary').onclick=()=>updateParty(id); setTimeout(()=>panel.scrollIntoView({behavior:'smooth',block:'start'}),0); } function updateParty(id){ const name=document.getElementById('partyName')?.value.trim(); if(!name){alert('Please enter Party Name.');return} const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const idx=parties.findIndex(x=>String(x.id)===String(id)); if(idx<0)return; parties[idx]={...parties[idx],name,type:document.getElementById('partyType').value,mobile:document.getElementById('partyMobile').value.trim(),email:document.getElementById('partyEmail').value.trim(),gstin:document.getElementById('partyGstin').value.trim(),pan:document.getElementById('partyPan').value.trim(),address:document.getElementById('partyAddress').value.trim(),city:document.getElementById('partyCity').value.trim(),state:document.getElementById('partyState').value.trim(),pin:document.getElementById('partyPin').value.trim(),opening:document.getElementById('partyOpening').value||'0',openingDate:(partyOpeningDateTextChanged(document.getElementById('partyOpeningDateDisplay')),document.getElementById('partyOpeningDate')?.value||''),limit:document.getElementById('partyLimit').value||'',terms:document.getElementById('partyTerms').value.trim(),balanceType:document.getElementById('partyBalanceType').value}; localStorage.setItem('mviapps_parties',JSON.stringify(parties)); alert('Party updated successfully.'); clearPartyForm(); closePartyForm(); renderParties(); } function renderParties(){ const list=document.getElementById('party-list'); if(!list)return; const staffIdentity=window.mviappsProductionCloud?.getIdentity?.(); const isStaff=staffIdentity?.mode==='staff'; const canEditParty=!isStaff||window.mviappsProductionCloud?.hasStaffPermission?.('parties','edit')===true; const canDeleteParty=!isStaff||window.mviappsProductionCloud?.hasStaffPermission?.('parties','delete')===true; const q=(document.getElementById('party-search')?.value||'').toLowerCase(); const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const filtered=parties.filter(x=>!q||String(x.name||'').toLowerCase().includes(q)||String(x.mobile||'').toLowerCase().includes(q)||String(x.gstin||'').toLowerCase().includes(q)); if(!filtered.length){list.innerHTML='
No parties found. Click “+ Add Party” to create your first party.
';return;} list.innerHTML=`
${filtered.map(x=>``).join('')}
PartyTypeMobileGSTINOpeningBalanceAction
${escapeHtml(x.name||'')}
${escapeHtml(x.city||'')}
${escapeHtml(x.type||'Customer')}${escapeHtml(x.mobile||'—')}${escapeHtml(x.gstin||'—')}₹ ${escapeHtml(x.opening||'0')}${escapeHtml(x.balanceType||'Debit')}${canEditParty?``:''} ${canDeleteParty?``:''}
`; } function viewPartyDetails(id){ const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const x=parties.find(p=>String(p.id)===String(id)); if(!x){alert('Party not found.');return;} const old=document.getElementById('partyDetailModal'); if(old)old.remove(); const val=(v,d='—')=>(v===undefined||v===null||v==='')?d:escapeHtml(v); const overlay=document.createElement('div'); overlay.id='partyDetailModal'; overlay.className='item-modal-overlay'; overlay.innerHTML=``; document.body.appendChild(overlay); overlay.style.display='flex'; overlay.addEventListener('click',e=>{if(e.target===overlay)closePartyDetails();}); document.addEventListener('keydown',partyModalEsc); } function closePartyDetails(){const m=document.getElementById('partyDetailModal');if(m)m.remove();document.removeEventListener('keydown',partyModalEsc);} function partyModalEsc(e){if(e.key==='Escape')closePartyDetails();} function deleteParty(id){if(!mviappsRequireStaffPermission('parties','delete'))return;if(!confirm('Delete this party?'))return; const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]').filter(x=>String(x.id)!==String(id)); localStorage.setItem('mviapps_parties',JSON.stringify(parties)); renderParties();} function itemManager(){ return `

Add Item

Create and store inventory items, including a product image.

Basic Information
Stock & Pricing
Product Image

The selected image will be stored with the item in this browser. Images are automatically compressed to reduce storage usage.

Image Preview
`; } function compressItemImage(file,callback){ const reader=new FileReader(); reader.onload=()=>{ const img=new Image(); img.onload=()=>{ const maxSide=900, w=img.naturalWidth||img.width, h=img.naturalHeight||img.height, scale=Math.min(1,maxSide/Math.max(w,h)); const canvas=document.createElement('canvas'); canvas.width=Math.max(1,Math.round(w*scale)); canvas.height=Math.max(1,Math.round(h*scale)); const ctx=canvas.getContext('2d'); ctx.drawImage(img,0,0,canvas.width,canvas.height); callback(canvas.toDataURL('image/jpeg',0.68)); }; img.onerror=()=>callback(reader.result); img.src=reader.result; }; reader.onerror=()=>callback(''); reader.readAsDataURL(file); } function previewItemImage(e){ const file=e.target.files?.[0]; const box=document.getElementById('itemPreviewBox'); if(!file||!box)return; compressItemImage(file,image=>{box.innerHTML=image?``:'Image Preview';}); } function optimizeExistingItemImages(items){ return Promise.all((items||[]).map(item=>new Promise(resolve=>{ const src=item&&item.image; if(!src||typeof src!=='string'||!src.startsWith('data:image')){resolve(item);return;} const img=new Image(); img.onload=()=>{try{const maxSide=900,w=img.naturalWidth||img.width,h=img.naturalHeight||img.height,scale=Math.min(1,maxSide/Math.max(w,h));const canvas=document.createElement('canvas');canvas.width=Math.max(1,Math.round(w*scale));canvas.height=Math.max(1,Math.round(h*scale));canvas.getContext('2d').drawImage(img,0,0,canvas.width,canvas.height);resolve({...item,image:canvas.toDataURL('image/jpeg',0.58)});}catch(e){resolve(item);}}; img.onerror=()=>resolve(item); img.src=src;}))); } async function saveItemsWithRecovery(items){ try{localStorage.setItem('mviapps_items',JSON.stringify(items));return true;}catch(e){try{const optimized=await optimizeExistingItemImages(items);const payload=JSON.stringify(optimized);localStorage.removeItem('mviapps_items');localStorage.setItem('mviapps_items',payload);return true;}catch(e2){return false;}}} /* MVIApps High Storage: IndexedDB item-image storage */ const MVI_ITEM_DB_NAME='mviapps_high_storage_v1',MVI_ITEM_DB_STORE='itemImages'; let mviItemDBPromise=null; function openMVIItemDB(){ if(mviItemDBPromise)return mviItemDBPromise; mviItemDBPromise=new Promise((resolve,reject)=>{ if(!window.indexedDB){reject(new Error('IndexedDB unavailable'));return;} const req=indexedDB.open(MVI_ITEM_DB_NAME,1); req.onupgradeneeded=()=>{const db=req.result;if(!db.objectStoreNames.contains(MVI_ITEM_DB_STORE))db.createObjectStore(MVI_ITEM_DB_STORE);}; req.onsuccess=()=>resolve(req.result); req.onerror=()=>reject(req.error||new Error('IndexedDB open failed')); }); return mviItemDBPromise; } async function putMVIItemImage(id,data){ if(!data)return; const db=await openMVIItemDB(); return new Promise((resolve,reject)=>{const tx=db.transaction(MVI_ITEM_DB_STORE,'readwrite');tx.objectStore(MVI_ITEM_DB_STORE).put(data,String(id));tx.oncomplete=()=>resolve(true);tx.onerror=()=>reject(tx.error||new Error('Image save failed'));}); } async function getMVIItemImage(id){ if(id===undefined||id===null)return ''; try{ const db=await openMVIItemDB(); return await new Promise((resolve,reject)=>{const tx=db.transaction(MVI_ITEM_DB_STORE,'readonly'),req=tx.objectStore(MVI_ITEM_DB_STORE).get(String(id));req.onsuccess=()=>resolve(req.result||'');req.onerror=()=>reject(req.error);}); }catch(e){return '';} } async function deleteMVIItemImage(id){ try{const db=await openMVIItemDB();return await new Promise((resolve,reject)=>{const tx=db.transaction(MVI_ITEM_DB_STORE,'readwrite');tx.objectStore(MVI_ITEM_DB_STORE).delete(String(id));tx.oncomplete=()=>resolve(true);tx.onerror=()=>reject(tx.error);});}catch(e){return false;} } async function migrateItemsToIndexedDB(){ try{ const raw=localStorage.getItem('mviapps_items'); if(!raw)return; let items=JSON.parse(raw); if(!Array.isArray(items))return; let changed=false; for(const item of items){ if(!item||!item.id)continue; if(typeof item.image==='string'&&item.image.startsWith('data:image')){ await putMVIItemImage(item.id,item.image); item.imageKey=String(item.id); delete item.image; changed=true; } } if(changed){ const payload=JSON.stringify(items); try{localStorage.setItem('mviapps_items',payload);} catch(e){localStorage.removeItem('mviapps_items');localStorage.setItem('mviapps_items',payload);} } }catch(e){console.warn('MVIApps IndexedDB item-image migration skipped:',e);} } async function getItemImageData(item){ if(!item)return ''; if(typeof item.image==='string'&&item.image)return item.image; return item.imageKey?await getMVIItemImage(item.imageKey):''; } async function prepareItemForStorage(item,imageData){ const out={...item}; delete out.image; if(imageData){await putMVIItemImage(out.id,imageData);out.imageKey=String(out.id);} else if(item.imageKey)out.imageKey=String(item.imageKey); else delete out.imageKey; return out; } async function appDataWithHighStorage(){ const d=appData(); try{ const items=JSON.parse(d.mviapps_items||'[]'); if(Array.isArray(items)){ const exportItems=[]; for(const item of items){ const copy={...item}; const img=await getItemImageData(item); if(img)copy.image=img; delete copy.imageKey; exportItems.push(copy); } d.mviapps_items=JSON.stringify(exportItems); } }catch(e){} return d; } async function optimizeAndMigrateItemsNow(){ await migrateItemsToIndexedDB(); const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); let migrated=0; for(const item of items){if(item?.imageKey)migrated++;} return migrated; } async function saveItem(){if(!mviappsRequireStaffPermission('items','create'))return; const name=document.getElementById('itemName')?.value.trim(); if(!name){alert('Please enter Item Name.');return} const code=(document.getElementById('itemCode')?.value||'').trim(); const existingItems=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); if(code && existingItems.some(x=>String(x?.code||'').trim().toLowerCase()===code.toLowerCase())){ alert('Item Code already exists! Please enter a different Item Code.'); document.getElementById('itemCode')?.focus(); return; } const file=document.getElementById('itemImage')?.files?.[0]; const finish=async(image='')=>{ const item={id:Date.now()+Math.random(),createdAt:new Date().toISOString().slice(0,10),name,code,category:document.getElementById('itemCategory').value.trim(),brand:document.getElementById('itemBrand').value.trim(),unit:document.getElementById('itemUnit').value.trim(),hsn:document.getElementById('itemHsn').value.trim(),weight:document.getElementById('itemWeight').value||'0',weightUnit:document.getElementById('itemWeightUnit').value||'KG',dimension:document.getElementById('itemDimension').value.trim(),dimensionUnit:document.getElementById('itemDimensionUnit').value||'CM',gst:document.getElementById('itemGst').value||'0',source:document.getElementById('itemSource').value.trim(),qty:document.getElementById('itemQty').value||'0',value:document.getElementById('itemValue').value||'0',purchase:document.getElementById('itemPurchase').value||'0',sale:document.getElementById('itemSale').value||'0',wholesale:document.getElementById('itemWholesale').value||'0',retail:document.getElementById('itemRetail').value||'0',min:document.getElementById('itemMin').value||'0'}; try{ const storedItem=await prepareItemForStorage(item,image); const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); if(code && items.some(x=>String(x?.code||'').trim().toLowerCase()===code.toLowerCase())){alert('Item Code already exists! Please enter a different Item Code.');document.getElementById('itemCode')?.focus();return;} localStorage.setItem('mviapps_items',JSON.stringify(items.concat(storedItem))); }catch(e){alert('Item save nahi ho paya. IndexedDB storage available nahi hai. Browser mein IndexedDB/site data allow karke dobara try karein.');return;} let gs=getGodowns(); if(!gs.length){gs=[{id:Date.now()+Math.random(),name:'Main Godown',location:'',createdAt:new Date().toISOString().slice(0,10)}];saveGodowns(gs);} const mainGodown=gs.find(g=>String(g.name||'').trim().toLowerCase()==='main godown')||gs[0]; let godownStock=getGodownStock(); const openingQty=Number(item.qty)||0; if(openingQty>0){const row=godownStock.find(x=>String(x.itemId)===String(item.id)&&String(x.godownId)===String(mainGodown.id)); if(row)row.qty=openingQty; else godownStock.push({id:Date.now()+Math.random(),itemId:item.id,godownId:mainGodown.id,qty:openingQty}); saveGodownStock(godownStock);} alert('Item saved successfully. Opening quantity has been added to Main Godown.'); clearItemForm(); }; if(file)compressItemImage(file,finish);else finish(''); } function clearItemForm(){ document.querySelectorAll('#content input').forEach(x=>{if(x.type==='file')x.value='';else if(x.type==='number')x.value='0';else x.value='';}); const b=document.getElementById('itemPreviewBox');if(b)b.innerHTML='Image Preview'; } function getSortedItems(){ return JSON.parse(localStorage.getItem('mviapps_items')||'[]').slice().sort((a,b)=> String(a?.name||'').trim().localeCompare(String(b?.name||'').trim(),undefined,{sensitivity:'base',numeric:true}) ); } function itemDetails(){ return `

Item Details

View, modify and manage all saved inventory items.

Total Items: 0
ImageItemCodeUnitPurchase RateSale RateQuantityStock ValueAction
Production Cloud Items — Read OnlyChecks authenticated Business scope, Item records and stock snapshot response. Does not copy, edit, or upload records.
`; } async function renderItems(){ const rows=document.getElementById('itemRows');if(!rows)return; const q=(document.getElementById('itemSearch')?.value||'').toLowerCase(), c=(document.getElementById('itemCategorySearch')?.value||'').toLowerCase(); const allItems=getSortedItems(); const categoryItems=c?allItems.filter(x=>String(x.category||'').toLowerCase().includes(c)):allItems; const totalEl=document.getElementById('itemTotalCount'); if(totalEl) totalEl.innerHTML=`Total Items: ${categoryItems.length}`; const items=categoryItems.filter(x=>(!q||String(x.name||'').toLowerCase().includes(q)||String(x.code||'').toLowerCase().includes(q))); const imageMap=new Map(); await Promise.all(items.map(async x=>imageMap.set(String(x.id),await getItemImageData(x)))); rows.innerHTML=items.length?items.map((x)=>{const st=getCurrentStockSnapshot(x),img=imageMap.get(String(x.id))||'';return `${img?``:'—'}${escapeHtml(x.name||'')}
${escapeHtml(x.category||'')}${x.code||'—'}${x.unit||'—'}₹ ${x.purchase||'0'}₹ ${x.sale||'0'}${st.qty}₹ ${st.value.toFixed(2)} `}).join(''):`No items found. Click “+ Add Item” to create your first item.`; } async function viewItemDetails(id){ const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); const x=items.find(i=>i.id===id); if(!x){alert('Item not found.');return;} const itemImage=await getItemImageData(x); const old=document.getElementById('itemDetailModal'); if(old)old.remove(); const val=(v,d='—')=>(v===undefined||v===null||v==='')?d:escapeHtml(v); const overlay=document.createElement('div'); overlay.id='itemDetailModal'; overlay.className='item-modal-overlay'; overlay.innerHTML=``; document.body.appendChild(overlay); overlay.style.display='flex'; overlay.addEventListener('click',e=>{if(e.target===overlay)closeItemDetails();}); document.addEventListener('keydown',itemModalEsc); } function openItemStatement(id){ const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); const item=items.find(i=>String(i.id)===String(id)); if(!item){alert('Item not found.');return;} migratePurchaseReturnsToStockMovements(); const old=document.getElementById('itemStatementModal');if(old)old.remove(); const bounds=getFinancialYearBounds(); const fyFrom=bounds.from||'',fyTo=bounds.to||''; const moves=getStockMovements().filter(m=>String(m.itemId)===String(item.id)).slice().sort((a,b)=>String(a.date||'').localeCompare(String(b.date||''))||(Number(a.id)||0)-(Number(b.id)||0)); const totals=stockTotals(item); const purchases=JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]'); const sales=JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]'); const salesReturns=JSON.parse(localStorage.getItem('mviapps_sales_returns')||'[]'); const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const dateInFY=d=>{const z=String(d||'').slice(0,10);return (!fyFrom||!z||z>=fyFrom)&&(!fyTo||!z||z<=fyTo);}; const indianDate=d=>{const z=String(d||'').slice(0,10);if(!/^\d{4}-\d{2}-\d{2}$/.test(z))return z||'—';const [y,m,day]=z.split('-');return day+'/'+m+'/'+y;}; const esc=v=>escapeHtml(v==null?'':String(v)); const partyName=(type,ref)=>{ let list=type==='purchase'?purchases:sales;const inv=list.find(x=>String(x.invoiceNo||x.number||'')===String(ref||'')); if(inv){const raw=type==='purchase'?(inv.supplierName||inv.supplier):(inv.customerName||inv.customer);if(raw){const p=parties.find(z=>String(z.id)===String(raw));return p?.name||raw;}} return '—'; }; const createdAt=String(item.createdAt||'').slice(0,10); const itemExistsAtFYStart=!createdAt||!fyFrom||createdAt<=fyFrom; // Item Details' Opening Quantity is the initial stock entered for the item. // For items created after the selected FY began, that quantity becomes the // statement's opening stock from the item's creation date; for older items, // keep the existing FY-opening calculation from stockTotals(). let opening=itemExistsAtFYStart?(Number(totals.opening)||0):(Number(item.qty)||0); const openingDate=(!itemExistsAtFYStart && createdAt && (!fyTo||createdAt<=fyTo))?createdAt:fyFrom; let balance=opening; const rows=[]; rows.push({date:openingDate,type:'Opening Stock',ref:'Opening Balance',party:'—',inQty:opening,outQty:0,balance}); moves.filter(m=>dateInFY(m.date)).forEach(m=>{ const q=Math.max(0,Number(m.qty)||0);let type='',inQty=0,outQty=0,party='—',ref=m.ref||'—'; if(m.type==='purchase'){type='Purchase';inQty=q;party=partyName('purchase',ref);} else if(m.type==='sale'){type='Sale';outQty=q;party=partyName('sale',ref);} else if(m.type==='sales-return'){type='Sales Return';inQty=q;const ret=salesReturns.find(x=>String(x.number||x.invoiceNo||'')===String(ref||''));party=ret?.customerName||ret?.partyName||ret?.customer||'—';} else if(m.type==='return'){type='Purchase Return';outQty=q;party=partyName('purchase',ref);} else if(m.type==='adjustment'){type=m.adjustmentType==='increase'?'Stock Adjustment (+)':'Stock Adjustment (-)';if(m.adjustmentType==='increase')inQty=q;else outQty=q;} else return; balance=balance+inQty-outQty; rows.push({date:m.date,type,ref,party,inQty,outQty,balance}); }); const totalIn=rows.slice(1).reduce((a,r)=>a+r.inQty,0),totalOut=rows.slice(1).reduce((a,r)=>a+r.outQty,0); const godowns=typeof getGodowns==='function'?getGodowns():[]; const mainGodown=godowns.find(g=>String(g.name||'').trim().toLowerCase()==='main godown')||godowns[0]; const godownLabel=gid=>{const g=godowns.find(x=>String(x.id)===String(gid));return g?.name||'—';}; const saleGodownFor=(ref)=>{const inv=sales.find(x=>String(x.invoiceNo||x.number||'')===String(ref||''));const it=(inv?.items||[]).find(x=>String(x.itemId)===String(item.id));return it?.godownId?godownLabel(it.godownId):'—';}; const overlay=document.createElement('div');overlay.id='itemStatementModal';overlay.className='item-modal-overlay'; overlay.innerHTML=`

${esc(item.name||'Item')} — Item Statement

Financial Year: ${esc(getActiveFinancialYear())}
Opening Qty${opening} ${esc(item.unit||'')}
Total Purchase${totalIn} ${esc(item.unit||'')}
Total Out${totalOut} ${esc(item.unit||'')}
Closing Qty${Math.max(0,balance)} ${esc(item.unit||'')}
${rows.map(r=>{let godown='—';if(r.type==='Opening Stock'||r.type==='Purchase'||r.type==='Purchase Return')godown=mainGodown?.name||'—';else if(r.type==='Sale')godown=saleGodownFor(r.ref);else if(r.type==='Sales Return'){const mv=moves.find(m=>m.type==='sales-return'&&String(m.ref||'')===String(r.ref||'')&&String(m.itemId)===String(item.id));godown=mv?.godownId?godownLabel(mv.godownId):'—';}else if(r.type.startsWith('Stock Adjustment')){const mv=moves.find(m=>String(m.ref||'')===String(r.ref||'')&&String(m.date||'')===String(r.date||'')&&m.type==='adjustment');godown=mv?.godownId?godownLabel(mv.godownId):'—';}return ``;}).join('')}
DateTransactionGodownRef. No.PartyIn QtyOut QtyBalance
${indianDate(r.date)}${esc(r.type)}${esc(godown)}${esc(r.ref)}${esc(r.party)}${r.inQty?r.inQty:'—'}${r.outQty?r.outQty:'—'}${r.balance}
Opening ${opening} + Inward ${totalIn} − Outward ${totalOut} = Closing ${Math.max(0,balance)} ${esc(item.unit||'')}
`; document.body.appendChild(overlay);overlay.style.display='flex';overlay.addEventListener('click',e=>{if(e.target===overlay)closeItemStatement();}); document.addEventListener('keydown',itemStatementEsc); } function closeItemStatement(){const m=document.getElementById('itemStatementModal');if(m)m.remove();document.removeEventListener('keydown',itemStatementEsc);} function itemStatementEsc(e){if(e.key==='Escape')closeItemStatement();} function closeItemDetails(){const m=document.getElementById('itemDetailModal');if(m)m.remove();document.removeEventListener('keydown',itemModalEsc);} function itemModalEsc(e){if(e.key==='Escape')closeItemDetails();} async function editItem(id){if(!mviappsRequireStaffPermission('items','edit'))return; const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); const item=items.find(x=>x.id===id); if(!item){alert('Item not found.');return;} const itemImage=await getItemImageData(item); const content=document.getElementById('content'); if(!content)return; content.innerHTML=`

Modify Item

Update item details, pricing, stock and product image.

Basic Information
Source
Stock & Pricing
Product Image

Leave empty to keep the existing image.

${itemImage?``:'No Image'}
`; window.scrollTo(0,0); } function escapeAttr(v){return String(v??'').replace(/&/g,'&').replace(/"/g,'"').replace(//g,'>');} function previewEditItemImage(e){ const file=e.target.files?.[0],box=document.getElementById('editItemPreviewBox');if(!file||!box)return; const reader=new FileReader();reader.onload=()=>{box.innerHTML=``;};reader.readAsDataURL(file); } async function updateItem(id){if(!mviappsRequireStaffPermission('items','edit'))return; const name=document.getElementById('editItemName')?.value.trim(); if(!name){alert('Please enter Item Name.');return;} const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); const idx=items.findIndex(x=>x.id===id);if(idx<0){alert('Item not found.');return;} const old=items[idx],file=document.getElementById('editItemImage')?.files?.[0]; const updatedCode=(document.getElementById('editItemCode')?.value||'').trim(); if(updatedCode && items.some((x,i)=>i!==idx&&String(x?.code||'').trim().toLowerCase()===updatedCode.toLowerCase())){alert('Item Code already exists! Please enter a different Item Code.');document.getElementById('editItemCode')?.focus();return;} const finish=async(imageData,hasNewImage)=>{ const updated={...old,name,code:updatedCode,category:document.getElementById('editItemCategory').value.trim(),brand:document.getElementById('editItemBrand').value.trim(),unit:document.getElementById('editItemUnit').value.trim(),hsn:document.getElementById('editItemHsn').value.trim(),weight:document.getElementById('editItemWeight').value||'0',weightUnit:document.getElementById('editItemWeightUnit').value||'KG',dimension:document.getElementById('editItemDimension').value.trim(),dimensionUnit:document.getElementById('editItemDimensionUnit').value||'CM',gst:document.getElementById('editItemGst').value||'0',source:document.getElementById('editItemSource').value.trim(),qty:document.getElementById('editItemQty').value||'0',value:document.getElementById('editItemValue').value||'0',purchase:document.getElementById('editItemPurchase').value||'0',sale:document.getElementById('editItemSale').value||'0',wholesale:document.getElementById('editItemWholesale').value||'0',retail:document.getElementById('editItemRetail').value||'0',min:document.getElementById('editItemMin').value||'0'}; try{ if(hasNewImage){await putMVIItemImage(id,imageData);updated.imageKey=String(id);delete updated.image;} else if(old.imageKey){updated.imageKey=String(old.imageKey);delete updated.image;} else if(old.image){await putMVIItemImage(id,old.image);updated.imageKey=String(id);delete updated.image;} items[idx]=updated;localStorage.setItem('mviapps_items',JSON.stringify(items));alert('Item modified successfully.');show('item-details'); }catch(e){alert('Item modify nahi ho paya. IndexedDB storage error.');} }; if(file){compressItemImage(file,(img)=>finish(img,true));}else finish('',false); } async function deleteItem(id){if(!mviappsRequireStaffPermission('items','delete'))return; if(!confirm('Delete this item?'))return; const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); const target=items.find(x=>String(x.id)===String(id)); const filtered=items.filter(x=>String(x.id)!==String(id)); localStorage.setItem('mviapps_items',JSON.stringify(filtered)); if(target?.imageKey)await deleteMVIItemImage(target.imageKey); else if(target?.image)await deleteMVIItemImage(target.id); renderItems(); } function stockSummary(){const cats=typeof getItemCategories==='function'?getItemCategories():[...new Set(JSON.parse(localStorage.getItem('mviapps_items')||'[]').map(x=>String(x.category||'').trim()).filter(Boolean))].sort((a,b)=>a.localeCompare(b));return `

Stock Summary

Current item-wise stock position from your saved inventory.

ItemOpeningPurchaseSaleReturnsClosing QtyStock Value
`} function printStockSummary(){const rows=document.getElementById('stockSummaryRows');const table=rows?.closest('table');if(!table)return;const search=document.getElementById('stockSummarySearch')?.value||'';const category=document.getElementById('stockSummaryCategory')?.value||'';const win=window.open('','_blank');if(!win)return;win.document.write(`Stock Summary

Stock Summary

Current item-wise stock position

${(search||category)?`
${search?'Search: '+escapeHtml(search):''}${search&&category?'   |   ':''}${category?'Category: '+escapeHtml(category):''}
`:''}${table.outerHTML}`);win.document.close();win.focus();setTimeout(()=>{win.print();setTimeout(()=>win.close(),300)},250)} function getStockMovements(){return JSON.parse(localStorage.getItem('mviapps_stock_movements')||'[]');} function migratePurchaseReturnsToStockMovements(){const returns=JSON.parse(localStorage.getItem('mviapps_purchase_returns')||'[]');if(!returns.length)return;let moves=getStockMovements(),changed=false;returns.forEach(r=>(r.items||[]).forEach(it=>{const exists=moves.some(m=>m.type==='return'&&String(m.ref)===String(r.invoiceNo)&&String(m.itemId)===String(it.itemId));if(!exists&&(Number(it.qty)||0)>0){moves.push({id:Date.now()+Math.random(),date:r.date||'',itemId:it.itemId,qty:Number(it.qty)||0,type:'return',ref:r.invoiceNo,rate:Number(it.rate)||0});changed=true;}}));if(changed)localStorage.setItem('mviapps_stock_movements',JSON.stringify(moves));} function stockTotals(item){ migratePurchaseReturnsToStockMovements(); const bounds=getFinancialYearBounds(); const fyFrom=bounds.from||''; const fyTo=bounds.to||''; const created=String(item.createdAt||'').slice(0,10); const itemExistsAtFYStart=!created||!fyFrom||created<=fyFrom; const moves=getStockMovements().filter(m=>String(m.itemId)===String(item.id)).slice().sort((a,b)=>String(a.date||'').localeCompare(String(b.date||''))||(Number(a.id)||0)-(Number(b.id)||0)); let purchase=0,sale=0,returns=0,adjustmentIn=0,adjustmentOut=0; const defaultRate=Number(item.purchase)||0; // For items created during the selected FY, item.qty/value are the stock // entered when the item was created. Keep the FY Opening column at zero, // but include this initial stock in Closing Qty and Stock Value. const createdDuringFY=!!created && !!fyFrom && created>fyFrom && (!fyTo||created<=fyTo); let qty=(itemExistsAtFYStart||createdDuringFY)?(Number(item.qty)||0):0; let value=(itemExistsAtFYStart||createdDuringFY)?(Number(item.value)||0):0; const purchaseInvoices=JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]'); const purchaseRateForMove=(m)=>{ if(Number(m.rate)>0)return Number(m.rate); const inv=purchaseInvoices.find(x=>String(x.invoiceNo||x.number||'')===String(m.ref||'')); const it=(inv?.items||[]).find(x=>String(x.itemId)===String(item.id)); return Number(it?.rate||it?.purchaseRate||0)||defaultRate; }; if(qty>0&&value<=0&&defaultRate>0)value=qty*defaultRate; const applyMove=(m,track)=>{ const q=Math.max(0,Number(m.qty)||0); if(!q)return; const rate=purchaseRateForMove(m); if(m.type==='purchase'){if(track)purchase+=q;qty+=q;value+=q*rate;} else if(m.type==='sales-return'){if(track)returns+=q;qty+=q;value+=q*rate;} else if(m.type==='sale'){if(track)sale+=q;const avg=qty>0?value/qty:defaultRate;const used=Math.min(q,Math.max(0,qty));qty-=q;value=Math.max(0,value-used*avg);} else if(m.type==='return'){if(track)returns+=q;const avg=qty>0?value/qty:rate;const used=Math.min(q,Math.max(0,qty));qty-=q;value=Math.max(0,value-used*avg);} else if(m.type==='adjustment'){if(m.adjustmentType==='increase'){if(track)adjustmentIn+=q;qty+=q;value+=q*rate;}else{if(track)adjustmentOut+=q;const avg=qty>0?value/qty:defaultRate;const used=Math.min(q,Math.max(0,qty));qty-=q;value=Math.max(0,value-used*avg);}} }; moves.forEach(m=>{ const d=String(m.date||'').slice(0,10); // Do not apply any pre-creation movements to a newly created item. if(createdDuringFY&&created&&d&&dfyTo)return; applyMove(m,true); }); const opening= itemExistsAtFYStart ? (Number(item.qty)||0) : 0; let openingQty=opening, openingValue=itemExistsAtFYStart?(Number(item.value)||0):0; if(openingQty>0&&openingValue<=0&&defaultRate>0)openingValue=openingQty*defaultRate; // Rebuild FY opening quantity/value separately from the base item opening. openingQty=itemExistsAtFYStart?(Number(item.qty)||0):0; openingValue=itemExistsAtFYStart?(Number(item.value)||0):0; if(openingQty>0&&openingValue<=0&&defaultRate>0)openingValue=openingQty*defaultRate; moves.forEach(m=>{const d=String(m.date||'').slice(0,10);if(!fyFrom||!d||d>=fyFrom)return; const q=Math.max(0,Number(m.qty)||0),rate=purchaseRateForMove(m);if(!q)return; if(m.type==='purchase'){openingQty+=q;openingValue+=q*rate;} else if(m.type==='sales-return'){openingQty+=q;openingValue+=q*rate;} else if(m.type==='sale'||m.type==='return'){const avg=openingQty>0?openingValue/openingQty:(m.type==='return'?rate:defaultRate);const used=Math.min(q,Math.max(0,openingQty));openingQty-=q;openingValue=Math.max(0,openingValue-used*avg);} else if(m.type==='adjustment'){if(m.adjustmentType==='increase'){openingQty+=q;openingValue+=q*rate;}else{const avg=openingQty>0?openingValue/openingQty:defaultRate;const used=Math.min(q,Math.max(0,openingQty));openingQty-=q;openingValue=Math.max(0,openingValue-used*avg);}} }); const closing=Math.max(0,qty); if(closing>0&&value<=0&&defaultRate>0)value=closing*defaultRate; return {opening:Math.max(0,openingQty),purchase,sale,returns,adjustmentIn,adjustmentOut,closing,stockValue:Math.max(0,value),openingValue:Math.max(0,openingValue)}; } function getCurrentStockSnapshot(item){ const t=stockTotals(item); // Item Details > Current Stock Quantity must match Item Statement. // If the item was created during the selected FY, its saved opening qty // (item.qty) is the opening balance from its creation date; stockTotals() // intentionally excludes that base qty for FY reporting, so use the same // opening-balance rule as Item Statement here. const bounds=getFinancialYearBounds(); const fyFrom=bounds.from||'',fyTo=bounds.to||''; const created=String(item.createdAt||'').slice(0,10); const createdInFY=!!created && (!fyFrom || created>=fyFrom) && (!fyTo || created<=fyTo); if(!createdInFY)return {qty:t.closing,value:t.stockValue}; let qty=Math.max(0,Number(item.qty)||0); const moves=getStockMovements().filter(m=>String(m.itemId)===String(item.id)); moves.forEach(m=>{ const d=String(m.date||'').slice(0,10); if(fyFrom&&d&&dfyTo)return; const q=Math.max(0,Number(m.qty)||0); if(!q)return; if(m.type==='purchase'||m.type==='sales-return')qty+=q; else if(m.type==='sale'||m.type==='return')qty-=q; else if(m.type==='adjustment')qty += m.adjustmentType==='increase'?q:-q; }); return {qty:Math.max(0,qty),value:t.stockValue}; } function renderStockSummary(){const rows=document.getElementById('stockSummaryRows');if(!rows)return;const q=(document.getElementById('stockSummarySearch')?.value||'').toLowerCase(),c=(document.getElementById('stockSummaryCategory')?.value||'').trim().toLowerCase();const items=getSortedItems().filter(x=>(!q||String(x.name||'').toLowerCase().includes(q)||String(x.code||'').toLowerCase().includes(q))&&(!c||String(x.category||'').trim().toLowerCase()===c));rows.innerHTML=items.length?items.map(x=>{const t=stockTotals(x);return `${escapeHtml(x.name||'')}
${escapeHtml(x.code||x.category||'')}${t.opening}${t.purchase}${t.sale}${t.returns}${t.closing}₹ ${t.stockValue.toFixed(2)}`}).join(''):`No stock items found. Add items from Item Details.`;} function stockLedger(){return `

Stock Ledger

View device-local history separately from authoritative Production Cloud stock movements.

DateItemTypeReferenceIn QtyOut QtyBalance Qty
`} function printStockLedger(){const rows=document.getElementById('stockLedgerRows');const table=rows?.closest('table');if(!table)return;const win=window.open('','_blank');if(!win)return;win.document.write(`Stock Ledger

Stock Ledger

Item-wise opening stock and stock movement history

${table.outerHTML}`);win.document.close();win.focus();setTimeout(()=>{win.print();win.close()},250)} function renderStockLedger(){const rows=document.getElementById('stockLedgerRows');if(!rows)return;const q=(document.getElementById('stockLedgerSearch')?.value||'').toLowerCase(),type=document.getElementById('stockLedgerType')?.value||'';const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]');const bounds=getFinancialYearBounds(),from=bounds.from,to=bounds.to,moves=[];items.forEach(x=>{const t=stockTotals(x);if(t.opening!==0)moves.push({date:from||x.createdAt||'',itemId:x.id,item:x.name,type:'opening',ref:'Opening Stock',inQty:t.opening,outQty:0});});getStockMovements().forEach(m=>{const d=String(m.date||'').slice(0,10);if(from&&d&&dto)return;const x=items.find(i=>String(i.id)===String(m.itemId));if(x){const isAdj=m.type==='adjustment';moves.push({date:m.date||'',itemId:x.id,item:x.name,type:m.type,ref:m.ref||'—',inQty:(m.type==='purchase'||m.type==='sales-return'||(isAdj&&m.adjustmentType==='increase'))?(Number(m.qty)||0):0,outQty:(m.type==='sale'||m.type==='return'||(isAdj&&m.adjustmentType==='decrease'))?(Number(m.qty)||0):0});}});const filtered=moves.filter(m=>(!q||m.item.toLowerCase().includes(q))&&(!type||m.type===type)).sort((a,b)=>String(a.date).localeCompare(String(b.date)));const balances={};rows.innerHTML=filtered.length?filtered.map(m=>{balances[m.itemId]=(balances[m.itemId]||0)+m.inQty-m.outQty;return `${escapeHtml(m.date||'—')}${escapeHtml(m.item)}${m.type.charAt(0).toUpperCase()+m.type.slice(1)}${escapeHtml(m.ref)}${m.inQty||0}${m.outQty||0}${balances[m.itemId]}`}).join(''):`No stock movement found.`;} // Production Cloud Stock Ledger — read-only view over the authoritative Worker replay snapshot. let mviappsCloudStockLedgerSnapshot=null; let mviappsCloudStockLedgerBusy=false; function mviappsSetStockLedgerMode(mode){ const cloud=mode==='cloud',localView=document.getElementById('stockLedgerLocalView'),cloudView=document.getElementById('stockLedgerCloudView'); if(localView)localView.hidden=cloud;if(cloudView)cloudView.hidden=!cloud; const localTab=document.getElementById('stockLedgerLocalTab'),cloudTab=document.getElementById('stockLedgerCloudTab'); if(localTab){localTab.className=cloud?'btn secondary':'btn';localTab.setAttribute('aria-pressed',String(!cloud));} if(cloudTab){cloudTab.className=cloud?'btn':'btn secondary';cloudTab.setAttribute('aria-pressed',String(cloud));} if(cloud&&!mviappsCloudStockLedgerSnapshot&&!mviappsCloudStockLedgerBusy)mviappsRefreshCloudStockLedger(); } function mviappsCloudStockLedgerStatus(message,isError=false){const el=document.getElementById('stockLedgerCloudStatus');if(el){el.textContent=message;el.style.color=isError?'#b91c1c':'var(--muted)';}} async function mviappsRefreshCloudStockLedger(){ if(mviappsCloudStockLedgerBusy)return false; const cloud=window.mviappsProductionCloud;if(!cloud?.stockLedgerSnapshot){mviappsCloudStockLedgerStatus('Production Cloud authentication or Stock Ledger snapshot adapter is unavailable.',true);return false;} mviappsCloudStockLedgerBusy=true;const b=document.getElementById('stockLedgerCloudRefresh');if(b)b.disabled=true; mviappsCloudStockLedgerStatus('Reading authenticated Production Cloud stock movements and authoritative balances…'); try{ const snap=await cloud.stockLedgerSnapshot(); if(!snap||!Array.isArray(snap.items)||!Array.isArray(snap.godowns)||!Array.isArray(snap.balances))throw new Error('Worker returned an incomplete stock snapshot.'); if(snap.balances.some(x=>!Array.isArray(x.events)))throw new Error('Worker snapshot does not include replayed stock movement events. Refresh is blocked; no local data will be substituted.'); mviappsCloudStockLedgerSnapshot=snap;mviappsRenderCloudStockLedger(); const eventCount=snap.balances.reduce((n,x)=>n+x.events.length,0); mviappsCloudStockLedgerStatus('PASS — '+snap.items.length+' Cloud Items, '+snap.godowns.length+' Godowns, '+eventCount+' replayed stock events. Closing balances are from the authoritative Worker snapshot. Loaded: '+new Date(snap.loadedAt||Date.now()).toLocaleString('en-IN')); return true; }catch(e){mviappsCloudStockLedgerSnapshot=null;mviappsRenderCloudStockLedger();mviappsCloudStockLedgerStatus('Cloud Stock Ledger unavailable: '+(e?.message||String(e))+'. Local Ledger has not been used as a fallback.',true);return false;} finally{mviappsCloudStockLedgerBusy=false;if(b)b.disabled=false;} } function mviappsRenderCloudStockLedger(){ const snap=mviappsCloudStockLedgerSnapshot,balRows=document.getElementById('stockLedgerCloudBalances'),moveRows=document.getElementById('stockLedgerCloudRows');if(!balRows||!moveRows)return; if(!snap){balRows.innerHTML='Authoritative Cloud balances are not loaded.';moveRows.innerHTML='No Cloud movement data available.';return;} const items=new Map(snap.items.map(x=>[String(x.id),x])),godowns=new Map(snap.godowns.map(x=>[String(x.id),x])); const search=(document.getElementById('stockLedgerCloudSearch')?.value||'').trim().toLowerCase(),type=document.getElementById('stockLedgerCloudType')?.value||''; const balanceLines=[];for(const entry of snap.balances){const item=items.get(String(entry.itemId));if(!item)continue;for(const g of snap.godowns){const qty=Number(entry.balances?.[g.id]||0);balanceLines.push({item,g,qty});}} const visibleBalances=balanceLines.filter(x=>!search||String(x.item.name||'').toLowerCase().includes(search)||String(x.item.code||'').toLowerCase().includes(search)); balRows.innerHTML=visibleBalances.length?visibleBalances.map(x=>`${escapeHtml(x.item.name||'')}${escapeHtml(x.item.code||'—')}${escapeHtml(x.g.name||'')}${x.qty}${escapeHtml(x.item.unit||'')}`).join(''):'No matching Cloud item balances.'; const all=[]; for(const entry of snap.balances){const item=items.get(String(entry.itemId));if(!item)continue;const mainId=String(entry.mainGodownId||snap.godowns.find(g=>String(g.name||'').toLowerCase()==='main godown')?.id||snap.godowns[0]?.id||'');const opening=Number(item.qty||0); const localBalances={};for(const g of snap.godowns)localBalances[String(g.id)]=0;if(mainId)localBalances[mainId]=opening; if(opening!==0)all.push({date:'',order:0,itemId:String(item.id),item,godownId:mainId,type:'opening',ref:'Opening Stock',inQty:opening,outQty:0,balance:localBalances[mainId]||0}); const events=[...(entry.events||[])].sort((a,b)=>String(a.date).localeCompare(String(b.date))||Number(a.order||0)-Number(b.order||0)||String(a.ref||'').localeCompare(String(b.ref||''))||String(a.type||'').localeCompare(String(b.type||''))); for(const e of events){const gid=String(e.godownId||mainId),kind=String(e.type||'');const positive=['purchase','sales-return','adjustment-in','transfer-in'].includes(kind);const negative=['purchase-return','sale','adjustment-out','transfer-out'].includes(kind);if(!positive&&!negative)continue;const q=Number(e.qty)||0;if(!(q>0))continue;localBalances[gid]=(Number(localBalances[gid])||0)+(positive?q:-q);const movement=kind.startsWith('adjustment-')?'adjustment':kind.startsWith('transfer-')?'transfer':kind; all.push({date:e.date||'',order:Number(e.order||0),itemId:String(item.id),item,godownId:gid,type:movement,rawType:kind,ref:e.ref||'—',inQty:positive?q:0,outQty:negative?q:0,balance:localBalances[gid]||0}); } } all.sort((a,b)=>String(a.date).localeCompare(String(b.date))||a.order-b.order||String(a.ref||'').localeCompare(String(b.ref||''))||String(a.rawType||'').localeCompare(String(b.rawType||''))||a.item.name.localeCompare(b.item.name)||a.godownId.localeCompare(b.godownId)); const filtered=all.filter(x=>(!search||String(x.item.name||'').toLowerCase().includes(search)||String(x.item.code||'').toLowerCase().includes(search))&&(!type||x.type===type)); moveRows.innerHTML=filtered.length?filtered.map(x=>{const g=godowns.get(x.godownId);const label=x.type==='adjustment'?(x.rawType==='adjustment-in'?'Stock Adjustment (+)':'Stock Adjustment (-)'):x.type==='transfer'?(x.rawType==='transfer-in'?'Godown Transfer (In)':'Godown Transfer (Out)'):x.type==='opening'?'Opening Stock':x.type==='purchase-return'?'Purchase Return':x.type==='sales-return'?'Sales Return':x.type.charAt(0).toUpperCase()+x.type.slice(1);return `${escapeHtml(x.date||'—')}${escapeHtml(x.item.name||'')}${escapeHtml(g?.name||'Unknown Godown')}${escapeHtml(label)}${escapeHtml(x.ref||'—')}${x.inQty||'—'}${x.outQty||'—'}${x.balance}`;}).join(''):'No matching Cloud stock movements.'; } function exportStockSummary(){const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]');let csv='Item,Opening,Purchase,Sale,Returns,Closing Qty,Stock Value\n';items.forEach(x=>{const t=stockTotals(x);csv+=`"${String(x.name||'').replace(/"/g,'""')}",${t.opening},${t.purchase},${t.sale},${t.returns},${t.closing},${(t.closing*(Number(x.purchase)||0)).toFixed(2)}\n`;});downloadCSV(csv,'stock-summary.csv');} function exportStockLedger(){const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]');let csv='Date,Item,Type,Reference,In Qty,Out Qty\n';items.forEach(x=>{if(Number(x.qty||0))csv+=`"${x.createdAt||''}","${String(x.name||'').replace(/"/g,'""')}",Opening,Opening Stock,${Number(x.qty)||0},0\n`;});getStockMovements().forEach(m=>{const x=items.find(i=>String(i.id)===String(m.itemId));if(x)csv+=`"${m.date||''}","${String(x.name||'').replace(/"/g,'""')}",${m.type},"${String(m.ref||'').replace(/"/g,'""')}",${m.type==='purchase'?Number(m.qty)||0:0},${m.type==='sale'?Number(m.qty)||0:0}\n`;});downloadCSV(csv,'stock-ledger.csv');} function downloadCSV(csv,name){const blob=new Blob([csv],{type:'text/csv;charset=utf-8;'}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=name;a.click();URL.revokeObjectURL(a.href);} function itemForm(){return `

Add Item

Enter product information, pricing and opening stock.

Basic Information
${fields(["Item Name *","Item Code","Category","Brand","Unit","HSN/SAC","GST Rate"])}
Stock & Pricing
${fields(["Opening Quantity","Opening Value","Purchase Rate","Sale Rate","Wholesale Rate","Retail Rate","Minimum Stock Level"])}
Product Image
${fields(["Product Image"])}
`} function invoice(type){ if(type==='Purchase Return') return purchaseInvoice(true); if(type!=='Sale Invoice') return purchaseInvoice(false); const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); const partyOpts=parties.length?parties.map(x=>``).join(''):''; return `

Sales Invoice

Create a clean sales invoice with customer, items, tax and payment details.

Invoice Information

Items & Godown-wise Stock

ItemGodownAvailable QtySale QtyUnitRateDiscount %GST %Amount
No items added. “+ Add Item” button se item add karein.
A separate Godown can be selected for each item.

Notes & Terms

Invoice Summary

${['Sub Total','Discount','Taxable Amount','CGST','SGST','IGST','Round Off'].map(x=>`
${x}₹ 0.00
`).join('')}
Grand Total₹ 0.00
`; } function purchaseInvoice(isReturn=false){ const now=new Date(), pad=n=>String(n).padStart(2,'0'); const purchaseReturnYear=now.getFullYear(), purchaseReturnMonth=now.getMonth(); const purchaseReturnFirstMonthDate=purchaseReturnYear+'-'+pad(purchaseReturnMonth+1)+'-01'; const purchaseReturnLastDay=new Date(purchaseReturnYear,purchaseReturnMonth+1,0).getDate(); const purchaseReturnLastMonthDate=purchaseReturnYear+'-'+pad(purchaseReturnMonth+1)+'-'+pad(purchaseReturnLastDay); const purchaseReturnFirstMonthDisplay='01/'+pad(purchaseReturnMonth+1)+'/'+purchaseReturnYear; const purchaseReturnLastMonthDisplay=pad(purchaseReturnLastDay)+'/'+pad(purchaseReturnMonth+1)+'/'+purchaseReturnYear; const prefix=isReturn?'Purchase Return':'Purchase'; const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const partyOpts=parties.length?parties.map(x=>``).join(''):''; return `

${prefix} Invoice

${isReturn?'Record returned goods to a supplier.':'Record supplier purchases with item, quantity, tax and payment details.'}

${prefix} Information

Items

ItemQtyUnitPurchase RateDiscount %GST %Amount
No items added. “+ Add Item” button se item add karein.
Add item details in a separate popup.${!isReturn?`
Used for Service Item(s) automatically recorded as Expenses.
`:''}

Notes & Terms

Purchase Summary

${['Sub Total','Discount','Taxable Amount','CGST','SGST','IGST','Round Off'].map(x=>`
${x}₹ 0.00
`).join('')}
Grand Total₹ 0.00
${isReturn?`

Purchase Return Entries

Current month entries are shown by default. Select From Date and To Date to view older entries.

From Date
To Date
DateReturn No.SupplierItemsPayment ModeTotalAction
`:''}`; } function toggleSaleInvoiceSummary(){const box=document.getElementById('saleInvoiceSummary'),btn=document.getElementById('saleInvoiceSummaryToggle');if(!box||!btn)return;const collapsed=box.classList.toggle('collapsed');btn.textContent=collapsed?'▼':'▲';btn.setAttribute('aria-label',collapsed?'Expand Invoice Summary':'Collapse Invoice Summary');btn.title=collapsed?'Expand Invoice Summary':'Collapse Invoice Summary';} function newSaleInvoice(){window._editingSaleId=null;document.getElementById('content').innerHTML=invoice('Sale Invoice');} function newPurchaseInvoice(){window._editingPurchaseId=null;window._editingPurchaseReturnId=null;document.getElementById('content').innerHTML=invoice('Purchase');const b=document.querySelector('[onclick="savePurchaseInvoice(false)"]');if(b)b.textContent='Save Purchase';} function getNextAutoNumber(key,prefix){ let arr=[]; try{const parsed=JSON.parse(localStorage.getItem(key)||'[]');arr=Array.isArray(parsed)?parsed:[];}catch(e){arr=[];} const numberFields=['number','incomeNo','invoiceNo','receiptNo','paymentNo','expenseNo','returnNo']; const used=new Set(); let max=0; const re=new RegExp('^'+String(prefix).replace(/[.*+?^${}()|[\]\\]/g,'\\$&')+'-(\\d+)$','i'); arr.forEach(x=>{ numberFields.forEach(field=>{ const value=String(x?.[field]??'').trim(); if(!value)return; used.add(value.toUpperCase()); const m=value.match(re); if(m) max=Math.max(max,Number(m[1])||0); }); }); let next=max+1; let candidate=prefix+'-'+String(next).padStart(4,'0'); while(used.has(candidate.toUpperCase())){ next++; candidate=prefix+'-'+String(next).padStart(4,'0'); } return candidate; } function autoFillDocumentNumbers(){ const inv=document.getElementById('saleInvoiceNo'); if(inv && !inv.value.trim()) inv.value=getNextAutoNumber('mviapps_sales_invoices','INV'); const acc=document.getElementById('accountNo'); const type=window._accountEntryType||''; if(acc && !acc.value.trim()){ if(type==='Payment-In') acc.value=getNextAutoNumber('mviapps_payment_in','REC'); if(type==='Payment-Out') acc.value=getNextAutoNumber('mviapps_payment_out','PAY'); if(type==='Other Income') acc.value=getNextAutoNumber('mviapps_other_income','INC'); } const exp=document.getElementById('expenseNo'); if(exp && !exp.value.trim()) exp.value=getNextAutoNumber('mviapps_expenses','EXP'); } function pointOfSalePage(){ const today=new Date().toISOString().slice(0,10); return `

Point of Sale (POS)

Fast counter billing

Connecting to Production Cloud…
#ITEM CODEITEM NAMEQTYUNITPRICE/UNIT(₹)DISCOUNT %AMOUNT
Search and select an item to add it to the bill.
🧾 Total₹ 0.00
Items: 0, Quantity: 0
Change to Return:₹ 0.00
`; } function exitPOSFullScreen(){ const el=document.getElementById('mviPosFullscreen'); if(el)el.remove(); try{show('sale-invoices');}catch(e){} } function posLoadCustomers(){ const el=document.getElementById('posCustomer');if(!el)return; const parties=Array.isArray(window._mviPOSCloudContext?.parties)?window._mviPOSCloudContext.parties:[]; el.innerHTML=''+parties.map(p=>``).join(''); posSyncCustomerPickerLabel(); posRenderCustomerOptions(); } function posCustomerPhone(p){ return String(p?.phone||p?.mobile||p?.phoneNumber||p?.mobileNo||p?.contact||p?.contactNo||'').trim(); } function posSyncCustomerPickerLabel(){ const select=document.getElementById('posCustomer'); const label=document.getElementById('posCustomerSelectedLabel'); if(!select||!label)return; const option=select.selectedOptions?.[0]; label.textContent=option?.textContent||'Walk-in / Cash Customer'; } function posToggleCustomerPicker(){ const popup=document.getElementById('posCustomerPopup'); const trigger=document.getElementById('posCustomerTrigger'); const search=document.getElementById('posCustomerSearch'); if(!popup||!trigger)return; const opening=!popup.classList.contains('open'); popup.classList.toggle('open',opening); trigger.setAttribute('aria-expanded',opening?'true':'false'); if(opening){if(search)search.value='';posRenderCustomerOptions();setTimeout(()=>search?.focus(),0);} } function posCloseCustomerPicker(){ const popup=document.getElementById('posCustomerPopup'); const trigger=document.getElementById('posCustomerTrigger'); popup?.classList.remove('open');trigger?.setAttribute('aria-expanded','false'); } function posRenderCustomerOptions(){ const results=document.getElementById('posCustomerResults'); if(!results)return; const parties=Array.isArray(window._mviPOSCloudContext?.parties)?window._mviPOSCloudContext.parties:[]; const q=String(document.getElementById('posCustomerSearch')?.value||'').trim().toLowerCase(); const matches=parties.filter(p=>!q||String(p.name||'').toLowerCase().includes(q)||posCustomerPhone(p).toLowerCase().includes(q)); const walkIn=``; const partyOptions=matches.map(p=>``).join(''); results.innerHTML=walkIn+(partyOptions||(!q?'
No saved customers found.
':'
No matching customer. Try another name or phone number.
')); } function posChooseCustomer(id){ const select=document.getElementById('posCustomer');if(!select)return; select.value=String(id||''); posSyncCustomerPickerLabel(); posCloseCustomerPicker(); if(typeof posUpdateCustomer==='function')posUpdateCustomer(); } function posCustomerSearchKeydown(event){ if(event.key==='Escape'){event.preventDefault();posCloseCustomerPicker();document.getElementById('posCustomerTrigger')?.focus();} if(event.key==='Enter'){event.preventDefault();const first=document.querySelector('#posCustomerResults .mvi-pos-customer-option');first?.click();} } document.addEventListener('click',function(event){ const picker=document.getElementById('posCustomerPicker'); if(picker&&!picker.contains(event.target))posCloseCustomerPicker(); }); function posGetItems(){ return Array.isArray(window._mviPOSCloudContext?.items)?window._mviPOSCloudContext.items:[]; } function posGetRows(){ return [...document.querySelectorAll('#posItemsBody tr[data-pos-row]')]; } function posFindStock(itemId){ const item=posGetItems().find(i=>String(i.id)===String(itemId)); if(!item)return 0; const row=(window._mviPOSCloudContext?.balances||[]).find(x=>String(x.itemId)===String(itemId)); return Number(row?.total)||0; } function posGetItemBarcode(item){ return String(item?.barcode ?? item?.barCode ?? item?.Barcode ?? item?.itemBarcode ?? item?.sku ?? '').trim(); } function renderPOSItemSuggestions(){ const box=document.getElementById('posItemSuggestions'),input=document.getElementById('posItemSearch');if(!box||!input)return; const q=(input.value||'').toLowerCase().trim(); if(!q){box.style.display='none';box.innerHTML='';return;} const items=posGetItems().filter(i=>String(i.name||'').toLowerCase().includes(q)||String(i.code||i.itemCode||'').toLowerCase().includes(q)||posGetItemBarcode(i).toLowerCase().includes(q)).slice(0,12); box.innerHTML=items.length?items.map(i=>``).join(''):'
No item found.
'; box.style.display='block'; } function posAddFirstSuggestion(){ const input=document.getElementById('posItemSearch'); const q=String(input?.value||'').trim().toLowerCase(); if(q){ const exact=posGetItems().find(i=>String(i.code||i.itemCode||'').trim().toLowerCase()===q||posGetItemBarcode(i).toLowerCase()===q); if(exact){posAddItem(exact.id);return;} } const first=document.querySelector('#posItemSuggestions button');if(first)first.click(); } function posQuickItemEntry(){ const input=document.getElementById('posItemSearch'); if(!input)return; input.focus(); input.select(); } function posAddItem(itemId){if(!mviappsRequireStaffPermission('sales','create'))return; const item=posGetItems().find(i=>String(i.id)===String(itemId));if(!item)return; if(window._mviPOSCloudContext?.stockVerified!==true){const e=window._mviPOSCloudContext?.stockError;alert('Cloud Item is available, but authoritative stock is not verified. POS cannot add or sell this item yet.'+(e?.code?'\nCode: '+e.code:'')+(e?.message?'\n'+e.message:''));return;} const available=posFindStock(itemId); if(available<=0){alert(`No stock available for ${item.name||'this item'}.`);return;} const body=document.getElementById('posItemsBody');if(!body)return; const existing=body.querySelector(`tr[data-pos-row][data-item-id="${CSS.escape(String(itemId))}"]`); if(existing){ const q=existing.querySelector('.pos-row-qty'); const next=(Number(q.value)||0)+1; if(next>available){alert(`Only ${available} ${item.unit||''} available for ${item.name||'this item'}.`);q.focus();return;} q.value=next;posRecalcRow(existing); }else{ if(body.querySelector('.mvi-pos-empty'))body.innerHTML=''; const tr=document.createElement('tr');tr.dataset.posRow='1';tr.dataset.itemId=item.id;tr.dataset.availableStock=String(available); const price=Number(item.sale)||0; tr.innerHTML=`${escapeHtml(item.code||item.itemCode||'')}${escapeHtml(item.name||'')}
Available: ${available} ${escapeHtml(item.unit||'')}
${escapeHtml(item.unit||'')}₹ 0.00`; body.appendChild(tr);posRecalcRow(tr); } document.getElementById('posItemSearch').value='';document.getElementById('posItemSuggestions').style.display='none';document.getElementById('posItemSearch').focus(); posRefreshNumbers(); } function posRecalcRow(tr){ if(!tr)return; const qtyEl=tr.querySelector('.pos-row-qty'); let q=Number(qtyEl?.value)||0; const available=Number(tr.dataset.availableStock)||posFindStock(tr.dataset.itemId); if(q<0){q=0;if(qtyEl)qtyEl.value='0';} if(q>available){q=available;if(qtyEl)qtyEl.value=String(available);} const r=Number(tr.querySelector('.pos-row-rate')?.value)||0,d=Math.min(100,Math.max(0,Number(tr.querySelector('.pos-row-disc')?.value)||0)); const discEl=tr.querySelector('.pos-row-disc');if(discEl&&Number(discEl.value)!==d)discEl.value=String(d); const amount=q*r*(1-d/100);const el=tr.querySelector('.pos-row-amount');if(el)el.textContent='₹ '+amount.toFixed(2); posRefreshNumbers(); } function posRefreshNumbers(){ const rows=posGetRows();let total=0,qty=0; rows.forEach((tr,i)=>{const n=tr.querySelector('.pos-row-no');if(n)n.textContent=i+1;const q=Number(tr.querySelector('.pos-row-qty')?.value)||0,r=Number(tr.querySelector('.pos-row-rate')?.value)||0,d=Number(tr.querySelector('.pos-row-disc')?.value)||0;qty+=q;total+=q*r*(1-d/100);}); const t=document.getElementById('posTotal');if(t)t.textContent='₹ '+total.toFixed(2); const full=document.getElementById('posFullAmount'),received=document.getElementById('posAmountReceived'); if(full?.checked && received){received.value=total.toFixed(2);received.readOnly=true;} const ic=document.getElementById('posItemCount');if(ic)ic.textContent=rows.length; const qc=document.getElementById('posQtyCount');if(qc)qc.textContent=qty; posCalculateReturn(); } function posUseFullAmount(box){ const received=document.getElementById('posAmountReceived'); if(!received)return; if(box?.checked){ received.value=posGetTotal().toFixed(2); received.readOnly=true; }else{ received.readOnly=false; received.focus(); received.select(); } posCalculateReturn(); } function posCalculateReturn(){ const total=posGetTotal(),received=Number(document.getElementById('posAmountReceived')?.value)||0; const change=Math.max(0,received-total);const el=document.getElementById('posChange');if(el)el.textContent='₹ '+change.toFixed(2); } function posGetTotal(){ return posGetRows().reduce((s,tr)=>{const q=Number(tr.querySelector('.pos-row-qty')?.value)||0,r=Number(tr.querySelector('.pos-row-rate')?.value)||0,d=Number(tr.querySelector('.pos-row-disc')?.value)||0;return s+q*r*(1-d/100)},0); } function posRemoveRow(tr){ tr?.remove();const body=document.getElementById('posItemsBody');if(body&&!posGetRows().length)body.innerHTML='Search and select an item to add it to the bill.';posRefreshNumbers(); } function posRemoveSelected(){ const rows=posGetRows();if(rows.length)posRemoveRow(rows[rows.length-1]); } function posFocusQty(){const r=posGetRows();if(r.length)r[r.length-1].querySelector('.pos-row-qty')?.focus();} function posFocusDiscount(){const r=posGetRows();if(r.length)r[r.length-1].querySelector('.pos-row-disc')?.focus();} function posFocusCustomer(){document.getElementById('posCustomer')?.focus();} function posLoadBankAccounts(selectedId=''){ const el=document.getElementById('posBankAccount');if(!el)return; const rows=Array.isArray(window._mviPOSCloudContext?.bankAccounts)?window._mviPOSCloudContext.bankAccounts:[]; el.innerHTML=''+rows.map(a=>{const id=String(a.id??'');const label=String(a.accountName||a.name||a.bankName||'Bank Account');return ``;}).join('')||''; } function posPaymentModeChanged(){ const mode=document.getElementById('posPaymentMode')?.value||'Cash'; const bank=document.getElementById('posBankWrap'),due=document.getElementById('posDueDateWrap'); if(bank)bank.style.display=['Bank','UPI','Card'].includes(mode)?'':'none'; if(due)due.style.display=mode==='Credit'?'':'none'; const received=document.getElementById('posAmountReceived'); if(received && mode==='Credit')received.value='0'; if(['Bank','UPI','Card'].includes(mode))posLoadBankAccounts(document.getElementById('posBankAccount')?.value||''); posCalculateReturn(); } function posSetCreditPayment(){posOpenCreditReceipt();} function posCreditReceiptData(){ const parties=Array.isArray(window._mviPOSCloudContext?.parties)?window._mviPOSCloudContext.parties:[]; return {parties}; } async function posCreditReceiptOutstanding(partyId){ const fyb=getFinancialYearBounds(getActiveFinancialYear()); const cloud=window.mviappsProductionCloud; if(!cloud?.businessDataRequest)throw new Error('Production Cloud ledger adapter is unavailable.'); const result=await cloud.businessDataRequest('/business/data/party-ledger?partyId='+encodeURIComponent(partyId)+'&from='+encodeURIComponent(fyb.from)+'&to='+encodeURIComponent(fyb.to)+'&defaultFY=1',{method:'GET'}); if(!Number.isFinite(Number(result?.closingBalance)))throw new Error('Cloud Party Ledger did not return a valid closing balance.'); return Math.max(0,Number(result.closingBalance)); } async function posRetryPendingCreditReceipt(){ const key='mviapps_pos_credit_receipt_pending';let pending=null;try{pending=JSON.parse(sessionStorage.getItem(key)||'null');}catch(e){} if(!pending?.record||!pending?.mutationId){alert('No pending POS Credit Receipt request was found.');return;} if(!confirm('Retry the exact saved receipt '+String(pending.record.number||pending.record.id)+' for ₹'+Number(pending.record.amount||0).toFixed(2)+'? This uses the same request ID to prevent duplicate posting.'))return; try{ const result=await window.mviappsProductionCloud.businessDataRequest('/business/pos/credit-receipt',{method:'POST',id:pending.record.id,record:pending.record,mutationId:pending.mutationId}); sessionStorage.removeItem(key);await mviPOSLoadCloudContext(); alert('Pending receipt '+pending.record.number+' is confirmed in Production Cloud. '+(result?.alreadyApplied?'The earlier request had already committed.':'The receipt has now been committed.')); return result; }catch(e){alert((e?.message||'Pending receipt status is still unresolved.')+' The exact request remains saved in this browser session.');} } async function posOpenCreditReceipt(){ let pending=null;try{pending=JSON.parse(sessionStorage.getItem('mviapps_pos_credit_receipt_pending')||'null');}catch(e){} if(pending?.record&&pending?.mutationId){await posRetryPendingCreditReceipt();return;} if(!window._mviPOSCloudContext?.parties) { try{await mviPOSLoadCloudContext();}catch(e){alert('Cloud Parties could not be loaded. '+(e?.message||''));return;} } document.getElementById('mviPosCreditReceiptOverlay')?.remove(); const {parties}=posCreditReceiptData(); const overlay=document.createElement('div'); overlay.id='mviPosCreditReceiptOverlay'; overlay.style.cssText='position:fixed;inset:0;z-index:10030;background:rgba(15,23,42,.58);display:flex;align-items:center;justify-content:center;padding:8px;box-sizing:border-box'; const today=new Date();const localToday=`${today.getFullYear()}-${String(today.getMonth()+1).padStart(2,'0')}-${String(today.getDate()).padStart(2,'0')}`; overlay.innerHTML=`

Receive Credit Payment

Record money received against a customer's outstanding balance.
Select a customer to view outstanding credit.
`; document.body.appendChild(overlay); overlay.addEventListener('click',e=>{if(e.target===overlay)posCloseCreditReceipt();}); document.getElementById('posCreditReceiptParty')?.focus(); } function posCloseCreditReceipt(){document.getElementById('mviPosCreditReceiptOverlay')?.remove();} function posOpenCreditReceiptDatePicker(){const p=document.getElementById('posCreditReceiptDatePicker');if(!p)return;const t=(document.getElementById('posCreditReceiptDate')?.value||'').trim();const m=t.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);if(m){const iso=m[3]+'-'+m[2].padStart(2,'0')+'-'+m[1].padStart(2,'0');if(!Number.isNaN(Date.parse(iso)))p.value=iso;}try{p.showPicker?.();if(typeof p.showPicker!=='function')p.click();}catch(e){try{p.click();}catch(ignore){}}} function posSetCreditReceiptDateFromPicker(iso){const d=document.getElementById('posCreditReceiptDate');if(d&&iso)d.value=iso.split('-').reverse().join('/');} async function posCreditReceiptUpdateBalance(){ const partyId=document.getElementById('posCreditReceiptParty')?.value||''; const box=document.getElementById('posCreditReceiptBalance');if(!box)return; if(!partyId){box.textContent='Select a customer to view outstanding credit.';delete box.dataset.error;delete box.dataset.loadedPartyId;return;} delete box.dataset.error;delete box.dataset.loadedPartyId;box.textContent='Loading authoritative Cloud Party Ledger…'; try{const due=await posCreditReceiptOutstanding(partyId);box.dataset.loadedPartyId=partyId;box.dataset.outstanding=String(due);box.innerHTML='Cloud Party Ledger outstanding: ₹'+due.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2})+'';}catch(e){box.textContent='Outstanding balance unavailable. Receipt saving must wait for a successful Cloud ledger refresh.';box.dataset.error=e?.message||String(e);} } async function posSaveCreditReceipt(){ const partyId=document.getElementById('posCreditReceiptParty')?.value||''; const dateText=(document.getElementById('posCreditReceiptDate')?.value||'').trim(); const dateMatch=dateText.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/); const date=dateMatch?`${dateMatch[3]}-${dateMatch[2].padStart(2,'0')}-${dateMatch[1].padStart(2,'0')}`:''; const validDate=!!date&&(()=>{const d=new Date(date+'T00:00:00');return d.getFullYear()===Number(dateMatch[3])&&d.getMonth()+1===Number(dateMatch[2])&&d.getDate()===Number(dateMatch[1]);})(); const amount=Number(document.getElementById('posCreditReceiptAmount')?.value)||0; if(!partyId){alert('Please select a customer.');return;} if(!validDate){alert('Please enter the receipt date in dd/mm/yyyy format or select it from the calendar.');return;} if(!ensureEntryDateInActiveFY(date,'Receipt Date'))return; if(amount<=0){alert('Please enter a valid amount received.');return;} const {parties}=posCreditReceiptData(); const party=parties.find(p=>String(p.id)===String(partyId)); if(!party){alert('Selected Cloud Customer was not found.');return;} const mode=document.getElementById('posCreditReceiptMode')?.value||'Cash'; const bankAccountId=document.getElementById('posCreditReceiptAccount')?.value||''; if(mode!=='Cash'&&!bankAccountId){alert('Select a Cloud Bank Account for this receipt mode.');return;} const outstandingBox=document.getElementById('posCreditReceiptBalance'); if(outstandingBox?.dataset.error||outstandingBox?.dataset.loadedPartyId!==partyId){alert('Wait for the selected customer Cloud Party Ledger balance to load successfully.');return;} const due=Number(outstandingBox.dataset.outstanding); if(!Number.isFinite(due)||due<=0){alert('This customer has no outstanding debit balance to receive against.');return;} if(amount>due+0.000001){alert('Receipt amount cannot exceed the current Cloud outstanding balance of ₹'+due.toFixed(2)+'.');return;} const pendingKey='mviapps_pos_credit_receipt_pending';let pending=null; try{pending=JSON.parse(sessionStorage.getItem(pendingKey)||'null');}catch(e){pending=null;} let record,mutationId; if(pending?.record&&pending?.mutationId){ const same=String(pending.record.partyId||'')===partyId&&String(pending.record.date||'')===date&&Number(pending.record.amount)===amount&&String(pending.record.paymentMode||'')===mode&&String(pending.record.bankAccountId||'')===bankAccountId; if(!same){alert('A different POS Credit Receipt is still pending. Do not edit or create another receipt until the exact pending request is confirmed.');return;} record=pending.record;mutationId=pending.mutationId; } else{ const bank=Array.isArray(window._mviPOSCloudContext?.bankAccounts)?window._mviPOSCloudContext.bankAccounts.find(x=>String(x.id)===bankAccountId):null; record={id:'POS-REC-'+crypto.randomUUID(),number:'POS-REC-'+new Date().toISOString().replace(/[-:.TZ]/g,'').slice(0,14)+'-'+crypto.randomUUID().slice(0,6).toUpperCase(),date,partyId,partyName:party.name||party.partyName||'',incomeHead:'',amount,paymentMode:mode,account:bank?.accountName||bank?.name||bank?.bankName||bankAccountId,bankAccountId,reference:document.getElementById('posCreditReceiptReference')?.value.trim()||'',notes:document.getElementById('posCreditReceiptNotes')?.value.trim()||'Credit payment received from POS'}; mutationId='pos-credit-receipt-'+crypto.randomUUID(); pending={record,mutationId};sessionStorage.setItem(pendingKey,JSON.stringify(pending)); } const saveButton=document.querySelector('#mviPosCreditReceiptOverlay .btn:not(.secondary)');if(saveButton){saveButton.disabled=true;saveButton.textContent='Saving…';} try{ const result=await window.mviappsProductionCloud.businessDataRequest('/business/pos/credit-receipt',{method:'POST',id:record.id,record,mutationId}); sessionStorage.removeItem(pendingKey);posCloseCreditReceipt(); await mviPOSLoadCloudContext(); alert('Credit payment receipt '+record.number+' saved in Production Cloud and posted to Cash/Bank and Party Ledger.'); return result; }catch(e){if(saveButton){saveButton.disabled=false;saveButton.textContent='Retry Same Receipt';}alert((e?.message||'Cloud Credit Receipt failed.')+' The exact request is retained in this browser session for a safe retry. Do not create a new receipt until its status is confirmed.');} } function posOpenDatePicker(){ const e=document.getElementById('posDate');if(!e)return; try{e.focus({preventScroll:true});if(typeof e.showPicker==='function')e.showPicker();else e.click();}catch(err){try{e.click();}catch(ignore){}} } function posSyncDateDisplay(){const p=document.getElementById('posDate'),d=document.getElementById('posDateDisplay');if(p&&d)d.value=p.value?p.value.split('-').reverse().join('/'):'';} async function posBillHistory(){ posCloseBillHistoryBox(); const overlay=document.createElement('div');overlay.id='mviPosHistoryOverlay'; overlay.style.cssText='position:fixed;inset:0;background:rgba(15,23,42,.45);z-index:10021;display:flex;align-items:center;justify-content:center;padding:16px;box-sizing:border-box'; overlay.innerHTML=`

POS Bill History

Cloud-saved POS bills · edit, delete or reprint
Loading Cloud POS bills…
`; document.body.appendChild(overlay); try{const r=await window.mviappsCloudBusinessData.readAll('salesInvoices',{pageSize:100,maxPages:100});if(r.complete!==true)throw new Error('Cloud POS history is incomplete; increase page coverage before using it.');window._mviPOSHistoryInvoices=(r.records||[]).map(x=>({...x.record,id:String(x.id),updatedAt:x.updatedAt||null})).filter(x=>String(x.notes||'').toUpperCase()==='POS SALE').sort((a,b)=>String(b.date||'').localeCompare(String(a.date||'')));posRenderBillHistory();} catch(e){const box=document.getElementById('posHistoryList');if(box)box.textContent='Cloud history unavailable: '+(e?.message||'Unknown error');} } function posCloseBillHistoryBox(){document.getElementById('mviPosHistoryOverlay')?.remove();window._mviPOSHistoryInvoices=null;} function posRenderBillHistory(){ const box=document.getElementById('posHistoryList');if(!box)return; const all=Array.isArray(window._mviPOSHistoryInvoices)?window._mviPOSHistoryInvoices:[]; const q=(document.getElementById('posHistorySearch')?.value||'').trim().toLowerCase(); const date=document.getElementById('posHistoryDate')?.value||''; const list=all.filter(b=>{ const hay=`${b.invoiceNo||''} ${b.customerName||''}`.toLowerCase(); return (!q||hay.includes(q))&&(!date||String(b.date||'')===date); }); if(!list.length){box.innerHTML='
No POS bills found.
';return;} box.innerHTML=list.slice(0,100).map(b=>{ const itemCount=Array.isArray(b.items)?b.items.length:0; return `
${escapeHtml(b.invoiceNo||'POS Bill')}
${escapeHtml((b.date||'').split('-').reverse().join('/'))} · ${escapeHtml(b.customerName||'Walk-in / Cash Customer')} · ${itemCount} item(s) · ${escapeHtml(b.paymentMode||'Cash')}
₹ ${Number(b.total||0).toFixed(2)}
`; }).join(''); } function posEditHistoryBill(id){ const all=Array.isArray(window._mviPOSHistoryInvoices)?window._mviPOSHistoryInvoices:[]; const b=all.find(x=>String(x.id)===String(id)); if(!b){alert('Bill not found.');return;} if(!ensureEntryDateInActiveFY(b.date,'Bill Date'))return; if(!Array.isArray(b.items)||!b.items.length){alert('This bill has no items to edit.');return;} const items=posGetItems(); for(const it of b.items){ if(!items.find(x=>String(x.id)===String(it.itemId))){alert('An item in this bill no longer exists. The bill was not opened for editing.');return;} } posCloseBillHistoryBox();clearPOSBill(); window._mviPOSEditingId=String(b.id); const d=document.getElementById('posDate'),dd=document.getElementById('posDateDisplay'); if(d)d.value=b.date||'';if(dd)dd.value=b.date?b.date.split('-').reverse().join('/'):''; posLoadCustomers(); const c=document.getElementById('posCustomer');if(c){c.value=b.customer||'';posSyncCustomerPickerLabel();} posLoadBankAccounts(b.bankAccount||''); const p=document.getElementById('posPaymentMode');if(p){p.value=b.paymentMode||'Cash';posPaymentModeChanged();} const ba=document.getElementById('posBankAccount');if(ba)ba.value=b.bankAccount||''; const ref=document.getElementById('posReference');if(ref)ref.value=b.reference||''; const due=document.getElementById('posDueDate');if(due)due.value=b.dueDate||''; const received=document.getElementById('posAmountReceived');if(received)received.value=b.paymentMode==='Credit'?'0':String(b.amountReceived||0); for(const it of b.items){ posAddItem(it.itemId); const tr=posGetRows().find(r=>String(r.dataset.itemId)===String(it.itemId)); if(tr){tr.querySelector('.pos-row-qty').value=String(it.qty);tr.querySelector('.pos-row-rate').value=String(it.rate);tr.querySelector('.pos-row-disc').value=String(it.discount||0);posRecalcRow(tr);} } posRefreshNumbers(); const btn=document.querySelector('.mvi-pos-save');if(btn)btn.innerHTML='Update & Print Bill'; document.getElementById('posItemSearch')?.focus(); } async function posDeleteHistoryBill(id){ const all=Array.isArray(window._mviPOSHistoryInvoices)?window._mviPOSHistoryInvoices:[];const b=all.find(x=>String(x.id)===String(id)); if(!b||!b.updatedAt){alert('Cloud bill version is missing. Refresh history before deleting.');return;} if(!confirm('Delete this Cloud POS bill? Stock will be restored by the atomic Cloud transaction.'))return; try{await window.mviappsCloudBusinessData.remove('salesInvoices',String(b.id),'pos-delete-'+crypto.randomUUID(),b.updatedAt);await posBillHistory();} catch(e){alert(e?.message||'Cloud POS delete failed. Refresh history and verify before retrying.');} } function posReprintHistoryBill(id){ const all=Array.isArray(window._mviPOSHistoryInvoices)?window._mviPOSHistoryInvoices:[]; const record=all.find(x=>String(x.id)===String(id)); if(!record){alert('Bill not found.');return;} posPrintBill(record); } async function posGetHeldBills(){ const cloud=window.mviappsProductionCloud; if(!cloud?.businessDataRequest)throw new Error('Production Cloud Held Bills adapter is unavailable.'); const result=await cloud.businessDataRequest('/business/pos/held-bills',{method:'GET'}); if(result?.complete!==true||!Array.isArray(result.heldBills))throw new Error('Cloud Held Bills list is incomplete; no local fallback is used.'); window._mviPOSHeldBills=result.heldBills.map(x=>({...x.record,id:String(x.id),updatedAt:String(x.updatedAt||'')})); return window._mviPOSHeldBills; } async function posRetryPendingHeldBill(){ const key='mviapps_pos_held_bill_pending';let pending=null;try{pending=JSON.parse(sessionStorage.getItem(key)||'null');}catch(e){} if(!pending?.record||!pending?.mutationId){alert('No pending Cloud Held Bill request was found.');return;} if(!confirm('Retry the exact pending Held Bill for '+String(pending.record.customerName||'Walk-in customer')+'? It will remain a draft and will not post stock or accounts.'))return; try{ await window.mviappsProductionCloud.businessDataRequest('/business/pos/held-bills',{method:'POST',id:pending.record.id,record:pending.record,mutationId:pending.mutationId}); sessionStorage.removeItem(key);alert('Held Bill is confirmed in Production Cloud.');await posRecallBill(); }catch(e){alert((e?.message||'Cloud Held Bill status is unresolved.')+' The exact draft request remains saved for a safe retry.');} } async function posHoldBill(){ const rows=posGetRows(); if(!rows.length){alert('Please add at least one item before holding the bill.');return;} const date=document.getElementById('posDate')?.value||''; if(!ensureEntryDateInActiveFY(date,'Date'))return; let pending=null;try{pending=JSON.parse(sessionStorage.getItem('mviapps_pos_held_bill_pending')||'null');}catch(e){} if(pending?.record&&pending?.mutationId){await posRetryPendingHeldBill();return;} const customerId=document.getElementById('posCustomer')?.value||''; const customerEl=document.getElementById('posCustomer'); const customerName=customerEl?.selectedOptions?.[0]?.textContent||'Walk-in / Cash Customer'; const items=rows.map(tr=>({itemId:tr.dataset.itemId||'',qty:Number(tr.querySelector('.pos-row-qty')?.value)||0,rate:Number(tr.querySelector('.pos-row-rate')?.value)||0,discount:Number(tr.querySelector('.pos-row-disc')?.value)||0})); if(items.some(x=>x.qty<=0)){alert('Please enter a valid quantity for every item.');return;} const record={id:'POS-HOLD-'+crypto.randomUUID(),createdAt:new Date().toISOString(),date,customerId,customerName,paymentMode:document.getElementById('posPaymentMode')?.value||'Cash',amountReceived:Number(document.getElementById('posAmountReceived')?.value)||0,bankAccount:document.getElementById('posBankAccount')?.value||'',reference:(document.getElementById('posReference')?.value||'').trim(),dueDate:document.getElementById('posDueDate')?.value||'',items,total:posGetTotal()}; const mutationId='pos-held-bill-'+crypto.randomUUID();sessionStorage.setItem('mviapps_pos_held_bill_pending',JSON.stringify({record,mutationId})); try{ await window.mviappsProductionCloud.businessDataRequest('/business/pos/held-bills',{method:'POST',id:record.id,record,mutationId}); sessionStorage.removeItem('mviapps_pos_held_bill_pending');alert('Bill held successfully in Production Cloud. No stock or accounting entry was posted.');clearPOSBill(); }catch(e){alert((e?.message||'Cloud Held Bill save failed.')+' The exact draft request is retained in this browser session for safe retry.');} } function posCloseRecallBox(){document.getElementById('mviPosRecallOverlay')?.remove();} async function posDeleteHeldBill(id){ const held=Array.isArray(window._mviPOSHeldBills)?window._mviPOSHeldBills:[],b=held.find(x=>String(x.id)===String(id)); if(!b||!b.updatedAt){alert('Cloud Held Bill version is missing. Refresh the list before deleting.');return;} if(!confirm('Delete this Cloud Held Bill draft? No stock or accounting entry will be affected.'))return; try{await window.mviappsProductionCloud.businessDataRequest('/business/pos/held-bills',{method:'DELETE',id:String(b.id),mutationId:'pos-held-delete-'+crypto.randomUUID(),expectedUpdatedAt:b.updatedAt});await posRecallBill();} catch(e){alert(e?.message||'Cloud Held Bill delete failed. Refresh and verify before retrying.');} } async function posRecallBill(){ posCloseRecallBox(); let held=[];try{held=await posGetHeldBills();}catch(e){alert('Cloud Held Bills could not be loaded. '+(e?.message||''));return;} if(!held.length){alert('No Cloud Held Bills found.');return;} const rows=held.map(b=>`
${escapeHtml(b.customerName||'Walk-in / Cash Customer')}
${escapeHtml((b.date||'').split('-').reverse().join('/'))} · ${b.items?.length||0} item(s) · ₹ ${Number(b.total||0).toFixed(2)} · ${escapeHtml(b.paymentMode||'Cash')}
`).join(''); const ov=document.createElement('div');ov.id='mviPosRecallOverlay';ov.style.cssText='position:fixed;inset:0;background:rgba(15,23,42,.45);z-index:10020;display:flex;align-items:center;justify-content:center;padding:16px;box-sizing:border-box'; ov.innerHTML=`

Cloud Held Bills

Shared Production Cloud drafts · no stock or accounts are posted until checkout
${rows}
`; document.body.appendChild(ov); } async function posRecallHeldBill(id){ const held=Array.isArray(window._mviPOSHeldBills)?window._mviPOSHeldBills:[],b=held.find(x=>String(x.id)===String(id)); if(!b)return; if(!ensureEntryDateInActiveFY(b.date,'Bill Date'))return; const items=posGetItems(); for(const it of (b.items||[])){ const item=items.find(x=>String(x.id)===String(it.itemId));const available=posFindStock(it.itemId); if(!item){alert('An Item in this Cloud Held Bill no longer exists. The draft was not recalled.');return;} if(Number(it.qty)>available){alert(`Insufficient current stock for ${item.name||'an item'} while recalling this draft. Available quantity is ${available} ${item.unit||''}.`);return;} } if(posGetRows().length&&!confirm('Current POS bill will be cleared. Continue recalling this Cloud Held Bill?'))return; posCloseRecallBox();clearPOSBill(true); const d=document.getElementById('posDate'),dd=document.getElementById('posDateDisplay');if(d)d.value=b.date||'';if(dd)dd.value=b.date?b.date.split('-').reverse().join('/') : ''; posLoadCustomers();const c=document.getElementById('posCustomer');if(c){c.value=b.customerId||'';posSyncCustomerPickerLabel();} posLoadBankAccounts(b.bankAccount||'');const p=document.getElementById('posPaymentMode');if(p){p.value=b.paymentMode||'Cash';posPaymentModeChanged();} const ba=document.getElementById('posBankAccount');if(ba)ba.value=b.bankAccount||''; const ref=document.getElementById('posReference');if(ref)ref.value=b.reference||''; const due=document.getElementById('posDueDate');if(due)due.value=b.dueDate||''; const received=document.getElementById('posAmountReceived');if(received)received.value=b.paymentMode==='Credit'?'0':String(b.amountReceived||0); for(const it of (b.items||[])){posAddItem(it.itemId);const tr=posGetRows().find(r=>String(r.dataset.itemId)===String(it.itemId));if(tr){tr.querySelector('.pos-row-qty').value=String(it.qty);tr.querySelector('.pos-row-rate').value=String(it.rate);tr.querySelector('.pos-row-disc').value=String(it.discount||0);posRecalcRow(tr);}} posRefreshNumbers();document.getElementById('posItemSearch')?.focus(); try{await window.mviappsProductionCloud.businessDataRequest('/business/pos/held-bills',{method:'DELETE',id:String(b.id),mutationId:'pos-held-recall-'+crypto.randomUUID(),expectedUpdatedAt:b.updatedAt});window._mviPOSHeldBills=held.filter(x=>String(x.id)!==String(b.id));alert('Cloud Held Bill recalled successfully and removed from the held list. Review current stock and totals before checkout.');} catch(e){alert('The draft is loaded into the POS form, but its Cloud copy could not be removed. Do not recall it again; refresh Held Bills and delete the duplicate draft after confirming this form is safe. '+(e?.message||''));} } function clearPOSBill(silent=false){ if(!silent && posGetRows().length){ if(!confirm('Current POS bill will be cleared. Continue?'))return; } window._mviPOSEditingId=null; const saveBtn=document.querySelector('.mvi-pos-save');if(saveBtn)saveBtn.innerHTML='Save & Print Bill [Ctrl+P]'; const s=document.getElementById('posItemSearch');if(s)s.value=''; const b=document.getElementById('posItemsBody');if(b)b.innerHTML='Search and select an item to add it to the bill.'; const a=document.getElementById('posAmountReceived');if(a)a.value='0'; const p=document.getElementById('posPaymentMode');if(p){p.value='Cash';posPaymentModeChanged();} const ref=document.getElementById('posReference');if(ref)ref.value=''; const due=document.getElementById('posDueDate');if(due)due.value=''; const d=document.getElementById('posDate'),dd=document.getElementById('posDateDisplay');const today=new Date().toISOString().slice(0,10);if(d)d.value=today;if(dd)dd.value=today.split('-').reverse().join('/'); posRefreshNumbers(); posLoadCustomers(); s?.focus(); } function posPrintBill(record){ const party=record.customerName||'Walk-in / Cash Customer'; const win=window.open('','_blank');if(!win){alert('Please allow pop-ups to print the POS bill.');return;} const rows=record.items.map((it,i)=>`${i+1}${escapeHtml(it.itemName||'')}${it.qty}₹ ${Number(it.rate).toFixed(2)}₹ ${Number(it.amount).toFixed(2)}`).join(''); win.document.write(`${escapeHtml(record.invoiceNo)}
MVIApps
POS BILL
Bill: ${escapeHtml(record.invoiceNo)}
Date: ${escapeHtml(record.date.split('-').reverse().join('/'))}
Customer: ${escapeHtml(party)}
${rows}
#ItemQtyRateAmt
Total: ₹ ${Number(record.total).toFixed(2)}
Payment: ${escapeHtml(record.paymentMode)}
${record.bankAccount?`
Bank: ${escapeHtml((document.getElementById('posBankAccount')?.selectedOptions?.[0]?.textContent)||record.bankAccount)}
`:''}${record.reference?`
Reference: ${escapeHtml(record.reference)}
`:''}${record.paymentMode==='Credit'?`
Due: ₹ ${Number(record.total).toFixed(2)}${record.dueDate?` · Due Date: ${escapeHtml(record.dueDate.split('-').reverse().join('/'))}`:''}
`:`
Received: ₹ ${Number(record.amountReceived||0).toFixed(2)} · Change: ₹ ${Number(record.changeAmount||0).toFixed(2)}
`}`); win.document.close();win.focus();setTimeout(()=>{win.print();setTimeout(()=>win.close(),500)},300); } function mviPOSSyncCashLedger(record, previousRecord){ try{ const cashKey='mviapps_cash_transactions'; let tx=JSON.parse(localStorage.getItem(cashKey)||'[]'); if(!Array.isArray(tx))tx=[]; const invoiceNo=String(record?.invoiceNo||''); const oldInvoiceNo=String(previousRecord?.invoiceNo||invoiceNo); const match=(x)=>String(x?.source||'').toLowerCase()==='pos sale' && String(x?.ref||'')===oldInvoiceNo; const oldTxIndex=previousRecord?tx.findIndex(match):-1; const oldTx=oldTxIndex>=0?tx[oldTxIndex]:null; const oldCashAmount=oldTx?Number(oldTx.amount)||0:0; const newCashAmount=String(record?.paymentMode||'')==='Cash' ? Math.max(0,Number(record?.total)||0) : 0; if(oldTxIndex>=0)tx.splice(oldTxIndex,1); if(newCashAmount>0){ tx.push({id:oldTx?.id||('pos-cash-'+String(record?.id||Date.now())),type:'POS Sale',description:'POS Sale '+invoiceNo,date:record?.date||new Date().toISOString().slice(0,10),amount:newCashAmount,source:'POS Sale',ref:invoiceNo}); } const delta=newCashAmount-oldCashAmount; if(Math.abs(delta)>0.000001)saveCashBalance(getCashBalance()+delta); localStorage.setItem(cashKey,JSON.stringify(tx)); }catch(e){console.error('POS cash ledger sync failed',e);} } async function savePOSBill(){ if(window._mviPOSSaving)return; window._mviPOSSaving=true; const saveBtn=document.querySelector('.mvi-pos-save');const originalSaveText=saveBtn?.textContent||'Save & Print Bill [Ctrl+P]'; if(saveBtn){saveBtn.disabled=true;saveBtn.textContent='Saving to Cloud…';} const unlock=()=>{window._mviPOSSaving=false;if(saveBtn){saveBtn.disabled=false;saveBtn.textContent=originalSaveText;}}; try{ let pendingCheckout=window._mviPOSPendingCheckout||null; if(!pendingCheckout){try{pendingCheckout=JSON.parse(sessionStorage.getItem('mviapps_pos_pending_cloud_checkout')||'null');}catch{pendingCheckout=null;}} if(pendingCheckout?.mutationId&&pendingCheckout?.record?.id){ const pendingRecord=pendingCheckout.record; const visibleRows=posGetRows(); const visibleItems=visibleRows.map(tr=>({ itemId:String(tr.dataset.itemId||''), qty:Number(tr.querySelector('.pos-row-qty')?.value)||0, rate:Number(tr.querySelector('.pos-row-rate')?.value)||0, discount:Number(tr.querySelector('.pos-row-disc')?.value)||0 })).sort((a,b)=>a.itemId.localeCompare(b.itemId)); const pendingItems=(pendingRecord.items||[]).map(it=>({ itemId:String(it.itemId||''), qty:Number(it.qty)||0, rate:Number(it.rate)||0, discount:Number(it.discount)||0 })).sort((a,b)=>a.itemId.localeCompare(b.itemId)); const sameItems=JSON.stringify(visibleItems)===JSON.stringify(pendingItems); const visibleDate=document.getElementById('posDate')?.value||''; const visibleMode=document.getElementById('posPaymentMode')?.value||'Cash'; const visibleCustomer=document.getElementById('posCustomer')?.value||''; const visibleReceived=Number(document.getElementById('posAmountReceived')?.value)||0; const visibleReference=document.getElementById('posReference')?.value.trim()||''; const sameHeader=visibleDate===String(pendingRecord.date||'') && visibleMode===String(pendingRecord.paymentMode||'Cash') && visibleCustomer===String(pendingRecord.customer||'') && Math.abs(visibleReceived-Number(pendingRecord.amountReceived||0))<0.000001 && visibleReference===String(pendingRecord.reference||''); const exactVisibleBill=sameItems&&sameHeader; if(!exactVisibleBill){ // The visible draft is different. Never send the old request again until a fresh, // complete Cloud invoice read proves whether that exact checkout already committed. await mviPOSLoadCloudContext(); const cloudInvoices=window._mviPOSCloudContext?.salesInvoices; if(!Array.isArray(cloudInvoices))throw new Error('Cloud Sales Invoice history could not be verified completely. Keep this bill unchanged; no checkout request was sent.'); const committed=cloudInvoices.find(x=>String(x.id||'')===String(pendingRecord.id) ||(String(x.invoiceNo||'')&&String(x.invoiceNo)===String(pendingRecord.invoiceNo))); if(committed){ window._mviPOSPendingCheckout=null; try{sessionStorage.removeItem('mviapps_pos_pending_cloud_checkout');}catch{} alert('The earlier POS checkout is already present in Production Cloud. Its pending retry marker has been cleared. Your current bill was not saved; press Save once to submit this current bill separately.'); return; } // Cloud returned a complete invoice list and the old invoice is absent. Archive // the exact uncertain request locally for audit, then release the active retry lock. const archiveKey='mviapps_pos_abandoned_checkout_archive'; try{ const prior=JSON.parse(sessionStorage.getItem(archiveKey)||'[]'); const list=Array.isArray(prior)?prior:[]; if(!list.some(x=>String(x?.mutationId||'')===String(pendingCheckout.mutationId))){ list.push({...pendingCheckout,archivedAt:new Date().toISOString(),reason:'Complete Cloud Sales Invoice read confirmed invoice absent before a changed draft was submitted.'}); sessionStorage.setItem(archiveKey,JSON.stringify(list.slice(-10))); } }catch(archiveError){ throw new Error('Cloud confirms the previous invoice is absent, but its pending request could not be archived safely. No new checkout was sent. '+(archiveError?.message||'')); } window._mviPOSPendingCheckout=null; sessionStorage.removeItem('mviapps_pos_pending_cloud_checkout'); pendingCheckout=null; }else{ // Exact same bill: retry the original mutation ID (idempotent Cloud request). const retry=await window.mviappsProductionCloud.businessDataRequest('/business/pos/checkout',{method:'POST',id:pendingRecord.id,record:pendingRecord,mutationId:pendingCheckout.mutationId}); if(retry?.saved!==true||retry?.atomic!==true)throw new Error('Pending POS checkout is not yet confirmed. Keep the original bill unchanged and verify Cloud Bill History before retrying.'); window._mviPOSPendingCheckout=null;try{sessionStorage.removeItem('mviapps_pos_pending_cloud_checkout');}catch{} alert('Pending POS checkout was confirmed in Production Cloud.');posPrintBill(pendingRecord);await mviPOSLoadCloudContext();clearPOSBill();return; } } if(!window._mviPOSCloudContext?.loadedAt)throw new Error('Production Cloud context is not ready. Refresh POS before saving.'); if(!ensureEntryDateInActiveFY(document.getElementById('posDate')?.value,'Date'))return; const rows=posGetRows();if(!rows.length)throw new Error('Please add at least one item.'); const paymentMode=document.getElementById('posPaymentMode')?.value||'Cash'; if(window._mviPOSEditingId)throw new Error('Editing an already-posted POS bill is temporarily blocked. Use a reviewed reversal/correction workflow; no change was made.'); const customerId=document.getElementById('posCustomer')?.value||''; if(paymentMode==='Credit'&&!customerId)throw new Error('Select a Cloud Customer for a Credit POS bill.'); const party=customerId?window._mviPOSCloudContext.parties.find(p=>String(p.id)===String(customerId)):null; if(paymentMode==='Credit'&&!party)throw new Error('Selected Customer is not present in Production Cloud.'); const bankAccountId=['Bank','UPI','Card'].includes(paymentMode)?(document.getElementById('posBankAccount')?.value||''):''; if(['Bank','UPI','Card'].includes(paymentMode)&&!bankAccountId)throw new Error('Select the receiving Cloud Bank account for this tender.'); const dueDate=document.getElementById('posDueDate')?.value||'';if(dueDate&&!ensureEntryDateInActiveFY(dueDate,'Due Date'))return; if(dueDate&&dueDate<(document.getElementById('posDate')?.value||''))throw new Error('Due Date cannot be earlier than the bill date.'); const items=posGetItems();const editingId=window._mviPOSEditingId?String(window._mviPOSEditingId):''; const existing=editingId?(window._mviPOSHistoryInvoices||[]).find(x=>String(x.id)===editingId)||(window._mviPOSCloudContext.salesInvoices||[]).find(x=>String(x.id)===editingId):null; if(editingId&&(!existing||!existing.updatedAt))throw new Error('Latest Cloud bill version is unavailable. Reopen POS Bill History and retry.'); const invoiceNo=existing?.invoiceNo||('POS-'+new Date().toISOString().replace(/[-:TZ.]/g,'').slice(0,14)+'-'+crypto.randomUUID().slice(0,6).toUpperCase()); const stockRows=(window._mviPOSCloudContext.balances||[]).map(x=>({...x,balances:{...(x.balances||{})}}));const godowns=window._mviPOSCloudContext.godowns||[]; if(existing){for(const oldLine of (existing.items||[])){const row=stockRows.find(x=>String(x.itemId)===String(oldLine.itemId));if(!row)continue;const alloc=Array.isArray(oldLine.stockAllocations)&&oldLine.stockAllocations.length?oldLine.stockAllocations:[{godownId:oldLine.godownId||'',qty:Number(oldLine.qty)||0}];for(const a of alloc){const gid=String(a.godownId||godowns.find(g=>String(g.name||'').toLowerCase()==='main godown')?.id||godowns[0]?.id||'');row.balances[gid]=(Number(row.balances[gid])||0)+(Number(a.qty)||0);}row.total=Object.values(row.balances).reduce((sum,v)=>sum+(Number(v)||0),0);}} const saleItems=rows.map(tr=>{const item=items.find(i=>String(i.id)===String(tr.dataset.itemId));const qty=Number(tr.querySelector('.pos-row-qty')?.value)||0,rate=Number(tr.querySelector('.pos-row-rate')?.value)||0,discount=Number(tr.querySelector('.pos-row-disc')?.value)||0;if(!item||qty<=0)throw new Error('Every POS line must reference a Cloud Item and have a positive quantity.');return {itemId:String(item.id),itemName:item.name||'',category:item.category||'',qty,rate,discount,gst:0,amount:qty*rate*(1-discount/100)};}); const remainingByItem=new Map();for(const r of stockRows)remainingByItem.set(String(r.itemId),{...r.balances}); for(const line of saleItems){if(String(line.category||'').trim().toLowerCase()==='services')continue;let remaining=line.qty;const available=stockRows.find(x=>String(x.itemId)===line.itemId);if(!available||Number(available.total)0){allocations.push({godownId:gid,qty});balances[gid]-=qty;remaining-=qty;}if(remaining<=1e-9)break;}if(remaining>1e-9)throw new Error('Cloud stock allocation failed for '+line.itemName+'. Refresh stock and retry.');line.godownId=allocations[0]?.godownId||'';line.stockAllocations=allocations;} const date=document.getElementById('posDate')?.value||new Date().toISOString().slice(0,10);const total=saleItems.reduce((sum,x)=>sum+Number(x.amount||0),0); const tendered=paymentMode==='Credit'?0:Number(document.getElementById('posAmountReceived')?.value||total); if(paymentMode!=='Credit'&&(!Number.isFinite(tendered)||tendered+0.0000010.000001)throw new Error('Bank/UPI/Card tender must equal the exact bill total; cash change is supported only for Cash mode.'); const record={id:crypto.randomUUID(),customer:customerId,customerName:party?.name||'',partyId:customerId,partyName:party?.name||'',date,invoiceNo,paymentMode,bankAccount:bankAccountId,reference:document.getElementById('posReference')?.value.trim()||'',dueDate:paymentMode==='Credit'?dueDate:'',amountReceived:tendered,changeAmount:paymentMode==='Cash'?Math.max(0,tendered-total):0,notes:'POS Sale',items:saleItems,total,totalAmount:total}; const mutationId='pos-checkout-'+crypto.randomUUID(); window._mviPOSPendingCheckout={mutationId,record};try{sessionStorage.setItem('mviapps_pos_pending_cloud_checkout',JSON.stringify({mutationId,record}));}catch{} const checkout=await window.mviappsProductionCloud.businessDataRequest('/business/pos/checkout',{method:'POST',id:record.id,record,mutationId}); if(checkout?.saved!==true||checkout?.atomic!==true)throw new Error('Worker did not confirm the complete atomic POS checkout. Keep this bill unchanged and retry/verify Cloud history before creating another bill.'); window._mviPOSPendingCheckout=null;try{sessionStorage.removeItem('mviapps_pos_pending_cloud_checkout');}catch{} alert('POS bill and its stock/accounting posting were committed together in Production Cloud.'); posPrintBill(record);window._mviPOSEditingId=null;window._mviPOSEditingUpdatedAt=null;await mviPOSLoadCloudContext();clearPOSBill(); }catch(e){alert(e?.message||'Cloud POS save failed. Refresh Cloud data and verify before retrying.');} finally{unlock();} } async function mviPOSLoadCloudContext(){ const bridge=window.mviappsCloudBusinessData,cloud=window.mviappsProductionCloud; if(!bridge?.readAll||!cloud?.posStockSnapshot)throw new Error('Production Cloud POS adapter is unavailable.'); // Load the Cloud masters independently of the stock preflight. A stock snapshot // failure must not hide valid Cloud Items from the POS search; it must only block // adding/checkout until the authoritative balance is verified. const [items,parties,godowns,bankAccounts,salesInvoices]=await Promise.all([ bridge.readAll('items',{pageSize:75,maxPages:100}), bridge.readAll('parties',{pageSize:100,maxPages:100}), bridge.readAll('godowns',{pageSize:100,maxPages:20}), bridge.readAll('bankAccounts',{pageSize:100,maxPages:20}), bridge.readAll('salesInvoices',{pageSize:100,maxPages:100}) ]); for(const [name,result] of Object.entries({items,parties,godowns,bankAccounts,salesInvoices}))if(result.complete!==true)throw new Error('Cloud '+name+' list is incomplete. POS remains read-only until a complete refresh succeeds.'); const unwrap=r=>(r.records||[]).map(x=>({...x.record,id:String(x.id),updatedAt:x.updatedAt||null})); const context={items:unwrap(items),parties:unwrap(parties),godowns:unwrap(godowns),bankAccounts:unwrap(bankAccounts),salesInvoices:unwrap(salesInvoices),balances:[],loadedAt:null,stockVerified:false,stockError:null,mastersLoadedAt:new Date().toISOString()}; window._mviPOSCloudContext=context; try{ const snapshot=await cloud.posStockSnapshot(); if(!snapshot||!Array.isArray(snapshot.balances)||!Array.isArray(snapshot.godowns))throw Object.assign(new Error('Worker returned an incomplete authoritative stock snapshot.'),{code:'INVALID_STOCK_SNAPSHOT_RESPONSE'}); context.balances=snapshot.balances; context.loadedAt=snapshot.loadedAt||new Date().toISOString(); context.stockVerified=true; }catch(snapshotError){ context.stockError={message:snapshotError?.message||String(snapshotError),code:snapshotError?.code||'STOCK_SNAPSHOT_FAILED',status:snapshotError?.status||null}; console.error('[MVIApps POS STOCK SNAPSHOT ERROR]',snapshotError); } window._mviPOSCloudContext=context; return context; } function initPointOfSale(){ posLoadCustomers();posLoadBankAccounts();posPaymentModeChanged();posRefreshNumbers(); const status=document.getElementById('posCloudStatus'); if(status)status.textContent='Refreshing Production Cloud Item Master and stock…'; mviPOSLoadCloudContext().then(context=>{ posLoadCustomers();posLoadBankAccounts();renderPOSItemSuggestions();posRefreshNumbers(); if(status){ if(context.stockVerified)status.textContent='Connected to Production Cloud · Item Master loaded · Authoritative Godown stock verified'; else status.textContent='Cloud Items loaded ('+context.items.length+'), but stock verification failed ['+context.stockError.code+']: '+context.stockError.message+' · POS saving remains disabled.'; } if(!context.stockVerified)console.warn('[MVIApps POS] Stock preflight unavailable; checkout remains blocked.',context.stockError); }).catch(error=>{if(status)status.textContent='Cloud Item Master unavailable — POS saving is disabled. '+(error?.code?('['+error.code+'] '):'')+(error?.message||'');console.error('[MVIApps POS Cloud]',error);}); document.getElementById('posItemSearch')?.focus(); document.removeEventListener('keydown',mviPOSKeyHandler); document.addEventListener('keydown',mviPOSKeyHandler); } function mviPOSKeyHandler(e){ if(!document.getElementById('posItemSearch'))return; if(e.ctrlKey&&e.key.toLowerCase()==='t'){e.preventDefault();clearPOSBill(false);} if(e.ctrlKey&&e.key.toLowerCase()==='h'){e.preventDefault();posHoldBill();} if(e.ctrlKey&&e.key.toLowerCase()==='b'){e.preventDefault();posBillHistory();} if(e.ctrlKey&&e.key.toLowerCase()==='r'){e.preventDefault();posRecallBill();} if(e.ctrlKey&&e.key.toLowerCase()==='p'){e.preventDefault();savePOSBill();} if(e.ctrlKey&&e.key.toLowerCase()==='m'){e.preventDefault();posSetCreditPayment();} if(e.key==='F5'){e.preventDefault();posQuickItemEntry();} if(e.key==='F5'){e.preventDefault();posQuickItemEntry();} if(e.key==='F2'){e.preventDefault();posFocusQty();} if(e.key==='F3'){e.preventDefault();posFocusDiscount();} if(e.key==='F4'){e.preventDefault();posRemoveSelected();} if(e.key==='F11'){e.preventDefault();posFocusCustomer();} } function saleInvoices(){ return `

Sales Invoices

View, search, print, modify and delete your saved sales invoices.

From
To
DateInvoice No.CustomerItemsPayment ModeTotalAction
`; } function openSaleInvoiceFilterDatePicker(which){const picker=document.getElementById(which==='from'?'saleInvoiceFrom':'saleInvoiceTo');if(!picker)return;try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();}catch(e){try{picker.click();}catch(ignore){}}} function syncSaleInvoiceFilterDateDisplay(which){const picker=document.getElementById(which==='from'?'saleInvoiceFrom':'saleInvoiceTo'),display=document.getElementById(which==='from'?'saleInvoiceFromDisplay':'saleInvoiceToDisplay');if(display)display.value=picker?.value?picker.value.split('-').reverse().join('/') : '';} function prepareSaleInvoiceFilterManualDate(which){const display=document.getElementById(which==='from'?'saleInvoiceFromDisplay':'saleInvoiceToDisplay');if(display&&!display.dataset.manualReady){display.value='';display.dataset.manualReady='1';}} function formatSaleInvoiceFilterDateInput(el){if(!el)return;el.dataset.manualReady='1';const digits=(el.value||'').replace(/\D/g,'').slice(0,8);let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out;} function syncSaleInvoiceFilterManualDate(which){const display=document.getElementById(which==='from'?'saleInvoiceFromDisplay':'saleInvoiceToDisplay'),picker=document.getElementById(which==='from'?'saleInvoiceFrom':'saleInvoiceTo');if(!display||!picker)return;let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/');if(!value){delete display.dataset.manualReady;picker.value='';renderSaleInvoices();return;}const parts=value.split('/');if(parts.length===3){const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2];if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){const test=new Date(Number(yyyy),Number(mm)-1,Number(dd));if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;renderSaleInvoices();return;}}}syncSaleInvoiceFilterDateDisplay(which);delete display.dataset.manualReady;renderSaleInvoices();} function renderSaleInvoices(){ const rows=document.getElementById('saleInvoiceRows');if(!rows)return; const arr=filterByActiveFinancialYear(JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]')); const q=(document.getElementById('saleInvoiceSearch')?.value||'').toLowerCase(),from=document.getElementById('saleInvoiceFrom')?.value||'',to=document.getElementById('saleInvoiceTo')?.value||''; const filtered=arr.filter(x=>(!q||String(x.invoiceNo||'').toLowerCase().includes(q)||String(x.customerName||x.customer||'').toLowerCase().includes(q))&&(!from||x.date>=from)&&(!to||x.date<=to)).sort((a,b)=>(b.date||'').localeCompare(a.date||'')||(b.id-a.id)); rows.innerHTML=filtered.length?filtered.map(x=>`${escapeHtml(x.date||'')}${escapeHtml(x.invoiceNo||'')}${escapeHtml(x.customerName||x.customer||'')}${x.items?.length||0}${escapeHtml(x.paymentMode||'')}${escapeHtml(x.total||'₹ 0.00')} `).join(''):`No sales invoices found. Click “+ New Sale” to create one.`; } function getSaleInvoice(id){return JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]').find(x=>String(x.id)===String(id));} function saleItemName(id){const x=JSON.parse(localStorage.getItem('mviapps_items')||'[]').find(i=>String(i.id)===String(id));return x?.name||'Item';} function viewSaleInvoice(id){const x=getSaleInvoice(id);if(!x)return;const items=(x.items||[]).map(it=>`${escapeHtml(saleItemName(it.itemId))}${escapeHtml(getGodowns().find(g=>String(g.id)===String(it.godownId))?.name||'—')}${it.qty}₹ ${Number(it.rate||0).toFixed(2)}${it.discount||0}%${it.gst||0}%₹ ${(Number(it.qty||0)*Number(it.rate||0)*(1-Number(it.discount||0)/100)*(1+Number(it.gst||0)/100)).toFixed(2)}`).join(''); const old=document.getElementById('saleInvoiceModal');if(old)old.remove();document.body.insertAdjacentHTML('beforeend',`

Sales Invoice ${escapeHtml(x.invoiceNo||'')}

${escapeHtml(x.date||'')} · ${escapeHtml(x.customerName||x.customer||'')}


${items}
ItemGodownQtyRateDiscountGSTAmount
Grand Total: ${escapeHtml(x.total||'₹ 0.00')}
`); } function getCompanyDetails(){ const g=k=>localStorage.getItem(k)||''; return {name:g('mviapps_companyName'),trade:g('mviapps_tradeName'),address:g('mviapps_companyAddress'),city:g('mviapps_companyCity'),state:g('mviapps_companyState'),pin:g('mviapps_companyPin'),mobile:g('mviapps_companyMobile'),email:g('mviapps_companyEmail'),website:g('mviapps_companyWebsite'),pan:g('mviapps_companyPan'),gstin:g('mviapps_companyGstin'),logo:g('mviapps_company_logo'),signature:g('mviapps_authorized_signature')}; } function companyPrintHeader(){ const c=getCompanyDetails(), name=c.name||'Company Name'; const address=[c.address,c.city,c.state,c.pin].filter(Boolean).join(', '); const contact=[c.mobile,c.email,c.website].filter(Boolean).join(' | '); const tax=[c.gstin?'GSTIN: '+c.gstin:'',c.pan?'PAN: '+c.pan:''].filter(Boolean).join('   |   '); const logo=c.logo?``:''; return `
${logo?`
${logo}
`:''}
${escapeHtml(name)}
${c.trade?`
${escapeHtml(c.trade)}
`:''}${address?`
${escapeHtml(address)}
`:''}${contact?`
${escapeHtml(contact)}
`:''}${tax?`
${tax}
`:''}
`; } function companySignature(){const c=getCompanyDetails();return c.signature?`
Authorized Signatory
`:''} function printSaleInvoice(id){ const x=getSaleInvoice(id);if(!x)return; const w=window.open('','_blank');if(!w){alert('Please allow pop-ups to print the invoice.');return;} const c=getCompanyDetails(), parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const party=parties.find(p=>String(p.id)===String(x.customer))||parties.find(p=>String(p.name||'').toLowerCase()===String(x.customerName||x.customer||'').toLowerCase())||{}; const esc=escapeHtml; const money=n=>'₹ '+(Number(n)||0).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}); const numberToWords=n=>{ n=Math.round(Number(n)||0);if(n===0)return 'Zero Rupees only'; const ones=['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen']; const tens=['','','Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety']; const under1000=v=>{let a=[];if(v>=100){a.push(ones[Math.floor(v/100)]+' Hundred');v%=100;if(v)a.push('and');}if(v>=20){a.push(tens[Math.floor(v/10)]);if(v%10)a.push(ones[v%10]);}else if(v>0)a.push(ones[v]);return a.join(' ');}; let parts=[];const cr=Math.floor(n/10000000);n%=10000000;const lk=Math.floor(n/100000);n%=100000;const th=Math.floor(n/1000);n%=1000; if(cr)parts.push(under1000(cr)+' Crore');if(lk)parts.push(under1000(lk)+' Lakh');if(th)parts.push(under1000(th)+' Thousand');if(n)parts.push(under1000(n)); return parts.join(' ')+' Rupees only'; }; const items=x.items||[]; let subtotal=0; const rows=items.map((it,i)=>{ const qty=Number(it.qty)||0,rate=Number(it.rate)||0,discount=Number(it.discount)||0,gst=Number(it.gst)||0; const base=qty*rate,disc=base*discount/100,taxable=base-disc,tax=taxable*gst/100,amount=taxable+tax;subtotal+=base; const item=JSON.parse(localStorage.getItem('mviapps_items')||'[]').find(v=>String(v.id)===String(it.itemId))||{}; const unit=item.unit||'Pcs'; return `${i+1}${esc(saleItemName(it.itemId))}${qty}${esc(unit)}${money(rate)}${money(amount)}`; }).join(''); const total=Number(String(x.total||'').replace(/[^0-9.-]/g,''))||items.reduce((a,it)=>a+(Number(it.qty)||0)*(Number(it.rate)||0)*(1-(Number(it.discount)||0)/100)*(1+(Number(it.gst)||0)/100),0); const previousBalance=Math.abs(Number(getPartyLedgerOpening(party,x.date))||0); const isCredit=String(x.paymentMode||'').toLowerCase()==='credit'; const received=isCredit?0:total; const balance=isCredit?total:0; const currentBalance=previousBalance+balance; const address=[c.address,c.city,c.state,c.pin].filter(Boolean).join(', '); const contact=[c.mobile?'Phone: '+c.mobile:'',c.email?'Email: '+c.email:''].filter(Boolean).join('     '); const logo=c.logo?``:''; const signature=c.signature?``:''; const terms=x.notes||'Thanks for doing business with us!'; w.document.write(`${esc(localStorage.getItem('mviapps_invoiceTitle')||'Tax Invoice')} ${esc(x.invoiceNo||'')}
${esc(localStorage.getItem('mviapps_invoiceTitle')||'Tax Invoice')}
${logo}
${esc(c.name||'Company Name')}
${c.trade?`
${esc(c.trade)}
`:''}${address?`
${esc(address)}
`:''}${contact?`
${contact}
`:''}
Invoice No.:  ${esc(x.invoiceNo||'')}
Date:  ${esc((x.date||'').split('-').reverse().join('/'))}
Bill To:
${esc(x.customerName||x.customer||'')}${party.address?`
${esc(party.address)}
`:''}${party.mobile?`
Phone: ${esc(party.mobile)}
`:''}${party.gstin?`
GSTIN: ${esc(party.gstin)}
`:''}
${rows}
#Item NameQuantityUnitPrice Unit(₹)Amount(₹)
Total${items.reduce((a,it)=>a+(Number(it.qty)||0),0)}${money(total)}
Sub Total${money(subtotal)}
Total${money(total)}
Invoice Amount in Words${esc(numberToWords(total))}
Previous Balance${money(previousBalance)}
Current Balance${money(currentBalance)}
Terms & Conditions:
${esc(terms)}
For ${esc(c.name||'Company Name')}:
${signature}
Authorized Signatory
`); w.document.close();w.focus();setTimeout(()=>{try{w.print();w.onafterprint=()=>w.close();}catch(e){console.error('Sales invoice print error:',e);}},300); } function startNewSaleInvoice(){window._editingSaleId=null;const b=document.querySelector('[onclick="saveSaleInvoice()"]');if(b)b.textContent='Save Invoice';} function editSaleInvoice(id){const x=getSaleInvoice(id);if(!x)return;show('sale-invoices');setTimeout(()=>{const page=document.getElementById('content');page.innerHTML=invoice('Sale Invoice');document.getElementById('saleCustomer').value=x.customer||'';document.getElementById('saleDate').value=x.date||'';syncSalesInvoiceDateDisplay();document.getElementById('saleInvoiceNo').value=x.invoiceNo||'';document.getElementById('salePaymentMode').value=x.paymentMode||'Cash';document.getElementById('saleBankAccount').value=x.bankAccount||'';mviappsToggleBankAccount('salePaymentMode','saleBankWrap','saleBankAccount');document.getElementById('saleReference').value=x.reference||'';document.getElementById('saleDueDate').value=x.dueDate||'';syncSalesInvoiceDueDateDisplay();document.getElementById('saleNotes').value=x.notes||'';window._editingSaleId=x.id;const body=document.getElementById('saleInvoiceItems');body.innerHTML='';(x.items||[]).forEach(it=>addSaleInvoiceItemWithData(it));calculateSaleInvoice();const b=document.querySelector('[onclick="saveSaleInvoice()"]');if(b)b.textContent='Update Invoice';},0);} function addSaleInvoiceItemWithData(it){const tr=addSaleInvoiceItemRow(it);if(!tr)return;const sel=tr.querySelector('.sale-item');sel.value=String(it.itemId);saleItemChanged(sel);const gd=tr.querySelector('.sale-godown');if(gd&&it.godownId)gd.value=String(it.godownId);saleGodownChanged(gd);tr.querySelector('.sale-qty').value=it.qty??1;tr.querySelector('.sale-rate').value=it.rate??0;tr.querySelector('.sale-discount').value=it.discount??0;tr.querySelector('.sale-gst').value=it.gst??0;calculateSaleInvoice();} function deleteSaleInvoice(id){if(!confirm('Delete this sales invoice?'))return;const arr=JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]'),x=arr.find(v=>String(v.id)===String(id));localStorage.setItem('mviapps_sales_invoices',JSON.stringify(arr.filter(v=>String(v.id)!==String(id))));if(x){const items=getSortedItems(),gs=getGodowns(),stock=getGodownStock();(x.items||[]).forEach(it=>{if(!it.godownId)return;const item=items.find(i=>String(i.id)===String(it.itemId));if(item)syncGodownStockWithClosing(item,gs);let r=stock.find(v=>String(v.itemId)===String(it.itemId)&&String(v.godownId)===String(it.godownId));if(!r){r={id:Date.now()+Math.random(),itemId:it.itemId,godownId:it.godownId,qty:0};stock.push(r)}r.qty=(Number(r.qty)||0)+(Number(it.qty)||0);});saveGodownStock(stock);const moves=JSON.parse(localStorage.getItem('mviapps_stock_movements')||'[]');localStorage.setItem('mviapps_stock_movements',JSON.stringify(moves.filter(m=>!(m.type==='sale'&&String(m.ref)===String(x.invoiceNo)))));if(String(x.notes||'')==='POS Sale'){const cashKey='mviapps_cash_transactions';let tx=JSON.parse(localStorage.getItem(cashKey)||'[]');if(!Array.isArray(tx))tx=[];const ref=String(x.invoiceNo||'');const removedAmount=tx.filter(t=>String(t?.source||'').toLowerCase()==='pos sale'&&String(t?.ref||'')===ref).reduce((sum,t)=>sum+(Number(t?.amount)||0),0);tx=tx.filter(t=>!(String(t?.source||'').toLowerCase()==='pos sale'&&String(t?.ref||'')===ref));localStorage.setItem(cashKey,JSON.stringify(tx));if(removedAmount>0)saveCashBalance(Math.max(0,getCashBalance()-removedAmount));}}renderSaleInvoices();} function purchaseInvoices(){ return `

Purchase Invoices

View, search, print and modify your saved purchase invoices.

From
To
DateBill No.SupplierItemsPayment ModeTotalAction
`; } function openPurchaseInvoiceFilterDatePicker(which){ const picker=document.getElementById(which==='from'?'purchaseInvoiceFrom':'purchaseInvoiceTo'); if(!picker)return; try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();} catch(e){try{picker.click();}catch(ignore){}} } function syncPurchaseInvoiceFilterDateDisplay(which){ const picker=document.getElementById(which==='from'?'purchaseInvoiceFrom':'purchaseInvoiceTo'); const display=document.getElementById(which==='from'?'purchaseInvoiceFromDisplay':'purchaseInvoiceToDisplay'); if(display)display.value=picker?.value?picker.value.split('-').reverse().join('/') : ''; } function preparePurchaseInvoiceFilterManualDate(which){ const display=document.getElementById(which==='from'?'purchaseInvoiceFromDisplay':'purchaseInvoiceToDisplay'); if(display&&!display.dataset.manualReady){display.value='';display.dataset.manualReady='1';} } function formatPurchaseInvoiceFilterDateInput(el){ if(!el)return;el.dataset.manualReady='1'; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out; } function syncPurchaseInvoiceFilterManualDate(which){ const display=document.getElementById(which==='from'?'purchaseInvoiceFromDisplay':'purchaseInvoiceToDisplay'); const picker=document.getElementById(which==='from'?'purchaseInvoiceFrom':'purchaseInvoiceTo'); if(!display||!picker)return; let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/'); if(!value){picker.value='';delete display.dataset.manualReady;renderPurchaseInvoices();return;} const parts=value.split('/'); if(parts.length===3){ const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2]; if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){ const test=new Date(Number(yyyy),Number(mm)-1,Number(dd)); if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){ picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;renderPurchaseInvoices();return; } } } syncPurchaseInvoiceFilterDateDisplay(which);delete display.dataset.manualReady; } function syncPurchaseInvoiceFilterDateDisplays(){syncPurchaseInvoiceFilterDateDisplay('from');syncPurchaseInvoiceFilterDateDisplay('to');} function renderPurchaseInvoices(){ const rows=document.getElementById('purchaseInvoiceRows'); if(!rows)return; const arr=filterByActiveFinancialYear(JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]')); const q=(document.getElementById('purchaseInvoiceSearch')?.value||'').toLowerCase(); const from=document.getElementById('purchaseInvoiceFrom')?.value||'',to=document.getElementById('purchaseInvoiceTo')?.value||''; const filtered=arr.filter(x=>(!q||String(x.invoiceNo||'').toLowerCase().includes(q)||String(x.supplier||'').toLowerCase().includes(q))&&(!from||x.date>=from)&&(!to||x.date<=to)).sort((a,b)=>(b.date||'').localeCompare(a.date||'')||(b.id-a.id)); rows.innerHTML=filtered.length?filtered.map(x=>`${escapeHtml(x.date||'')}${escapeHtml(x.invoiceNo||'')}${escapeHtml(x.supplierName||x.supplier||'')}${x.items?.length||0}${escapeHtml(x.paymentMode||'')}${escapeHtml(x.total||'₹ 0.00')} `).join(''):`No purchase invoices found. Save a purchase first.`; } function getPurchaseInvoice(id){return JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]').find(x=>String(x.id)===String(id));} function purchaseItemName(id){const x=JSON.parse(localStorage.getItem('mviapps_items')||'[]').find(i=>String(i.id)===String(id));return x?.name||'Item';} function viewPurchaseInvoice(id){const x=getPurchaseInvoice(id);if(!x)return;const items=(x.items||[]).map(it=>`${escapeHtml(purchaseItemName(it.itemId))}${it.qty}₹ ${Number(it.rate||0).toFixed(2)}${it.discount||0}%${it.gst||0}%₹ ${(Number(it.qty||0)*Number(it.rate||0)*(1-Number(it.discount||0)/100)*(1+Number(it.gst||0)/100)).toFixed(2)}`).join(''); const old=document.getElementById('purchaseInvoiceModal'); if(old)old.remove(); document.body.insertAdjacentHTML('beforeend',`

Purchase Invoice ${escapeHtml(x.invoiceNo||'')}

${escapeHtml(x.date||'')} · ${escapeHtml(x.supplierName||x.supplier||'')}


${items}
ItemQtyRateDiscountGSTAmount
Grand Total: ${escapeHtml(x.total||'₹ 0.00')}
`); } function printPurchaseInvoice(id){ const x=getPurchaseInvoice(id);if(!x)return; const w=window.open('','_blank');if(!w){alert('Please allow pop-ups to print the invoice.');return;} const c=getCompanyDetails(), parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const party=parties.find(p=>String(p.id)===String(x.supplier))||parties.find(p=>String(p.name||'').toLowerCase()===String(x.supplierName||x.supplier||'').toLowerCase())||{}; const esc=escapeHtml; const money=n=>'₹ '+(Number(n)||0).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}); const numberToWords=n=>{ n=Math.round(Number(n)||0);if(n===0)return 'Zero Rupees only'; const ones=['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen']; const tens=['','','Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety']; const under1000=v=>{let a=[];if(v>=100){a.push(ones[Math.floor(v/100)]+' Hundred');v%=100;if(v)a.push('and');}if(v>=20){a.push(tens[Math.floor(v/10)]);if(v%10)a.push(ones[v%10]);}else if(v>0)a.push(ones[v]);return a.join(' ');}; let parts=[];const cr=Math.floor(n/10000000);n%=10000000;const lk=Math.floor(n/100000);n%=100000;const th=Math.floor(n/1000);n%=1000; if(cr)parts.push(under1000(cr)+' Crore');if(lk)parts.push(under1000(lk)+' Lakh');if(th)parts.push(under1000(th)+' Thousand');if(n)parts.push(under1000(n)); return parts.join(' ')+' Rupees only'; }; const items=x.items||[]; let subtotal=0,totalQty=0; const rows=items.map((it,i)=>{ const qty=Number(it.qty)||0,rate=Number(it.rate)||0,discount=Number(it.discount)||0,gst=Number(it.gst)||0; const base=qty*rate,disc=base*discount/100,taxable=base-disc,tax=taxable*gst/100,amount=taxable+tax; subtotal+=base;totalQty+=qty; const item=JSON.parse(localStorage.getItem('mviapps_items')||'[]').find(v=>String(v.id)===String(it.itemId))||{}; const unit=item.unit||'Pcs'; return `${i+1}${esc(purchaseItemName(it.itemId))}${qty}${esc(unit)}${money(rate)}${money(amount)}`; }).join(''); const total=Number(String(x.total||'').replace(/[^0-9.-]/g,''))||items.reduce((a,it)=>a+(Number(it.qty)||0)*(Number(it.rate)||0)*(1-(Number(it.discount)||0)/100)*(1+(Number(it.gst)||0)/100),0); const previousBalance=Math.max(0,-(Number(getPartyLedgerOpening(party,x.date))||0)); const isCredit=String(x.paymentMode||'').toLowerCase()==='credit'; const currentBalance=previousBalance+(isCredit?total:0); const address=[c.address,c.city,c.state,c.pin].filter(Boolean).join(', '); const contact=[c.mobile?'Phone: '+c.mobile:'',c.email?'Email: '+c.email:''].filter(Boolean).join('     '); const logo=c.logo?``:''; const signature=c.signature?``:''; const supplierName=party.name||x.supplierName||x.supplier||''; const supplierAddress=[party.address,party.city,party.state,party.pin].filter(Boolean).join(', '); const terms=x.notes||'Thanks for doing business with us!'; w.document.write(`Purchase Invoice ${esc(x.invoiceNo||'')}
Bill
${logo}
${esc(c.name||'Company Name')}
${c.trade?`
${esc(c.trade)}
`:''}${address?`
${esc(address)}
`:''}${contact?`
${contact}
`:''}
Bill No.:  ${esc(x.invoiceNo||'')}
Date:  ${esc((x.date||'').split('-').reverse().join('/'))}
Bill From:
${esc(supplierName)}${supplierAddress?`
${esc(supplierAddress)}
`:''}
${rows||``}
#Item nameQuantityUnitPrice/ Unit(₹)Amount(₹)
No items
Total${totalQty}${money(total)}
Sub Total:${money(subtotal)}
Total:${money(total)}
Bill Amount in Words:${esc(numberToWords(total))}
Previous Balance:${money(previousBalance)}
Current Balance:${money(currentBalance)}
Terms & Conditions:
${esc(terms)}
For ${esc(c.name||'Company Name')}:
${signature}
Authorized Signatory
`); w.document.close();w.focus();setTimeout(()=>{try{w.print();w.onafterprint=()=>w.close();}catch(e){console.error('Purchase invoice print error:',e);}},300); } function editPurchaseInvoice(id){ const x=getPurchaseInvoice(id); if(!x)return; window._editingPurchaseId=x.id; const page=document.getElementById('content'); if(!page)return; page.innerHTML=invoice('Purchase'); setTimeout(()=>{ const supplier=document.getElementById('purchaseSupplier'); const date=document.getElementById('purchaseDate'); const invoiceNo=document.getElementById('purchaseInvoiceNo'); const paymentMode=document.getElementById('purchasePaymentMode'); const bankAccount=document.getElementById('purchaseBankAccount'); const reference=document.getElementById('purchaseReference'); const dueDate=document.getElementById('purchaseDueDate'); const notes=document.getElementById('purchaseNotes'); if(supplier)supplier.value=x.supplier||''; if(date){date.value=x.date||'';syncPurchaseInvoiceDateDisplay();} if(invoiceNo)invoiceNo.value=x.invoiceNo||''; if(paymentMode)paymentMode.value=x.paymentMode||'Cash'; if(bankAccount)bankAccount.value=x.bankAccount||''; mviappsToggleBankAccount('purchasePaymentMode','purchaseBankWrap','purchaseBankAccount'); if(reference)reference.value=x.reference||''; if(dueDate){dueDate.value=x.dueDate||'';syncPurchaseInvoiceDueDateDisplay();} if(notes)notes.value=x.notes||''; const serviceHead=document.getElementById('purchaseServiceExpenseHead'); if(serviceHead){const existingExpense=JSON.parse(localStorage.getItem('mviapps_expenses')||'[]').find(e=>e.sourcePurchaseInvoice===true&&String(e.sourcePurchaseInvoiceId||'')===String(x.id));if(existingExpense&&![...serviceHead.options].some(o=>o.value===existingExpense.category))serviceHead.add(new Option(existingExpense.category,existingExpense.category));if(existingExpense)serviceHead.value=existingExpense.category;} const body=document.getElementById('purchaseInvoiceItems'); if(body){ body.innerHTML=''; (x.items||[]).forEach(it=>addPurchaseInvoiceItemWithData(it)); } calculatePurchaseInvoice(); const b=document.querySelector('[onclick="savePurchaseInvoice(false)"]'); if(b)b.textContent='Update Purchase'; },0); } function addPurchaseInvoiceItemWithData(it){addPurchaseInvoiceItemRow({itemId:it.itemId,qty:it.qty??1,rate:it.rate??0,discount:it.discount??0,gst:it.gst??0});} function deletePurchaseInvoice(id){if(!confirm('Delete this purchase invoice?'))return;const arr=JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]');const x=arr.find(v=>String(v.id)===String(id));localStorage.setItem('mviapps_purchase_invoices',JSON.stringify(arr.filter(v=>String(v.id)!==String(id))));if(x){const moves=JSON.parse(localStorage.getItem('mviapps_stock_movements')||'[]');localStorage.setItem('mviapps_stock_movements',JSON.stringify(moves.filter(m=>!(m.type==='purchase'&&String(m.ref)===String(x.invoiceNo)))));const expenses=JSON.parse(localStorage.getItem('mviapps_expenses')||'[]');localStorage.setItem('mviapps_expenses',JSON.stringify(expenses.filter(e=>!(e.sourcePurchaseInvoice===true&&String(e.sourcePurchaseInvoiceId)===String(x.id)))));}renderPurchaseInvoices();} function getPurchaseReturn(id){return JSON.parse(localStorage.getItem('mviapps_purchase_returns')||'[]').find(x=>String(x.id)===String(id));} function openPurchaseReturnListDatePicker(which){ const picker=document.getElementById(which==='from'?'purchaseReturnFrom':'purchaseReturnTo'); if(!picker)return; try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();}catch(e){try{picker.click();}catch(ignore){}} } function syncPurchaseReturnListDateDisplay(which){ const picker=document.getElementById(which==='from'?'purchaseReturnFrom':'purchaseReturnTo'); const display=document.getElementById(which==='from'?'purchaseReturnFromDisplay':'purchaseReturnToDisplay'); if(display)display.value=picker?.value?picker.value.split('-').reverse().join('/') : ''; } function preparePurchaseReturnListManualDate(which){ const display=document.getElementById(which==='from'?'purchaseReturnFromDisplay':'purchaseReturnToDisplay'); if(display)display.dataset.manualReady='1'; } function formatPurchaseReturnListDateInput(el){ if(!el)return; el.dataset.manualReady='1'; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits; if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2); if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4); el.value=out; } function syncPurchaseReturnListManualDate(which){ const display=document.getElementById(which==='from'?'purchaseReturnFromDisplay':'purchaseReturnToDisplay'); const picker=document.getElementById(which==='from'?'purchaseReturnFrom':'purchaseReturnTo'); if(!display||!picker)return; let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/'); if(!value){picker.value='';delete display.dataset.manualReady;renderPurchaseReturns();return;} const parts=value.split('/'); if(parts.length===3){ const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2]; if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){ const test=new Date(Number(yyyy),Number(mm)-1,Number(dd)); if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){ picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;renderPurchaseReturns();return; } } } syncPurchaseReturnListDateDisplay(which);delete display.dataset.manualReady;renderPurchaseReturns(); } function renderPurchaseReturns(){ const rows=document.getElementById('purchaseReturnRows');if(!rows)return; const from=document.getElementById('purchaseReturnFrom')?.value||'', to=document.getElementById('purchaseReturnTo')?.value||''; const arr=filterByActiveFinancialYear(JSON.parse(localStorage.getItem('mviapps_purchase_returns')||'[]')).filter(x=>{ const d=String(x.date||''); return (!from||!d||d>=from)&&(!to||!d||d<=to); }).sort((a,b)=>(b.date||'').localeCompare(a.date||'')||(Number(b.id)||0)-(Number(a.id)||0)); rows.innerHTML=arr.length?arr.map(x=>`${escapeHtml(x.date||'')}${escapeHtml(x.invoiceNo||'')}${escapeHtml(x.supplierName||x.supplier||'')}${x.items?.length||0}${escapeHtml(x.paymentMode||'')}${escapeHtml(x.total||'₹ 0.00')} `).join(''):`No purchase returns found for the selected date range.`; } function viewPurchaseReturn(id){ const x=getPurchaseReturn(id);if(!x)return; const items=(x.items||[]).map(it=>`${escapeHtml(purchaseItemName(it.itemId))}${it.qty}₹ ${Number(it.rate||0).toFixed(2)}${it.discount||0}%${it.gst||0}%`).join(''); const old=document.getElementById('purchaseReturnModal');if(old)old.remove(); document.body.insertAdjacentHTML('beforeend',`

Purchase Return ${escapeHtml(x.invoiceNo||'')}

${escapeHtml(x.date||'')} · ${escapeHtml(x.supplierName||x.supplier||'')}


${items}
ItemQtyRateDiscountGST
Grand Total: ${escapeHtml(x.total||'₹ 0.00')}
`); } function editPurchaseReturn(id){ const x=getPurchaseReturn(id);if(!x)return; window._editingPurchaseReturnId=x.id;show('purchase-returns'); setTimeout(()=>{document.getElementById('purchaseSupplier').value=x.supplier||'';document.getElementById('purchaseDate').value=x.date||'';syncPurchaseInvoiceDateDisplay();document.getElementById('purchaseInvoiceNo').value=x.invoiceNo||'';document.getElementById('purchasePaymentMode').value=x.paymentMode||'Cash';document.getElementById('purchaseBankAccount').value=x.bankAccount||'';mviappsToggleBankAccount('purchasePaymentMode','purchaseBankWrap','purchaseBankAccount');document.getElementById('purchaseReference').value=x.reference||'';document.getElementById('purchaseDueDate').value=x.dueDate||'';syncPurchaseInvoiceDueDateDisplay();document.getElementById('purchaseNotes').value=x.notes||'';const body=document.getElementById('purchaseInvoiceItems');body.innerHTML='';(x.items||[]).forEach(it=>addPurchaseInvoiceItemWithData(it));calculatePurchaseInvoice();const b=document.querySelector('[onclick="savePurchaseInvoice(true)"]');if(b)b.textContent='Update Return';},0); } function deletePurchaseReturn(id){ if(!confirm('Delete this purchase return?'))return; const arr=JSON.parse(localStorage.getItem('mviapps_purchase_returns')||'[]'); const deleted=arr.find(v=>String(v.id)===String(id)); localStorage.setItem('mviapps_purchase_returns',JSON.stringify(arr.filter(v=>String(v.id)!==String(id)))); if(deleted){let moves=JSON.parse(localStorage.getItem('mviapps_stock_movements')||'[]');moves=moves.filter(m=>!(m.type==='return'&&String(m.ref)===String(deleted.invoiceNo)));localStorage.setItem('mviapps_stock_movements',JSON.stringify(moves));} renderPurchaseReturns(); } function addPurchaseInvoiceItem(){openPurchaseAddItemPopup(document.querySelector('[onclick="savePurchaseInvoice(true)"]')!==null);} function addPurchaseInvoiceItemRow(data={}){const body=document.getElementById('purchaseInvoiceItems');if(!body)return null;if(body.querySelector('.empty'))body.innerHTML='';const items=getSortedItems();const opts=items.map(x=>``).join('');const tr=document.createElement('tr');tr.innerHTML=`
₹ 0.00`;body.appendChild(tr);if(data.itemId){const sel=tr.querySelector('.purchase-item');sel.value=String(data.itemId);purchaseItemChanged(sel);if(data.rate!==undefined&&data.rate!==null){const rateInput=tr.querySelector('.purchase-rate');if(rateInput)rateInput.value=Number(data.rate)||0;}}calculatePurchaseInvoice();return tr;} function purchaseItemChanged(sel){const o=sel.options[sel.selectedIndex],tr=sel.closest('tr');if(!tr)return;tr.querySelector('.purchase-rate').value=o?.dataset.rate||0;tr.querySelector('.purchase-unit').value=o?.dataset.unit||'Nos';tr.querySelector('.purchase-gst').value=o?.dataset.gst||0;calculatePurchaseInvoice();} function calculatePurchaseInvoice(){let sub=0,disc=0,taxable=0,cgst=0,sgst=0,igst=0;document.querySelectorAll('#purchaseInvoiceItems tr').forEach(tr=>{const q=Number(tr.querySelector('.purchase-qty')?.value)||0,r=Number(tr.querySelector('.purchase-rate')?.value)||0,d=Number(tr.querySelector('.purchase-discount')?.value)||0,g=Number(tr.querySelector('.purchase-gst')?.value)||0;const base=q*r,discount=base*d/100,tx=base-discount,tax=tx*g/100;sub+=base;disc+=discount;taxable+=tx;cgst+=tax/2;sgst+=tax/2;const a=tr.querySelector('.purchase-amount');if(a)a.textContent='₹ '+(tx+tax).toFixed(2);});const total=taxable+cgst+sgst+igst,rounded=Math.round(total),roundOff=rounded-total;const set=(id,v)=>{const e=document.getElementById(id);if(e)e.textContent='₹ '+v.toFixed(2)};set('purchaseSubTotal',sub);set('purchaseDiscount',disc);set('purchaseTaxableAmount',taxable);set('purchaseCGST',cgst);set('purchaseSGST',sgst);set('purchaseIGST',igst);set('purchaseRoundOff',roundOff);set('purchaseGrand',rounded);} function openPurchaseAddItemPopup(isReturn=false){ closePurchaseAddItemPopup(); const items=getSortedItems(); const itemOpts=items.map(x=>``).join(''); const overlay=document.createElement('div');overlay.id='purchaseAddItemPopup';overlay.className='sale-add-item-overlay'; overlay.innerHTML=``; overlay.addEventListener('click',e=>{if(e.target===overlay)closePurchaseAddItemPopup();});document.body.appendChild(overlay);document.body.classList.add('sale-popup-open');setTimeout(()=>document.getElementById('purchasePopupItemSearch')?.focus(),50); } function closePurchaseAddItemPopup(){document.getElementById('purchaseAddItemPopup')?.remove();if(!document.getElementById('saleAddItemPopup'))document.body.classList.remove('sale-popup-open');} function purchasePopupItemInput(input){const sel=document.getElementById('purchasePopupItem');if(!sel)return;const value=(input.value||'').trim().toLowerCase();const option=Array.from(sel.options).find(o=>o.value&&o.textContent.trim().toLowerCase()===value);if(option){sel.value=option.value;purchasePopupItemChanged();return;}const partial=Array.from(sel.options).find(o=>o.value&&o.textContent.toLowerCase().includes(value));if(value&&partial&&input.value.trim()===partial.textContent.trim()){sel.value=partial.value;purchasePopupItemChanged();}} function purchasePopupItemChanged(){const sel=document.getElementById('purchasePopupItem'),o=sel?.options[sel.selectedIndex];if(!o)return;const search=document.getElementById('purchasePopupItemSearch');if(search)search.value=o.value?o.textContent:'';const rate=document.getElementById('purchasePopupRate');if(rate)rate.value=o.dataset.rate||0;const unit=document.getElementById('purchasePopupUnit');if(unit)unit.value=o.dataset.unit||'Nos';calculatePurchasePopupAmount();} function calculatePurchasePopupAmount(){const q=Number(document.getElementById('purchasePopupQty')?.value)||0,r=Number(document.getElementById('purchasePopupRate')?.value)||0,d=Number(document.getElementById('purchasePopupDiscount')?.value)||0,g=Number(document.getElementById('purchasePopupGst')?.value)||0;const base=q*r,discount=base*d/100,taxable=base-discount,tax=taxable*g/100,amount=taxable+tax;const el=document.getElementById('purchasePopupAmount');if(el)el.textContent='₹ '+amount.toFixed(2);} function savePurchasePopupItem(continueAdding){const isReturn=document.querySelector('[onclick="savePurchaseInvoice(true)"]')!==null;const itemId=document.getElementById('purchasePopupItem')?.value||'',qty=Number(document.getElementById('purchasePopupQty')?.value)||0;if(!itemId){alert('Please select an Item.');return;}if(qty<=0){alert((isReturn?'Return':'Purchase')+' quantity must be greater than zero.');return;}addPurchaseInvoiceItemRow({itemId,qty,rate:Number(document.getElementById('purchasePopupRate')?.value)||0,discount:Number(document.getElementById('purchasePopupDiscount')?.value)||0,gst:Number(document.getElementById('purchasePopupGst')?.value)||0});if(continueAdding){openPurchaseAddItemPopup(isReturn);}else closePurchaseAddItemPopup();} function clearPurchaseInvoice(){show('purchase-invoices');} function syncPurchaseInvoiceStockMovements(){ const invoices=JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]'); const returns=JSON.parse(localStorage.getItem('mviapps_purchase_returns')||'[]'); let moves=getStockMovements(); let changed=false; const ensureMove=(date,itemId,qty,type,ref,rate)=>{ if(!(Number(qty)>0)||!itemId||!ref)return; const exists=moves.some(m=>m.type===type&&String(m.ref)===String(ref)&&String(m.itemId)===String(itemId)); if(!exists){moves.push({id:Date.now()+Math.random(),date:date||'',itemId,qty:Number(qty)||0,type,ref,rate:Number(rate)||0});changed=true;} }; invoices.forEach(inv=>(inv.items||[]).forEach(it=>{if(!isServiceSaleItem(it.itemId))ensureMove(inv.date,it.itemId,it.qty,'purchase',inv.invoiceNo,it.rate);})); returns.forEach(inv=>(inv.items||[]).forEach(it=>{if(!isServiceSaleItem(it.itemId))ensureMove(inv.date,it.itemId,it.qty,'return',inv.invoiceNo,it.rate);})); invoices.forEach(inv=>(inv.items||[]).filter(it=>!isServiceSaleItem(it.itemId)).forEach(it=>moves.forEach(m=>{if(m.type==='purchase'&&String(m.ref)===String(inv.invoiceNo)&&String(m.itemId)===String(it.itemId)&&!(Number(m.rate)>0)&&Number(it.rate)>0){m.rate=Number(it.rate);changed=true;}}))); returns.forEach(inv=>(inv.items||[]).filter(it=>!isServiceSaleItem(it.itemId)).forEach(it=>moves.forEach(m=>{if(m.type==='return'&&String(m.ref)===String(inv.invoiceNo)&&String(m.itemId)===String(it.itemId)&&!(Number(m.rate)>0)&&Number(it.rate)>0){m.rate=Number(it.rate);changed=true;}}))); if(changed)localStorage.setItem('mviapps_stock_movements',JSON.stringify(moves)); return moves; } function savePurchaseInvoice(isReturn=false){if(!mviappsRequireStaffPermission('purchases','create'))return; if(!ensureEntryDateInActiveFY(document.getElementById('purchaseDate')?.value,'Date'))return; const supplier=document.getElementById('purchaseSupplier')?.value||'';let no=document.getElementById('purchaseInvoiceNo')?.value.trim()||'';const rows=[...document.querySelectorAll('#purchaseInvoiceItems tr')].filter(tr=>tr.querySelector('.purchase-item')); if(!supplier){alert('Please select a supplier.');return;} if(!no&&isReturn){alert('Please enter Bill/Return No.');return;} if(!rows.length){alert('Please add at least one item.');return;} const key=isReturn?'mviapps_purchase_returns':'mviapps_purchase_invoices',arr=JSON.parse(localStorage.getItem(key)||'[]'); const editingId=isReturn?window._editingPurchaseReturnId:window._editingPurchaseId; const existing=editingId?arr.find(x=>String(x.id)===String(editingId)):null; const normalizeBillNo=value=>String(value??'').trim().toUpperCase(); const isBillNoAlreadyUsed=candidate=>{ let current=[]; try{const parsed=JSON.parse(localStorage.getItem(key)||'[]');current=Array.isArray(parsed)?parsed:[];}catch(e){current=arr;} return current.some(x=>normalizeBillNo(x?.invoiceNo||x?.number)===normalizeBillNo(candidate)&&String(x?.id)!==String(editingId||'')); }; if(isReturn){ if(isBillNoAlreadyUsed(no)){alert('This Purchase Return No. already exists. Please enter a unique Return No.');return;} }else{ // Re-check the latest saved Purchase records immediately before saving. If a prefilled number is stale/duplicate, generate and verify a fresh one. let attempts=0; while(!no||isBillNoAlreadyUsed(no)){ no=getNextAutoNumber(key,'PUR'); attempts++; if(attempts>10000||isBillNoAlreadyUsed(no)){ alert('Could not generate a unique Purchase Bill No. Please try again. No entry was saved.');return; } } const noField=document.getElementById('purchaseInvoiceNo');if(noField)noField.value=no; } const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const party=parties.find(p=>String(p.id)===String(supplier)); const date=document.getElementById('purchaseDate')?.value||'',paymentMode=document.getElementById('purchasePaymentMode')?.value||'',bankAccount=document.getElementById('purchaseBankAccount')?.value||'',reference=document.getElementById('purchaseReference')?.value||'',dueDate=document.getElementById('purchaseDueDate')?.value||'',notes=document.getElementById('purchaseNotes')?.value||''; const allItems=rows.map(tr=>({itemId:tr.querySelector('.purchase-item').value,qty:Number(tr.querySelector('.purchase-qty').value)||0,rate:Number(tr.querySelector('.purchase-rate').value)||0,discount:Number(tr.querySelector('.purchase-discount').value)||0,gst:Number(tr.querySelector('.purchase-gst').value)||0})); if(allItems.some(it=>!it.itemId)){alert('Please select an item in every row or remove the empty row.');return;} const itemMaster=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); const isService=it=>!isReturn&&isServiceSaleItem(itemMaster.find(i=>String(i.id)===String(it.itemId))); const goodsItems=allItems.filter(it=>!isService(it)),serviceItems=allItems.filter(isService); const calcTotal=items=>{let total=0;items.forEach(it=>{const base=(Number(it.qty)||0)*(Number(it.rate)||0),taxable=base-base*(Number(it.discount)||0)/100;total+=taxable+taxable*(Number(it.gst)||0)/100;});return Math.round(total).toFixed(2);}; const totalText=document.getElementById('purchaseGrand')?.textContent||'₹ 0.00'; const baseRecord={id:editingId||Date.now(),supplier,supplierName:party?.name||supplier,date,invoiceNo:no,paymentMode,bankAccount,reference,dueDate,notes}; // Service rows are recorded as Expenses against the same supplier bill. Only stock goods remain in Purchase. if(!isReturn){ let expenses=JSON.parse(localStorage.getItem('mviapps_expenses')||'[]'); const oldAuto=expenses.filter(x=>x.sourcePurchaseInvoiceId!=null&&String(x.sourcePurchaseInvoiceId)===String(editingId||'')); // Also recognize the bill-number link so updates remain safe if the original Purchase was service-only. // Only use a legacy bill-number fallback while editing an existing Purchase; a new service-only entry must never match/delete another entry just because party and bill number match. Match at most one legacy, unlinked expense. const related=(editingId&&existing?expenses.filter(x=>x.sourcePurchaseInvoice===true&&(x.sourcePurchaseInvoiceId==null||x.sourcePurchaseInvoiceId==='')&&String(x.supplierInvoiceNo||'')===String(existing.invoiceNo||no)&&String(x.partyId||'')===String(supplier)).slice(0,1):[]); // When editing a goods-only Purchase record, its previously auto-created service expense is not in the item grid; preserve it unless service rows are explicitly present to replace it. if(serviceItems.length){ const removeIds=new Set([...oldAuto,...related].map(x=>String(x.id))); expenses=expenses.filter(x=>!removeIds.has(String(x.id))); } if(serviceItems.length){ const serviceAmount=Number(calcTotal(serviceItems)); const category=(document.getElementById('purchaseServiceExpenseHead')?.value||oldAuto[0]?.category||related[0]?.category||'Office Expenses').trim(); const serviceLines=serviceItems.map(it=>{const item=itemMaster.find(i=>String(i.id)===String(it.itemId));return `${item?.name||'Service'} × ${it.qty} @ ₹${Number(it.rate||0).toFixed(2)} (Discount ${Number(it.discount)||0}%, GST ${Number(it.gst)||0}%)`;}).join('\n'); const expenseNo=oldAuto[0]?.number||related[0]?.number||getNextAutoNumber('mviapps_expenses','EXP'); expenses.push({id:oldAuto[0]?.id||related[0]?.id||Date.now()+Math.random(),number:expenseNo,date,category,entryType:'party',partyId:supplier,partyName:party?.name||supplier,amount:serviceAmount,paymentMode,account:bankAccount,bankAccount,reference:no,notes:`Supplier Bill No.: ${no}${reference?' | Reference: '+reference:''}${dueDate?' | Due Date: '+dueDate:''}\nAutomatically recorded from Purchase Service Item(s):\n${serviceLines}${notes?'\nNotes: '+notes:''}`,supplierInvoiceNo:no,dueDate,sourcePurchaseInvoice:true,sourcePurchaseInvoiceId:editingId||baseRecord.id}); } localStorage.setItem('mviapps_expenses',JSON.stringify(expenses)); const goodsIndex=arr.findIndex(x=>String(x.id)===String(editingId)); if(goodsItems.length){ const record={...baseRecord,items:goodsItems,total:'₹ '+calcTotal(goodsItems)}; if(goodsIndex>=0)arr[goodsIndex]=record;else arr.push(record); }else if(goodsIndex>=0){arr.splice(goodsIndex,1);} localStorage.setItem(key,JSON.stringify(arr)); }else{ const record={...baseRecord,items:allItems,total:totalText}; if(editingId){const idx=arr.findIndex(x=>String(x.id)===String(editingId));if(idx>=0)arr[idx]=record;else arr.push(record);}else arr.push(record); localStorage.setItem(key,JSON.stringify(arr)); } syncPurchaseInvoiceStockMovements(); let moves=JSON.parse(localStorage.getItem('mviapps_stock_movements')||'[]'); if(isReturn){ if(existing)moves=moves.filter(m=>!(m.type==='return'&&String(m.ref)===String(existing.invoiceNo))); moves=moves.filter(m=>!(m.type==='return'&&String(m.ref)===String(no))); allItems.forEach(it=>{if(!isServiceSaleItem(it.itemId))moves.push({id:Date.now()+Math.random(),date,itemId:it.itemId,qty:it.qty,type:'return',ref:no,rate:Number(it.rate)||0});}); }else{ if(existing)moves=moves.filter(m=>!(m.type==='purchase'&&String(m.ref)===String(existing.invoiceNo))); moves=moves.filter(m=>!(m.type==='purchase'&&String(m.ref)===String(no))); goodsItems.forEach(it=>moves.push({id:Date.now()+Math.random(),date,itemId:it.itemId,qty:it.qty,type:'purchase',ref:no,rate:Number(it.rate)||0})); } localStorage.setItem('mviapps_stock_movements',JSON.stringify(moves)); const refreshedItems=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); refreshedItems.forEach(it=>{const st=getCurrentStockSnapshot(it);it.currentQty=st.qty;it.currentValue=st.value;}); localStorage.setItem('mviapps_items',JSON.stringify(refreshedItems)); window._editingPurchaseId=null; window._editingPurchaseReturnId=null; const msg=isReturn?(editingId?'Purchase return updated successfully.':'Purchase return saved successfully.'):(goodsItems.length?(editingId?'Purchase updated; service items were updated in Expenses.':'Purchase saved; service items were automatically recorded in Expenses.'):(serviceItems.length?'Service item(s) recorded in Expenses; no Purchase entry was created.':'Purchase saved successfully.')); alert(msg); show(isReturn?'purchase-returns':(goodsItems.length||isReturn?'purchase-invoices':'expenses')); } function isServiceSaleItem(itemOrId){ const item=(itemOrId&&typeof itemOrId==='object')?itemOrId:JSON.parse(localStorage.getItem('mviapps_items')||'[]').find(i=>String(i.id)===String(itemOrId)); const category=String(item?.category||'').trim().toLowerCase(); return category==='service'||category==='services'; } function getSaleGodownOptions(selectedId){ const gs=getGodowns(); return gs.map(g=>``).join(''); } function addSaleInvoiceItem(){ openSaleAddItemPopup(); } function addSaleInvoiceItemRow(data={}){ const body=document.getElementById('saleInvoiceItems'); if(!body)return null; if(body.querySelector('.empty')) body.innerHTML=''; const items=getSortedItems(); const opts=items.map(x=>``).join(''); const tr=document.createElement('tr'); tr.innerHTML=`
—₹ 0.00`; body.appendChild(tr); if(data.itemId){ const sel=tr.querySelector('.sale-item');sel.value=String(data.itemId);saleItemChanged(sel); // Keep the rate and adjustments entered in the Add Item popup; item selection // initializes defaults, so restore the popup values after that initialization. tr.querySelector('.sale-qty').value=Number(data.qty)||1; tr.querySelector('.sale-rate').value=Number(data.rate)||0; tr.querySelector('.sale-discount').value=Number(data.discount)||0; tr.querySelector('.sale-gst').value=Number(data.gst)||0; } if(data.godownId){const gd=tr.querySelector('.sale-godown');gd.value=String(data.godownId);saleGodownChanged(gd);} calculateSaleInvoice(); return tr; } function closeSaleAddItemPopup(){document.getElementById('saleAddItemPopup')?.remove();document.body.classList.remove('sale-popup-open');} function openSaleAddItemPopup(){ closeSaleAddItemPopup(); const items=getSortedItems(); const itemOpts=items.map(x=>``).join(''); const overlay=document.createElement('div'); overlay.id='saleAddItemPopup'; overlay.className='sale-add-item-overlay'; overlay.innerHTML=``; overlay.addEventListener('click',e=>{if(e.target===overlay)closeSaleAddItemPopup();}); document.body.appendChild(overlay); document.body.classList.add('sale-popup-open'); setTimeout(()=>document.getElementById('salePopupItemSearch')?.focus(),50); } function salePopupItemInput(input){ const sel=document.getElementById('salePopupItem'); if(!sel||!input)return; const value=(input.value||'').trim().toLowerCase(); const option=Array.from(sel.options).find(o=>o.value&&o.textContent.trim().toLowerCase()===value); if(option){ sel.value=option.value; salePopupItemChanged(); return; } const partial=Array.from(sel.options).find(o=>o.value&&o.textContent.toLowerCase().includes(value)); if(value&&partial&&input.value.trim()===partial.textContent.trim()){ sel.value=partial.value; salePopupItemChanged(); } } function salePopupItemChanged(){ const sel=document.getElementById('salePopupItem'),o=sel?.options[sel.selectedIndex];if(!o)return; const search=document.getElementById('salePopupItemSearch');if(search)search.value=o.value?o.textContent:''; const rate=document.getElementById('salePopupRate');if(rate)rate.value=o.dataset.rate||0; const unit=document.getElementById('salePopupUnit');if(unit)unit.value=o.dataset.unit||'Nos'; const box=document.getElementById('salePopupItemSuggestions');if(box)box.style.display='none'; const gd=document.getElementById('salePopupGodown'),service=isServiceSaleItem(o.value);if(gd){if(service)gd.value='';gd.disabled=service;gd.title=service?'Godown is not required for a service':'';} updateSalePopupAvailability();calculateSalePopupAmount(); } function salePopupGodownChanged(){updateSalePopupAvailability();} function updateSalePopupAvailability(){ const itemId=document.getElementById('salePopupItem')?.value||'',godownId=document.getElementById('salePopupGodown')?.value||'',el=document.getElementById('salePopupAvailable'); const item=JSON.parse(localStorage.getItem('mviapps_items')||'[]').find(i=>String(i.id)===String(itemId)); if(item&&isServiceSaleItem(item)){if(el)el.textContent='Service item — no stock';return 0;} if(!itemId||!godownId){if(el)el.textContent='Available Qty: —';return 0;} if(!item){if(el)el.textContent='Available Qty: —';return 0;} const gs=getGodowns();if(gs.length)syncGodownStockWithClosing(item,gs); const q=getItemGodownQty(itemId,godownId);if(el)el.textContent=`Available Qty: ${q} ${item.unit||''}`;return q; } function calculateSalePopupAmount(){ const q=Number(document.getElementById('salePopupQty')?.value)||0,r=Number(document.getElementById('salePopupRate')?.value)||0,d=Number(document.getElementById('salePopupDiscount')?.value)||0,g=Number(document.getElementById('salePopupGst')?.value)||0; const base=q*r,discount=base*d/100,taxable=base-discount,tax=taxable*g/100,amount=taxable+tax;const el=document.getElementById('salePopupAmount');if(el)el.textContent='₹ '+amount.toFixed(2); } function saveSalePopupItem(continueAdding){ const search=document.getElementById('salePopupItemSearch');if(search)salePopupItemInput(search); const itemId=document.getElementById('salePopupItem')?.value||'',godownId=document.getElementById('salePopupGodown')?.value||'',qty=Number(document.getElementById('salePopupQty')?.value)||0,service=isServiceSaleItem(itemId); if(!itemId){alert('Please select an Item.');return;} if(!service&&!godownId){alert('Please select a Godown.');return;} if(qty<=0){alert('Sale quantity must be greater than zero.');return;} const available=updateSalePopupAvailability();if(!service&&qty>available){const item=JSON.parse(localStorage.getItem('mviapps_items')||'[]').find(i=>String(i.id)===String(itemId));alert(`Insufficient stock for ${item?.name||'item'} in selected godown. Available quantity is ${available} ${item?.unit||''}.`);return;} addSaleInvoiceItemRow({itemId,godownId,qty,rate:Number(document.getElementById('salePopupRate')?.value)||0,discount:Number(document.getElementById('salePopupDiscount')?.value)||0,gst:Number(document.getElementById('salePopupGst')?.value)||0}); if(continueAdding){openSaleAddItemPopup();}else closeSaleAddItemPopup(); } function filterSaleItemSuggestions(input){ const tr=input.closest('tr'),box=tr?.querySelector('.sale-item-suggestions'),sel=tr?.querySelector('.sale-item'); if(!tr||!box||!sel)return; const q=(input.value||'').trim().toLowerCase(); const options=Array.from(sel.options).filter(o=>o.value); const matches=options.filter(o=>!q||o.textContent.toLowerCase().includes(q)).slice(0,50); box.innerHTML=matches.length?matches.map(o=>{ const itemName=o.textContent.split(' — ')[0], code=o.textContent.includes(' — ')?o.textContent.split(' — ').slice(1).join(' — '):''; return `
${escapeHtml(itemName)}
${code?`
Code: ${escapeHtml(code)}
`:''}
`; }).join(''):'
No matching item
'; box.style.display='block'; } function selectSaleItemSuggestion(el,itemId){ const tr=el.closest('tr'),sel=tr?.querySelector('.sale-item'),input=tr?.querySelector('.sale-item-search'),box=tr?.querySelector('.sale-item-suggestions'); if(!tr||!sel)return; sel.value=String(itemId); if(input){const o=sel.options[sel.selectedIndex];input.value=o?o.textContent:'';} if(box)box.style.display='none'; saleItemChanged(sel); } function saleItemChanged(sel){ const o=sel.options[sel.selectedIndex],tr=sel.closest('tr');if(!tr)return; const gd=tr.querySelector('.sale-godown'),service=isServiceSaleItem(sel.value);if(gd){if(service)gd.value='';gd.disabled=service;gd.title=service?'Godown is not required for a service':'';} const search=tr.querySelector('.sale-item-search'); if(search) search.value=o?.value?o.textContent:''; const box=tr.querySelector('.sale-item-suggestions'); if(box) box.style.display='none'; tr.querySelector('.sale-rate').value=o?.dataset.rate||0; tr.querySelector('.sale-unit').value=o?.dataset.unit||'Nos'; updateSaleRowAvailability(tr); calculateSaleInvoice(); } function saleGodownChanged(sel){const tr=sel.closest('tr');if(!tr)return;updateSaleRowAvailability(tr);calculateSaleInvoice();} function updateSaleRowAvailability(tr){ const itemId=tr.querySelector('.sale-item')?.value||'',godownId=tr.querySelector('.sale-godown')?.value||''; const item=JSON.parse(localStorage.getItem('mviapps_items')||'[]').find(i=>String(i.id)===String(itemId)); const el=tr.querySelector('.sale-available'); if(item&&isServiceSaleItem(item)){if(el)el.textContent='No stock';return 0;} if(!item||!godownId){if(el)el.textContent='—';return 0;} const gs=getGodowns(); if(gs.length)syncGodownStockWithClosing(item,gs); const q=getItemGodownQty(itemId,godownId); if(el)el.textContent=`${q} ${item.unit||''}`; return q; } function calculateSaleInvoice(){ let sub=0,disc=0,taxable=0,cgst=0,sgst=0,igst=0; document.querySelectorAll('#saleInvoiceItems tr').forEach(tr=>{updateSaleRowAvailability(tr);const q=Number(tr.querySelector('.sale-qty')?.value)||0,r=Number(tr.querySelector('.sale-rate')?.value)||0,d=Number(tr.querySelector('.sale-discount')?.value)||0,g=Number(tr.querySelector('.sale-gst')?.value)||0;const base=q*r,discount=base*d/100,tx=base-discount,tax=tx*g/100;sub+=base;disc+=discount;taxable+=tx;cgst+=tax/2;sgst+=tax/2;const a=tr.querySelector('.sale-amount');if(a)a.textContent='₹ '+(tx+tax).toFixed(2);}); const total=taxable+cgst+sgst+igst,rounded=Math.round(total),roundOff=rounded-total; const set=(id,v)=>{const e=document.getElementById(id);if(e)e.textContent='₹ '+v.toFixed(2)}; set('saleSubTotal',sub);set('saleDiscount',disc);set('saleTaxable',taxable);set('saleCgst',cgst);set('saleSgst',sgst);set('saleIgst',igst);set('saleRound',roundOff);set('saleGrand',rounded); } function clearSaleInvoice(){show('sale-invoices');} function saveSaleInvoice(){if(!mviappsRequireStaffPermission('sales','create'))return; if(!ensureEntryDateInActiveFY(document.getElementById('saleDate')?.value,'Date'))return; const customer=document.getElementById('saleCustomer')?.value||'';let invoiceNo=document.getElementById('saleInvoiceNo')?.value.trim()||'';const rows=[...document.querySelectorAll('#saleInvoiceItems tr')].filter(tr=>tr.querySelector('.sale-item')); if(!customer){alert('Please select a customer.');return;} if(!invoiceNo){alert('Please enter Invoice No.');return;} if(!rows.length){alert('Please add at least one item.');return;} const invoices=JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]'),editingId=window._editingSaleId||null,existing=editingId?invoices.find(x=>String(x.id)===String(editingId)):null; if(invoices.some(x=>String(x?.invoiceNo||x?.number||'').trim().toUpperCase()===invoiceNo.toUpperCase()&&String(x.id)!==String(editingId||''))){invoiceNo=getNextAutoNumber('mviapps_sales_invoices','INV');const noField=document.getElementById('saleInvoiceNo');if(noField)noField.value=invoiceNo;} const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'),party=parties.find(p=>String(p.id)===String(customer)); const saleItems=rows.map(tr=>({itemId:tr.querySelector('.sale-item').value,godownId:tr.querySelector('.sale-godown')?.value||'',qty:Number(tr.querySelector('.sale-qty').value)||0,rate:Number(tr.querySelector('.sale-rate').value)||0,discount:Number(tr.querySelector('.sale-discount').value)||0,gst:Number(tr.querySelector('.sale-gst').value)||0})); const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); for(const it of saleItems){const service=isServiceSaleItem(items.find(i=>String(i.id)===String(it.itemId)));if(!it.itemId||(!service&&!it.godownId)){alert('Please select Item and Godown for every stock item.');return;}if(it.qty<=0){alert('Sale quantity must be greater than zero.');return;}} const gs=getGodowns(); const oldGodownItems=existing?.items||[]; oldGodownItems.forEach(it=>{if(it.godownId){const item=items.find(i=>String(i.id)===String(it.itemId));if(item&&!isServiceSaleItem(item))syncGodownStockWithClosing(item,gs);}}); saleItems.forEach(it=>{const item=items.find(i=>String(i.id)===String(it.itemId));if(item&&!isServiceSaleItem(item))syncGodownStockWithClosing(item,gs);}); const temp=getGodownStock(); // Restore stock consumed by the previous version of this invoice before validating the new version. oldGodownItems.forEach(it=>{if(!it.godownId||isServiceSaleItem(items.find(i=>String(i.id)===String(it.itemId))))return;let r=temp.find(x=>String(x.itemId)===String(it.itemId)&&String(x.godownId)===String(it.godownId));if(!r){r={id:Date.now()+Math.random(),itemId:it.itemId,godownId:it.godownId,qty:0};temp.push(r)}r.qty=(Number(r.qty)||0)+(Number(it.qty)||0);}); for(const it of saleItems){if(isServiceSaleItem(items.find(i=>String(i.id)===String(it.itemId))))continue;const r=temp.find(x=>String(x.itemId)===String(it.itemId)&&String(x.godownId)===String(it.godownId));const available=Number(r?.qty)||0;if(it.qty>available){const item=items.find(i=>String(i.id)===String(it.itemId));alert(`Insufficient stock for ${item?.name||'item'} in selected godown. Available quantity is ${available} ${item?.unit||''}.`);return;}} saleItems.forEach(it=>{if(isServiceSaleItem(items.find(i=>String(i.id)===String(it.itemId))))return;let r=temp.find(x=>String(x.itemId)===String(it.itemId)&&String(x.godownId)===String(it.godownId));if(!r){r={id:Date.now()+Math.random(),itemId:it.itemId,godownId:it.godownId,qty:0};temp.push(r)}r.qty=(Number(r.qty)||0)-it.qty;}); saveGodownStock(temp); const record={id:editingId||Date.now(),customer,customerName:party?.name||customer,date:document.getElementById('saleDate')?.value||'',invoiceNo,paymentMode:document.getElementById('salePaymentMode')?.value||'',bankAccount:document.getElementById('saleBankAccount')?.value||'',reference:document.getElementById('saleReference')?.value||'',dueDate:document.getElementById('saleDueDate')?.value||'',notes:document.getElementById('saleNotes')?.value||'',items:saleItems,total:document.getElementById('saleGrand')?.textContent||'₹ 0.00'}; if(editingId){const idx=invoices.findIndex(x=>String(x.id)===String(editingId));if(idx>=0)invoices[idx]=record;else invoices.push(record);}else invoices.push(record);localStorage.setItem('mviapps_sales_invoices',JSON.stringify(invoices)); let moves=JSON.parse(localStorage.getItem('mviapps_stock_movements')||'[]');if(existing)moves=moves.filter(m=>!(m.type==='sale'&&String(m.ref)===String(existing.invoiceNo)));moves=moves.filter(m=>!(m.type==='sale'&&String(m.ref)===String(record.invoiceNo)));record.items.forEach(it=>{if(!isServiceSaleItem(items.find(i=>String(i.id)===String(it.itemId))))moves.push({id:Date.now()+Math.random(),date:record.date,itemId:it.itemId,qty:it.qty,type:'sale',ref:record.invoiceNo,godownId:it.godownId});});localStorage.setItem('mviapps_stock_movements',JSON.stringify(moves)); window._editingSaleId=null;alert(editingId?'Sales invoice updated successfully.':'Sales invoice saved successfully.');show('sale-invoices'); } function getItemCategories(){ const saved=JSON.parse(localStorage.getItem('mviapps_item_categories')||'null'); return Array.isArray(saved)?saved:['General','Raw Material','Finished Goods','Services','Consumables','Other']; } function itemCategories(){ return `

Item Categories

Create and manage categories used while adding inventory items.

Saved Item Categories

These categories will appear in the Item Entry form.

#Category NameAction
`; } function renderItemCategories(){ const rows=document.getElementById('itemCategoryRows');if(!rows)return; const q=(document.getElementById('itemCategorySearch')?.value||'').toLowerCase(); const cats=getItemCategories(); const visible=cats.map((c,index)=>({c,index})).filter(x=>String(x.c).toLowerCase().includes(q)); rows.innerHTML=visible.length?visible.map((x,i)=>`${i+1}${escapeHtml(x.c)} `).join(''):`No item categories found.`; } function editItemCategoryByIndex(index){const cats=getItemCategories();const oldName=cats[index];if(oldName===undefined)return;editItemCategory(oldName);} function deleteItemCategoryByIndex(index){const cats=getItemCategories();const name=cats[index];if(name===undefined)return;deleteItemCategory(name);} function addItemCategory(){if(!mviappsRequireStaffPermission('items','create'))return; const input=document.getElementById('newItemCategory'),name=input?.value.trim()||''; if(!name){alert('Please enter an item category name.');return;} const cats=getItemCategories();if(cats.some(c=>c.toLowerCase()===name.toLowerCase())){alert('This item category already exists.');return;} cats.push(name);localStorage.setItem('mviapps_item_categories',JSON.stringify(cats));input.value='';renderItemCategories();alert('Item category added successfully.'); } function editItemCategory(oldName){if(!mviappsRequireStaffPermission('items','edit'))return; const name=prompt('Enter new item category name:',oldName);if(name===null)return;const next=name.trim();if(!next){alert('Category name cannot be empty.');return;} const cats=getItemCategories();if(cats.some(c=>c.toLowerCase()===next.toLowerCase()&&c.toLowerCase()!==oldName.toLowerCase())){alert('This item category already exists.');return;} const idx=cats.findIndex(c=>c===oldName);if(idx<0)return;cats[idx]=next;localStorage.setItem('mviapps_item_categories',JSON.stringify(cats));renderItemCategories(); } function deleteItemCategory(name){if(!mviappsRequireStaffPermission('items','delete'))return; const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'); const used=items.some(x=>String(x.category||'').toLowerCase()===String(name).toLowerCase()); if(used){alert('This category is already used by an item. Please change the item category before deleting it.');return;} if(!confirm('Delete the item category "'+name+'"?'))return; const cats=getItemCategories().filter(c=>c!==name);localStorage.setItem('mviapps_item_categories',JSON.stringify(cats));renderItemCategories(); } function getExpenseCategories(){ const defaults=['Rent','Electricity','Telephone / Internet','Office Expenses','Salary / Wages','Transport / Fuel','Repair & Maintenance','Advertising & Marketing','Stationery','Bank Charges','Professional Fees','Travelling','Miscellaneous','Other']; let cats=JSON.parse(localStorage.getItem('mviapps_expense_categories')||'null'); if(!Array.isArray(cats)||!cats.length){cats=defaults;localStorage.setItem('mviapps_expense_categories',JSON.stringify(cats));} return [...new Set(cats.map(x=>String(x||'').trim()).filter(Boolean))]; } function expenseCategories(){ return `

Expense Categories

Create and manage the categories that appear in the Expense entry dropdown.

Saved Expense Categories

These categories will automatically appear in Expenses.

#Category NameAction
`; } function renderExpenseCategories(){ const rows=document.getElementById('expenseCategoryRows');if(!rows)return; const q=(document.getElementById('expenseCategorySearch')?.value||'').toLowerCase(); const cats=getExpenseCategories(); const visible=cats.map((c,index)=>({c,index})).filter(x=>String(x.c).toLowerCase().includes(q)); rows.innerHTML=visible.length?visible.map((x,i)=>`${i+1}${escapeHtml(x.c)} `).join(''):`No expense categories found.`; } function editExpenseCategoryByIndex(index){const cats=getExpenseCategories();const oldName=cats[index];if(oldName===undefined)return;editExpenseCategory(oldName);} function deleteExpenseCategoryByIndex(index){const cats=getExpenseCategories();const name=cats[index];if(name===undefined)return;deleteExpenseCategory(name);} function addExpenseCategory(){ const input=document.getElementById('newExpenseCategory'),name=input?.value.trim()||''; if(!name){alert('Please enter a category name.');return;} const cats=getExpenseCategories(); if(cats.some(c=>c.toLowerCase()===name.toLowerCase())){alert('This expense category already exists.');return;} cats.push(name);localStorage.setItem('mviapps_expense_categories',JSON.stringify(cats));input.value='';renderExpenseCategories();alert('Expense category added successfully.'); } function editExpenseCategory(oldName){ const name=prompt('Enter new category name:',oldName); if(name===null)return; const next=name.trim(); if(!next){alert('Category name cannot be empty.');return;} const cats=getExpenseCategories(); if(cats.some(c=>c.toLowerCase()===next.toLowerCase()&&c.toLowerCase()!==oldName.toLowerCase())){alert('This expense category already exists.');return;} const idx=cats.findIndex(c=>c===oldName); if(idx<0)return; cats[idx]=next; localStorage.setItem('mviapps_expense_categories',JSON.stringify(cats)); renderExpenseCategories(); alert('Expense category updated successfully.'); } function deleteExpenseCategory(name){ if(!confirm('Delete the expense category "'+name+'"?'))return; const cats=getExpenseCategories().filter(c=>c!==name); localStorage.setItem('mviapps_expense_categories',JSON.stringify(cats)); renderExpenseCategories(); alert('Expense category deleted successfully.'); } function getIncomeHeads(){ const defaults=['Commission','Interest Income','Discount Received','Rent Received','Service Income','Other']; let heads=JSON.parse(localStorage.getItem('mviapps_other_income_heads')||'null'); if(!Array.isArray(heads)||!heads.length){heads=defaults;localStorage.setItem('mviapps_other_income_heads',JSON.stringify(heads));} return [...new Set(heads.map(x=>String(x||'').trim()).filter(Boolean))]; } function incomeHeads(){ return `

Other Income Heads

Create and manage the heads that appear in the Other Income entry dropdown.

Saved Other Income Heads

These heads will automatically appear in Other Income.

#Income HeadAction
`; } function renderIncomeHeads(){ const rows=document.getElementById('incomeHeadRows');if(!rows)return; const q=(document.getElementById('incomeHeadSearch')?.value||'').toLowerCase(); const heads=getIncomeHeads(); const visible=heads.map((h,index)=>({h,index})).filter(x=>String(x.h).toLowerCase().includes(q)); rows.innerHTML=visible.length?visible.map((x,i)=>`${i+1}${escapeHtml(x.h)} `).join(''):`No other income heads found.`; } function editIncomeHeadByIndex(index){const heads=getIncomeHeads();const oldName=heads[index];if(oldName===undefined)return;editIncomeHead(oldName);} function deleteIncomeHeadByIndex(index){const heads=getIncomeHeads();const name=heads[index];if(name===undefined)return;deleteIncomeHead(name);} function addIncomeHead(){ const input=document.getElementById('newIncomeHead'),name=input?.value.trim()||'';if(!name){alert('Please enter an income head.');return;} const heads=getIncomeHeads();if(heads.some(h=>h.toLowerCase()===name.toLowerCase())){alert('This income head already exists.');return;} heads.push(name);localStorage.setItem('mviapps_other_income_heads',JSON.stringify(heads));input.value='';renderIncomeHeads();alert('Other income head added successfully.'); } function editIncomeHead(oldName){ const name=prompt('Enter new income head:',oldName);if(name===null)return;const next=name.trim();if(!next){alert('Income head cannot be empty.');return;} const heads=getIncomeHeads();if(heads.some(h=>h.toLowerCase()===next.toLowerCase()&&h.toLowerCase()!==oldName.toLowerCase())){alert('This income head already exists.');return;} const idx=heads.findIndex(h=>h===oldName);if(idx<0)return;heads[idx]=next;localStorage.setItem('mviapps_other_income_heads',JSON.stringify(heads));renderIncomeHeads();alert('Other income head updated successfully.'); } function deleteIncomeHead(name){ if(!confirm('Delete the other income head "'+name+'"?'))return; const heads=getIncomeHeads().filter(h=>h!==name);localStorage.setItem('mviapps_other_income_heads',JSON.stringify(heads));renderIncomeHeads();alert('Other income head deleted successfully.'); } async function mviappsLoadAccountHeadOptions(selectId,group){ const select=document.getElementById(selectId);if(!select)return false; const prior=String(select.value||''); try{ const rows=await loadCloudAccountHeads(); const active=rows.filter(x=>String(x.group||'').toLowerCase()===String(group).toLowerCase()&&String(x.id||'').trim()); select.innerHTML=''+active.map(x=>'').join(''); if(prior&&active.some(x=>String(x.id)===prior))select.value=prior; select.dataset.cloudHeadsLoaded='1';select.dataset.cloudHeadsGroup=group; if(!active.length){select.innerHTML='';return false;} return true; }catch(e){select.innerHTML='';throw new Error('Production Cloud Account Heads could not be verified: '+(e?.message||String(e)));} } async function mviappsEnsureAccountHeadSelection(selectId,group){ const el=document.getElementById(selectId);if(!el)throw new Error('Account Head selector is missing.'); if(el.dataset.cloudHeadsLoaded!=='1'||el.dataset.cloudHeadsGroup!==group){await mviappsLoadAccountHeadOptions(selectId,group);throw new Error('Cloud '+group+' Account Heads loaded. Please select the correct Account Head and save again.');} const id=String(el.value||'');if(!id)throw new Error('Please select a valid Production Cloud '+group+' Account Head.'); const row=getAccountHeads().find(x=>String(x.id)===id&&String(x.group||'').toLowerCase()===group.toLowerCase()); if(!row)throw new Error('Selected Account Head is no longer active. Reload the form and select again.'); return {id,name:String(row.name||'')}; } function expensePage(){ const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]').slice().sort((a,b)=>String(a.name||'').localeCompare(String(b.name||''),undefined,{sensitivity:'base',numeric:true})); const opts=parties.map(p=>``).join(''); const cats=getExpenseCategories(); return `

Expenses

Record business expenses with or without a party, just like a practical business accounting workflow.

Saved Expenses

View, modify or delete expense entries.

DateExpense No.CategoryPartyPayment ModeAmountAction
`; } function openExpenseDatePicker(){ const picker=document.getElementById('expenseDate'); if(!picker)return; try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();} catch(e){try{picker.click();}catch(ignore){}} } function syncExpenseDateDisplay(){ const date=document.getElementById('expenseDate')?.value||''; const display=document.getElementById('expenseDateDisplay'); if(display)display.value=date?date.split('-').reverse().join('/') : ''; } function prepareExpenseManualDate(){ const display=document.getElementById('expenseDateDisplay'); if(display&&!display.dataset.manualReady){display.value='';display.dataset.manualReady='1';} } function formatExpenseDateInput(el){ if(!el)return;el.dataset.manualReady='1'; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out; } function syncExpenseManualDate(){ const display=document.getElementById('expenseDateDisplay'),picker=document.getElementById('expenseDate');if(!display||!picker)return; let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/');if(!value){delete display.dataset.manualReady;return;} const parts=value.split('/'); if(parts.length===3){const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2]; if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){const test=new Date(Number(yyyy),Number(mm)-1,Number(dd)); if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;return;}}} syncExpenseDateDisplay();delete display.dataset.manualReady; } function toggleExpenseParty(){const type=document.getElementById('expenseEntryType')?.value,wrap=document.getElementById('expensePartyWrap');if(wrap)wrap.style.display=type==='party'?'block':'none';const p=document.getElementById('expenseParty');if(type!=='party'&&p)p.value='';updateExpenseSummary();} function updateExpenseSummary(){const c=document.getElementById('expenseSummaryCategory'),p=document.getElementById('expenseSummaryParty');if(c)c.textContent=document.getElementById('expenseCategory')?.value||'—';const sel=document.getElementById('expenseParty');if(p)p.textContent=sel?.selectedOptions?.[0]?.textContent&&sel.value?sel.selectedOptions[0].textContent:'Not linked';} function updateExpenseTotal(){const e=document.getElementById('expenseGrand');if(e)e.textContent='₹ '+(Number(document.getElementById('expenseAmount')?.value)||0).toFixed(2);updateExpenseSummary();} function clearExpense(){show('expenses');} async function saveExpense(){ if(!ensureEntryDateInActiveFY(document.getElementById('expenseDate')?.value,'Date'))return; const cloud=window.mviappsProductionCloud,identity=cloud?.getIdentity?.(); if(!identity){alert('Production Owner/Staff login is required. Expense was not saved locally.');return;} try{ if(identity.mode==='staff'&&!cloud.hasStaffPermission('expenses','create'))throw new Error('Staff permission denied: expenses.create'); if(window._editingExpenseId)throw new Error('Posted Production Cloud Expenses are immutable. Use the approved reversal/correction workflow when available.'); const selectedExpenseHead=await mviappsEnsureAccountHeadSelection('expenseCategory','Expenses');let no=document.getElementById('expenseNo')?.value.trim()||'';const date=document.getElementById('expenseDate')?.value||'',category=selectedExpenseHead.name,accountHeadId=selectedExpenseHead.id,amount=Number(document.getElementById('expenseAmount')?.value)||0; const entryType=document.getElementById('expenseEntryType')?.value||'direct',partyId=entryType==='party'?(document.getElementById('expenseParty')?.value||''):''; const mode=document.getElementById('expenseMode')?.value||'Cash',bankAccountId=document.getElementById('expenseBank')?.value||''; if(!no)throw new Error('Expense No. is required.');if(!date)throw new Error('Expense Date is required.');if(!category)throw new Error('Please select an Expense Category.'); if(!(amount>0)||!Number.isFinite(amount))throw new Error('Please enter a valid amount.'); if(entryType==='party'&&!partyId)throw new Error('Please select a Supplier/Party or choose Expense without Party.'); if(mode==='Credit'&&(!partyId||entryType!=='party'))throw new Error('Credit Expense must be linked to a Supplier/Party.'); if(!['Cash','Bank','UPI','Cheque','Card','Credit'].includes(mode))throw new Error('Select a valid Expense Payment Mode.'); if(mode!=='Cash'&&mode!=='Credit'&&!bankAccountId)throw new Error('Please select a Cloud Bank Account.'); if(identity.mode==='staff'&&mode!=='Cash'&&mode!=='Credit'&&!cloud.hasStaffPermission('bankCash','create'))throw new Error('Staff permission denied: bankCash.create'); const [partyResult,expenseResult]=await Promise.all([ window.mviappsCloudBusinessData.readAll('parties',{pageSize:100,maxPages:100}), window.mviappsCloudBusinessData.readAll('expenses',{pageSize:100,maxPages:100}) ]); if(!partyResult.complete||!expenseResult.complete)throw new Error('Cloud Party or Expense list is incomplete; Expense was not saved.'); const partyRow=partyId?partyResult.records.find(x=>String(x.id)===String(partyId)):null; if(partyId&&!partyRow)throw new Error('Selected Supplier/Party was not found in Production Cloud. Refresh and try again.'); if(partyRow&&!['supplier','both'].includes(String(partyRow.record.type||partyRow.record.partyType||'').toLowerCase()))throw new Error('Expense Party must be Supplier or Both type.'); const pendingKey='mviapps_production_pending_expense_v1';let pending=null;try{pending=JSON.parse(sessionStorage.getItem(pendingKey)||'null');}catch{pending=null;} if(pending?.record?.number){no=String(pending.record.number);const noEl=document.getElementById('expenseNo');if(noEl)noEl.value=no;} else{const nums=expenseResult.records.map(x=>String(x.record?.number||'').match(/(\d+)$/)).filter(Boolean).map(x=>Number(x[1])).filter(Number.isFinite);no='EXP-'+String((nums.length?Math.max(...nums):0)+1).padStart(5,'0');const noEl=document.getElementById('expenseNo');if(noEl)noEl.value=no;} if(expenseResult.records.some(x=>String(x.record?.number||'').trim().toLowerCase()===no.toLowerCase()&&String(x.id)!==String(pending?.record?.id||'')))throw new Error('This Expense No. already exists in Production Cloud. Refresh the list.'); const formSnapshot={number:no,date,category,accountHeadId,entryType,partyId:String(partyId||''),amount,paymentMode:mode,bankAccountId:mode==='Cash'||mode==='Credit'?'':String(bankAccountId),reference:document.getElementById('expenseReference')?.value||'',notes:document.getElementById('expenseNotes')?.value||''}; let record,mutationId; if(pending?.record&&pending?.mutationId){const prior=pending.record;const same=Object.keys(formSnapshot).every(k=>String(prior[k]??'')===String(formSnapshot[k]??''));if(!same)throw new Error('A previous Expense request may already have reached Cloud. Restore the same details and retry, or refresh Cloud Expenses and verify it before starting another Expense.');record=prior;mutationId=String(pending.mutationId);} else{record={id:'EXP-'+crypto.randomUUID(),...formSnapshot,partyName:String(partyRow?.record.name||partyRow?.record.partyName||''),account:mode==='Cash'?'cash-on-hand':mode==='Credit'?'':bankAccountId};mutationId='expense-'+crypto.randomUUID();sessionStorage.setItem(pendingKey,JSON.stringify({record,mutationId}));} const result=await cloud.businessDataRequest('/business/expenses/post',{method:'POST',id:record.id,record,mutationId}); if(!result?.saved)throw new Error('Worker did not confirm Expense posting.'); sessionStorage.removeItem(pendingKey);window._mviappsCloudExpenseRows=null;window._editingExpenseId=null; alert(result.alreadyApplied?'This Expense was already saved.':'Expense saved successfully in Production Cloud with Accounting Journal.');show('expenses');return; }catch(error){alert(error?.message||'Expense could not be saved. No local fallback was used.');return;} } function openExpenseListDatePicker(which){const picker=document.getElementById(which==='from'?'expenseListFrom':'expenseListTo');if(!picker)return;try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();}catch(e){try{picker.click();}catch(ignore){}}} function syncExpenseListDateDisplay(which){const picker=document.getElementById(which==='from'?'expenseListFrom':'expenseListTo'),display=document.getElementById(which==='from'?'expenseListFromDisplay':'expenseListToDisplay');if(display)display.value=picker?.value?picker.value.split('-').reverse().join('/') : '';renderExpenses();} function prepareExpenseListManualDate(which){const display=document.getElementById(which==='from'?'expenseListFromDisplay':'expenseListToDisplay');if(display&&!display.dataset.manualReady){display.value='';display.dataset.manualReady='1';}} function formatExpenseListDateInput(el){if(!el)return;el.dataset.manualReady='1';const digits=(el.value||'').replace(/\D/g,'').slice(0,8);let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out;} function syncExpenseListManualDate(which){const display=document.getElementById(which==='from'?'expenseListFromDisplay':'expenseListToDisplay'),picker=document.getElementById(which==='from'?'expenseListFrom':'expenseListTo');if(!display||!picker)return;let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/');if(!value){picker.value='';delete display.dataset.manualReady;renderExpenses();return;}const parts=value.split('/');if(parts.length===3){const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2];if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){const test=new Date(Number(yyyy),Number(mm)-1,Number(dd));if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;renderExpenses();return;}}}syncExpenseListDateDisplay(which);delete display.dataset.manualReady;} function initExpenseListDateRange(){const now=new Date(),y=now.getFullYear(),m=now.getMonth();const iso=d=>d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+String(d.getDate()).padStart(2,'0');const from=document.getElementById('expenseListFrom'),to=document.getElementById('expenseListTo');if(!from||!to)return;if(!from.value)from.value=iso(new Date(y,m,1));if(!to.value)to.value=iso(new Date(y,m+1,0));document.getElementById('expenseListFromDisplay').value=from.value.split('-').reverse().join('/');document.getElementById('expenseListToDisplay').value=to.value.split('-').reverse().join('/');} async function mviappsLoadCloudExpenses(){ const bridge=window.mviappsCloudBusinessData;if(!bridge?.readAll)throw new Error('Production Cloud Expenses adapter is unavailable.'); const result=await bridge.readAll('expenses',{pageSize:100,maxPages:100});if(!result.complete)throw new Error('Cloud Expense list is incomplete; do not treat it as the full list.'); window._mviappsCloudExpenseRows=(result.records||[]).map(x=>({...x.record,id:String(x.id),updatedAt:x.updatedAt||null}));return window._mviappsCloudExpenseRows; } async function mviappsLoadExpenseCloudMasters(){ const identity=window.mviappsProductionCloud?.getIdentity?.();if(!identity)return; try{ const [p,b]=await Promise.all([window.mviappsCloudBusinessData.readAll('parties',{pageSize:100,maxPages:100}),window.mviappsCloudBusinessData.readAll('bankAccounts',{pageSize:100,maxPages:100})]); if(!p.complete||!b.complete)throw new Error('Cloud Party or Bank Account list is incomplete.'); const parties=p.records.filter(x=>['supplier','both'].includes(String(x.record.type||x.record.partyType||'').toLowerCase())).sort((a,b)=>String(a.record.name||'').localeCompare(String(b.record.name||''))); const party=document.getElementById('expenseParty');if(party){const selected=party.value;party.innerHTML=''+parties.map(x=>``).join('');party.value=selected;} const bank=document.getElementById('expenseBank');if(bank){const selected=bank.value;bank.innerHTML=''+b.records.map(x=>``).join('');bank.value=selected;} const expenses=await mviappsLoadCloudExpenses();const nums=expenses.map(x=>String(x.number||'').match(/(\d+)$/)).filter(Boolean).map(x=>Number(x[1])).filter(Number.isFinite);const next=(nums.length?Math.max(...nums):0)+1;const no=document.getElementById('expenseNo');if(no&&!window._editingExpenseId)no.value='EXP-'+String(next).padStart(5,'0'); }catch(e){console.error('Cloud Expense masters failed',e);const rows=document.getElementById('expenseRows');if(rows)rows.innerHTML=`${escapeHtml(e.message||'Cloud Expense data unavailable.')}`;} } async function renderExpenses(){const rows=document.getElementById('expenseRows');if(!rows)return;initExpenseListDateRange();const from=document.getElementById('expenseListFrom')?.value||'',to=document.getElementById('expenseListTo')?.value||''; const identity=window.mviappsProductionCloud?.getIdentity?.();if(!identity){rows.innerHTML='Production login required. Local Expense records are not used in Fresh Production.';return;} rows.innerHTML='Loading Production Cloud Expenses…'; try{const cloudRows=await mviappsLoadCloudExpenses();const arr=filterByActiveFinancialYear(cloudRows).filter(x=>(!from||String(x.date||'')>=from)&&(!to||String(x.date||'')<=to)); rows.innerHTML=arr.length?arr.slice().reverse().map(x=>`${escapeHtml(x.date||'')}${escapeHtml(x.number||'')}${escapeHtml(x.category||'')}${escapeHtml(x.partyName||'Direct Expense')}${escapeHtml(x.paymentMode||'')}₹ ${Number(x.amount||0).toFixed(2)}`).join(''):`No Cloud Expenses found for the selected period.`; }catch(e){rows.innerHTML=`Cloud Expenses could not be loaded: ${escapeHtml(e.message||'Unknown error')}`;} } function getExpense(id){return (window._mviappsCloudExpenseRows||[]).find(x=>String(x.id)===String(id))||null;} function viewExpense(id){const x=getExpense(id);if(!x)return;const old=document.getElementById('expenseModal');if(old)old.remove();document.body.insertAdjacentHTML('beforeend',`

Expense ${escapeHtml(x.number||'')}


Date
${escapeHtml(x.date||'')}
Category
${escapeHtml(x.category||'')}
Party
${escapeHtml(x.partyName||'Direct Expense')}
Payment Mode
${escapeHtml(x.paymentMode||'')}
Account
${escapeHtml(mviappsBankDisplay(x.account||x.bankAccount||''))}
Reference
${escapeHtml(x.reference||'')}
Description

${escapeHtml(x.notes||'—')}

₹ ${Number(x.amount||0).toFixed(2)}

Posted Cloud Expenses are read-only. Corrections require an approved reversal workflow.

`);} function editExpense(id){alert('Posted Production Cloud Expenses are immutable. Use the approved reversal/correction workflow when available.');} function deleteExpense(id){alert('Posted Production Cloud Expenses cannot be deleted directly. Use the approved reversal/correction workflow when available.');} function updateExpense(){alert('Posted Production Cloud Expenses are immutable. Use the approved reversal/correction workflow when available.');} function receivablePage(){ return `

Receivable

Customer-wise outstanding balances based on Production Cloud credit sales, receipts and sales returns.

Total Receivable
Loading Cloud data…
CustomerOpening ReceivableCredit SalesPayment-InSales ReturnClosing ReceivableAction
Loading Production Cloud Receivables…
`; } function payablePage(){ return `

Payable

Party-wise payable balances based on actual credit purchases, expenses and purchase returns.

Total Payable
Loading Cloud data…
PartyOpening PayableCredit PurchaseCredit ExpensePayment-OutPurchase ReturnClosing PayableAction
Loading Production Cloud Payables…
`; } function payableMoney(v){return Number(String(v??'').replace(/,/g,'').replace(/[^0-9.-]/g,''))||0;} function payableDateInRange(x,from,to){const d=String(x.date||'');return (!from||d>=from)&&(!to||d<=to);} function payablePartyId(x){return String(x.partyId||x.supplierId||x.customerId||x.supplier||x.customer||x.party||'');} function renderReceivable(){return renderProductionCloudReceivable();} function formatPartyOutstandingDate(value){const v=String(value||'');return /^\d{4}-\d{2}-\d{2}$/.test(v)?v.split('-').reverse().join('/'):v;} function partyOutstandingDateIds(type,which){const prefix=type==='receivable'?'receivable':'payable';return {picker:prefix+(which==='from'?'From':'To'),display:prefix+(which==='from'?'From':'To')+'Display'};} function syncPartyOutstandingDateDisplay(type,which){const ids=partyOutstandingDateIds(type,which),picker=document.getElementById(ids.picker),display=document.getElementById(ids.display);if(display)display.value=picker?.value?formatPartyOutstandingDate(picker.value):'';} function formatPartyOutstandingDateInput(el){if(!el)return;const digits=(el.value||'').replace(/\D/g,'').slice(0,8);let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out;} function syncPartyOutstandingManualDate(type,which){const ids=partyOutstandingDateIds(type,which),display=document.getElementById(ids.display),picker=document.getElementById(ids.picker);if(!display||!picker)return;let value=(display.value||'').trim().replace(/[.\\-]/g,'/');if(!value){picker.value='';display.value='';type==='receivable'?renderReceivable():renderPayable();return;}const parts=value.split('/');if(parts.length===3){const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2];if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){const test=new Date(Number(yyyy),Number(mm)-1,Number(dd));if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;type==='receivable'?renderReceivable():renderPayable();return;}}}syncPartyOutstandingDateDisplay(type,which);type==='receivable'?renderReceivable():renderPayable();} function openPartyOutstandingDatePicker(type,which){const ids=partyOutstandingDateIds(type,which),picker=document.getElementById(ids.picker);if(!picker)return;try{if(typeof picker.showPicker==='function')picker.showPicker();else{picker.focus();picker.click();}}catch(e){picker.focus();picker.click();}} function renderPayable(){ const rows=document.getElementById('payableRows');if(!rows)return; const q=(document.getElementById('payableSearch')?.value||'').toLowerCase().trim(),from=document.getElementById('payableFrom')?.value||'',to=document.getElementById('payableTo')?.value||''; let data=getPartyOutstandingData(from,to).filter(r=>r.payable>0 && (!q||String(r.name).toLowerCase().includes(q))); data.sort((a,b)=>String(a.name||'').localeCompare(String(b.name||''),undefined,{sensitivity:'base',numeric:true})); rows.innerHTML=data.length?data.map(r=>` ${escapeHtml(r.name)} ${plMoney(r.creditPurchases)} ${plMoney(r.creditExpenses)} ${plMoney(-r.purchaseReturns)} ${plMoney(r.payable)} `).join(''):`No payable balance found.`; } function paintProductionCloudReceivableRows(all,from,to){ const rows=document.getElementById('receivableRows'),summary=document.getElementById('receivableSummary');if(!rows)return; const q=(document.getElementById('receivableSearch')?.value||'').toLowerCase().trim(),data=(all||[]).filter(r=>!q||r.name.toLowerCase().includes(q)); const total=data.reduce((n,r)=>n+r.receivable,0),opening=data.reduce((n,r)=>n+r.openingReceivable,0),sales=data.reduce((n,r)=>n+r.creditSales,0),payments=data.reduce((n,r)=>n+r.paymentIn,0),returns=data.reduce((n,r)=>n+r.salesReturns,0),fmt=n=>'₹ '+Number(n||0).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}); if(summary)summary.innerHTML=`
Total Closing Receivable
${fmt(total)}
Opening Receivable
${fmt(opening)}
Credit Sales
${fmt(sales)}
Payment-In
${fmt(payments)}
Sales Returns
${fmt(returns)}
Customer Parties with Balance
${data.length}
Period
${from.split('-').reverse().join('/')} – ${to.split('-').reverse().join('/')}
`; rows.innerHTML=data.length?data.map(r=>`${escapeHtml(r.name)}${fmt(r.openingReceivable)}${fmt(r.creditSales)}${fmt(-r.paymentIn)}${fmt(-r.salesReturns)}${fmt(r.receivable)}`).join(''):`No Cloud Receivable balance found for the selected period.`; } async function renderProductionCloudReceivable(){ const rows=document.getElementById('receivableRows');if(!rows)return; const summary=document.getElementById('receivableSummary'),identity=window.mviappsProductionCloud?.getIdentity?.(); if(!identity){rows.innerHTML='Production Owner/Staff login required. Local or Ver 4.5 records are not used in Fresh Production Receivable.';if(summary)summary.innerHTML='
Total Receivable
—
';return;} rows.innerHTML='Loading complete Production Cloud Receivable data…'; if(summary)summary.innerHTML='
Total Receivable
Loading…
'; try{ const bridge=window.mviappsCloudBusinessData;if(!bridge?.readAll)throw new Error('Production Cloud data adapter is unavailable.'); const fy=getFinancialYearBounds(),rawFrom=document.getElementById('receivableFrom')?.value||'',rawTo=document.getElementById('receivableTo')?.value||'',from=rawFrom||fy.from,to=rawTo||fy.to; if(!from||!to||from>to)throw new Error('Select a valid Receivable date range.'); if(Array.isArray(window._mviappsCloudReceivableRows)&&window._mviappsCloudReceivablePeriod?.from===from&&window._mviappsCloudReceivablePeriod?.to===to){paintProductionCloudReceivableRows(window._mviappsCloudReceivableRows,from,to);return;} const [partyResult,salesResult,returnResult,paymentResult]=await Promise.all([ bridge.readAll('parties',{pageSize:100,maxPages:100}), bridge.readAll('salesInvoices',{pageSize:100,maxPages:100}), bridge.readAll('salesReturns',{pageSize:100,maxPages:100}), bridge.readAll('paymentIn',{pageSize:100,maxPages:100}) ]); const results=[partyResult,salesResult,returnResult,paymentResult]; if(results.some(x=>!x?.complete))throw new Error('One or more Cloud collections are incomplete. Receivable totals are withheld rather than showing a partial balance.'); const norm=v=>String(v??'').trim().toLowerCase(); const isoDate=v=>{const x=String(v??'').trim();if(/^\d{4}-\d{2}-\d{2}$/.test(x)){const d=new Date(x+'T00:00:00.000Z');return Number.isFinite(d.getTime())&&d.toISOString().slice(0,10)===x?x:'';}const m=x.match(/^(\d{1,2})[\/.-](\d{1,2})[\/.-](\d{4})$/);if(!m)return '';const candidate=`${m[3]}-${m[2].padStart(2,'0')}-${m[1].padStart(2,'0')}`,d=new Date(candidate+'T00:00:00.000Z');return Number.isFinite(d.getTime())&&d.toISOString().slice(0,10)===candidate?candidate:'';}; const moneyPaise=v=>{if(v===null||v===undefined||String(v).trim()==='')return 0;const c=String(v).replace(/,/g,'').replace(/[^0-9.-]/g,'');if(!c||!/^-?(?:\d+\.?\d*|\.\d+)$/.test(c.trim()))return NaN;const n=Number(c);return Number.isFinite(n)&&Math.abs(n)<=90000000000000?Math.round(n*100):NaN;}; const parties=partyResult.records.map(x=>({...x.record,id:String(x.id)})).filter(p=>['customer','both'].includes(norm(p.type||p.partyType))); const txRows=[]; const append=(result,type)=>{for(const item of result.records){const r=item.record||{},date=isoDate(r.date);if(!date)throw new Error('Invalid or missing date in Cloud '+type+' record '+String(item.id)+'.');let amount=0,debit=0,credit=0; if(type==='sales_invoice'){if(norm(r.paymentMode)!=='credit')continue;amount=moneyPaise(r.total??r.totalAmount??0);debit=amount;} else if(type==='sales_return'){amount=moneyPaise(r.total??r.totalAmount??0);credit=amount;} else if(type==='payment_in'){amount=moneyPaise(r.amount??0);credit=amount;} if(!Number.isSafeInteger(amount)||amount<0||!Number.isSafeInteger(debit)||!Number.isSafeInteger(credit))throw new Error('Invalid or negative amount in Cloud '+type+' record '+String(item.id)+'. Receivable calculation stopped safely.'); if(amount===0)continue; const aliases=[r.partyId,r.customerId,r.customer,r.party,r.customerName,r.partyName].map(norm).filter(Boolean); txRows.push({id:String(item.id),date,type,debit,credit,aliases}); }}; append(salesResult,'sales_invoice');append(returnResult,'sales_return');append(paymentResult,'payment_in'); const all=[]; for(const p of parties){const id=String(p.id||'');if(!id)continue;const aliases=new Set([id,p.name,p.partyName].map(norm).filter(Boolean)),linked=txRows.filter(t=>t.aliases.some(a=>aliases.has(a))); const opening=moneyPaise(p.opening??0);if(!Number.isSafeInteger(opening))throw new Error('Invalid opening balance for Cloud Party '+String(p.name||id)+'.'); const openingDate=isoDate(p.openingDate||'');const signedOpening=norm(p.balanceType)==='credit'?-Math.abs(opening):Math.abs(opening),defaultFY=!rawFrom&&!rawTo; let openingAtStart=(openingDate&&openingDate>from)?0:signedOpening;if(defaultFY&&openingDate&&openingDate>from&&openingDate<=to)openingAtStart=signedOpening; let closing=openingAtStart;const totals={creditSales:0,paymentIn:0,salesReturns:0}; linked.sort((a,b)=>a.date.localeCompare(b.date)||a.type.localeCompare(b.type)||a.id.localeCompare(b.id)); for(const t of linked){if(openingDate&&t.dateto)continue;const delta=t.debit-t.credit;if(t.datea.name.localeCompare(b.name,undefined,{sensitivity:'base',numeric:true}));window._mviappsCloudReceivableRows=all;window._mviappsCloudReceivablePeriod={from,to};paintProductionCloudReceivableRows(all,from,to); }catch(error){window._mviappsCloudReceivableRows=null;rows.innerHTML=`Cloud Receivable could not be calculated: ${escapeHtml(error?.message||'Unknown error')}`;if(summary)summary.innerHTML='
Total Receivable
Not available
';} } function clearReceivableFilters(){['receivableSearch','receivableFrom','receivableTo','receivableFromDisplay','receivableToDisplay'].forEach(id=>{const e=document.getElementById(id);if(e)e.value='';});renderReceivable();} function clearPayableFilters(){['payableSearch','payableFrom','payableTo','payableFromDisplay','payableToDisplay'].forEach(id=>{const e=document.getElementById(id);if(e)e.value='';});renderPayable();} function payableDateInRange(x,from,to){const d=String(x.date||'');return (!from||d>=from)&&(!to||d<=to);} function payablePartyId(x){return String(x.partyId||x.supplierId||x.customerId||x.supplier||x.customer||x.party||'');} /* Party outstanding is calculated from the actual party ledger: Customer: credit sales less receipts and sales returns = Receivable. Supplier: credit purchases/expenses less payments and purchase returns = Payable. Both: each side is calculated independently. */ function getPartyOutstandingData(from='',to=''){ const fyb=getFinancialYearBounds(); if(!from)from=fyb.from; if(!to)to=fyb.to; const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const map={}; parties.forEach(p=>{ const id=String(p.id||p.name||''); if(id)map[id]={id,name:p.name||'Unnamed Party',type:p.type||'Both',opening:Number(p.opening)||0,openingDate:getPartyOpeningDate(p),openingType:String(p.balanceType||'Debit').toLowerCase(),receivable:0,payable:0,creditSales:0,paymentIn:0,salesReturns:0,creditPurchases:0,paymentOut:0,purchaseReturns:0,creditExpenses:0}; }); const ensure=(x)=>{ const id=payablePartyId(x);if(!id)return null; if(!map[id])map[id]={id,name:x.partyName||x.customerName||x.supplierName||x.party||id,type:'Both',opening:0,openingDate:'',openingType:'debit',receivable:0,payable:0,creditSales:0,paymentIn:0,salesReturns:0,creditPurchases:0,paymentOut:0,purchaseReturns:0,creditExpenses:0}; if(!map[id].name||map[id].name===id)map[id].name=x.partyName||x.customerName||x.supplierName||x.party||id; return map[id]; }; const allByParty={}; const addTx=(key)=>JSON.parse(localStorage.getItem(key)||'[]').forEach(x=>{ const id=payablePartyId(x),d=String(x.date||'');if(!id||!d)return; const r=ensure(x);if(!r)return; let debit=0,credit=0,kind=''; if(key==='mviapps_sales_invoices'&&String(x.paymentMode||'').toLowerCase()==='credit'){debit=payableMoney(x.total);kind='creditSales';} else if(key==='mviapps_sales_returns'){credit=payableMoney(x.total);kind='salesReturns';} else if(key==='mviapps_payment_in'){credit=payableMoney(x.amount);kind='paymentIn';} else if(key==='mviapps_purchase_invoices'&&String(x.paymentMode||'').toLowerCase()==='credit'){credit=payableMoney(x.total);kind='creditPurchases';} else if(key==='mviapps_purchase_returns'){debit=payableMoney(x.total);kind='purchaseReturns';} else if(key==='mviapps_payment_out'){debit=payableMoney(x.amount);kind='paymentOut';} else if(key==='mviapps_expenses'&&String(x.paymentMode||'').toLowerCase()==='credit'){credit=payableMoney(x.amount);kind='creditExpenses';} if(debit||credit)(allByParty[id]||(allByParty[id]=[])).push({date:d,debit,credit,kind}); }); ['mviapps_sales_invoices','mviapps_sales_returns','mviapps_payment_in','mviapps_purchase_invoices','mviapps_purchase_returns','mviapps_payment_out','mviapps_expenses'].forEach(addTx); Object.values(map).forEach(r=>{ const openingDate=String(r.openingDate||''); const base=String(r.openingType||'debit')==='credit'?-Math.abs(Number(r.opening)||0):Math.abs(Number(r.opening)||0); let closing=0; // Opening balance applies from its Opening Balance Date. Legacy records use the selected FY start. if(!openingDate || !to || openingDate<=to)closing=base; const tx=(allByParty[r.id]||[]).slice().sort((a,b)=>String(a.date).localeCompare(String(b.date))); tx.forEach(x=>{ if(openingDate&&x.dateto)return; if(from&&x.dater.receivable||r.payable||r.opening||r.creditSales||r.paymentIn||r.salesReturns||r.creditPurchases||r.paymentOut||r.purchaseReturns||r.creditExpenses); } function getPartyOutstandingTotals(from='',to=''){ return getPartyOutstandingData(from,to).reduce((a,r)=>({receivable:a.receivable+r.receivable,payable:a.payable+r.payable}),{receivable:0,payable:0}); } function paintProductionCloudPayableRows(all,from,to){ const rows=document.getElementById('payableRows'),summary=document.getElementById('payableSummary');if(!rows)return; const q=(document.getElementById('payableSearch')?.value||'').toLowerCase().trim(),data=(all||[]).filter(r=>!q||r.name.toLowerCase().includes(q)); const total=data.reduce((n,r)=>n+r.payable,0),opening=data.reduce((n,r)=>n+r.openingPayable,0),purchases=data.reduce((n,r)=>n+r.creditPurchases,0),expenses=data.reduce((n,r)=>n+r.creditExpenses,0),payments=data.reduce((n,r)=>n+r.paymentOut,0),returns=data.reduce((n,r)=>n+r.purchaseReturns,0),fmt=n=>'₹ '+Number(n||0).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}); if(summary)summary.innerHTML=`
Total Closing Payable
${fmt(total)}
Opening Payable
${fmt(opening)}
Credit Purchases
${fmt(purchases)}
Credit Expenses
${fmt(expenses)}
Payment-Out
${fmt(payments)}
Purchase Returns
${fmt(returns)}
Supplier Parties with Balance
${data.length}
Period
${from.split('-').reverse().join('/')} – ${to.split('-').reverse().join('/')}
`; rows.innerHTML=data.length?data.map(r=>`${escapeHtml(r.name)}${fmt(r.openingPayable)}${fmt(r.creditPurchases)}${fmt(r.creditExpenses)}${fmt(-r.paymentOut)}${fmt(-r.purchaseReturns)}${fmt(r.payable)}`).join(''):`No Cloud Payable balance found for the selected period.`; } async function renderPayable(){ const rows=document.getElementById('payableRows');if(!rows)return; const summary=document.getElementById('payableSummary'); const identity=window.mviappsProductionCloud?.getIdentity?.(); if(!identity){rows.innerHTML='Production Owner/Staff login required. Local or Ver 4.5 records are not used in Fresh Production Payable.';if(summary)summary.innerHTML='
Total Payable
—
';return;} rows.innerHTML='Loading complete Production Cloud Payable data…'; if(summary)summary.innerHTML='
Total Payable
Loading…
'; try{ const bridge=window.mviappsCloudBusinessData;if(!bridge?.readAll)throw new Error('Production Cloud data adapter is unavailable.'); const fy=getFinancialYearBounds(),rawFrom=document.getElementById('payableFrom')?.value||'',rawTo=document.getElementById('payableTo')?.value||''; const from=rawFrom||fy.from,to=rawTo||fy.to; if(!from||!to||from>to)throw new Error('Select a valid Payable date range.'); if(Array.isArray(window._mviappsCloudPayableRows)&&window._mviappsCloudPayablePeriod?.from===from&&window._mviappsCloudPayablePeriod?.to===to){paintProductionCloudPayableRows(window._mviappsCloudPayableRows,from,to);return;} const [partyResult,purchaseResult,returnResult,paymentResult,expenseResult]=await Promise.all([ bridge.readAll('parties',{pageSize:100,maxPages:100}), bridge.readAll('purchaseInvoices',{pageSize:100,maxPages:100}), bridge.readAll('purchaseReturns',{pageSize:100,maxPages:100}), bridge.readAll('paymentOut',{pageSize:100,maxPages:100}), bridge.readAll('expenses',{pageSize:100,maxPages:100}) ]); const results=[partyResult,purchaseResult,returnResult,paymentResult,expenseResult]; if(results.some(x=>!x?.complete))throw new Error('One or more Cloud collections are incomplete. Payable totals are withheld rather than showing a partial balance.'); const norm=v=>String(v??'').trim().toLowerCase(); const isoDate=v=>{const x=String(v??'').trim();if(/^\d{4}-\d{2}-\d{2}$/.test(x)){const d=new Date(x+'T00:00:00.000Z');return Number.isFinite(d.getTime())&&d.toISOString().slice(0,10)===x?x:'';}const m=x.match(/^(\d{1,2})[\/.-](\d{1,2})[\/.-](\d{4})$/);if(!m)return '';const y=m[3],mo=m[2].padStart(2,'0'),day=m[1].padStart(2,'0'),candidate=`${y}-${mo}-${day}`,d=new Date(candidate+'T00:00:00.000Z');return Number.isFinite(d.getTime())&&d.toISOString().slice(0,10)===candidate?candidate:'';}; const moneyPaise=v=>{if(v===null||v===undefined||String(v).trim()==='')return 0;const c=String(v).replace(/,/g,'').replace(/[^0-9.-]/g,'');if(!c||!/^-?(?:\d+\.?\d*|\.\d+)$/.test(c))return NaN;const n=Number(c);return Number.isFinite(n)&&Math.abs(n)<=90000000000000?Math.round(n*100):NaN;}; const parties=partyResult.records.map(x=>({...x.record,id:String(x.id)})).filter(p=>['supplier','both'].includes(norm(p.type||p.partyType))); const txRows=[]; const append=(result,type)=>{for(const item of result.records){const r=item.record||{},date=isoDate(r.date);if(!date)continue;let amount=0,debit=0,credit=0; if(type==='purchase_invoice'){if(norm(r.paymentMode)!=='credit')continue;amount=moneyPaise(r.total??0);credit=amount;} else if(type==='purchase_return'){amount=moneyPaise(r.total??0);debit=amount;} else if(type==='payment_out'){amount=moneyPaise(r.amount??0);debit=amount;} else if(type==='expense'){if(norm(r.paymentMode)!=='credit')continue;amount=moneyPaise(r.amount??0);credit=amount;} if(!Number.isSafeInteger(amount)||!Number.isSafeInteger(debit)||!Number.isSafeInteger(credit))throw new Error('Invalid amount in Cloud '+type+' record '+String(item.id)+'. Payable calculation stopped safely.'); if(amount===0)continue; const aliases=[r.partyId,r.supplierId,r.customerId,r.party,r.supplier,r.customer,r.partyName,r.supplierName,r.customerName].map(norm).filter(Boolean); txRows.push({id:String(item.id),date,type,debit,credit,aliases}); }}; append(purchaseResult,'purchase_invoice');append(returnResult,'purchase_return');append(paymentResult,'payment_out');append(expenseResult,'expense'); const all=[]; for(const p of parties){ const id=String(p.id||'');if(!id)continue; const aliases=new Set([id,p.name,p.partyName].map(norm).filter(Boolean)); const linked=txRows.filter(t=>t.aliases.some(a=>aliases.has(a))); const opening=moneyPaise(p.opening??0);if(!Number.isSafeInteger(opening))throw new Error('Invalid opening balance for Cloud Party '+String(p.name||id)+'.'); const openingDate=isoDate(p.openingDate||'');const signedOpening=norm(p.balanceType)==='credit'?-Math.abs(opening):Math.abs(opening); const defaultFY=!rawFrom&&!rawTo; let openingAtStart=(openingDate&&openingDate>from)?0:signedOpening; if(defaultFY&&openingDate&&openingDate>from&&openingDate<=to)openingAtStart=signedOpening; let closing=openingAtStart; const totals={creditPurchases:0,creditExpenses:0,paymentOut:0,purchaseReturns:0}; linked.sort((a,b)=>a.date.localeCompare(b.date)||a.type.localeCompare(b.type)||a.id.localeCompare(b.id)); for(const t of linked){if(openingDate&&t.dateto)continue;const delta=t.debit-t.credit;if(t.date=from){closing+=delta;if(t.type==='purchase_invoice')totals.creditPurchases+=t.credit;if(t.type==='expense')totals.creditExpenses+=t.credit;if(t.type==='payment_out')totals.paymentOut+=t.debit;if(t.type==='purchase_return')totals.purchaseReturns+=t.debit;}} const payable=Math.max(0,-closing/100);if(payable<=0)continue; all.push({id,name:String(p.name||p.partyName||id),openingPayable:Math.max(0,-openingAtStart/100),creditPurchases:totals.creditPurchases/100,creditExpenses:totals.creditExpenses/100,paymentOut:totals.paymentOut/100,purchaseReturns:totals.purchaseReturns/100,payable,closingSigned:closing/100}); } all.sort((a,b)=>a.name.localeCompare(b.name,undefined,{sensitivity:'base',numeric:true})); window._mviappsCloudPayableRows=all;window._mviappsCloudPayablePeriod={from,to}; paintProductionCloudPayableRows(all,from,to); }catch(error){window._mviappsCloudPayableRows=null;rows.innerHTML=`Cloud Payable could not be calculated: ${escapeHtml(error?.message||'Unknown error')}`;if(summary)summary.innerHTML='
Total Payable
Not available
';} } function clearPayableFilters(){['payableSearch','payableFrom','payableTo','payableFromDisplay','payableToDisplay'].forEach(id=>{const e=document.getElementById(id);if(e)e.value='';});renderPayable();} function payment(type){ window._accountEntryType=type; const isOther=type==='Other Income', isIn=type==='Payment-In'; const key=isOther?'mviapps_other_income':(isIn?'mviapps_payment_in':'mviapps_payment_out'); const prefix=isOther?'INC':(isIn?'REC':'PAY'); const noLabel=isOther?'Income No.':(isIn?'Receipt No.':'Payment No.'); const partyLabel=isOther?'Income Head':(isIn?'Received From':'Paid To'); const action=isOther?'Save Income':(isIn?'Save Receipt':'Save Payment'); const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const incomeHeadOptions=''; const partyOptions=parties.map(p=>``).join(''); const partyField=isOther ? `
` : `
`; const now=new Date(), year=now.getFullYear(), monthIndex=now.getMonth(); const firstMonthDate=year+'-'+String(monthIndex+1).padStart(2,'0')+'-01'; const lastMonthDate=year+'-'+String(monthIndex+1).padStart(2,'0')+'-'+String(new Date(year,monthIndex+1,0).getDate()).padStart(2,'0'); const firstMonthDisplay='01/'+String(monthIndex+1).padStart(2,'0')+'/'+year; const lastMonthDisplay=String(new Date(year,monthIndex+1,0).getDate()).padStart(2,'0')+'/'+String(monthIndex+1).padStart(2,'0')+'/'+year; return `

${type}

${isOther?'Record and track non-sales income.':(isIn?'Record customer receipts and collections.':'Record supplier payments and other outgoing payments.')}

${!isOther&&!!window.mviappsProductionCloud?.getIdentity?.()?``:''}
${isIn?`

Payment-In Entries

Current month entries are shown by default. Select From Date and To Date to view older entries.

From Date
To Date
Date${noLabel}${partyLabel}Payment ModeAmountAction
`:`

${isOther?'Other Income Entries':'Payment-Out Entries'}

${isOther?'Current month entries are shown by default. Select From Date and To Date to view older entries.':'View recorded outgoing payments.'}

${isOther?`
From Date
To Date
`:`
From Date
To Date
`}
Date${noLabel}${partyLabel}Payment ModeAmountAction
`}`; } function openPaymentInDatePicker(){ const picker=document.getElementById('accountDate'); if(!picker)return; try{ picker.focus({preventScroll:true}); if(typeof picker.showPicker==='function') picker.showPicker(); }catch(e){ try{picker.click();}catch(ignore){} } } function syncPaymentInDateDisplay(){ const date=document.getElementById('accountDate')?.value||''; const display=document.getElementById('accountDateDisplay'); if(display) display.value=date?date.split('-').reverse().join('/') : ''; } function preparePaymentInManualDate(){ const display=document.getElementById('accountDateDisplay'); if(display && !display.dataset.manualReady){ display.value=''; display.dataset.manualReady='1'; } } function formatPaymentInDateInput(el){ if(!el)return; el.dataset.manualReady='1'; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits; if(digits.length>2) out=digits.slice(0,2)+'/'+digits.slice(2); if(digits.length>4) out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4); el.value=out; } function syncPaymentInManualDate(){ const display=document.getElementById('accountDateDisplay'); const picker=document.getElementById('accountDate'); if(!display||!picker)return; let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/'); if(!value)return; const parts=value.split('/'); if(parts.length===3){ const dd=parts[0].padStart(2,'0'); const mm=parts[1].padStart(2,'0'); const yyyy=parts[2]; if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){ const test=new Date(Number(yyyy),Number(mm)-1,Number(dd)); if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){ picker.value=yyyy+'-'+mm+'-'+dd; display.value=dd+'/'+mm+'/'+yyyy; delete display.dataset.manualReady; return; } } } syncPaymentInDateDisplay(); delete display.dataset.manualReady; } function openSalesInvoiceDatePicker(){ const picker=document.getElementById('saleDate'); if(!picker)return; try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();} catch(e){try{picker.click();}catch(ignore){}} } function syncSalesInvoiceDateDisplay(){ const date=document.getElementById('saleDate')?.value||''; const display=document.getElementById('saleDateDisplay'); if(display)display.value=date?date.split('-').reverse().join('/') : ''; } function prepareSalesInvoiceManualDate(){ const display=document.getElementById('saleDateDisplay'); if(display&&!display.dataset.manualReady){display.value='';display.dataset.manualReady='1';} } function formatSalesInvoiceDateInput(el){ if(!el)return;el.dataset.manualReady='1'; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out; } function syncSalesInvoiceManualDate(){ const display=document.getElementById('saleDateDisplay'),picker=document.getElementById('saleDate');if(!display||!picker)return; let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/');if(!value)return; const parts=value.split('/'); if(parts.length===3){const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2]; if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){const test=new Date(Number(yyyy),Number(mm)-1,Number(dd)); if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;return;}}} syncSalesInvoiceDateDisplay();delete display.dataset.manualReady; } function openPurchaseInvoiceDatePicker(){ const picker=document.getElementById('purchaseDate'); if(!picker)return; try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();} catch(e){try{picker.click();}catch(ignore){}} } function syncPurchaseInvoiceDateDisplay(){ const date=document.getElementById('purchaseDate')?.value||''; const display=document.getElementById('purchaseDateDisplay'); if(display)display.value=date?date.split('-').reverse().join('/') : ''; } function preparePurchaseInvoiceDateManual(){ const display=document.getElementById('purchaseDateDisplay'); if(display&&!display.dataset.manualReady){display.value='';display.dataset.manualReady='1';} } function formatPurchaseInvoiceDateInput(el){ if(!el)return;el.dataset.manualReady='1'; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out; } function syncPurchaseInvoiceDateManual(){ const display=document.getElementById('purchaseDateDisplay'),picker=document.getElementById('purchaseDate');if(!display||!picker)return; let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/');if(!value)return; const parts=value.split('/'); if(parts.length===3){const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2]; if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){const test=new Date(Number(yyyy),Number(mm)-1,Number(dd)); if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;return;}}} syncPurchaseInvoiceDateDisplay();delete display.dataset.manualReady; } function openPurchaseInvoiceDueDatePicker(){ const picker=document.getElementById('purchaseDueDate'); if(!picker)return; try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();} catch(e){try{picker.click();}catch(ignore){}} } function syncPurchaseInvoiceDueDateDisplay(){ const date=document.getElementById('purchaseDueDate')?.value||''; const display=document.getElementById('purchaseDueDateDisplay'); if(display)display.value=date?date.split('-').reverse().join('/') : ''; } function preparePurchaseInvoiceDueDateManual(){ const display=document.getElementById('purchaseDueDateDisplay'); if(display&&!display.dataset.manualReady){display.value='';display.dataset.manualReady='1';} } function formatPurchaseInvoiceDueDateInput(el){ if(!el)return;el.dataset.manualReady='1'; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out; } function syncPurchaseInvoiceDueDateManual(){ const display=document.getElementById('purchaseDueDateDisplay'),picker=document.getElementById('purchaseDueDate');if(!display||!picker)return; let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/');if(!value){picker.value='';delete display.dataset.manualReady;return;} const parts=value.split('/'); if(parts.length===3){const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2]; if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){const test=new Date(Number(yyyy),Number(mm)-1,Number(dd)); if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;return;}}} syncPurchaseInvoiceDueDateDisplay();delete display.dataset.manualReady; } function openSalesInvoiceDueDatePicker(){ const picker=document.getElementById('saleDueDate'); if(!picker)return; try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();} catch(e){try{picker.click();}catch(ignore){}} } function syncSalesInvoiceDueDateDisplay(){ const date=document.getElementById('saleDueDate')?.value||''; const display=document.getElementById('saleDueDateDisplay'); if(display)display.value=date?date.split('-').reverse().join('/') : ''; } function prepareSalesInvoiceDueDateManual(){ const display=document.getElementById('saleDueDateDisplay'); if(display&&!display.dataset.manualReady){display.value='';display.dataset.manualReady='1';} } function formatSalesInvoiceDueDateInput(el){ if(!el)return;el.dataset.manualReady='1'; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out; } function syncSalesInvoiceDueDateManual(){ const display=document.getElementById('saleDueDateDisplay'),picker=document.getElementById('saleDueDate');if(!display||!picker)return; let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/');if(!value){picker.value='';delete display.dataset.manualReady;return;} const parts=value.split('/'); if(parts.length===3){const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2]; if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){const test=new Date(Number(yyyy),Number(mm)-1,Number(dd)); if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;return;}}} syncSalesInvoiceDueDateDisplay();delete display.dataset.manualReady; } async function mviappsPreparePaymentInCloudForm(){ return mviappsPreparePaymentCloudForm('Payment-In'); } async function mviappsPreparePaymentOutCloudForm(){ return mviappsPreparePaymentCloudForm('Payment-Out'); } async function mviappsPreparePaymentCloudForm(type){ const isIn=type==='Payment-In',kind=isIn?'paymentIn':'paymentOut',prefix=isIn?'REC':'PAY',identity=window.mviappsProductionCloud?.getIdentity?.(); if(!identity||!window.mviappsCloudBusinessData)return; const partySelect=document.getElementById('accountParty'),bankSelect=document.getElementById('accountBank'); if(!partySelect||!bankSelect)return; try{ const [parties,banks,payments]=await Promise.all([ window.mviappsCloudBusinessData.readAll('parties',{pageSize:100,maxPages:100}), window.mviappsCloudBusinessData.readAll('bankAccounts',{pageSize:100,maxPages:100}), window.mviappsCloudBusinessData.readAll(kind,{pageSize:100,maxPages:100}) ]); if(!parties.complete||!banks.complete||!payments.complete)throw new Error('Cloud Party, Bank Account or '+type+' list is incomplete. Form setup stopped safely.'); const selectedParty=partySelect.value,selectedBank=bankSelect.value; partySelect.innerHTML=''; parties.records.filter(row=>{if(isIn)return true;const t=String(row.record?.type||row.record?.partyType||'').trim().toLowerCase();return t==='supplier'||t==='both';}).forEach(row=>{const option=document.createElement('option');option.value=String(row.id);option.textContent=String(row.record.name||row.record.partyName||'Unnamed Party');partySelect.appendChild(option);}); if(selectedParty)partySelect.value=selectedParty; bankSelect.innerHTML=''; banks.records.forEach(row=>{const option=document.createElement('option');option.value=String(row.id);option.textContent=String(row.record.name||row.record.accountName||row.record.bankName||'Bank Account');bankSelect.appendChild(option);}); if(selectedBank)bankSelect.value=selectedBank; if(isIn)window._mviappsCloudPaymentInRows=payments.records;else window._mviappsCloudPaymentOutRows=payments.records; const used=payments.records.map(x=>String(x.record.number||'').trim().toUpperCase()); let n=1;for(const value of used){const m=value.match(new RegExp('^'+prefix+'-(\\d+)$'));if(m)n=Math.max(n,Number(m[1])+1);} const numberInput=document.getElementById('accountNo'); let pending=null; if(!isIn){try{pending=JSON.parse(sessionStorage.getItem('mviapps_production_pending_payment_out_v1')||'null');}catch{pending=null;} if(pending?.record&&pending?.mutationId){const saved=payments.records.some(x=>String(x.id)===String(pending.record.id)||String(x.record?.id)===String(pending.record.id)||(String(x.record?.number||'').toLowerCase()===String(pending.record.number||'').toLowerCase()&&String(x.record?.partyId||'')===String(pending.record.partyId||'')&&Number(x.record?.amount)===Number(pending.record.amount)&&String(x.record?.date||'')===String(pending.record.date))); if(saved){sessionStorage.removeItem('mviapps_production_pending_payment_out_v1');pending=null;window.__mviappsPaymentOutPendingConfirmed=true;} }else pending=null; } if(numberInput&&!window._editingAccountId){numberInput.value=pending?.record?.number||prefix+'-'+String(n).padStart(4,'0');} if(pending?.record){const r=pending.record;const set=(id,value)=>{const el=document.getElementById(id);if(el)el.value=value??'';};set('accountDate',r.date);set('accountParty',r.partyId);set('accountAmount',r.amount);set('accountMode',r.paymentMode||'Cash');set('accountBank',r.bankAccountId||'');set('accountReference',r.reference||'');set('accountNotes',r.notes||'');if(typeof syncPaymentInDateDisplay==='function')syncPaymentInDateDisplay();} mviappsToggleBankAccount('accountMode','accountBankWrap','accountBank'); renderAccountEntries(type); }catch(error){ const rows=document.getElementById('accountRows');if(rows)rows.innerHTML=''+escapeHtml(error?.message||'Cloud form setup failed.')+''; document.querySelectorAll('#content button[onclick*="saveAccountEntry"]').forEach(button=>{if(String(button.getAttribute('onclick')||'').includes(type))button.disabled=true;}); alert(error?.message||'Could not prepare '+type+' from Production Cloud.'); } } function updateAccountTotal(){const e=document.getElementById('accountGrand');if(e)e.textContent='₹ '+(Number(document.getElementById('accountAmount')?.value)||0).toFixed(2);} function clearAccountEntry(){window._editingAccountId=null;show(window._accountEntryType==='Other Income'?'other-income':window._accountEntryType==='Payment-In'?'payment-in':'payment-out');} async function saveAccountEntry(type){ if(!ensureEntryDateInActiveFY(document.getElementById('accountDate')?.value,'Date'))return; const isOther=type==='Other Income', isIn=type==='Payment-In'; if((isIn||type==='Payment-Out') && !window.mviappsProductionCloud?.getIdentity?.()){alert('Sign in as Production Owner or Staff before saving a Payment-In or Payment-Out entry. Local-only payment saving is disabled.');return;} if(isIn && window.mviappsProductionCloud?.getIdentity?.()){ try{ const cloud=window.mviappsProductionCloud, identity=cloud.getIdentity(); if(identity.mode==='staff' && !cloud.hasStaffPermission('payments','create')) throw new Error('Staff permission denied: payments.create'); const no=document.getElementById('accountNo')?.value.trim()||'', amount=Number(document.getElementById('accountAmount')?.value)||0; const partyId=document.getElementById('accountParty')?.value||'', mode=document.getElementById('accountMode')?.value||'Cash'; const date=document.getElementById('accountDate')?.value||'', account=document.getElementById('accountBank')?.value||''; if(window._editingAccountId) throw new Error('Posted Cloud Payment-In receipts are immutable. Use the approved reversal/correction workflow when available.'); if(!no) throw new Error('Please enter Receipt No.'); if(!(amount>0) || !Number.isFinite(amount)) throw new Error('Please enter a valid amount.'); if(!partyId) throw new Error('Please select a Party.'); if(!date) throw new Error('Please select Receipt Date.'); if(!['Cash','Bank','UPI','Cheque','Card'].includes(mode)) throw new Error('Select a valid Payment Mode.'); if(mode!=='Cash'&&!account) throw new Error('Please select a Cloud Bank Account.'); if(identity.mode==='staff' && mode!=='Cash' && !cloud.hasStaffPermission('bankCash','create')) throw new Error('Staff permission denied: bankCash.create'); const partyResult=await window.mviappsCloudBusinessData.readAll('parties',{pageSize:100,maxPages:20}); if(!partyResult.complete) throw new Error('Cloud Party list is incomplete; receipt was not saved.'); const partyRow=partyResult.records.find(x=>String(x.id)===String(partyId)); if(!partyRow) throw new Error('Selected Party was not found in Production Cloud. Refresh Parties and try again.'); const record={id:'PIN-'+crypto.randomUUID(),number:no,date,partyId:String(partyId),partyName:String(partyRow.record.name||partyRow.record.partyName||''),amount,paymentMode:mode,account:mode==='Cash'?'cash-on-hand':account,bankAccountId:mode==='Cash'?'':account,reference:document.getElementById('accountReference')?.value||'',notes:document.getElementById('accountNotes')?.value||'',receiptType:'on_account'}; const mutationId='payment-in-'+crypto.randomUUID(); const result=await cloud.businessDataRequest('/business/payment-in/post',{method:'POST',id:record.id,record,mutationId}); if(!result?.saved) throw new Error('Worker did not confirm Payment-In posting.'); window._mviappsCloudPaymentInRows=null; window._editingAccountId=null; alert(result.alreadyApplied?'This receipt was already saved.':'Payment-In saved successfully in Production Cloud.'); show('payment-in'); return; }catch(error){alert(error?.message||'Payment-In could not be saved. No local fallback was used.');return;} } if(type==='Payment-Out' && window.mviappsProductionCloud?.getIdentity?.()){ try{ const cloud=window.mviappsProductionCloud,identity=cloud.getIdentity(); if(identity.mode==='staff'&&!cloud.hasStaffPermission('payments','create'))throw new Error('Staff permission denied: payments.create'); const no=document.getElementById('accountNo')?.value.trim()||'',amount=Number(document.getElementById('accountAmount')?.value)||0; const partyId=document.getElementById('accountParty')?.value||'',mode=document.getElementById('accountMode')?.value||'Cash'; const date=document.getElementById('accountDate')?.value||'',account=document.getElementById('accountBank')?.value||''; if(window._editingAccountId)throw new Error('Posted Cloud Payment-Out payments are immutable. Use the approved reversal/correction workflow when available.'); if(!no)throw new Error('Please enter Payment No.'); if(!(amount>0)||!Number.isFinite(amount))throw new Error('Please enter a valid amount.'); if(!partyId)throw new Error('Please select a Supplier/Party.'); if(!date)throw new Error('Please select Payment Date.'); if(!['Cash','Bank','UPI','Cheque','Card'].includes(mode))throw new Error('Select a valid Payment Mode.'); if(mode!=='Cash'&&!account)throw new Error('Please select a Cloud Bank Account.'); if(identity.mode==='staff'&&mode!=='Cash'&&!cloud.hasStaffPermission('bankCash','create'))throw new Error('Staff permission denied: bankCash.create'); const [partyResult,paymentResult]=await Promise.all([ window.mviappsCloudBusinessData.readAll('parties',{pageSize:100,maxPages:100}), window.mviappsCloudBusinessData.readAll('paymentOut',{pageSize:100,maxPages:100}) ]); if(!partyResult.complete||!paymentResult.complete)throw new Error('Cloud Party or Payment-Out list is incomplete; payment was not saved.'); const partyRow=partyResult.records.find(x=>String(x.id)===String(partyId)); if(!partyRow)throw new Error('Selected Supplier/Party was not found in Production Cloud. Refresh Parties and try again.'); const formSnapshot={number:no,date,partyId:String(partyId),amount,paymentMode:mode,bankAccountId:mode==='Cash'?'':account,reference:document.getElementById('accountReference')?.value||'',notes:document.getElementById('accountNotes')?.value||''}; const pendingKey='mviapps_production_pending_payment_out_v1';let pending=null;try{pending=JSON.parse(sessionStorage.getItem(pendingKey)||'null');}catch{pending=null;} let record,mutationId; if(pending?.record&&pending?.mutationId){const prior=pending.record;const same=String(prior.number)===formSnapshot.number&&String(prior.date)===formSnapshot.date&&String(prior.partyId)===formSnapshot.partyId&&Number(prior.amount)===formSnapshot.amount&&String(prior.paymentMode)===formSnapshot.paymentMode&&String(prior.bankAccountId||'')===formSnapshot.bankAccountId&&String(prior.reference||'')===formSnapshot.reference&&String(prior.notes||'')===formSnapshot.notes; if(!same)throw new Error('A previous Payment-Out request may already have reached Cloud. Restore the pending details and retry the same entry, or refresh Cloud Payment-Out and verify it before starting another payment.'); record=prior;mutationId=String(pending.mutationId); }else{record={id:'POUT-'+crypto.randomUUID(),...formSnapshot,partyName:String(partyRow.record.name||partyRow.record.partyName||''),account:mode==='Cash'?'cash-on-hand':account,paymentType:'on_account'};mutationId='payment-out-'+crypto.randomUUID();sessionStorage.setItem(pendingKey,JSON.stringify({record,mutationId}));} const result=await cloud.businessDataRequest('/business/payment-out/post',{method:'POST',id:record.id,record,mutationId}); if(!result?.saved)throw new Error('Worker did not confirm Payment-Out posting.'); sessionStorage.removeItem(pendingKey);window._mviappsCloudPaymentOutRows=null;window._editingAccountId=null;alert(result.alreadyApplied?'This payment was already saved.':'Payment-Out saved successfully in Production Cloud.'); show('payment-out');return; }catch(error){alert(error?.message||'Payment-Out could not be saved. No local fallback was used.');return;} } const key=isOther?'mviapps_other_income':(isIn?'mviapps_payment_in':'mviapps_payment_out'); const no=document.getElementById('accountNo')?.value.trim()||''; const amount=Number(document.getElementById('accountAmount')?.value)||0; if(!no){alert('Please enter '+(isOther?'Income No.':(isIn?'Receipt No.':'Payment No.'))+'.');return;} if(amount<=0){alert('Please enter a valid amount.');return;} const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const partyId=document.getElementById('accountParty')?.value||''; const party=parties.find(p=>String(p.id)===String(partyId)); const head=document.getElementById('accountHead')?.value.trim()||''; if(!isOther&&!partyId){alert('Please select a party.');return;} if(isOther&&!head){alert('Please enter an income head.');return;} const arr=JSON.parse(localStorage.getItem(key)||'[]'); // Re-check auto-generated numbers at save time to prevent duplicate receipts/payments // when a form was opened before another entry was saved. Existing edits keep their number. let savedNo=no; if((type==='Payment-In'||type==='Payment-Out'||type==='Other Income') && !window._editingAccountId){ const isReceipt=type==='Payment-In',isIncome=type==='Other Income'; const prefix=isReceipt?'REC':(isIncome?'INC':'PAY'); const used=new Set(arr.map(x=>String(x?.number||(isReceipt?x?.receiptNo:(isIncome?x?.incomeNo:x?.paymentNo))||'').trim().toUpperCase()).filter(Boolean)); if(used.has(savedNo.toUpperCase())){ let n=1, m=savedNo.match(new RegExp('^'+prefix+'-(\\d+)$','i')); if(m)n=Math.max(1,Number(m[1])||1); let candidate=prefix+'-'+String(n).padStart(4,'0'); while(used.has(candidate.toUpperCase())){n++;candidate=prefix+'-'+String(n).padStart(4,'0');} savedNo=candidate; } } const record={id:window._editingAccountId||Date.now(),number:savedNo,date:document.getElementById('accountDate')?.value||'',partyId,partyName:party?.name||'',incomeHead:head,amount,paymentMode:document.getElementById('accountMode')?.value||'',account:document.getElementById('accountBank')?.value||'',reference:document.getElementById('accountReference')?.value||'',notes:document.getElementById('accountNotes')?.value||''}; const idx=window._editingAccountId?arr.findIndex(x=>String(x.id)===String(window._editingAccountId)):-1; if(idx>=0)arr[idx]=record;else arr.push(record); localStorage.setItem(key,JSON.stringify(arr)); const msg=idx>=0?type+' updated successfully.':type+' saved successfully.'; window._editingAccountId=null; alert(msg); show(isOther?'other-income':(isIn?'payment-in':'payment-out')); } function getAccountEntries(type){ if(type==='Payment-In' && window.mviappsProductionCloud?.getIdentity?.()) return (window._mviappsCloudPaymentInRows||[]).map(x=>x.record); if(type==='Payment-Out' && window.mviappsProductionCloud?.getIdentity?.()) return (window._mviappsCloudPaymentOutRows||[]).map(x=>x.record); const key=type==='Other Income'?'mviapps_other_income':(type==='Payment-In'?'mviapps_payment_in':'mviapps_payment_out'); return JSON.parse(localStorage.getItem(key)||'[]'); } function openPaymentInListDatePicker(which){ const picker=document.getElementById(which==='from'?'paymentInFrom':'paymentInTo'); if(!picker)return; try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();}catch(e){try{picker.click();}catch(ignore){}} } function syncPaymentInListDateDisplay(which){ const picker=document.getElementById(which==='from'?'paymentInFrom':'paymentInTo'); const display=document.getElementById(which==='from'?'paymentInFromDisplay':'paymentInToDisplay'); if(display)display.value=picker?.value?picker.value.split('-').reverse().join('/') : ''; } function preparePaymentInListManualDate(which){ const display=document.getElementById(which==='from'?'paymentInFromDisplay':'paymentInToDisplay'); if(display)display.dataset.manualReady='1'; } function formatPaymentInListDateInput(el){ if(!el)return; el.dataset.manualReady='1'; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out; } function syncPaymentInListManualDate(which){ const display=document.getElementById(which==='from'?'paymentInFromDisplay':'paymentInToDisplay'); const picker=document.getElementById(which==='from'?'paymentInFrom':'paymentInTo'); if(!display||!picker)return; let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/'); if(!value){picker.value='';delete display.dataset.manualReady;renderAccountEntries('Payment-In');return;} const parts=value.split('/'); if(parts.length===3){ const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2]; if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){ const test=new Date(Number(yyyy),Number(mm)-1,Number(dd)); if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){ picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;renderAccountEntries('Payment-In');return; } } } syncPaymentInListDateDisplay(which);delete display.dataset.manualReady;renderAccountEntries('Payment-In'); } function openPaymentOutListDatePicker(which){ const picker=document.getElementById(which==='from'?'paymentOutFrom':'paymentOutTo'); if(!picker)return; try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();}catch(e){try{picker.click();}catch(ignore){}} } function syncPaymentOutListDateDisplay(which){ const picker=document.getElementById(which==='from'?'paymentOutFrom':'paymentOutTo'); const display=document.getElementById(which==='from'?'paymentOutFromDisplay':'paymentOutToDisplay'); if(display)display.value=picker?.value?picker.value.split('-').reverse().join('/') : ''; } function preparePaymentOutListManualDate(which){ const display=document.getElementById(which==='from'?'paymentOutFromDisplay':'paymentOutToDisplay'); if(display)display.dataset.manualReady='1'; } function formatPaymentOutListDateInput(el){ if(!el)return; el.dataset.manualReady='1'; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out; } function syncPaymentOutListManualDate(which){ const display=document.getElementById(which==='from'?'paymentOutFromDisplay':'paymentOutToDisplay'); const picker=document.getElementById(which==='from'?'paymentOutFrom':'paymentOutTo'); if(!display||!picker)return; let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/'); if(!value){picker.value='';delete display.dataset.manualReady;renderAccountEntries('Payment-Out');return;} const parts=value.split('/'); if(parts.length===3){ const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2]; if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){ const test=new Date(Number(yyyy),Number(mm)-1,Number(dd)); if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){ picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;renderAccountEntries('Payment-Out');return; } } } syncPaymentOutListDateDisplay(which);delete display.dataset.manualReady;renderAccountEntries('Payment-Out'); } function openOtherIncomeListDatePicker(which){ const picker=document.getElementById(which==='from'?'otherIncomeFrom':'otherIncomeTo'); if(!picker)return; try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();}catch(e){try{picker.click();}catch(ignore){}} } function syncOtherIncomeListDateDisplay(which){ const picker=document.getElementById(which==='from'?'otherIncomeFrom':'otherIncomeTo'); const display=document.getElementById(which==='from'?'otherIncomeFromDisplay':'otherIncomeToDisplay'); if(display)display.value=picker?.value?picker.value.split('-').reverse().join('/') : ''; } function prepareOtherIncomeListManualDate(which){ const display=document.getElementById(which==='from'?'otherIncomeFromDisplay':'otherIncomeToDisplay'); if(display)display.dataset.manualReady='1'; } function formatOtherIncomeListDateInput(el){ if(!el)return; el.dataset.manualReady='1'; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out; } function syncOtherIncomeListManualDate(which){ const display=document.getElementById(which==='from'?'otherIncomeFromDisplay':'otherIncomeToDisplay'); const picker=document.getElementById(which==='from'?'otherIncomeFrom':'otherIncomeTo'); if(!display||!picker)return; let value=(display.value||'').trim().replace(/\./g,'/').replace(/-/g,'/'); if(!value){picker.value='';delete display.dataset.manualReady;renderAccountEntries('Other Income');return;} const parts=value.split('/'); if(parts.length===3){ const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2]; if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){ const test=new Date(Number(yyyy),Number(mm)-1,Number(dd)); if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){ picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;delete display.dataset.manualReady;renderAccountEntries('Other Income');return; } } } syncOtherIncomeListDateDisplay(which);delete display.dataset.manualReady;renderAccountEntries('Other Income'); } async function renderAccountEntries(type){ const rows=document.getElementById('accountRows'); if(!rows)return; if(type==='Payment-In' && window.mviappsProductionCloud?.getIdentity?.()){ try{const result=await window.mviappsCloudBusinessData.readAll('paymentIn',{pageSize:100,maxPages:20});if(!result.complete)throw new Error('Payment-In Cloud list is incomplete; list not displayed as complete.');window._mviappsCloudPaymentInRows=result.records;} catch(error){rows.innerHTML=''+escapeHtml(error?.message||'Could not load Production Cloud Payment-In entries.')+'';return;} } if(type==='Payment-Out' && window.mviappsProductionCloud?.getIdentity?.()){ try{const result=await window.mviappsCloudBusinessData.readAll('paymentOut',{pageSize:100,maxPages:100});if(!result.complete)throw new Error('Payment-Out Cloud list is incomplete; list not displayed as complete.');window._mviappsCloudPaymentOutRows=result.records;} catch(error){rows.innerHTML=''+escapeHtml(error?.message||'Could not load Production Cloud Payment-Out entries.')+'';return;} } const q=(document.getElementById('accountSearch')?.value||'').toLowerCase().trim(); const paymentInFrom=document.getElementById('paymentInFrom')?.value||'', paymentInTo=document.getElementById('paymentInTo')?.value||''; const otherIncomeFrom=document.getElementById('otherIncomeFrom')?.value||'', otherIncomeTo=document.getElementById('otherIncomeTo')?.value||''; const paymentOutFrom=document.getElementById('paymentOutFrom')?.value||'', paymentOutTo=document.getElementById('paymentOutTo')?.value||''; const arr=filterByActiveFinancialYear(getAccountEntries(type)).filter(x=>{ const d=String(x.date||''); if(type==='Payment-In'){ return (!paymentInFrom||!d||d>=paymentInFrom)&&(!paymentInTo||!d||d<=paymentInTo); } if(type==='Other Income'){ return (!otherIncomeFrom||!d||d>=otherIncomeFrom)&&(!otherIncomeTo||!d||d<=otherIncomeTo); } if(type==='Payment-Out'){ return (!paymentOutFrom||!d||d>=paymentOutFrom)&&(!paymentOutTo||!d||d<=paymentOutTo); } return !q||[x.number,x.partyName,x.incomeHead,x.paymentMode,x.reference,x.notes].some(v=>String(v||'').toLowerCase().includes(q)); }).sort((a,b)=>(b.date||'').localeCompare(a.date||'')||(Number(b.id)||0)-(Number(a.id)||0)); const isOther=type==='Other Income', noLabel=isOther?'Income No.':(type==='Payment-In'?'Receipt No.':'Payment No.'), partyLabel=isOther?'Income Head':(type==='Payment-In'?'Received From':'Paid To'); rows.innerHTML=arr.length?arr.map(x=>`${escapeHtml(x.date||'')}${escapeHtml(x.number||'')}${escapeHtml(isOther?x.incomeHead:(x.partyName||'—'))}${escapeHtml(x.paymentMode||'')}₹ ${Number(x.amount||0).toFixed(2)} ${(type==='Payment-In'||type==='Payment-Out')&&window.mviappsProductionCloud?.getIdentity?.()?'Posted · immutable':` `}`).join(''):`No ${type==='Payment-In'||type==='Other Income'?type.toLowerCase()+' entries found for the selected date range.':type.toLowerCase()+' entries found for the current month.'}`; } function getAccountEntry(type,id){return getAccountEntries(type).find(x=>String(x.id)===String(id));} function viewAccountEntry(type,id){ const x=getAccountEntry(type,id);if(!x)return; const isOther=type==='Other Income'; const old=document.getElementById('accountEntryModal');if(old)old.remove(); document.body.insertAdjacentHTML('beforeend',`

${escapeHtml(type)} ${escapeHtml(x.number||'')}

${escapeHtml(x.date||'')}


${isOther?'Income Head':'Party'}
${escapeHtml(isOther?(x.incomeHead||''):(x.partyName||''))}
Payment Mode
${escapeHtml(x.paymentMode||'')}
Account
${escapeHtml(mviappsBankDisplay(x.account||x.bankAccount||''))}
Reference
${escapeHtml(x.reference||'')}
Description

${escapeHtml(x.notes||'—')}

₹ ${Number(x.amount||0).toFixed(2)}

${(type==='Payment-In'||type==='Payment-Out')&&window.mviappsProductionCloud?.getIdentity?.()?'':`
`}
`); } function editAccountEntry(type,id){ if((type==='Payment-In'||type==='Payment-Out')&&window.mviappsProductionCloud?.getIdentity?.()){alert('Posted Cloud payment records are immutable. Use the approved reversal/correction workflow when available.');return;} const x=getAccountEntry(type,id);if(!x)return; const page=type==='Other Income'?'other-income':(type==='Payment-In'?'payment-in':'payment-out'); window._editingAccountId=x.id;show(page); setTimeout(()=>{ document.getElementById('accountNo').value=x.number||''; document.getElementById('accountDate').value=x.date||''; if(type==='Payment-In'||type==='Other Income')syncPaymentInDateDisplay(); if(type==='Other Income')document.getElementById('accountHead').value=x.incomeHead||''; else document.getElementById('accountParty').value=x.partyId||''; document.getElementById('accountAmount').value=x.amount||0; document.getElementById('accountMode').value=x.paymentMode||'Cash'; document.getElementById('accountBank').value=x.account||x.bankAccount||''; mviappsToggleBankAccount('accountMode','accountBankWrap','accountBank'); document.getElementById('accountReference').value=x.reference||''; document.getElementById('accountNotes').value=x.notes||''; const buttons=document.querySelectorAll('#content button'); buttons.forEach(b=>{if((type==='Other Income'&&b.textContent.trim()==='Save Income')||(type==='Payment-In'&&b.textContent.trim()==='Save Receipt')||(type==='Payment-Out'&&b.textContent.trim()==='Save Payment'))b.textContent=type==='Other Income'?'Update Income':(type==='Payment-In'?'Update Receipt':'Update Payment');}); updateAccountTotal(); },0); } function deleteAccountEntry(type,id){ if((type==='Payment-In'||type==='Payment-Out')&&window.mviappsProductionCloud?.getIdentity?.()){alert('Posted Cloud payment records cannot be deleted. Use the approved reversal/correction workflow when available.');return;} const x=getAccountEntry(type,id);if(!x)return; if(!confirm('Delete this '+type.toLowerCase()+' entry?'))return; const key=type==='Other Income'?'mviapps_other_income':(type==='Payment-In'?'mviapps_payment_in':'mviapps_payment_out'); localStorage.setItem(key,JSON.stringify(getAccountEntries(type).filter(v=>String(v.id)!==String(id)))); renderAccountEntries(type); } function settings(arr){return `

${arr[0]}

Configure mviapps for your business.

${fields(arr)}
`} function settingSection(title,desc,body,action='Save Changes'){return `

${title}

${desc}

${body}
`} function settingInput(label,id,placeholder='',type='text'){const v=localStorage.getItem('mviapps_'+id)||'';return `
`} function settingSelect(label,id,opts){const v=localStorage.getItem('mviapps_'+id)||'';return `
`} function settingTextarea(label,id,placeholder=''){const v=localStorage.getItem('mviapps_'+id)||'';return `
`} function settingsPage(title,sub,sections){return `

${title}

${sub}

${sections.join('')}
`} function companySettings(){ const logo=localStorage.getItem('mviapps_company_logo')||''; const sign=localStorage.getItem('mviapps_authorized_signature')||''; const savedName=localStorage.getItem('mviapps_companyName')||''; const savedTrade=localStorage.getItem('mviapps_tradeName')||''; const savedMobile=localStorage.getItem('mviapps_companyMobile')||''; const savedEmail=localStorage.getItem('mviapps_companyEmail')||''; const savedGstin=localStorage.getItem('mviapps_companyGstin')||''; const savedAddress=localStorage.getItem('mviapps_companyAddress')||''; const savedCity=localStorage.getItem('mviapps_companyCity')||''; const savedState=localStorage.getItem('mviapps_companyState')||''; const savedPin=localStorage.getItem('mviapps_companyPin')||''; const hasSaved=!!( savedName||savedTrade||savedMobile||savedEmail||savedGstin|| savedAddress||savedCity||savedState||savedPin||logo||sign|| localStorage.getItem('mviapps_companyWebsite')|| localStorage.getItem('mviapps_companyPan')|| localStorage.getItem('mviapps_contactPerson')|| localStorage.getItem('mviapps_alternateMobile') ); const esc=v=>escapeHtml(v||''); const savedCard=`

Saved Company Details

Your saved company information is shown here and can be modified anytime.

${hasSaved?`
${esc(savedName)||'—'}
${esc(savedTrade)||'—'}
${esc(savedMobile)||'—'}
${esc(savedEmail)||'—'}
${esc(savedGstin)||'—'}
${esc(localStorage.getItem('mviapps_companyWebsite')||'')||'—'}
${esc(localStorage.getItem('mviapps_companyPan')||'')||'—'}
${esc(localStorage.getItem('mviapps_contactPerson')||'')||'—'}
${esc(localStorage.getItem('mviapps_alternateMobile')||'')||'—'}
${esc([savedAddress,savedCity,savedState,savedPin].filter(Boolean).join(', '))||'—'}
${logo?`
`:''} ${sign?`
`:''}
`:`
No company details have been saved yet. Enter the details below and click Save Changes.
`}
`; return savedCard + settingsPage('Company Details','Keep your business identity, contact information, logo and authorized signatory organized.',[ settingSection('Business Information','Basic information shown across the application.',`
${settingInput('Company Name','companyName','Enter company name')}${settingInput('Business / Trade Name','tradeName','Optional trade name')}${settingInput('Mobile','companyMobile','Enter mobile number')}${settingInput('Email','companyEmail','Enter email address','email')}${settingInput('Website','companyWebsite','Enter website')}${settingInput('PAN','companyPan','Enter PAN')}${settingInput('GSTIN','companyGstin','Enter GSTIN')}
`), settingSection('Business Address','Registered or operating address details.',`
${settingTextarea('Address','companyAddress','Enter complete address')}${settingInput('City','companyCity','Enter city')}${settingInput('State','companyState','Enter state')}${settingInput('PIN Code','companyPin','Enter PIN code')}
`), settingSection('Logo & Authorized Signatory','Upload your company logo and authorized signatory signature for use in invoices and printed documents.',`
${logo?``:'No logo uploaded'}
${sign?``:'No signature uploaded'}
`), settingSection('Business Contact','Optional contact information for invoices and correspondence.',`
${settingInput('Contact Person','contactPerson','Enter contact person')}${settingInput('Alternate Mobile','alternateMobile','Enter alternate mobile')}
`) ]); } function enableCompanyEdit(){ const first=document.querySelector('#content .settings-stack'); if(first) first.scrollIntoView({behavior:'smooth',block:'start'}); const root=document.getElementById('content'); if(root) root.querySelectorAll('.settings-card').forEach(c=>c.style.display='block'); loadCompanySettings(); } function invoiceSettings(){return settingsPage('Invoice Settings','Set numbering, titles, print information and invoice terms.',[settingSection('Invoice Numbering','Configure the default numbering pattern.',`
${settingInput('Invoice Prefix','invoicePrefix','e.g. INV-')}${settingInput('Starting Number','startingNumber','e.g. 1001','number')}${settingSelect('Numbering Format','numberingFormat',['Sequential','Yearly Reset','Monthly Reset'])}${settingInput('Invoice Title','invoiceTitle','e.g. TAX INVOICE')}
`),settingSection('Invoice Print Details','Information displayed on printed invoices.',`
${settingTextarea('Bank Details','invoiceBank','Enter bank name, account and IFSC')}${settingTextarea('Terms & Conditions','invoiceTerms','Enter invoice terms and conditions')}${settingTextarea('Footer Text','invoiceFooter','Enter footer text')}
`),settingSection('Print Options','Choose the standard invoice print behavior.',`
${settingSelect('Paper Size','paperSize',['A4','A5','Thermal 80mm','Thermal 58mm'])}${settingSelect('Invoice Copies','invoiceCopies',['1','2','3'])}${settingSelect('Show Company GSTIN','showCompanyGstin',['Yes','No'])}${settingSelect('Show Signature Area','showSignature',['Yes','No'])}
`)] )} function taxSettings(){return settingsPage('Tax Settings','Manage GST registration and default tax rates.',[settingSection('GST Registration','Set the tax identity used by the business.',`
${settingInput('GSTIN','taxGstin','Enter GSTIN')}${settingSelect('Tax Registration Type','taxRegType',['Regular','Composition','Unregistered'])}${settingInput('Default GST Rate (%)','defaultGst','0','number')}
`),settingSection('Tax Components','Configure the standard GST components used on invoices.',`
${settingInput('CGST (%)','defaultCgst','0','number')}${settingInput('SGST (%)','defaultSgst','0','number')}${settingInput('IGST (%)','defaultIgst','0','number')}${settingSelect('Tax Inclusive Pricing','taxInclusive',['No','Yes'])}
`),settingSection('Tax Display','Control how tax information appears to the user.',`
${settingSelect('Show HSN / SAC','showHsn',['Yes','No'])}${settingSelect('Show Tax Summary','showTaxSummary',['Yes','No'])}
`)] )} function itemSettings(){return settingsPage('Item Settings','Set sensible defaults for item entry, pricing and stock.',[settingSection('Item Defaults','Default values used while adding new items.',`
${settingInput('Default Category','itemCategory','Enter category')}${settingInput('Default Brand','itemBrand','Enter brand')}${settingSelect('Default Unit','itemUnit',['PCS','KG','G','MG','TON','LTR','MTR','BOX','SET'])}${settingInput('Default HSN / SAC','itemHsn','Enter HSN / SAC')}
`),settingSection('Pricing Defaults','Default pricing values for new items.',`
${settingInput('Default Purchase Rate','defaultPurchaseRate','0','number')}${settingInput('Default Sale Rate','defaultSaleRate','0','number')}${settingInput('Default Wholesale Rate','defaultWholesaleRate','0','number')}${settingInput('Default Retail Rate','defaultRetailRate','0','number')}
`),settingSection('Stock Defaults','Choose how stock entries behave.',`
${settingSelect('Track Stock','trackStock',['Yes','No'])}${settingSelect('Allow Negative Stock','negativeStock',['No','Yes'])}${settingSelect('Use Opening Stock','openingStock',['Yes','No'])}
`)] )} function getAccountHeads(){try{const a=JSON.parse(localStorage.getItem('mviapps_account_heads_cloud_cache')||'[]');return Array.isArray(a)?a:[]}catch(e){return[]}} function saveAccountHeads(a){localStorage.setItem('mviapps_account_heads_cloud_cache',JSON.stringify(a||[]))} function getLocalAccountHeads(){try{const a=JSON.parse(localStorage.getItem('mviapps_account_heads')||'[]');return Array.isArray(a)?a:[]}catch(e){return[]}} function accountSettings(){return `

Account Heads

Manage accounting heads and the Business control accounts used for receivables and payables.

Account Head List

Production Cloud master for this Business. Existing Local Account Heads are preserved separately until explicitly imported. Bank & Cash accounts are managed separately.

Account HeadGroupNatureControl RolePosting RoleDescriptionAction
`} function accountHeadCloud(){const c=window.mviappsProductionCloud;if(!c?.businessDataRequest)throw new Error('Production Cloud connection is unavailable.');return c;} function accountHeadMutationId(id,verb){return 'mviapps-account-head-'+verb+'-'+String(id)+'-'+crypto.randomUUID()} function accountHeadImportKey(businessId){return 'mviapps_account_heads_cloud_imported_'+String(businessId||'')} function getImportedLocalAccountHeadIds(businessId){try{const x=JSON.parse(localStorage.getItem(accountHeadImportKey(businessId))||'[]');return new Set(Array.isArray(x)?x.map(String):[])}catch(e){return new Set()}} function saveImportedLocalAccountHeadIds(businessId,ids){localStorage.setItem(accountHeadImportKey(businessId),JSON.stringify([...ids]))} async function loadCloudAccountHeads(){ const cloud=accountHeadCloud(); const result=await cloud.businessDataRequest('/business/data/account-heads',{method:'GET'}); if(!result||!Array.isArray(result.records))throw new Error('Cloud Account Heads response is invalid.'); const rows=result.records.map(x=>({...x.record,id:String(x.id||x.record?.id),updatedAt:x.updatedAt||x.record?.updatedAt||null})); saveAccountHeads(rows);return rows; } async function importLocalAccountHeads(){ const cloud=accountHeadCloud(),identity=cloud.getIdentity?.(),businessId=String(identity?.business?.id||''); if(identity?.mode!=='owner'||!businessId){alert('Sign in with the Production Business Owner account to import Local Account Heads.');return;} const local=getLocalAccountHeads(),cloudRows=getAccountHeads(),cloudNames=new Set(cloudRows.map(x=>String(x.name||'').trim().toLowerCase())),imported=getImportedLocalAccountHeadIds(businessId); const pending=local.filter(x=>String(x.id||'').trim()&&!imported.has(String(x.id))&&!cloudNames.has(String(x.name||'').trim().toLowerCase())); const already=local.filter(x=>String(x.id||'').trim()&&cloudNames.has(String(x.name||'').trim().toLowerCase())); if(!pending.length){already.forEach(x=>imported.add(String(x.id)));saveImportedLocalAccountHeadIds(businessId,imported);alert('No new Local Account Heads need importing. Existing Local records remain preserved.');await renderAccountHeads();return;} if(!confirm('Import '+pending.length+' Local Account Head(s) into this Production Business Cloud? Existing Local records will NOT be deleted or overwritten. Same-name Cloud records will be skipped.'))return; const btn=document.getElementById('importLocalAccountHeadsBtn');if(btn)btn.disabled=true; try{ for(const x of pending){const id=String(x.id),name=String(x.name||'').trim();if(!name)continue; const record={id,name,group:String(x.group||''),nature:String(x.nature||''),description:String(x.description||'')}; await cloud.businessDataRequest('/business/data/account-heads',{method:'POST',record,id,mutationId:'mviapps-account-head-import-'+businessId+'-'+id}); imported.add(id);saveImportedLocalAccountHeadIds(businessId,imported);cloudNames.add(name.toLowerCase()); } already.forEach(x=>imported.add(String(x.id)));saveImportedLocalAccountHeadIds(businessId,imported); await renderAccountHeads();alert('Local Account Head import completed. Original Local records have been preserved.'); }catch(e){alert('Import stopped safely: '+(e?.message||String(e))+ '\nSuccessfully imported records are recorded for exact retry. Original Local records remain untouched.');await renderAccountHeads();} finally{if(btn?.isConnected)btn.disabled=false;} } async function renderAccountHeads(){const body=document.getElementById('accountHeadRows');if(!body)return;const status=document.getElementById('accountHeadCloudStatus'),add=document.getElementById('addAccountHeadBtn'),imp=document.getElementById('importLocalAccountHeadsBtn');if(add)add.hidden=true;if(imp)imp.hidden=true;body.innerHTML=`Loading Account Heads from Production Cloud…`;try{const a=await loadCloudAccountHeads(),identity=accountHeadCloud().getIdentity?.(),owner=identity?.mode==='owner'&&identity?.business?.role==='Owner',businessId=String(identity?.business?.id||''),local=getLocalAccountHeads(),imported=getImportedLocalAccountHeadIds(businessId),cloudNames=new Set(a.map(x=>String(x.name||'').trim().toLowerCase()));const pending=local.filter(x=>String(x.id||'').trim()&&!imported.has(String(x.id))&&!cloudNames.has(String(x.name||'').trim().toLowerCase()));const sameName=local.filter(x=>String(x.id||'').trim()&&cloudNames.has(String(x.name||'').trim().toLowerCase()));sameName.forEach(x=>imported.add(String(x.id)));if(sameName.length)saveImportedLocalAccountHeadIds(businessId,imported);if(status){status.textContent='Connected to Production Cloud · '+a.length+' Account Head(s)'+(local.length?' · '+local.length+' original Local record(s) preserved':'');status.style.color='#166534';}if(add)add.hidden=!owner;if(imp){imp.hidden=!(owner&&pending.length);imp.textContent='Import '+pending.length+' Local Account Head(s)';}body.innerHTML=a.length?a.map(x=>`${escapeHtml(x.name)}${escapeHtml(x.group||'')}${escapeHtml(x.nature||'')}${escapeHtml(x.controlRole==='receivable_control'?'Receivable Control':x.controlRole==='payable_control'?'Payable Control':'—')}${escapeHtml(({sales_income:'Sales',sales_return:'Sales Return',purchase:'Purchase',purchase_return:'Purchase Return',input_tax:'Input Tax',output_tax:'Output Tax'})[x.postingRole]||'—')}${escapeHtml(x.description||'')}${owner?` `:'View only'}`).join(''):`No Account Heads in Production Cloud.`;}catch(e){if(status){status.textContent='Cloud not confirmed: '+(e?.message||String(e))+' · Original Local cache has been preserved; edits are disabled.';status.style.color='#b91c1c';}body.innerHTML=`Could not verify Production Cloud Account Heads. Reload after reconnecting; Local records were not deleted.`;}} function openAccountHeadForm(id){const a=getAccountHeads(),x=a.find(v=>String(v.id)===String(id))||{};const modal=document.createElement('div');modal.id='accountHeadModal';modal.className='item-modal-overlay';modal.style.display='flex';modal.style.zIndex='100000';modal.innerHTML=`

${id?'Edit':'Add'} Account Head

Saved to this Production Business Cloud. Bank & Cash accounts are managed separately.

One active Account Head per control role.
One active Account Head per posting role. Group and Nature are validated automatically.
`;document.body.appendChild(modal);if(x.group)document.getElementById('ahGroup').value=x.group;if(x.nature)document.getElementById('ahNature').value=x.nature;if(x.controlRole)document.getElementById('ahControlRole').value=x.controlRole;if(x.postingRole)document.getElementById('ahPostingRole').value=x.postingRole;document.body.style.overflow='hidden';setTimeout(()=>document.getElementById('ahName')?.focus(),0)} function closeAccountHeadForm(){document.getElementById('accountHeadModal')?.remove();document.body.style.overflow=''} async function saveAccountHead(id){const name=document.getElementById('ahName')?.value.trim()||'',group=document.getElementById('ahGroup')?.value||'',nature=document.getElementById('ahNature')?.value||'',description=document.getElementById('ahDescription')?.value.trim()||'',controlRole=document.getElementById('ahControlRole')?.value||null,postingRole=document.getElementById('ahPostingRole')?.value||null;if(!name){alert('Please enter the Account Head Name.');return}if(!['Assets','Liabilities','Capital','Income','Expenses'].includes(group)||!['Debit','Credit'].includes(nature)){alert('Select a valid Group and Nature.');return}if((controlRole==='receivable_control'&&group!=='Assets')||(controlRole==='payable_control'&&group!=='Liabilities')){alert('Receivable Control must belong to Assets and Payable Control must belong to Liabilities.');return}if(controlRole&&!['receivable_control','payable_control'].includes(controlRole)){alert('Select a valid Control Role.');return}const postingRules={sales_income:['Income','Credit'],sales_return:['Income','Debit'],purchase:['Expenses','Debit'],purchase_return:['Expenses','Credit'],input_tax:['Assets','Debit'],output_tax:['Liabilities','Credit']};if(postingRole&&(!postingRules[postingRole]||postingRules[postingRole][0]!==group||postingRules[postingRole][1]!==nature)){alert('Posting Role requires '+(postingRules[postingRole]||['valid Group','valid Nature']).join(' / ')+'.');return}if(controlRole&&postingRole){alert('An Account Head cannot be both a Control Role and an Invoice Posting Role.');return}const a=getAccountHeads(),duplicate=a.find(v=>String(v.name||'').toLowerCase()===name.toLowerCase()&&String(v.id)!==String(id));if(duplicate){alert('This Account Head already exists.');return}const identity=accountHeadCloud().getIdentity?.();if(identity?.mode!=='owner'||identity?.business?.role!=='Owner'){alert('Only the Production Business Owner can change Account Heads.');return}const old=a.find(v=>String(v.id)===String(id));if(id&&!old?.updatedAt){alert('Latest Cloud version is missing. Reload Account Heads before editing.');return}const record={id:id?String(id):crypto.randomUUID(),name,group,nature,description,controlRole,postingRole};const btn=document.querySelector('#accountHeadModal .btn:not(.secondary)');if(btn)btn.disabled=true;try{await accountHeadCloud().businessDataRequest('/business/data/account-heads',{method:id?'PUT':'POST',record,id:record.id,mutationId:accountHeadMutationId(record.id,id?'edit':'create'),...(id?{expectedUpdatedAt:old.updatedAt}:{})});closeAccountHeadForm();await renderAccountHeads();}catch(e){if(btn)btn.disabled=false;alert('Cloud save failed safely: '+(e?.message||String(e))+'\nOriginal Local records have been preserved. Reload Account Heads before retrying.');}} async function deleteAccountHead(id){const a=getAccountHeads(),x=a.find(v=>String(v.id)===String(id));if(!x)return;if(!confirm('Delete Account Head "'+x.name+'" from Production Cloud? This is a soft delete; the audit history is retained.'))return;try{await accountHeadCloud().businessDataRequest('/business/data/account-heads',{method:'DELETE',id:String(id),mutationId:accountHeadMutationId(id,'delete'),expectedUpdatedAt:x.updatedAt});await renderAccountHeads();}catch(e){alert('Cloud delete failed safely: '+(e?.message||String(e))+'\nReload Account Heads before retrying.');}} function applyMVIAppsAppearance(){ const root=document.documentElement, body=document.body; if(!body)return; const theme=localStorage.getItem('mviapps_theme')||'Light'; const accent=localStorage.getItem('mviapps_accentColor')||'#315efb'; const sidebar=localStorage.getItem('mviapps_sidebarPosition')||'Left'; const compact=localStorage.getItem('mviapps_compactLayout')||'No'; const font=localStorage.getItem('mviapps_fontSize')||'Medium'; root.style.setProperty('--primary',accent); root.style.setProperty('--primary2',accent); body.classList.toggle('appearance-dark',theme==='Dark' || (theme==='System Default' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)); body.classList.toggle('appearance-sidebar-right',sidebar==='Right'); body.classList.toggle('appearance-compact',compact==='Yes'); root.style.fontSize=font==='Small'?'14px':font==='Large'?'17px':'16px'; } function appearanceSettings(){return settingsPage('Appearance','Personalize the MVIApps interface, layout and print presentation.',[ settingSection('Application Branding','Control the name and header text shown across the application.',`
${settingInput('Application Name','appName','mviapps')}${settingInput('Header Text','headerText','Enter header text')}${settingInput('Sub Header Text','subHeaderText','Optional sub header')}
`), settingSection('Theme & Layout','Choose a professional interface style and workspace layout.',`
${settingSelect('Theme','theme',['Light','Dark','System Default'])}${settingSelect('Accent Color','accentColor',['#315efb','#0f9d75','#7c3aed','#ea580c','#0891b2'])}${settingSelect('Font Size','fontSize',['Small','Medium','Large'])}${settingSelect('Sidebar Position','sidebarPosition',['Left','Right'])}${settingSelect('Compact Layout','compactLayout',['No','Yes'])}
Live appearance
Save Changes to apply your selected theme, accent and layout.
`), settingSection('Logo & Printing','Control company branding on invoices and printed reports.',`
${settingInput('Logo File','logoFile','Choose or enter logo reference')}${settingSelect('Show Logo on Invoice','showLogo',['Yes','No'])}${settingSelect('Print Company Header','printHeader',['Yes','No'])}${settingSelect('Print Footer','printFooter',['Yes','No'])}
`), `
Appearance settingsThese preferences are stored locally in MVIApps and do not change your business transactions or accounting data.
` ])} function securitySettings(){return settingsPage('Security','Protect app access and manage users who can open MVIApps.',[ settingSection('Change My Login Details','Change the User ID and/or Password used to open MVIApps. Your current password is required for security.',`
`), settingSection('Staff Accounts','Owner creates a Business-scoped Staff User ID. The server generates a one-time initial password; Staff must change it at first sign-in.',`
`), settingSection('Session & Safety','Basic protection against accidental or unattended access.',`
${settingSelect('Auto Lock','autoLock',['Off','5 Minutes','10 Minutes','15 Minutes','30 Minutes'])}${settingSelect('Confirm Before Delete','confirmDelete',['Yes','No'])}
`), `
Security noteProduction Cloud Staff accounts use server-side authentication, assigned-Business restrictions and saved permissions enforced by the Production Worker. Auto Lock and local app users are separate device-level protection; they do not replace Production Cloud Staff access controls.
` ])} function previewCompanyImage(input,previewId,storageKey){const file=input.files&&input.files[0];if(!file)return;if(!file.type.startsWith('image/')){alert('Please select an image file.');input.value='';return;}if(file.size>2*1024*1024){alert('Please choose an image smaller than 2 MB.');input.value='';return;}const reader=new FileReader();reader.onload=function(e){try{localStorage.setItem(storageKey,e.target.result);const el=document.getElementById(previewId);if(el)el.innerHTML='';}catch(err){alert('Image could not be saved.');}};reader.readAsDataURL(file)} function removeCompanyImage(storageKey,previewId){localStorage.removeItem(storageKey);const el=document.getElementById(previewId);if(el)el.innerHTML='No image uploaded';} function loadSettingsPage(title){ const prefix='mviapps_'; const root=document.getElementById('content'); if(!root)return; root.querySelectorAll('input[id],textarea[id],select[id]').forEach(el=>{ if(el.type==='file')return; const v=localStorage.getItem(prefix+el.id); if(v!==null)el.value=v; }); if(title==='Security') setTimeout(mviappsRenderUserList,0); } function saveSettingsPage(title){ const root=document.getElementById('content'); if(!root)return; const prefix='mviapps_'; let saved=0; root.querySelectorAll('input[id],textarea[id],select[id]').forEach(el=>{ if(el.type==='file')return; localStorage.setItem(prefix+el.id,el.value||''); saved++; }); alert(title+' settings saved successfully.'); if(title==='Appearance') applyMVIAppsAppearance(); if(title==='Security') setTimeout(mviappsRenderUserList,0); if(title==='Company Details'){ root.innerHTML=companySettings(); loadCompanySettings(); } if(id==='data-safety'){renderDataSafety();} } function loadCompanySettings(){loadSettingsPage('Company Details');} /* ========================================================= MVIApps Drive Sync - Separate test copy; does not alter the main app build. - Uses the existing full-backup data model. - Google Drive scope: drive.file only. - Sync strategy: snapshot + conflict detection. ========================================================= */ const MVI_DRIVE_SYNC_SCOPE='https://www.googleapis.com/auth/drive.file'; const MVI_DRIVE_SYNC_FILE='MVIApps_Drive_Sync.json'; let mviDriveSyncToken=''; function driveSyncTestPage(){ return `

Drive Sync

Synchronize this MVIApps data safely across your devices using your Google Drive. Changes are protected by conflict detection.

1. Google Drive Connection
Not connected.
SecurityOnly the Client ID is used in this browser test. Never enter the Client Secret.
2. Safe Sync Controls

This sync uses a full MVIApps snapshot, including item images. It never silently overwrites data when both devices changed since the last sync. In that situation it reports a conflict and waits for your choice.

Connect Google Drive first.
3. Sync Information
No cloud snapshot loaded.
`; } function driveSyncMsg(text, cls=''){ const el=document.getElementById('driveSyncStatus'); if(el){el.textContent=text;el.className='status '+cls;} } function driveSyncAuthMsg(text, cls=''){ const el=document.getElementById('driveSyncAuthStatus'); if(el){el.textContent=text;el.className='status '+cls;} } function driveSyncSetButtons(enabled){ ['driveSyncNowBtn','driveSyncUploadBtn','driveSyncDownloadBtn'].forEach(id=>{const e=document.getElementById(id);if(e)e.disabled=!enabled;}); } async function driveSyncYieldForUi(){ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); } function driveSyncSetBusy(busy, message=''){ const ids=['driveSyncNowBtn','driveSyncUploadBtn','driveSyncDownloadBtn']; ids.forEach(id=>{const e=document.getElementById(id);if(e)e.disabled=busy||!mviDriveSyncToken;}); const now=document.getElementById('driveSyncNowBtn'); const up=document.getElementById('driveSyncUploadBtn'); const down=document.getElementById('driveSyncDownloadBtn'); if(busy){ if(now)now.textContent='Syncing...'; if(up)up.textContent='Uploading...'; if(down)down.textContent='Downloading...'; if(message)driveSyncMsg(message); }else{ if(now)now.textContent='Sync Now'; if(up)up.textContent='Use Local Data → Drive'; if(down)down.textContent='Use Cloud Data → This Device'; } } function driveSyncClientId(){ const input=document.getElementById('driveSyncClientId'); const v=(input?.value||localStorage.getItem('mviapps_drive_sync_client')||'').trim(); if(input && v) input.value=v; return v; } function driveSyncDevice(){ return (document.getElementById('driveSyncDevice')?.value||'Unknown Device').trim()||'Unknown Device'; } function driveSyncLastHash(){return localStorage.getItem('mviapps_drive_sync_last_cloud_hash')||'';} function driveSyncSaveState(cloudRevision,localHash){ localStorage.setItem('mviapps_drive_sync_last_cloud_revision',cloudRevision||''); localStorage.setItem('mviapps_drive_sync_last_local_hash',localHash||''); // Keep the old key for backwards compatibility with the previous test build. localStorage.setItem('mviapps_drive_sync_last_cloud_hash',cloudRevision||''); } function driveSyncLastHash(){return localStorage.getItem('mviapps_drive_sync_last_cloud_hash')||'';} function driveSyncLastCloudRevision(){return localStorage.getItem('mviapps_drive_sync_last_cloud_revision')||driveSyncLastHash();} function driveSyncLastLocalHash(){return localStorage.getItem('mviapps_drive_sync_last_local_hash')||'';} const MVI_DRIVE_SYNC_BASELINE='mviapps_drive_sync_base_manifest'; function driveSyncExcludeDataKey(k){ return k==='mviapps_drive_sync_last_cloud_hash'||k==='mviapps_drive_sync_last_cloud_revision'||k==='mviapps_drive_sync_last_local_hash'||k===MVI_DRIVE_SYNC_BASELINE||k==='mviapps_drive_sync_client'||k==='mviapps_drive_sync_last_device'||k==='mviapps_lastBackupAt'||k==='mviapps_lastBackupData'; } async function driveSyncGetLocalSnapshot(){ const data=await appDataWithHighStorage(); Object.keys(data).forEach(k=>{if(driveSyncExcludeDataKey(k))delete data[k];}); return data; } function driveSyncStable(value){ if(Array.isArray(value))return value.map(driveSyncStable); if(value&&typeof value==='object'){ const o={};Object.keys(value).sort().forEach(k=>{o[k]=driveSyncStable(value[k]);});return o; } return value; } async function driveSyncSha256(text){ const buf=new TextEncoder().encode(text),hash=await crypto.subtle.digest('SHA-256',buf); return Array.from(new Uint8Array(hash)).map(b=>b.toString(16).padStart(2,'0')).join(''); } async function driveSyncHashData(data){return driveSyncSha256(JSON.stringify(driveSyncStable(data)));} async function driveSyncBuildLocal(){const data=await driveSyncGetLocalSnapshot();return {data,hash:await driveSyncHashData(data)}} async function driveSyncBuildBaselineManifest(data){ const manifest={version:1,keys:{}}; for(const [key,raw] of Object.entries(data||{})){ let parsed;try{parsed=JSON.parse(raw)}catch(e){parsed=undefined} if(Array.isArray(parsed)){ const records={};let valid=true;const seen=new Set(); for(const item of parsed){ if(!item||typeof item!=='object'||Array.isArray(item)||item.id===undefined||item.id===null||String(item.id)===''||seen.has(String(item.id))){valid=false;break} const id=String(item.id);seen.add(id);records[id]=await driveSyncHashData(item); } manifest.keys[key]=valid?{type:'records',records}:{type:'value',hash:await driveSyncHashData(parsed)}; }else manifest.keys[key]={type:'value',hash:await driveSyncHashData(parsed===undefined?(raw===undefined?null:raw):parsed)}; } return manifest; } async function driveSyncSaveBaseline(data){localStorage.setItem(MVI_DRIVE_SYNC_BASELINE,JSON.stringify(await driveSyncBuildBaselineManifest(data)))} function driveSyncLoadBaseline(){try{const v=JSON.parse(localStorage.getItem(MVI_DRIVE_SYNC_BASELINE)||'null');if(v&&v.version===1&&v.keys){Object.keys(v.keys).forEach(k=>{if(driveSyncExcludeDataKey(k))delete v.keys[k]});return v}return null}catch(e){return null}} function driveSyncParseValue(raw){try{return JSON.parse(raw)}catch(e){return raw===undefined?undefined:raw}} async function driveSyncThreeWayMerge(baseline,localData,cloudData){ if(!baseline)return null;const merged={},conflicts=[],keys=new Set([...Object.keys(baseline.keys||{}),...Object.keys(localData||{}),...Object.keys(cloudData||{})]),absent=Symbol('absent'); for(const key of keys){ const b=baseline.keys?.[key]||null,lv=Object.prototype.hasOwnProperty.call(localData,key)?driveSyncParseValue(localData[key]):absent,cv=Object.prototype.hasOwnProperty.call(cloudData,key)?driveSyncParseValue(cloudData[key]):absent; if(b?.type==='records'){ const toMap=v=>{const m=new Map();if(Array.isArray(v))for(const x of v)if(x&&typeof x==='object'&&x.id!==undefined&&x.id!==null)m.set(String(x.id),x);return m}; if((lv!==absent&&!Array.isArray(lv))||(cv!==absent&&!Array.isArray(cv))){conflicts.push(key);continue} const bm=new Map(Object.entries(b.records||{})),lm=toMap(lv===absent?[]:lv),cm=toMap(cv===absent?[]:cv),ids=new Set([...bm.keys(),...lm.keys(),...cm.keys()]),out=[];let keyBad=false; for(const id of ids){ const bh=bm.has(id)?bm.get(id):null,lh=lm.has(id)?await driveSyncHashData(lm.get(id)):null,ch=cm.has(id)?await driveSyncHashData(cm.get(id)):null,lchg=lh!==bh,cchg=ch!==bh; if(!lchg&&!cchg){if(lm.has(id))out.push(lm.get(id));else if(cm.has(id))out.push(cm.get(id))} else if(lchg&&!cchg){if(lm.has(id))out.push(lm.get(id))} else if(!lchg&&cchg){if(cm.has(id))out.push(cm.get(id))} else if(lh===ch){if(lm.has(id))out.push(lm.get(id))} else{keyBad=true;conflicts.push(key+'#'+id)} } if(!keyBad)merged[key]=JSON.stringify(out);continue; } const bh=b?.hash||null,lh=lv===absent?null:await driveSyncHashData(lv),ch=cv===absent?null:await driveSyncHashData(cv),lchg=lh!==bh,cchg=ch!==bh;let chosen=absent; if(!lchg&&!cchg)chosen=lv!==absent?lv:cv;else if(lchg&&!cchg)chosen=lv;else if(!lchg&&cchg)chosen=cv;else if(lh===ch)chosen=lv;else{conflicts.push(key);continue} if(chosen!==absent)merged[key]=typeof chosen==='string'?chosen:JSON.stringify(chosen); } return conflicts.length?{conflicts,merged:null}:{conflicts:[],merged}; } async function driveSyncLegacyAdditiveMerge(localData,cloudData){ const merged={},conflicts=[],keys=new Set([...Object.keys(localData||{}),...Object.keys(cloudData||{})]); for(const key of keys){ const lraw=localData[key],craw=cloudData[key];if(lraw===undefined){merged[key]=craw;continue}if(craw===undefined){merged[key]=lraw;continue}if(lraw===craw){merged[key]=lraw;continue} let lv,cv;try{lv=JSON.parse(lraw);cv=JSON.parse(craw)}catch(e){lv=lraw;cv=craw} const isRecords=x=>Array.isArray(x)&&x.every(v=>v&&typeof v==='object'&&!Array.isArray(v)&&v.id!==undefined&&v.id!==null); if(isRecords(lv)&&isRecords(cv)){const lm=new Map(lv.map(x=>[String(x.id),x])),cm=new Map(cv.map(x=>[String(x.id),x])),out=[],bad=false;for(const [id,x] of lm){if(cm.has(id)){if(JSON.stringify(driveSyncStable(x))!==JSON.stringify(driveSyncStable(cm.get(id)))){bad=true;break}out.push(x)}else out.push(x)}if(!bad)for(const [id,x] of cm)if(!lm.has(id))out.push(x);if(bad)conflicts.push(key);else merged[key]=JSON.stringify(out)}else conflicts.push(key); } return conflicts.length?{conflicts,merged:null}:{conflicts:[],merged}; } function driveSyncNewRevision(){ if(crypto.randomUUID)return crypto.randomUUID(); return 'rev-'+Date.now()+'-'+Math.random().toString(36).slice(2); } async function driveSyncEnsureGIS(){for(let i=0;i<100;i++){if(window.google?.accounts?.oauth2)return;await new Promise(r=>setTimeout(r,100));}throw new Error('Google Identity Services did not load. Please check your internet connection.');} async function driveSyncSignIn(){ try{await driveSyncEnsureGIS();const id=driveSyncClientId();if(!id){driveSyncAuthMsg('Please enter the Google OAuth Client ID.','err');return;} localStorage.setItem('mviapps_drive_sync_client',id);localStorage.setItem('mviapps_drive_sync_last_device',driveSyncDevice()); const tc=google.accounts.oauth2.initTokenClient({client_id:id,scope:MVI_DRIVE_SYNC_SCOPE,callback:async r=>{ if(r.error){driveSyncAuthMsg('Authorization failed: '+(r.error_description||r.error),'err');return;} mviDriveSyncToken=r.access_token;driveSyncSetButtons(true);driveSyncAuthMsg('Google Drive connected successfully.','ok');await driveSyncRefreshCloud(); }});tc.requestAccessToken({prompt:''}); }catch(e){driveSyncAuthMsg(e.message||String(e),'err');} } function driveSyncClearSession(){ mviDriveSyncToken=''; ['mviapps_drive_sync_client','mviapps_drive_sync_last_cloud_hash','mviapps_drive_sync_last_cloud_revision','mviapps_drive_sync_last_local_hash','mviapps_drive_sync_last_device',MVI_DRIVE_SYNC_BASELINE].forEach(k=>localStorage.removeItem(k)); driveSyncSetButtons(false);const id=document.getElementById('driveSyncClientId');if(id)id.value='988343209498-efpe2k4lolbo12vb7b486vkdek20lqec.apps.googleusercontent.com';const h=document.getElementById('driveSyncLastHash');if(h)h.value='';driveSyncAuthMsg('Sync session cleared.');driveSyncMsg('Connect Google Drive first.'); } async function driveSyncApi(url,options={}){const res=await fetch(url,{...options,headers:{...(options.headers||{}),Authorization:`Bearer ${mviDriveSyncToken}`}});if(res.status===401)throw new Error('Google Drive authorization expired. Please click Sign in with Google Drive again.');if(!res.ok){let detail='';try{detail=await res.text();}catch(e){}throw new Error('Google Drive API error '+res.status+(detail?': '+detail.slice(0,300):''));}return res;} async function driveSyncFindFile(){const q=encodeURIComponent(`name='${MVI_DRIVE_SYNC_FILE.replace(/'/g,"\\'")}' and trashed=false`);const res=await driveSyncApi(`https://www.googleapis.com/drive/v3/files?q=${q}&spaces=drive&fields=files(id,name,modifiedTime,size)&pageSize=10`);const j=await res.json();return j.files?.[0]||null;} async function driveSyncReadFile(fileId){const res=await driveSyncApi(`https://www.googleapis.com/drive/v3/files/${encodeURIComponent(fileId)}?alt=media`);return await res.json();} function driveSyncRenderCloud(snapshot){const view=document.getElementById('driveSyncCloudView');if(!view)return;if(!snapshot){view.textContent='No cloud snapshot exists yet.';return;}view.textContent=JSON.stringify({schemaVersion:snapshot.schemaVersion,app:snapshot.app,device:snapshot.meta?.updatedBy||'',updatedAt:snapshot.meta?.updatedAt||'',revision:snapshot.meta?.cloudRevision||snapshot.meta?.cloudHash||'',dataSections:Object.keys(snapshot.data||{}).length,itemCount:(()=>{try{return JSON.parse(snapshot.data?.mviapps_items||'[]').length}catch(e){return 0}})()},null,2);} async function driveSyncRefreshCloud(){ try{const file=await driveSyncFindFile();if(!file){driveSyncRenderCloud(null);driveSyncMsg('No MVIApps integration-test cloud snapshot exists yet. The first Sync Now will create it.');const h=document.getElementById('driveSyncLastHash');if(h)h.value=driveSyncLastCloudRevision()||'None';return null;} const snapshot=await driveSyncReadFile(file.id);if(!snapshot?.data)throw new Error('Cloud file exists but does not contain a valid MVIApps snapshot.');Object.keys(snapshot.data||{}).forEach(k=>{if(driveSyncExcludeDataKey(k))delete snapshot.data[k]});driveSyncRenderCloud(snapshot); const cloudHash=snapshot.meta?.cloudHash||await driveSyncHashData(snapshot.data),cloudRevision=snapshot.meta?.cloudRevision||cloudHash; const h=document.getElementById('driveSyncLastHash');if(h)h.value=driveSyncLastCloudRevision()||'None';return {file,snapshot,cloudHash,cloudRevision}; }catch(e){driveSyncMsg(e.message||String(e),'err');return null;} } function driveSyncPayload(data,hash,revision){return {schemaVersion:2,app:'MVIApps Drive Sync',meta:{updatedBy:driveSyncDevice(),updatedAt:new Date().toISOString(),cloudHash:hash,cloudRevision:revision},data};} async function driveSyncUploadSnapshot(data,hash,fileId=null){ const revision=driveSyncNewRevision(),body=JSON.stringify(driveSyncPayload(data,hash,revision));let res; if(fileId){res=await driveSyncApi(`https://www.googleapis.com/upload/drive/v3/files/${encodeURIComponent(fileId)}?uploadType=media`,{method:'PATCH',headers:{'Content-Type':'application/json'},body});} else{const metadata={name:MVI_DRIVE_SYNC_FILE,mimeType:'application/json'},boundary='mviapps_sync_boundary_'+Date.now(),multipart='--'+boundary+'\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n'+JSON.stringify(metadata)+'\r\n--'+boundary+'\r\nContent-Type: application/json\r\n\r\n'+body+'\r\n--'+boundary+'--';res=await driveSyncApi('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,modifiedTime',{method:'POST',headers:{'Content-Type':'multipart/related; boundary='+boundary},body:multipart});} if(!res.ok)throw new Error('Could not save the cloud snapshot.');return {file:await res.json(),revision}; } async function driveSyncRestoreData(data){ if(typeof openMVIItemDB==='function')await openMVIItemDB();let backupItems=[];try{backupItems=JSON.parse(data.mviapps_items||'[]');}catch(e){backupItems=[];}if(!Array.isArray(backupItems))backupItems=[]; const oldKeys=[];for(let i=0;ilocalStorage.removeItem(k)); for(const [k,v] of Object.entries(data)){if(!k.startsWith('mviapps_')||k==='mviapps_items'||driveSyncExcludeDataKey(k))continue;localStorage.setItem(k,String(v));} const cleanItems=[];for(const item of backupItems){if(!item||typeof item!=='object')continue;const copy={...item},img=copy.image;delete copy.image;if(img&&typeof img==='string'&&img.startsWith('data:image')){await putMVIItemImage(copy.id,img);copy.imageKey=String(copy.id);}else if(copy.imageKey){copy.imageKey=String(copy.imageKey);}cleanItems.push(copy);}localStorage.setItem('mviapps_items',JSON.stringify(cleanItems)); } async function driveSyncDownloadCloud(force=false){ driveSyncSetBusy(true,'Downloading data from Google Drive... Please wait. Do not refresh or close this page.'); await driveSyncYieldForUi(); try{const found=await driveSyncRefreshCloud();if(!found){driveSyncMsg('No cloud data is available yet.','err');return;}if(!force&&!confirm('This will replace the MVIApps data on THIS TEST DEVICE with the cloud snapshot. A backup is strongly recommended first. Continue?'))return; await driveSyncRestoreData(found.snapshot.data);const after=await driveSyncBuildLocal();driveSyncSaveState(found.cloudRevision,after.hash);await driveSyncSaveBaseline(after.data);const h=document.getElementById('driveSyncLastHash');if(h)h.value=found.cloudRevision;driveSyncMsg('Cloud data loaded successfully. MVIApps will reload now.','ok');setTimeout(()=>location.reload(),700); }catch(e){console.error(e);driveSyncMsg('Cloud download failed: '+(e.message||String(e)),'err');} finally{driveSyncSetBusy(false);} } async function driveSyncUploadLocal(force=false){ driveSyncSetBusy(true,'Uploading local data to Google Drive... Please wait. Do not refresh or close this page.'); await driveSyncYieldForUi(); try{const found=await driveSyncRefreshCloud();const local=await driveSyncBuildLocal();if(!found){const created=await driveSyncUploadSnapshot(local.data,local.hash,null);driveSyncSaveState(created.revision,local.hash);await driveSyncSaveBaseline(local.data);driveSyncMsg('Local data uploaded successfully. Cloud snapshot created.','ok');await driveSyncRefreshCloud();return;} const lastRev=driveSyncLastCloudRevision(),lastLocal=driveSyncLastLocalHash(); if(!lastLocal&&lastRev){driveSyncSaveState(lastRev,local.hash);} const baselineLocal=driveSyncLastLocalHash(),baselineRev=driveSyncLastCloudRevision(); if(!force&&baselineRev&&found.cloudRevision!==baselineRev){driveSyncMsg('Conflict detected: the cloud changed after this device last synced. Use Sync Now to inspect, or explicitly choose Cloud/Local after reviewing your backup.','err');return;} if(!force&&!baselineRev&&Object.entries(found.snapshot.data||{}).length&&local.hash!==found.cloudHash){if(!confirm('This device has local data but no previous sync record. Uploading would replace the existing cloud snapshot. Continue only if this device is the source you want to keep.'))return;} const uploaded=await driveSyncUploadSnapshot(local.data,local.hash,found.file.id);driveSyncSaveState(uploaded.revision,local.hash);await driveSyncSaveBaseline(local.data);driveSyncMsg('Local data uploaded successfully to Google Drive.','ok');await driveSyncRefreshCloud(); }catch(e){console.error(e);driveSyncMsg('Cloud upload failed: '+(e.message||String(e)),'err');} finally{driveSyncSetBusy(false);} } async function driveSyncNow(){ driveSyncSetBusy(true,'Syncing with Google Drive... Please wait. Do not refresh or close this page.'); await driveSyncYieldForUi(); try{const found=await driveSyncRefreshCloud();const local=await driveSyncBuildLocal(); if(!found){const created=await driveSyncUploadSnapshot(local.data,local.hash,null);driveSyncSaveState(created.revision,local.hash);await driveSyncSaveBaseline(local.data);driveSyncMsg('First sync complete: local MVIApps data is now stored in the MVIApps cloud snapshot.','ok');await driveSyncRefreshCloud();return;} let lastRev=driveSyncLastCloudRevision(),lastLocal=driveSyncLastLocalHash(); if(!lastLocal&&lastRev){lastLocal=local.hash;driveSyncSaveState(lastRev,lastLocal);if(!driveSyncLoadBaseline())await driveSyncSaveBaseline(local.data);} if(!lastRev&&!lastLocal){ const nonEmpty=Object.entries(local.data).some(([k,v])=>k!=='mviapps_selected_financial_year'&&String(v||'').trim()&&String(v)!=='[]'&&String(v)!=='{}'); if(!nonEmpty){await driveSyncRestoreData(found.snapshot.data);const after=await driveSyncBuildLocal();driveSyncSaveState(found.cloudRevision,after.hash);await driveSyncSaveBaseline(after.data);driveSyncMsg('New device synchronized from the existing cloud snapshot. MVIApps will reload now.','ok');setTimeout(()=>location.reload(),700);return;} driveSyncMsg('Conflict: this device has local data and no previous sync record, while cloud data already exists. Use Cloud Data → This Device or Local Data → Drive after making a backup. Nothing was overwritten.','err');return; } const localChanged=local.hash!==lastLocal,cloudChanged=found.cloudRevision!==lastRev; if(!localChanged&&!cloudChanged){driveSyncSaveState(lastRev,lastLocal);if(!driveSyncLoadBaseline())await driveSyncSaveBaseline(local.data);driveSyncMsg('Already synchronized. No changes were needed.','ok');return;} if(cloudChanged&&!localChanged){await driveSyncRestoreData(found.snapshot.data);const after=await driveSyncBuildLocal();driveSyncSaveState(found.cloudRevision,after.hash);await driveSyncSaveBaseline(after.data);driveSyncMsg('Cloud changes were downloaded to this device. MVIApps will reload now.','ok');setTimeout(()=>location.reload(),700);return;} if(!cloudChanged&&localChanged){const uploaded=await driveSyncUploadSnapshot(local.data,local.hash,found.file.id);driveSyncSaveState(uploaded.revision,local.hash);await driveSyncSaveBaseline(local.data);driveSyncMsg('This device changed; its changes were uploaded to the MVIApps cloud snapshot.','ok');await driveSyncRefreshCloud();return;} // Both sides changed. First try a safe three-way merge against the last synchronized baseline. // If this device predates the baseline manifest, use a conservative additive merge: only // independent records are combined; any same-record difference remains a real conflict. const baseline=driveSyncLoadBaseline(); const result=baseline?await driveSyncThreeWayMerge(baseline,local.data,found.snapshot.data):await driveSyncLegacyAdditiveMerge(local.data,found.snapshot.data); if(result&&result.merged){ const mergedData=result.merged,mergedHash=await driveSyncHashData(mergedData); const uploaded=await driveSyncUploadSnapshot(mergedData,mergedHash,found.file.id); // Restore only after the merged snapshot has been safely written to Drive. await driveSyncRestoreData(mergedData); const after=await driveSyncBuildLocal();driveSyncSaveState(uploaded.revision,after.hash);await driveSyncSaveBaseline(after.data); driveSyncMsg('Changes from both devices were merged safely and synchronized. No conflicting records were overwritten.','ok'); await driveSyncRefreshCloud(); setTimeout(()=>location.reload(),700);return; } const detail=result?.conflicts?.slice(0,5).join(', ')||'one or more data sections'; driveSyncMsg('CONFLICT DETECTED: both this device and the cloud changed, and the changes could not be merged safely ('+detail+'). Nothing was overwritten. Please make a backup, then choose explicitly between Cloud Data → This Device or Local Data → Drive.','err'); }catch(e){console.error(e);driveSyncMsg('Sync failed: '+(e.message||String(e)),'err');} finally{driveSyncSetBusy(false);} } function driveSyncInitPage(){const id=document.getElementById('driveSyncClientId'),dev=document.getElementById('driveSyncDevice');if(id)id.value='988343209498-efpe2k4lolbo12vb7b486vkdek20lqec.apps.googleusercontent.com';if(dev)dev.value='';const h=document.getElementById('driveSyncLastHash');if(h)h.value=driveSyncLastCloudRevision()||'None';if(mviDriveSyncToken)driveSyncSetButtons(true);} function utility(){return `

Backup / Restore

Create a complete backup of all app data, restore the entire app, or export/import selected data.

Full Backup
Backup All Data

Creates one JSON file containing all mviapps data.

Full Restore
Restore All Data

Restores the complete app data from a backup JSON file.

Import / Export

Transfer selected app data without replacing the complete backup.

Export
Selected Data


Import
Add / Merge Data

Imports compatible exported data and merges it with existing records.

Local Master Data — Raw Export

Read-only export of original Party and Item records for controlled Local-to-Cloud migration mapping.

Local Master Records
Parties — Raw JSON

Exports every original Party record, including its ID, code, balances and other stored fields.

Local Master Records
Items — Raw JSON

Exports every original Item record, including its ID, code, opening quantity, stock fields and stored references.

Raw export reads LocalStorage only. It does not import, edit, delete, or synchronize records. Item image binaries stored separately in IndexedDB are not included; existing imageKey references remain unchanged in the exported records.

`} function appData(){const d={};for(let i=0;iURL.revokeObjectURL(a.href),1000)} function exportRawMasterCollection(key){ const allowed={mviapps_parties:'Parties',mviapps_items:'Items'}; if(!Object.prototype.hasOwnProperty.call(allowed,key)){alert('Unsupported master collection.');return;} const status=document.getElementById('mviappsRawMasterExportStatus'); try{ const raw=localStorage.getItem(key); if(raw===null){if(status)status.textContent=allowed[key]+': LocalStorage collection not found. No data was changed.';alert(allowed[key]+' collection was not found in this browser.');return;} const records=JSON.parse(raw); if(!Array.isArray(records)){if(status)status.textContent=allowed[key]+': stored value is not a JSON array. No data was changed.';alert('Cannot export '+allowed[key]+': stored data is not a JSON array.');return;} const now=new Date().toISOString(); const payload={type:'mviapps-raw-master-export',version:1,app:'mviapps',readOnly:true,exportedAt:now,collectionKey:key,collectionLabel:allowed[key],recordCount:records.length,source:'LocalStorage',records:records}; const date=now.slice(0,10); downloadJSON(payload,'MVIApps_'+allowed[key]+'_Raw_Export_'+date+'.json'); if(status)status.textContent=allowed[key]+': exported '+records.length+' original record(s) to JSON. LocalStorage, IndexedDB, Cloud data and Drive Sync were not changed.'; }catch(e){ const message=e&&e.message?e.message:String(e); if(status)status.textContent='Raw export failed for '+allowed[key]+': '+message+'. No data was changed.'; alert('Raw export failed: '+message); } } async function exportSelectedData(){ const type=document.getElementById('exportType')?.value||'all';let data={}; if(type==='all')data=await appDataWithHighStorage(); else if(type==='mviapps_items')data[type]=JSON.stringify(JSON.parse((await appDataWithHighStorage()).mviapps_items||'[]')); else{const raw=localStorage.getItem(type);data[type]=raw===null?null:raw;} const payload={type:'mviapps-selected-export',version:3,createdAt:new Date().toISOString(),app:'mviapps',selection:type,data}; downloadJSON(payload,'mviapps-'+(type==='all'?'all-data':type.replace(/^mviapps_/,'') )+'-'+new Date().toISOString().slice(0,10)+'.json');alert('Data exported successfully.'); } function mergeImportedArray(key,incoming){let current=[];try{current=JSON.parse(localStorage.getItem(key)||'[]')}catch(e){current=[]}if(!Array.isArray(incoming))return false;const map=new Map(current.map(x=>[String(x?.id??''),x]));incoming.forEach(x=>{const id=String(x?.id??'');if(id&&id!=='undefined'&&id!=='null')map.set(id,x);else current.push(x)});localStorage.setItem(key,JSON.stringify(Array.from(map.values())));return true} function importSelectedData(input){readJSONFile(input,obj=>{if(!obj||typeof obj!=='object'||!obj.data||typeof obj.data!=='object'){alert('Invalid import file. Please select an MVIApps exported JSON file.');return}const entries=Object.entries(obj.data).filter(([k])=>k.startsWith('mviapps_'));if(!entries.length){alert('No compatible MVIApps data found in this file.');return}if(!confirm('Import will add/merge the selected data with your existing records. Continue?'))return;let imported=0;entries.forEach(([key,value])=>{if(value===null||value===undefined)return;try{const parsed=typeof value==='string'?JSON.parse(value):value;if(Array.isArray(parsed)){if(mergeImportedArray(key,parsed))imported++;}else{localStorage.setItem(key,String(value));imported++;}}catch(e){localStorage.setItem(key,String(value));imported++;}});alert(imported+' data section(s) imported successfully. The app will now reload.');location.reload()})} async function createFullBackup(){ const now=new Date().toISOString();const data=await appDataWithHighStorage();const count=Object.keys(data).length; downloadJSON({type:'mviapps-full-backup',version:3,createdAt:now,app:'mviapps',data},'mviapps-backup-'+now.slice(0,10)+'.json'); localStorage.setItem('mviapps_lastBackupAt',now);alert('Backup created successfully. '+count+' data sections have been backed up, including product images.'); if(document.getElementById('backupStatus'))renderDataSafety(); } function readJSONFile(input,cb){const f=input.files&&input.files[0];if(!f)return;const r=new FileReader();r.onload=()=>{try{cb(JSON.parse(r.result))}catch(e){alert('Invalid backup file. Please select a valid mviapps backup JSON file.')}finally{input.value=''}};r.readAsText(f)} async function restoreFullBackup(input){ const f=input.files&&input.files[0]; if(!f)return; const reader=new FileReader(); reader.onload=async()=>{ try{ const obj=JSON.parse(reader.result); if(!obj||obj.type!=='mviapps-full-backup'||!obj.data||typeof obj.data!=='object'){alert('This is not a valid mviapps full backup file.');return;} const data=obj.data; let backupItems=[]; try{backupItems=JSON.parse(data.mviapps_items||'[]');}catch(e){backupItems=[];} if(!Array.isArray(backupItems))backupItems=[]; const imageCount=backupItems.filter(x=>typeof x?.image==='string'&&x.image.startsWith('data:image')).length; if(!confirm('Restore will replace all current mviapps data with this backup. '+backupItems.length+' items'+(imageCount?' and '+imageCount+' item images':'')+' will be restored. Continue?'))return; // IMPORTANT: item images are stored in IndexedDB, not localStorage. Older restore code // tried to put the image-heavy mviapps_items JSON directly into localStorage, which can // exceed the browser quota and make the restore fail. try{await openMVIItemDB();}catch(e){alert('Restore cannot continue because IndexedDB is unavailable. Please allow browser site storage and try again.');return;} const oldKeys=[];for(let i=0;ilocalStorage.removeItem(k)); // Restore every normal section first. Keep mviapps_items separate so its base64 images // never enter localStorage. for(const [k,v] of Object.entries(data)){ if(!k.startsWith('mviapps_')||k==='mviapps_items')continue; try{localStorage.setItem(k,String(v));} catch(e){throw new Error('Could not restore '+k+' because browser storage is full.');} } const cleanItems=[]; for(const item of backupItems){ if(!item||typeof item!=='object')continue; const copy={...item}; const img=copy.image; delete copy.image; if(img&&typeof img==='string'&&img.startsWith('data:image')){ await putMVIItemImage(copy.id,img); copy.imageKey=String(copy.id); }else if(copy.imageKey){copy.imageKey=String(copy.imageKey);} cleanItems.push(copy); } try{localStorage.setItem('mviapps_items',JSON.stringify(cleanItems));} catch(e){throw new Error('Could not restore the item list because browser storage is full.');} // Mark the restored backup time only after all data has been written successfully. const restoredAt=obj.createdAt||new Date().toISOString(); localStorage.setItem('mviapps_lastBackupAt',String(restoredAt)); alert('Backup restored successfully. '+Object.keys(data).filter(k=>k.startsWith('mviapps_')).length+' data sections and '+cleanItems.length+' items restored. The app will now reload.'); location.reload(); }catch(e){ console.error('MVIApps restore failed:',e); alert('Restore failed: '+(e?.message||'Browser storage error')+'\n\nYour backup file is valid, but the current browser could not save all restored data. Please make sure site storage is allowed and try again.'); }finally{input.value='';} }; reader.onerror=()=>{alert('Could not read the backup file. Please try again.');input.value='';}; reader.readAsText(f); } function dataSafetyPage(){return `

System & Data Safety

Important guidance to keep your MVIApps data safe on your computer or tablet.

Backup Status
Checking backup status...
Recommended Setup
  • Use an updated Chrome, Edge or Firefox browser.
  • Keep using the same browser/profile for regular work.
  • Do not clear browser/site data unless you have a backup.
  • Before changing computers, create a Full Backup.
  • On the new computer, use Restore All Data to bring your records back.
Data Safety Tips
  • Keep at least one backup outside the browser, such as a USB drive or secure folder.
  • Take a backup before major data changes or software/browser maintenance.
  • For important records, keep more than one backup copy.
  • Never share backup files publicly because they may contain business data.
App Information
`} function renderDataSafety(){const el=document.getElementById('backupStatus');if(!el)return;const raw=localStorage.getItem('mviapps_lastBackupAt');if(!raw){el.innerHTML='No backup recorded yet. Create a backup now to protect your data.';return}const d=new Date(raw);const age=Math.floor((Date.now()-d.getTime())/86400000);const label=isNaN(d.getTime())?'Unknown':d.toLocaleString();el.innerHTML=`Last backup: ${escapeHtml(label)}${age>=7?' — It has been 7 or more days; a fresh backup is recommended.':' — Backup record is recent.'}`} function resetProductionCloudDataPage(){return `

Reset Production Cloud Data

Clear all business records from the Production Cloud while keeping the Business identity and Owner login.

Permanent Production Cloud Reset

This is different from “Delete All App Data (This Browser)”. It clears Production Cloud records for this Business only.

  • Deletes Parties, Items, invoices, returns, payments, expenses, other income, all bank accounts and bank/cash transactions.
  • Deletes opening balances, accounting journals, payment allocations, stock events/state, stock adjustments, transfers and secondary/test Godowns. The verified Main Godown is preserved.
  • Deletes staff login accounts/sessions, invitations and non-Owner business memberships.
  • Keeps Business ID, Business identity, your Owner login and Owner membership, D1 schema/indexes/triggers and Worker/Firebase configuration.

Cannot be undone. Ensure your backup is safely stored before proceeding.

`} async function mviappsExecuteProductionCloudReset(){ const input=document.getElementById('mviappsResetCloudConfirm'),button=document.getElementById('mviappsResetCloudButton'),status=document.getElementById('mviappsResetCloudStatus'); if(!input||input.value.trim()!=='RESET PRODUCTION DATA'){if(status)status.textContent='Confirmation text does not match. No data was changed.';return;} const identity=window.mviappsProductionCloud?.getIdentity?.(); if(!identity||identity.mode!=='owner'||identity.business?.role!=='Owner'){if(status)status.textContent='Owner Production sign-in is required. No data was changed.';return;} if(!confirm('FINAL WARNING: Permanently delete all Production Cloud business records for '+(identity.business.name||identity.business.id)+'? Your Business ID and Owner login will remain.'))return; if(button)button.disabled=true;if(status)status.textContent='Submitting secure Owner-only reset. Do not close this page…'; try{ const result=await window.mviappsProductionCloud.resetProductionBusinessData('RESET PRODUCTION DATA'); if(!result?.success)throw new Error(result?.error||'Reset was not confirmed by the Production Worker.'); if(status)status.textContent='SUCCESS — Production Cloud business data has been cleared and verified.\nBusiness ID preserved: '+result.businessId+'\n\nDeleted row counts (before reset):\n'+Object.entries(result.before||{}).map(([k,v])=>k+': '+v).join('\n')+'\n\nRemaining rows in key collections: all zero.\nOwner login and Business identity preserved.'; input.value=''; }catch(error){if(status)status.textContent='RESET NOT CONFIRMED: '+(error?.message||String(error))+'\nCheck Worker deployment/logs before retrying. Do not assume data was deleted.';} finally{if(button)button.disabled=false;} } function deleteAllDataPage(){return `

Clear Local Business Data

Remove old business records from this browser only. Production Cloud data is not changed.

⚠ Clear Local Business Data

This removes old local Parties, Items, invoices, returns, payments, expenses, income, bank/cash records, stock/godown data and local company profile fields. It also clears locally stored item images.

Preserved: Firebase/Owner login, Production Cloud configuration, Google Drive connection metadata, and UI preferences such as theme, font size and layout.

This action cannot be undone. Your separate Ver 4.5 backup remains unaffected. This operation does not delete Production Cloud records.

`} async function deleteAllAppData(){if(!confirm('WARNING: Permanently clear old LOCAL business data from this browser? Production Cloud and Owner login will not be changed. Continue?'))return;const confirmation=prompt('To confirm local business data deletion, type CLEAR LOCAL DATA in capital letters:');if(confirmation!=='CLEAR LOCAL DATA'){alert('Deletion cancelled. Required confirmation was not entered.');return;}const preserve=new Set(['mviapps_accentColor','mviapps_compactLayout','mviapps_drive_sync_client','mviapps_drive_sync_last_cloud_hash','mviapps_drive_sync_last_cloud_revision','mviapps_drive_sync_last_device','mviapps_drive_sync_last_local_hash','mviapps_fontSize','mviapps_sidebarPosition','mviapps_theme']);const removed=[];for(let i=localStorage.length-1;i>=0;i--){const k=localStorage.key(i);if(k&&k.startsWith('mviapps_')&&!preserve.has(k)){localStorage.removeItem(k);removed.push(k);}}window._editingSaleId=null;window._editingPurchaseId=null;window._editingExpenseId=null;let images='not available';try{await new Promise((resolve,reject)=>{const req=indexedDB.deleteDatabase('mviapps_high_storage_v1');req.onsuccess=()=>{images='cleared';resolve();};req.onerror=()=>reject(req.error||new Error('IndexedDB delete failed'));req.onblocked=()=>reject(new Error('Close other MVIApps tabs and retry; item-image database is in use.'));});}catch(e){images='not cleared: '+(e?.message||String(e));}const status=document.getElementById('mviappsLocalResetStatus');const message='Local business data cleared. Removed '+removed.length+' local storage keys. Item image storage: '+images+'. Owner login, Production Cloud settings, Drive connection metadata and UI preferences were preserved. Production Cloud was not changed.';if(status)status.textContent=message;alert(message);show('dashboard');} function escapeHtml(v){return String(v??'').replace(/[&<>\"']/g,c=>({'&':'&','<':'<','>':'>','\"':'"',"'":'''}[c]));} function fields(label,placeholder){ if(Array.isArray(label)) return label.map(x=>`
`); return `
`; } function toggle(btn){ const group=btn.closest('.group'); const nav=group ? group.closest('.nav') : null; if(!group || !nav) return; const wasOpen=group.classList.contains('open'); // Category buttons only expand/collapse navigation. They do not navigate // away from the current page or force a Dashboard render. nav.querySelectorAll(':scope > .group.open').forEach(g=>{ if(g!==group) g.classList.remove('open'); }); group.classList.toggle('open',!wasOpen); } // Extra safeguard: if a menu is opened by any other UI event, close all // sibling main menus so there can never be more than one open dropdown. document.addEventListener('click',function(e){ const nav=e.target.closest('.sidebar .nav'); if(!nav) return; const clickedGroup=e.target.closest(':scope > .group'); if(clickedGroup) { nav.querySelectorAll(':scope > .group.open').forEach(g=>{ if(g!==clickedGroup && !clickedGroup.contains(g)) g.classList.remove('open'); }); } }); function getGodowns(){return JSON.parse(localStorage.getItem('mviapps_godowns')||'[]');} function saveGodowns(a){localStorage.setItem('mviapps_godowns',JSON.stringify(a));} function getGodownStock(){return JSON.parse(localStorage.getItem('mviapps_godown_stock')||'[]');} function saveGodownStock(a){localStorage.setItem('mviapps_godown_stock',JSON.stringify(a));} function godownManagement(){ return `

Godown Management

Manage storage locations and track item-wise stock at each godown.

Fresh Production Cloud — Godown & Stock WorkspaceSeparate Cloud records for the authenticated Business. No LocalStorage, IndexedDB, Ver 4.5 import or Drive Sync access.
Use the Cloud Workspace for Production Godowns, Stock Adjustments and Godown Transfers. Existing local forms below remain separate.
Manage Godown
GodownLocationAction
Transfer Stock
Manual Stock Adjustment

Manually increase or decrease stock in a specific godown. The adjustment will also be reflected in the item's overall closing stock.

Adjustment History

Yahan se pehle ki gayi manual stock adjustment entries ko modify ya delete kar sakte hain.

DateItemGodownTypeQtyBeforeAfterReason / RemarkAction
Check Item Availability by Godown
GodownAvailable QuantityUnit
Godown-wise Stock
ItemGodownQuantityUnitStock Value
`; } function applyGodownStaffPermissions(){const ident=window.mviappsProductionCloud?.getIdentity?.();const savedStaff=typeof readStaffSession==='function'?readStaffSession():null;const isOwner=ident?.mode==='owner';const staff=ident?.mode==='staff'||!!savedStaff;const ownerSetup=document.getElementById('mviappsCloudGodownOwnerSetupPanel');if(ownerSetup){const hideOwnerPanel=!isOwner;ownerSetup.hidden=hideOwnerPanel;ownerSetup.style.setProperty('display',hideOwnerPanel?'none':'','important');ownerSetup.setAttribute('aria-hidden',hideOwnerPanel?'true':'false');}if(!staff)return;const allowed=(module,action)=>window.mviappsProductionCloud?.hasStaffPermission?.(module,action)===true;const setVisible=(selector,show)=>document.querySelectorAll(selector).forEach(el=>{el.style.display=show?'':'none';});const setDisabled=(selector,enabled)=>document.querySelectorAll(selector).forEach(el=>{el.disabled=!enabled;});const canGodownCreate=allowed('godowns','create'),canGodownEdit=allowed('godowns','edit'),canStockCreate=allowed('stock','create'),canStockEdit=allowed('stock','edit');setVisible('button[onclick="saveGodown()"]',canGodownCreate||canGodownEdit);setDisabled('#godownName, #godownLocation',canGodownCreate||canGodownEdit);setVisible('button[onclick="transferStock()"]',canStockCreate);setDisabled('#transferItem, #transferQty, #transferFrom, #transferTo, #transferDateDisplay, #transferNote',canStockCreate);setVisible('#adjustSubmitBtn',canStockCreate||canStockEdit);setDisabled('#adjustGodown, #adjustItem, #adjustType, #adjustQty, #adjustDateDisplay, #adjustReason',canStockCreate||canStockEdit);} function initGodownPage(){ let gs=getGodowns(); if(!gs.length){gs=[{id:Date.now(),name:'Main Godown',location:'',createdAt:new Date().toISOString().slice(0,10)}];saveGodowns(gs);} renderGodowns(); populateGodownControls(); renderGodownStock(); renderItemGodownAvailability(); updateAdjustmentQty(); renderStockAdjustmentHistory(); applyGodownStaffPermissions(); } function renderGodowns(){const rows=document.getElementById('godownRows');if(!rows)return;const gs=getGodowns(),ident=window.mviappsProductionCloud?.getIdentity?.(),staff=ident?.mode==='staff',canEdit=!staff||window.mviappsProductionCloud?.hasStaffPermission?.('godowns','edit')===true,canDelete=!staff||window.mviappsProductionCloud?.hasStaffPermission?.('godowns','delete')===true;rows.innerHTML=gs.length?gs.map(g=>`${escapeHtml(g.name)}${escapeHtml(g.location||'—')}${canEdit?` `:''}${canDelete?``:''}${!canEdit&&!canDelete?'—':''}`).join(''):`No godowns found.`;} function saveGodown(){const editingId=window._editingGodownId;if(!mviappsRequireStaffPermission('godowns',editingId?'edit':'create'))return;const name=document.getElementById('godownName')?.value.trim();const location=document.getElementById('godownLocation')?.value.trim()||'';if(!name){alert('Please enter Godown Name.');return}const gs=getGodowns();if(editingId){if(gs.some(g=>String(g.id)!==String(editingId)&&String(g.name).trim().toLowerCase()===name.toLowerCase())){alert('Godown already exists.');return}const g=gs.find(x=>String(x.id)===String(editingId));if(!g){alert('Godown not found.');return}g.name=name;g.location=location;saveGodowns(gs);window._editingGodownId=null;document.getElementById('godownName').value='';document.getElementById('godownLocation').value='';const btn=document.querySelector('#godownName')?.closest('.panel')?.querySelector('button[onclick="saveGodown()"]');if(btn)btn.textContent='+ Add Godown';initGodownPage();alert('Godown modified successfully.');return}if(gs.some(g=>String(g.name).trim().toLowerCase()===name.toLowerCase())){alert('Godown already exists.');return}gs.push({id:Date.now(),name,location,createdAt:new Date().toISOString().slice(0,10)});saveGodowns(gs);document.getElementById('godownName').value='';document.getElementById('godownLocation').value='';initGodownPage();alert('Godown added successfully.');} function editGodown(id){if(!mviappsRequireStaffPermission('godowns','edit'))return;const g=getGodowns().find(x=>String(x.id)===String(id));if(!g)return;window._editingGodownId=g.id;const n=document.getElementById('godownName'),l=document.getElementById('godownLocation');if(n)n.value=g.name||'';if(l)l.value=g.location||'';const btn=n?.closest('.panel')?.querySelector('button[onclick="saveGodown()"]');if(btn)btn.textContent='Save Changes';n?.focus();} function deleteGodown(id){if(!mviappsRequireStaffPermission('godowns','delete'))return;const gs=getGodowns();if(gs.length<=1){alert('At least one godown must remain.');return}const stock=getGodownStock().filter(x=>String(x.godownId)===String(id)&&Number(x.qty)>0);if(stock.length){alert('This godown has stock. Transfer the stock to another godown before deleting it.');return}if(!confirm('Delete this godown?'))return;saveGodowns(gs.filter(g=>String(g.id)!==String(id)));initGodownPage();} function populateGodownControls(){const items=getSortedItems(),gs=getGodowns();const itemSel=document.getElementById('transferItem'),from=document.getElementById('transferFrom'),to=document.getElementById('transferTo'),filter=document.getElementById('godownStockFilter'),adjustGodown=document.getElementById('adjustGodown'),adjustItem=document.getElementById('adjustItem'),viewItem=document.getElementById('godownItemView');if(!itemSel)return;const itemOptions=''+items.map(i=>``).join('');const godownOptions=gs.map(g=>``).join('');itemSel.innerHTML=itemOptions;from.innerHTML=''+godownOptions;to.innerHTML=''+godownOptions;filter.innerHTML=''+godownOptions;if(adjustGodown)adjustGodown.innerHTML=''+godownOptions;if(adjustItem)adjustItem.innerHTML=itemOptions;if(viewItem)viewItem.innerHTML=itemOptions;const adjustDate=document.getElementById('adjustDate'),adjustDateDisplay=document.getElementById('adjustDateDisplay');if(adjustDate&&!adjustDate.value){const now=new Date(),yyyy=now.getFullYear(),mm=String(now.getMonth()+1).padStart(2,'0'),dd=String(now.getDate()).padStart(2,'0');adjustDate.value=yyyy+'-'+mm+'-'+dd;if(adjustDateDisplay)adjustDateDisplay.value=dd+'/'+mm+'/'+yyyy;}} function getItemGodownQty(itemId,godownId){return getGodownStock().filter(x=>String(x.itemId)===String(itemId)&&String(x.godownId)===String(godownId)).reduce((n,x)=>n+(Number(x.qty)||0),0);} function openAdjustmentDatePicker(){const picker=document.getElementById('adjustDate');if(!picker)return;try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();else picker.click();}catch(e){try{picker.click();}catch(ignore){}}} function syncAdjustmentDateDisplay(){const date=document.getElementById('adjustDate')?.value||'';const display=document.getElementById('adjustDateDisplay');if(display)display.value=date?date.split('-').reverse().join('/') : '';} function formatAdjustmentDateInput(el){if(!el)return;const digits=(el.value||'').replace(/\D/g,'').slice(0,8);let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out;} function syncAdjustmentDateManual(){const display=document.getElementById('adjustDateDisplay'),picker=document.getElementById('adjustDate');if(!display||!picker)return;let value=(display.value||'').trim().replace(/[.\-]/g,'/');if(!value){picker.value='';return;}const parts=value.split('/');if(parts.length===3){const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2];if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){const test=new Date(Number(yyyy),Number(mm)-1,Number(dd));if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;return;}}}syncAdjustmentDateDisplay();} function updateAdjustmentQty(){const itemId=document.getElementById('adjustItem')?.value,godownId=document.getElementById('adjustGodown')?.value,type=document.getElementById('adjustType')?.value||'increase',qty=Number(document.getElementById('adjustQty')?.value)||0;const item=JSON.parse(localStorage.getItem('mviapps_items')||'[]').find(i=>String(i.id)===String(itemId));const gs=getGodowns();if(item&&godownId&&gs.length)syncGodownStockWithClosing(item,gs);const current=item&&godownId?getItemGodownQty(itemId,godownId):0;const cur=document.getElementById('adjustCurrentQty');if(cur)cur.value=current;const preview=document.getElementById('adjustPreview');if(preview)preview.textContent=item&&godownId?`New quantity after adjustment: ${current+(type==='increase'?qty:-qty)} ${item.unit||''}`:'';} function findAdjustmentMovementIndex(moves,rec){let idx=moves.findIndex(m=>m.type==='adjustment'&&rec.id!=null&&String(m.adjustmentId||'')===String(rec.id));if(idx>=0)return idx;return moves.findIndex(m=>m.type==='adjustment'&&String(m.date||'')===String(rec.date||'')&&String(m.itemId)===String(rec.itemId)&&String(m.godownId)===String(rec.godownId)&&String(m.adjustmentType||'')===String(rec.adjustmentType||'')&&Math.abs((Number(m.qty)||0)-(Number(rec.adjustmentQty||rec.qty)||0))<0.000001&&String(m.reason||'')===String(rec.reason||''));} function renderStockAdjustmentHistory(){ const body=document.getElementById('stockAdjustmentHistoryRows');if(!body)return; const safeRead=(key)=>{try{const v=JSON.parse(localStorage.getItem(key)||'[]');return Array.isArray(v)?v:[];}catch(e){throw new Error('Could not read '+key+': '+(e&&e.message||e));}}; try{ let history=safeRead('mviapps_stock_adjustments'); const moves=safeRead('mviapps_stock_movements'); const items=safeRead('mviapps_items'); const gs=getGodowns(); let migrated=false; // Older app data can contain the stock movement but no separate history record. // Rebuild only the missing history metadata; do not change stock or movement quantities. moves.filter(m=>m&&m.type==='adjustment'&&(String(m.ref||'').toLowerCase().includes('manual stock adjustment')||m.adjustmentId!=null)).forEach(m=>{ const qty=Number(m.qty)||0, adjType=m.adjustmentType==='decrease'?'decrease':'increase'; const exists=history.some(r=>{ if(m.adjustmentId!=null&&r.id!=null&&String(r.id)===String(m.adjustmentId))return true; return String(r.date||'')===String(m.date||'')&&String(r.itemId)===String(m.itemId)&&String(r.godownId)===String(m.godownId)&&String(r.adjustmentType||'increase')===adjType&&Math.abs((Number(r.adjustmentQty||r.qty)||0)-qty)<0.000001&&String(r.reason||'')===String(m.reason||''); }); if(exists)return; const item=items.find(i=>String(i.id)===String(m.itemId)); history.push({id:m.adjustmentId??m.id??('legacy-adjustment-'+String(m.date||'')+'-'+String(m.itemId)+'-'+String(m.godownId)+'-'+history.length),date:m.date||'',itemId:m.itemId,itemName:item?.name||m.itemName||'',godownId:m.godownId,adjustmentQty:qty,adjustmentType:adjType,reason:m.reason||'',qtyBefore:null,qtyAfter:null,_recoveredFromMovement:true}); migrated=true; }); if(migrated)localStorage.setItem('mviapps_stock_adjustments',JSON.stringify(history)); body.innerHTML=history.length?history.slice().reverse().map((r,revIndex)=>{ const idx=history.length-1-revIndex,g=gs.find(x=>String(x.id)===String(r.godownId)),item=items.find(i=>String(i.id)===String(r.itemId)); const before=r.qtyBefore==null?'—':Number(r.qtyBefore),after=r.qtyAfter==null?'—':Number(r.qtyAfter); const ident=window.mviappsProductionCloud?.getIdentity?.(),staff=ident?.mode==='staff',canEdit=!staff||window.mviappsProductionCloud?.hasStaffPermission?.('stock','edit')===true,canDelete=!staff||window.mviappsProductionCloud?.hasStaffPermission?.('stock','delete')===true;return `${String(r.date||'').match(/^\d{4}-\d{2}-\d{2}$/)?String(r.date).split('-').reverse().join('/'):escapeHtml(r.date||'—')}${escapeHtml(r.itemName||item?.name||'—')}${escapeHtml(g?.name||'Unknown Godown')}${r.adjustmentType==='increase'?'Increase':'Decrease'}${Number(r.adjustmentQty||r.qty)||0}${before}${after}${escapeHtml(r.reason||'—')}${canEdit?` `:''}${canDelete?``:''}${!canEdit&&!canDelete?'—':''}`; }).join(''):`No manual stock adjustments found in the saved history or stock movements.`; }catch(e){console.error('Adjustment History load failed:',e);body.innerHTML=`Adjustment History could not load: ${escapeHtml(e&&e.message||String(e))}`;} } function cancelStockAdjustmentEdit(){window._editingStockAdjustmentId=null;window._editingStockAdjustmentIndex=null;const btn=document.getElementById('adjustSubmitBtn'),cancel=document.getElementById('adjustCancelBtn');if(btn)btn.textContent='Adjust Stock';if(cancel)cancel.style.display='none';const q=document.getElementById('adjustQty'),r=document.getElementById('adjustReason');if(q)q.value='0';if(r)r.value='';updateAdjustmentQty();} function editStockAdjustment(id,index){if(!mviappsRequireStaffPermission('stock','edit'))return;const history=JSON.parse(localStorage.getItem('mviapps_stock_adjustments')||'[]');let idx=history.findIndex(r=>String(r.id??'')===String(id));if(idx<0)idx=index;const r=history[idx];if(!r){alert('Adjustment entry not found.');return}window._editingStockAdjustmentId=r.id??null;window._editingStockAdjustmentIndex=idx;const set=(id,v)=>{const el=document.getElementById(id);if(el)el.value=v??''};set('adjustGodown',r.godownId);set('adjustItem',r.itemId);set('adjustType',r.adjustmentType||'increase');set('adjustQty',Number(r.adjustmentQty||r.qty)||0);set('adjustReason',r.reason||'');set('adjustDate',r.date||'');syncAdjustmentDateDisplay();const btn=document.getElementById('adjustSubmitBtn'),cancel=document.getElementById('adjustCancelBtn');if(btn)btn.textContent='Save Changes';if(cancel)cancel.style.display='inline-flex';updateAdjustmentQty();document.getElementById('adjustGodown')?.scrollIntoView({behavior:'smooth',block:'center'});} function deleteStockAdjustment(id,index){if(!mviappsRequireStaffPermission('stock','delete'))return;const history=JSON.parse(localStorage.getItem('mviapps_stock_adjustments')||'[]');let idx=history.findIndex(r=>String(r.id??'')===String(id));if(idx<0)idx=index;const rec=history[idx];if(!rec){alert('Adjustment entry not found.');return}if(!confirm('Delete this manual stock adjustment? The item and godown stock will be recalculated.'))return;history.splice(idx,1);localStorage.setItem('mviapps_stock_adjustments',JSON.stringify(history));const moves=getStockMovements(),mi=findAdjustmentMovementIndex(moves,rec);if(mi>=0)moves.splice(mi,1);localStorage.setItem('mviapps_stock_movements',JSON.stringify(moves));const item=JSON.parse(localStorage.getItem('mviapps_items')||'[]').find(i=>String(i.id)===String(rec.itemId));if(item)syncGodownStockWithClosing(item,getGodowns());if(String(window._editingStockAdjustmentId??'')===String(id))cancelStockAdjustmentEdit();renderStockAdjustmentHistory();renderGodownStock();renderItemGodownAvailability();updateAdjustmentQty();alert('Adjustment deleted and stock recalculated.');} window.editStockAdjustment=editStockAdjustment;window.deleteStockAdjustment=deleteStockAdjustment; // Use delegated click handling so History actions work even when inline handlers are blocked. if(!window._mviAdjustmentHistoryClickBound){window._mviAdjustmentHistoryClickBound=true;document.addEventListener('click',function(ev){const btn=ev.target&&ev.target.closest?ev.target.closest('[data-adjust-action]'):null;if(!btn)return;ev.preventDefault();ev.stopPropagation();const id=btn.getAttribute('data-adjust-id')||'',idx=Number(btn.getAttribute('data-adjust-index'));try{if(btn.getAttribute('data-adjust-action')==='modify')window.editStockAdjustment(id,idx);else if(btn.getAttribute('data-adjust-action')==='delete')window.deleteStockAdjustment(id,idx);}catch(err){console.error('Manual Stock Adjustment action failed:',err);alert('Action failed: '+(err&&err.message||String(err)));}});} function adjustStock(){if(!mviappsRequireStaffPermission('stock',window._editingStockAdjustmentIndex!=null?'edit':'create'))return;const date=document.getElementById('adjustDate')?.value||'';if(!ensureEntryDateInActiveFY(date,'Adjustment Date'))return;const itemId=document.getElementById('adjustItem')?.value,godownId=document.getElementById('adjustGodown')?.value,type=document.getElementById('adjustType')?.value||'increase',qty=Number(document.getElementById('adjustQty')?.value)||0,reason=document.getElementById('adjustReason')?.value.trim()||'';if(!itemId||!godownId||qty<=0){alert('Please select Godown, Item and enter a valid Quantity.');return}const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'),item=items.find(i=>String(i.id)===String(itemId)),gs=getGodowns();if(!item||!gs.some(g=>String(g.id)===String(godownId))){alert('Item or Godown not found.');return}const history=JSON.parse(localStorage.getItem('mviapps_stock_adjustments')||'[]'),editing=window._editingStockAdjustmentIndex!=null?history[window._editingStockAdjustmentIndex]:null;if(editing){const old={...editing};if(String(old.itemId)!==String(itemId)||String(old.godownId)!==String(godownId)){/* stock will be rebuilt for both items below */}const newRec={...old,date,itemId:item.id,itemName:item.name,godownId,adjustmentQty:qty,adjustmentType:type,reason};const moves=getStockMovements(),mi=findAdjustmentMovementIndex(moves,old);if(mi>=0)moves.splice(mi,1,{...moves[mi],date,itemId:item.id,qty,type:'adjustment',adjustmentType:type,ref:'Manual Stock Adjustment',godownId,reason,adjustmentId:old.id});else moves.push({id:Date.now()+Math.random(),adjustmentId:old.id,date,itemId:item.id,qty,type:'adjustment',adjustmentType:type,ref:'Manual Stock Adjustment',godownId,reason});history[window._editingStockAdjustmentIndex]=newRec;localStorage.setItem('mviapps_stock_adjustments',JSON.stringify(history));localStorage.setItem('mviapps_stock_movements',JSON.stringify(moves));const affected=new Set([String(old.itemId),String(item.id)]);items.filter(i=>affected.has(String(i.id))).forEach(i=>syncGodownStockWithClosing(i,gs));cancelStockAdjustmentEdit();renderStockAdjustmentHistory();renderGodownStock();renderItemGodownAvailability();alert('Adjustment modified and stock recalculated.');return}let stock=syncGodownStockWithClosing(item,gs),row=stock.find(x=>String(x.itemId)===String(itemId)&&String(x.godownId)===String(godownId));if(!row){row={id:Date.now()+Math.random(),itemId:item.id,godownId:godownId,qty:0};stock.push(row)}const before=Number(row.qty)||0;if(type==='decrease'&&qty>before){alert(`Cannot decrease by ${qty}. Available quantity in this godown is ${before} ${item.unit||''}.`);return}const after=before+(type==='increase'?qty:-qty);row.qty=after;saveGodownStock(stock);const id=Date.now()+Math.random(),moves=getStockMovements();moves.push({id,date,itemId:item.id,qty,type:'adjustment',adjustmentType:type,ref:'Manual Stock Adjustment',godownId,reason,adjustmentId:id});localStorage.setItem('mviapps_stock_movements',JSON.stringify(moves));history.push({id,date,itemId:item.id,itemName:item.name,godownId,qtyBefore:before,adjustmentQty:qty,adjustmentType:type,qtyAfter:after,reason});localStorage.setItem('mviapps_stock_adjustments',JSON.stringify(history));document.getElementById('adjustQty').value='0';document.getElementById('adjustReason').value='';updateAdjustmentQty();renderGodownStock();renderItemGodownAvailability();renderStockAdjustmentHistory();alert(`Stock ${type==='increase'?'increased':'decreased'} successfully.`);} function renderItemGodownAvailability(){const rows=document.getElementById('godownItemRows');if(!rows)return;const itemId=document.getElementById('godownItemView')?.value||'',items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'),gs=getGodowns();if(!itemId){rows.innerHTML='Select an item to view godown-wise availability.';const t=document.getElementById('godownItemTotal');if(t)t.textContent='';return}const item=items.find(i=>String(i.id)===String(itemId));if(!item)return;syncGodownStockWithClosing(item,gs);let total=0;rows.innerHTML=gs.map(g=>{const q=getItemGodownQty(itemId,g.id);total+=q;return `${escapeHtml(g.name)}${q}${escapeHtml(item.unit||'Nos')}`}).join('');const t=document.getElementById('godownItemTotal');if(t)t.textContent=`Total available across all godowns: ${total} ${item.unit||''}`;} function ensureOpeningAllocation(item,gs){let stock=getGodownStock(), has=stock.some(x=>String(x.itemId)===String(item.id));if(has)return stock;let g=gs.find(x=>String(x.name||'').trim().toLowerCase()==='main godown')||gs[0];const q=Number(item.qty)||0;if(g&&q>0)stock.push({id:Date.now()+Math.random(),itemId:item.id,godownId:g.id,qty:q});saveGodownStock(stock);return stock;} function syncGodownStockWithClosing(item,gs){ if(!item||!gs.length)return getGodownStock(); const main=gs.find(g=>String(g.name||'').trim().toLowerCase()==='main godown')||gs[0]; const itemId=String(item.id), mainId=String(main.id); // Use the item passed into this function. A reference to an undeclared // `items` variable here can throw when stock is recalculated from the sale popup. const isStockItem=!isServiceSaleItem(item); const stock=getGodownStock().filter(x=>String(x.itemId)!==itemId); const byId={}; gs.forEach(g=>byId[String(g.id)]={id:Date.now()+Math.random(),itemId:item.id,godownId:g.id,qty:0}); const add=(gid,q)=>{const r=byId[String(gid)];if(r)r.qty+=Number(q)||0;}; const sub=(gid,q)=>{const r=byId[String(gid)];if(r)r.qty=Math.max(0,(Number(r.qty)||0)-(Number(q)||0));}; // Opening stock entered in Item Details always starts in Main Godown. add(mainId,Number(item.qty)||0); const purchases=JSON.parse(localStorage.getItem('mviapps_purchase_invoices')||'[]'); const purchaseReturns=JSON.parse(localStorage.getItem('mviapps_purchase_returns')||'[]'); const sales=JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]'); const salesReturns=JSON.parse(localStorage.getItem('mviapps_sales_returns')||'[]'); const adjustments=JSON.parse(localStorage.getItem('mviapps_stock_adjustments')||'[]'); const transfers=JSON.parse(localStorage.getItem('mviapps_godown_transfers')||'[]'); const bounds=getFinancialYearBounds(),fyFrom=bounds.from||'',fyTo=bounds.to||''; const events=[]; purchases.forEach(inv=>(inv.items||[]).filter(it=>String(it.itemId)===itemId&&isStockItem).forEach(it=>events.push({date:inv.date||'',order:1,type:'purchase',qty:Number(it.qty)||0}))); purchaseReturns.forEach(inv=>(inv.items||[]).filter(it=>String(it.itemId)===itemId&&isStockItem).forEach(it=>events.push({date:inv.date||'',order:2,type:'return',qty:Number(it.qty)||0}))); sales.forEach(inv=>(inv.items||[]).filter(it=>String(it.itemId)===itemId&&isStockItem).forEach(it=>events.push({date:inv.date||'',order:4,type:'sale',qty:Number(it.qty)||0,godownId:it.godownId}))); salesReturns.forEach(ret=>(ret.items||[]).filter(it=>String(it.itemId)===itemId&&isStockItem).forEach(it=>events.push({date:ret.date||'',order:4.5,type:'sales-return',qty:Number(it.qty)||0,godownId:it.godownId}))); adjustments.filter(x=>String(x.itemId)===itemId).forEach(x=>events.push({date:x.date||'',order:5,type:'adjustment',qty:Number(x.adjustmentQty||x.qty)||0,adjustmentType:x.adjustmentType,godownId:x.godownId})); transfers.filter(x=>String(x.itemId)===itemId).forEach(x=>events.push({date:x.date||'',order:3,type:'transfer',qty:Number(x.qty)||0,from:x.fromGodownId,to:x.toGodownId})); events.sort((a,b)=>String(a.date).localeCompare(String(b.date))||a.order-b.order); // Build selected FY opening by applying movements before FY start, then show only FY movements. const openingEvents=events.filter(e=>{const d=String(e.date||'').slice(0,10);return !fyFrom||!d||d{const d=String(e.date||'').slice(0,10);return (!fyFrom||!d||d>=fyFrom)&&(!fyTo||!d||d<=fyTo);}); events.length=0;events.push(...openingEvents,...fyEvents); events.forEach(e=>{ if(e.type==='purchase') add(mainId,e.qty); else if(e.type==='return') sub(mainId,e.qty); else if(e.type==='sale') sub(e.godownId||mainId,e.qty); else if(e.type==='sales-return') add(e.godownId||mainId,e.qty); else if(e.type==='adjustment'){if(e.adjustmentType==='increase')add(e.godownId||mainId,e.qty);else sub(e.godownId||mainId,e.qty);} else if(e.type==='transfer'){sub(e.from,e.qty);add(e.to,e.qty);} }); const rebuilt=stock.concat(Object.values(byId).filter(x=>Math.abs(Number(x.qty)||0)>0.000001)); saveGodownStock(rebuilt); return rebuilt; } function updateTransferQty(){const itemId=document.getElementById('transferItem')?.value,from=document.getElementById('transferFrom')?.value;if(!itemId||!from){const a=document.getElementById('transferAvailable');if(a)a.textContent='';return}const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'),item=items.find(i=>String(i.id)===String(itemId)),gs=getGodowns();if(item)syncGodownStockWithClosing(item,gs);const q=getItemGodownQty(itemId,from);const a=document.getElementById('transferAvailable');if(a)a.textContent=`Available stock: ${q} ${item?.unit||''}`;} function openTransferDatePicker(){const picker=document.getElementById('transferDate');if(!picker)return;try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();else picker.click();}catch(e){try{picker.click();}catch(ignore){}}} function syncTransferDateDisplay(){const date=document.getElementById('transferDate')?.value||'';const display=document.getElementById('transferDateDisplay');if(display)display.value=date?date.split('-').reverse().join('/') : '';} function formatTransferDateInput(el){if(!el)return;const digits=(el.value||'').replace(/\D/g,'').slice(0,8);let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4);el.value=out;} function syncTransferDateManual(){const display=document.getElementById('transferDateDisplay'),picker=document.getElementById('transferDate');if(!display||!picker)return;let value=(display.value||'').trim().replace(/[.\-]/g,'/');if(!value){picker.value='';return;}const parts=value.split('/');if(parts.length===3){const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2];if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){const test=new Date(Number(yyyy),Number(mm)-1,Number(dd));if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;return;}}}syncTransferDateDisplay();} function transferStock(){if(!mviappsRequireStaffPermission('stock','create'))return; if(!ensureEntryDateInActiveFY(document.getElementById('transferDate')?.value,'Date'))return;const itemId=document.getElementById('transferItem')?.value,qty=Number(document.getElementById('transferQty')?.value)||0,from=document.getElementById('transferFrom')?.value,to=document.getElementById('transferTo')?.value,date=document.getElementById('transferDate')?.value||new Date().toISOString().slice(0,10),note=document.getElementById('transferNote')?.value.trim()||'';if(!itemId||!from||!to||qty<=0){alert('Please select Item, From Godown, To Godown and enter a valid Quantity.');return}if(String(from)===String(to)){alert('Source and destination godown cannot be the same.');return}const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'),item=items.find(i=>String(i.id)===String(itemId));if(!item){alert('Item not found.');return}let stock=syncGodownStockWithClosing(item,getGodowns());const available=getItemGodownQty(itemId,from);if(qty>available){alert(`Insufficient stock. Available stock is ${available} ${item.unit||''}.`);return}const src=stock.find(x=>String(x.itemId)===String(itemId)&&String(x.godownId)===String(from));if(src)src.qty=(Number(src.qty)||0)-qty;let dst=stock.find(x=>String(x.itemId)===String(itemId)&&String(x.godownId)===String(to));if(!dst){dst={id:Date.now()+Math.random(),itemId:item.id,godownId:to,qty:0};stock.push(dst)}dst.qty=(Number(dst.qty)||0)+qty;saveGodownStock(stock);const transfers=JSON.parse(localStorage.getItem('mviapps_godown_transfers')||'[]');transfers.push({id:Date.now(),date,itemId:item.id,itemName:item.name,fromGodownId:from,toGodownId:to,qty,note});localStorage.setItem('mviapps_godown_transfers',JSON.stringify(transfers));document.getElementById('transferQty').value='0';document.getElementById('transferNote').value='';updateTransferQty();renderGodownStock();alert('Stock transferred successfully.');} function renderGodownStock(){const rows=document.getElementById('godownStockRows');if(!rows)return;const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'),gs=getGodowns(),q=(document.getElementById('godownStockSearch')?.value||'').toLowerCase(),gf=document.getElementById('godownStockFilter')?.value||'';gs.forEach(g=>items.forEach(i=>ensureOpeningAllocation(i,gs)));const stock=getGodownStock();const out=[];items.forEach(i=>{stock.filter(x=>String(x.itemId)===String(i.id)&&Number(x.qty)>0&&(!gf||String(x.godownId)===String(gf))).forEach(x=>{const g=gs.find(z=>String(z.id)===String(x.godownId));if(g&&(!q||String(i.name||'').toLowerCase().includes(q)||String(i.code||'').toLowerCase().includes(q)))out.push({i,g,x})})});rows.innerHTML=out.length?out.map(r=>`${escapeHtml(r.i.name||'')}
${escapeHtml(r.i.code||'')}${escapeHtml(r.g.name)}${Number(r.x.qty).toLocaleString()}${escapeHtml(r.i.unit||'')}₹ ${(Number(r.x.qty)*(Number(r.i.purchase)||0)).toFixed(2)}`).join(''):`No godown stock found. Add items or transfer stock between godowns.`;} function getCashBalance(){ const v=Number(localStorage.getItem('mviapps_cash_balance')); return Number.isFinite(v)?v:0; } function getCashBalanceForActiveFinancialYear(){ const fyb=getFinancialYearBounds(getActiveFinancialYear()); let closing=getCashBalance(); if(!fyb.to)return closing; const all=JSON.parse(localStorage.getItem('mviapps_cash_transactions')||'[]'); all.forEach(x=>{if(String(x.date||'')>fyb.to)closing-=Number(x.amount)||0;}); return closing; } function saveCashBalance(v){localStorage.setItem('mviapps_cash_balance',String(Number(v)||0));} function getCashTransactions(){return filterByActiveFinancialYear(JSON.parse(localStorage.getItem('mviapps_cash_transactions')||'[]'));} function saveCashTransactions(a){localStorage.setItem('mviapps_cash_transactions',JSON.stringify(a));} function renderCashTransactions(){ const rows=document.getElementById('cashTransactionRows'); if(!rows)return; const tx=getCashTransactions().slice().sort((a,b)=>String(b.date||'').localeCompare(String(a.date||''))||(Number(b.id)||0)-(Number(a.id)||0)); rows.innerHTML=tx.length?tx.map(x=>`${escapeHtml(x.type||'')}${escapeHtml(x.description||'—')}${escapeHtml(x.date||'')}${Number(x.amount)>=0?'':'−'}₹ ${Math.abs(Number(x.amount)||0).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2})}`).join(''):`No cash transactions found.`; } function cashPage(){ const bal=getCashBalanceForActiveFinancialYear(); return `
Bank & Cash

Cash

Manage cash balance and cash adjustments.

Available Cash
₹ ${bal.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2})}
Current cash balance

Cash Transactions

Adjustments and bank-to-cash transfers.

TypeDescriptionDateAmount
`; } function openCashAdjustment(){ const today=new Date().toISOString().slice(0,10); const todayDisplay=today?today.split('-').reverse().join('/') : ''; const existing=document.getElementById('cashAdjustModal'); if(existing)existing.remove(); const bal=getCashBalanceForActiveFinancialYear(); const modal=document.createElement('div'); modal.id='cashAdjustModal'; modal.style.cssText='position:fixed;inset:0;z-index:100000;background:rgba(0,0,0,.42);display:flex;align-items:flex-start;justify-content:center;padding:12px 8px;overflow:auto;'; modal.innerHTML=`

Adjust Cash

Updated Cash: ₹ ${bal.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2})}
`; document.body.appendChild(modal); const update=()=>{ const amt=Number(document.getElementById('cashAdjustAmount')?.value)||0; const add=document.getElementById('cashAdjustAdd')?.checked; const next=bal+(add?amt:-amt); const p=document.getElementById('cashAdjustPreview'); if(p)p.textContent='₹ '+next.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}); }; document.getElementById('cashAdjustAmount')?.addEventListener('input',update); document.getElementById('cashAdjustAdd')?.addEventListener('change',update); document.getElementById('cashAdjustReduce')?.addEventListener('change',update); } function openCashAdjustmentDatePicker(){ const picker=document.getElementById('cashAdjustDate'); if(!picker)return; try{picker.focus({preventScroll:true});if(typeof picker.showPicker==='function')picker.showPicker();} catch(e){try{picker.click();}catch(ignore){}} } function syncCashAdjustmentDateDisplay(){ const date=document.getElementById('cashAdjustDate')?.value||''; const display=document.getElementById('cashAdjustDateDisplay'); if(display)display.value=date?date.split('-').reverse().join('/') : ''; } function formatCashAdjustmentDateInput(el){ if(!el)return; const digits=(el.value||'').replace(/\D/g,'').slice(0,8); let out=digits;if(digits.length>2)out=digits.slice(0,2)+'/'+digits.slice(2);if(digits.length>4)out=digits.slice(0,2)+'/'+digits.slice(2,4)+'/'+digits.slice(4); el.value=out; } function syncCashAdjustmentManualDate(){ const display=document.getElementById('cashAdjustDateDisplay'),picker=document.getElementById('cashAdjustDate'); if(!display||!picker)return; let value=(display.value||'').trim().replace(/[.\-]/g,'/'); if(!value){picker.value='';return;} const parts=value.split('/'); if(parts.length===3){ const dd=parts[0].padStart(2,'0'),mm=parts[1].padStart(2,'0'),yyyy=parts[2]; if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)){ const test=new Date(Number(yyyy),Number(mm)-1,Number(dd)); if(test.getFullYear()===Number(yyyy)&&test.getMonth()===Number(mm)-1&&test.getDate()===Number(dd)){ picker.value=yyyy+'-'+mm+'-'+dd;display.value=dd+'/'+mm+'/'+yyyy;return; } } } syncCashAdjustmentDateDisplay(); } function saveCashAdjustment(){ const amount=Number(document.getElementById('cashAdjustAmount')?.value)||0; if(amount<=0){alert('Please enter a valid amount.');return;} const add=document.getElementById('cashAdjustAdd')?.checked; const date=document.getElementById('cashAdjustDate')?.value||new Date().toISOString().slice(0,10); if(!ensureEntryDateInActiveFY(date,'Adjustment Date'))return; const description=document.getElementById('cashAdjustDescription')?.value.trim()||'Cash Adjustment'; const delta=add?amount:-amount; const current=getCashBalance(); if(delta<0 && current+delta<0 && !confirm('This adjustment will make the cash balance negative. Continue?'))return; saveCashBalance(current+delta); const tx=getCashTransactions(); tx.push({id:Date.now()+Math.random(),type:add?'Cash Added':'Cash Reduced',description,date,amount:delta}); saveCashTransactions(tx); document.getElementById('cashAdjustModal')?.remove(); show('cash'); setTimeout(renderCashTransactions,0); } function mviappsExpenseReportData(){ try{return JSON.parse(localStorage.getItem('mviapps_expenses')||'[]')}catch(e){return []} } function mviappsExpenseReportEsc(v){ return String(v==null?'':v).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"'); } function initExpenseReport(){ const f=document.getElementById('expenseReportFrom'), t=document.getElementById('expenseReportTo'); if(!f||!t)return; const fy=mviappsActiveFYReportRange(); f.value=fy.from; t.value=fy.to; syncReportDateDisplay('expenseReport','from'); syncReportDateDisplay('expenseReport','to'); mviappsFillExpenseReportMasters(); mviappsRunExpenseReport(); } function mviappsFillExpenseReportMasters(){ const es=filterByActiveFinancialYear(mviappsExpenseReportData()); const cats=[...new Set(es.map(x=>x.category||x.expenseCategory||'').filter(Boolean))].sort((a,b)=>String(a).localeCompare(String(b),undefined,{sensitivity:'base',numeric:true})); const parties=[...new Set(es.map(x=>x.partyName||x.party||'').filter(Boolean))].sort((a,b)=>String(a).localeCompare(String(b),undefined,{sensitivity:'base',numeric:true})); const c=document.getElementById('expenseReportCategory'), p=document.getElementById('expenseReportParty'); if(c){const v=c.value;c.innerHTML=''+cats.map(x=>``).join('');c.value=v;} if(p){const v=p.value;p.innerHTML=''+parties.map(x=>``).join('');p.value=v;} } function mviappsRunExpenseReport(){ mviappsFillExpenseReportMasters(); const es=mviappsExpenseReportData(); let {from:f,to:t}=mviappsConstrainReportRange(document.getElementById('expenseReportFrom')?.value||'',document.getElementById('expenseReportTo')?.value||''); const cat=document.getElementById('expenseReportCategory')?.value||'', mode=document.getElementById('expenseReportMode')?.value||''; const party=document.getElementById('expenseReportParty')?.value||'', q=(document.getElementById('expenseReportSearch')?.value||'').trim().toLowerCase(); const rows=es.filter(x=>{ const dt=String(x.date||'').slice(0,10), pc=String(x.category||x.expenseCategory||''), pp=String(x.partyName||x.party||''), pm=String(x.paymentMode||''); const hay=[x.number,x.expenseNo,x.category,x.expenseCategory,x.partyName,x.party,x.paymentMode,x.reference,x.referenceNo,x.notes,x.description].join(' ').toLowerCase(); return (!f||dt>=f)&&(!t||dt<=t)&&(!cat||pc===cat)&&(!mode||pm===mode)&&(!party||pp===party)&&(!q||hay.includes(q)); }).sort((a,b)=>String(a.date||'').localeCompare(String(b.date||'')) || String(a.number||a.expenseNo||'').localeCompare(String(b.number||b.expenseNo||''))); const body=document.querySelector('#expenseReportTable tbody'); if(!body)return; let total=0; body.innerHTML=rows.map(x=>{ const amt=Number(x.amount||0); total+=amt; const displayDate=String(x.date||'').slice(0,10).split('-').reverse().join('/'); return `${mviappsExpenseReportEsc(displayDate)}${mviappsExpenseReportEsc(x.number||x.expenseNo)}${mviappsExpenseReportEsc(x.category||x.expenseCategory)}${mviappsExpenseReportEsc(x.partyName||x.party||'Direct Expense')}${mviappsExpenseReportEsc(x.paymentMode)}${mviappsExpenseReportEsc(x.reference||x.referenceNo||'-')}₹ ${amt.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2})}`; }).join('') || 'No expense transactions found for the selected filters.'; const money='₹ '+total.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}); const ft=document.getElementById('expenseReportFootTotal'), tt=document.getElementById('expenseReportTotal'), per=document.getElementById('expenseReportPeriod'); if(ft)ft.textContent=money; if(tt)tt.textContent=rows.length+' transaction'+(rows.length===1?'':'s')+' · '+money; if(per)per.textContent=(f||'Start')+' to '+(t||'End'); } function mviappsPrintExpenseReport(){ const table=document.getElementById('expenseReportTable'); if(!table)return; const period=document.getElementById('expenseReportPeriod')?.textContent||''; const w=window.open('','_blank'); if(!w){alert('Please allow pop-ups to print the report.');return;} w.document.write(`Expense Report

Expense Report

${mviappsExpenseReportEsc(period)}

${table.outerHTML}`); w.document.close(); w.focus(); setTimeout(()=>w.print(),250); } function mviappsOtherIncomeReportData(){ try{const v=JSON.parse(localStorage.getItem('mviapps_other_income')||'[]');return Array.isArray(v)?v:[]}catch(e){return []} } function mviappsOtherIncomeReportBankName(x){ const id=String(x?.account??x?.bankAccount??'').trim(); return id ? mviappsBankDisplay(id) : '-'; } function mviappsOtherIncomeReportEsc(v){return String(v==null?'':v).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"')} function initOtherIncomeReport(){ const f=document.getElementById('otherIncomeReportFrom'),t=document.getElementById('otherIncomeReportTo');if(!f||!t)return; const fy=mviappsActiveFYReportRange(); f.value=fy.from; t.value=fy.to; syncReportDateDisplay('otherIncomeReport','from'); syncReportDateDisplay('otherIncomeReport','to'); mviappsFillOtherIncomeReportHeads();mviappsRunOtherIncomeReport(); } function mviappsFillOtherIncomeReportHeads(){ const heads=[...new Set(mviappsOtherIncomeReportData().map(x=>x.incomeHead||'').filter(Boolean))].sort((a,b)=>String(a).localeCompare(String(b),undefined,{sensitivity:'base',numeric:true})); const el=document.getElementById('otherIncomeReportHead');if(!el)return;const v=el.value; el.innerHTML=''+heads.map(x=>``).join('');el.value=v; } function mviappsRunOtherIncomeReport(){ mviappsFillOtherIncomeReportHeads(); let {from:f,to:t}=mviappsConstrainReportRange(document.getElementById('otherIncomeReportFrom')?.value||'',document.getElementById('otherIncomeReportTo')?.value||''); const head=document.getElementById('otherIncomeReportHead')?.value||'',mode=document.getElementById('otherIncomeReportMode')?.value||'',q=(document.getElementById('otherIncomeReportSearch')?.value||'').trim().toLowerCase(); const rows=mviappsOtherIncomeReportData().filter(x=>{const d=String(x.date||'').slice(0,10),h=String(x.incomeHead||''),m=String(x.paymentMode||''),hay=[x.number,x.incomeNo,x.incomeHead,x.paymentMode,x.account,x.reference,x.notes,x.description].join(' ').toLowerCase();return(!f||d>=f)&&(!t||d<=t)&&(!head||h===head)&&(!mode||m===mode)&&(!q||hay.includes(q));}).sort((a,b)=>String(a.date||'').localeCompare(String(b.date||''))||String(a.number||a.incomeNo||'').localeCompare(String(b.number||b.incomeNo||''))); const body=document.querySelector('#otherIncomeReportTable tbody');if(!body)return;let total=0; body.innerHTML=rows.map(x=>{const amt=Number(x.amount||0);total+=amt;const displayDate=(()=>{const p=String(x.date||'').slice(0,10).split('-');return p.length===3&&p[0].length===4?p[2]+'/'+p[1]+'/'+p[0]:String(x.date||'');})();return `${mviappsOtherIncomeReportEsc(displayDate)}${mviappsOtherIncomeReportEsc(x.number||x.incomeNo)}${mviappsOtherIncomeReportEsc(x.incomeHead)}${mviappsOtherIncomeReportEsc(x.paymentMode)}${mviappsOtherIncomeReportEsc(mviappsOtherIncomeReportBankName(x))}${mviappsOtherIncomeReportEsc(x.reference||x.referenceNo||'-')}${mviappsOtherIncomeReportEsc(x.notes||x.description||'-')}₹ ${amt.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2})}`}).join('')||'No other income transactions found for the selected filters.'; const money='₹ '+total.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}); const ft=document.getElementById('otherIncomeReportFootTotal'),tt=document.getElementById('otherIncomeReportTotal'),per=document.getElementById('otherIncomeReportPeriod');if(ft)ft.textContent=money;if(tt)tt.textContent=rows.length+' transaction'+(rows.length===1?'':'s')+' · '+money;if(per)per.textContent=(f||'Start')+' to '+(t||'End'); } function mviappsPrintOtherIncomeReport(){ const table=document.getElementById('otherIncomeReportTable');if(!table)return;const period=document.getElementById('otherIncomeReportPeriod')?.textContent||'';const w=window.open('','_blank');if(!w){alert('Please allow pop-ups to print the report.');return;} w.document.write(`Other Income Report

Other Income Report

${mviappsOtherIncomeReportEsc(period)}

${table.outerHTML}`);w.document.close();w.focus();setTimeout(()=>w.print(),250); } function otherIncomeCategoryReport(){ return `
▦
Reports
Other Income Category Report
View income grouped by income head for the selected period.
Other Income by Category
Income HeadTransactionsAmount
Total0₹0.00
`; } function initOtherIncomeCategoryReport(){ const f=document.getElementById('otherIncomeCategoryFrom'),t=document.getElementById('otherIncomeCategoryTo');if(!f||!t)return; const fy=mviappsActiveFYReportRange(); f.value=fy.from; t.value=fy.to; mviappsFillOtherIncomeCategoryHeads();mviappsRunOtherIncomeCategoryReport(); } function mviappsFillOtherIncomeCategoryHeads(){ const heads=[...new Set(mviappsOtherIncomeReportData().map(x=>x.incomeHead||'').filter(Boolean))].sort((a,b)=>String(a).localeCompare(String(b),undefined,{sensitivity:'base',numeric:true})); const el=document.getElementById('otherIncomeCategoryHead');if(!el)return;const v=el.value; el.innerHTML=''+heads.map(x=>``).join('');el.value=v; } function mviappsRunOtherIncomeCategoryReport(){ mviappsFillOtherIncomeCategoryHeads(); let {from:f,to:t}=mviappsConstrainReportRange(document.getElementById('otherIncomeCategoryFrom')?.value||'',document.getElementById('otherIncomeCategoryTo')?.value||''); const head=document.getElementById('otherIncomeCategoryHead')?.value||'',mode=document.getElementById('otherIncomeCategoryMode')?.value||'',q=(document.getElementById('otherIncomeCategorySearch')?.value||'').trim().toLowerCase(); const rows=mviappsOtherIncomeReportData().filter(x=>{const d=String(x.date||'').slice(0,10),h=String(x.incomeHead||''),m=String(x.paymentMode||''),hay=[x.number,x.incomeNo,x.incomeHead,x.paymentMode,x.account,x.bankAccount,x.reference,x.referenceNo,x.notes,x.description].join(' ').toLowerCase();return(!f||d>=f)&&(!t||d<=t)&&(!head||h===head)&&(!mode||m===mode)&&(!q||hay.includes(q));}); const grouped={};rows.forEach(x=>{const h=String(x.incomeHead||'Uncategorised').trim()||'Uncategorised';if(!grouped[h])grouped[h]={count:0,total:0};grouped[h].count++;grouped[h].total+=Number(x.amount||0)||0;}); const groups=Object.entries(grouped).sort((a,b)=>a[0].localeCompare(b[0],undefined,{sensitivity:'base',numeric:true})); const body=document.querySelector('#otherIncomeCategoryReportTable tbody');if(!body)return;let total=0,count=0; body.innerHTML=groups.map(([h,g])=>{total+=g.total;count+=g.count;return `${mviappsOtherIncomeReportEsc(h)}${g.count}₹ ${g.total.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2})}`}).join('')||'No other income transactions found for the selected filters.'; const money='₹ '+total.toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}); const ft=document.getElementById('otherIncomeCategoryFootTotal'),fc=document.getElementById('otherIncomeCategoryFootCount'),tt=document.getElementById('otherIncomeCategoryTotal'),per=document.getElementById('otherIncomeCategoryPeriod');if(ft)ft.textContent=money;if(fc)fc.textContent=count;if(tt)tt.textContent=groups.length+' categor'+(groups.length===1?'y':'ies')+' · '+money;if(per)per.textContent=(f||'Start')+' to '+(t||'End'); } function mviappsPrintOtherIncomeCategoryReport(){ const table=document.getElementById('otherIncomeCategoryReportTable');if(!table)return;const period=document.getElementById('otherIncomeCategoryPeriod')?.textContent||'';const w=window.open('','_blank');if(!w){alert('Please allow pop-ups to print the report.');return;} w.document.write(`Other Income Category Report

Other Income Category Report

${mviappsOtherIncomeReportEsc(period)}

${table.outerHTML}`);w.document.close();w.focus();setTimeout(()=>w.print(),250); } function salesReturnPage(){ const now=new Date(),today=now.getFullYear()+'-'+String(now.getMonth()+1).padStart(2,'0')+'-'+String(now.getDate()).padStart(2,'0'); const invoices=JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]'); const invoiceOptions=invoices.slice().sort((a,b)=>String(b.date||'').localeCompare(String(a.date||''))).map(x=>``).join(''); const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'); const partyOptions=parties.map(x=>``).join(''); return `

Sales Return

Record goods returned by a customer, with or without selecting the original sales invoice.

Return Information

Returned Items

ItemGodownReturn QtyRateDiscount %GST %Amount
Select an original invoice or click “Add Item”.

Return Summary

Subtotal₹ 0.00
Discount₹ 0.00
Tax₹ 0.00
Return Total₹ 0.00

Saved Sales Returns

Saved customer return entries.

DateReturn No.CustomerOriginal InvoiceItemsTotalAction
`; } function salesReturnModeChanged(){ const mode=document.getElementById('salesReturnMode')?.value||'with'; const original=document.getElementById('salesReturnOriginalInvoice');if(original){original.disabled=mode==='without';if(mode==='without')original.value='';} const customer=document.getElementById('salesReturnCustomer');if(customer)customer.disabled=mode==='with'&&!!original?.value; if(mode==='without'){const body=document.getElementById('salesReturnItems');if(body)body.innerHTML='Click “Add Item” to enter returned items.';} else if(!original?.value){const body=document.getElementById('salesReturnItems');if(body)body.innerHTML='Select an original invoice or click “Add Item”.';} calculateSalesReturn(); } function openSalesReturnDatePicker(){const el=document.getElementById('salesReturnDate');if(!el)return;try{el.focus({preventScroll:true});if(el.showPicker)el.showPicker();else el.click();}catch(e){try{el.click()}catch(ignore){}}} function syncSalesReturnDateDisplay(){const v=document.getElementById('salesReturnDate')?.value||'',el=document.getElementById('salesReturnDateDisplay');if(el)el.value=v?v.split('-').reverse().join('/') : '';} function formatSalesReturnDateInput(el){if(!el)return;const d=(el.value||'').replace(/\D/g,'').slice(0,8);let v=d;if(d.length>2)v=d.slice(0,2)+'/'+d.slice(2);if(d.length>4)v=d.slice(0,2)+'/'+d.slice(2,4)+'/'+d.slice(4);el.value=v;} function syncSalesReturnDateManual(){const el=document.getElementById('salesReturnDateDisplay'),picker=document.getElementById('salesReturnDate');if(!el||!picker)return;const v=(el.value||'').trim().replace(/[.-]/g,'/');const p=v.split('/');if(p.length===3){const dd=p[0].padStart(2,'0'),mm=p[1].padStart(2,'0'),yyyy=p[2];const d=new Date(Number(yyyy),Number(mm)-1,Number(dd));if(/^\d{2}$/.test(dd)&&/^\d{2}$/.test(mm)&&/^\d{4}$/.test(yyyy)&&d.getFullYear()===Number(yyyy)&&d.getMonth()===Number(mm)-1&&d.getDate()===Number(dd)){picker.value=yyyy+'-'+mm+'-'+dd;el.value=dd+'/'+mm+'/'+yyyy;return;}}syncSalesReturnDateDisplay();} function salesReturnItemOptions(selected=''){return JSON.parse(localStorage.getItem('mviapps_items')||'[]').map(x=>``).join('');} function salesReturnGodownOptions(selected=''){return getGodowns().map(g=>``).join('');} function salesReturnItemSearchChanged(input){const tr=input?.closest('tr');if(!tr)return;const sel=tr.querySelector('.sales-return-item'),q=String(input.value||'').trim().toLowerCase();let match=[...sel.options].find(o=>o.value&&String(o.dataset.label||o.textContent).toLowerCase()===q);if(match&&q){sel.value=match.value;salesReturnItemChanged(sel,false);}else if(!q){sel.value='';calculateSalesReturn();}} function addSalesReturnItemRow(data={}){ const body=document.getElementById('salesReturnItems');if(!body)return;if(body.querySelector('.empty'))body.innerHTML=''; const listId='salesReturnItemList_'+Date.now()+'_'+Math.floor(Math.random()*1000000);const tr=document.createElement('tr');tr.dataset.originalItemId=String(data.originalItemId||data.itemId||'');tr.dataset.maxReturnQty=String(data.maxReturnQty??''); tr.innerHTML=`
${JSON.parse(localStorage.getItem('mviapps_items')||'[]').map(x=>``).join('')}
₹ 0.00`; body.appendChild(tr);if(data.itemId){const sel=tr.querySelector('.sales-return-item');sel.value=String(data.itemId);tr.querySelector('.sales-return-item-search').value=sel.selectedOptions[0]?.dataset.label||sel.selectedOptions[0]?.textContent||'';salesReturnItemChanged(sel,true);tr.querySelector('.sales-return-qty').value=data.qty==null?'1':String(data.qty);tr.querySelector('.sales-return-rate').value=Number(data.rate)||0;tr.querySelector('.sales-return-discount').value=Number(data.discount)||0;tr.querySelector('.sales-return-gst').value=Number(data.gst)||0;tr.querySelector('.sales-return-godown').value=String(data.godownId||'');}calculateSalesReturn(); } function salesReturnItemChanged(sel,keepValues=false){const tr=sel?.closest('tr');if(!tr)return;const item=JSON.parse(localStorage.getItem('mviapps_items')||'[]').find(x=>String(x.id)===String(sel.value));const search=tr.querySelector('.sales-return-item-search');if(search)search.value=item?(item.name||'Unnamed Item')+(item.code?' — '+item.code:''):'';if(!keepValues){tr.querySelector('.sales-return-rate').value=Number(item?.sale)||0;tr.querySelector('.sales-return-discount').value=0;tr.querySelector('.sales-return-gst').value=Number(item?.gst)||0;}calculateSalesReturn();} function loadSalesReturnOriginalInvoice(){ const id=document.getElementById('salesReturnOriginalInvoice')?.value||'',inv=JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]').find(x=>String(x.id)===String(id)); const customer=document.getElementById('salesReturnCustomer');if(!inv){if(customer)customer.disabled=false;salesReturnModeChanged();return;} document.getElementById('salesReturnMode').value='with';if(customer){customer.value=String(inv.customer||'');customer.disabled=true;} const ref=document.getElementById('salesReturnReference');if(ref)ref.value=inv.invoiceNo||''; const returned=JSON.parse(localStorage.getItem('mviapps_sales_returns')||'[]').filter(x=>String(x.originalInvoiceId||'')===String(inv.id)||String(x.originalInvoiceNo||'')===String(inv.invoiceNo||'')); const body=document.getElementById('salesReturnItems');if(body)body.innerHTML=''; (inv.items||[]).forEach(it=>{const prior=returned.reduce((sum,r)=>sum+(r.items||[]).filter(z=>String(z.itemId)===String(it.itemId)).reduce((n,z)=>n+(Number(z.qty)||0),0),0);const remaining=Math.max(0,(Number(it.qty)||0)-prior);if(remaining<=0)return;addSalesReturnItemRow({...it,qty:Math.min(1,remaining),maxReturnQty:remaining,originalItemId:it.itemId});}); if(body&&!body.children.length)body.innerHTML='All quantities on this invoice have already been returned.';calculateSalesReturn(); } function calculateSalesReturn(){const body=document.getElementById('salesReturnItems');if(!body)return;let sub=0,discount=0,tax=0;[...body.querySelectorAll('tr')].forEach(tr=>{if(!tr.querySelector('.sales-return-item'))return;const q=Math.max(0,Number(tr.querySelector('.sales-return-qty')?.value)||0),r=Math.max(0,Number(tr.querySelector('.sales-return-rate')?.value)||0),d=Math.min(100,Math.max(0,Number(tr.querySelector('.sales-return-discount')?.value)||0)),g=Math.max(0,Number(tr.querySelector('.sales-return-gst')?.value)||0);const base=q*r,disc=base*d/100,tx=base-disc,vat=tx*g/100;sub+=base;discount+=disc;tax+=vat;const a=tr.querySelector('.sales-return-amount');if(a)a.textContent='₹ '+(tx+vat).toFixed(2);});const set=(id,v)=>{const el=document.getElementById(id);if(el)el.textContent='₹ '+v.toFixed(2)};set('salesReturnSubTotal',sub);set('salesReturnDiscount',discount);set('salesReturnTax',tax);set('salesReturnGrand',Math.round(sub-discount+tax));} let editingSalesReturnId=null; function clearSalesReturnForm(){editingSalesReturnId=null;show('sales-returns');} function saveSalesReturn(){ const date=document.getElementById('salesReturnDate')?.value||'';if(!ensureEntryDateInActiveFY(date,'Return Date'))return; const mode=document.getElementById('salesReturnMode')?.value||'with',originalId=mode==='with'?(document.getElementById('salesReturnOriginalInvoice')?.value||''):'',inv=originalId?JSON.parse(localStorage.getItem('mviapps_sales_invoices')||'[]').find(x=>String(x.id)===String(originalId)):null; if(mode==='with'&&!inv){alert('Please select the Original Invoice, or choose Without Original Invoice.');return;} const customer=document.getElementById('salesReturnCustomer')?.value||'';if(!customer){alert('Please select a customer.');return;} const number=document.getElementById('salesReturnNo')?.value.trim()||'';if(!number){alert('Sales Return No. is missing.');return;} const rows=[...document.querySelectorAll('#salesReturnItems tr')].filter(tr=>tr.querySelector('.sales-return-item'));if(!rows.length){alert('Please add at least one returned item.');return;} const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'),godowns=getGodowns();const returnedItems=rows.map(tr=>({itemId:tr.querySelector('.sales-return-item').value,godownId:tr.querySelector('.sales-return-godown').value||'',qty:Number(tr.querySelector('.sales-return-qty').value)||0,rate:Number(tr.querySelector('.sales-return-rate').value)||0,discount:Number(tr.querySelector('.sales-return-discount').value)||0,gst:Number(tr.querySelector('.sales-return-gst').value)||0})); for(const it of returnedItems){if(!it.itemId||it.qty<=0){alert('Select an item and enter a return quantity greater than zero for every row.');return;}if(!isServiceSaleItem(items.find(x=>String(x.id)===String(it.itemId)))&&!godowns.some(g=>String(g.id)===String(it.godownId))){alert('Please select the Godown for every stock item.');return;}} if(inv){const oldReturns=JSON.parse(localStorage.getItem('mviapps_sales_returns')||'[]').filter(x=>String(x.originalInvoiceId||'')===String(inv.id)||String(x.originalInvoiceNo||'')===String(inv.invoiceNo||''));for(const it of returnedItems){const sold=(inv.items||[]).filter(x=>String(x.itemId)===String(it.itemId)).reduce((n,x)=>n+(Number(x.qty)||0),0);const already=oldReturns.reduce((n,r)=>n+(r.items||[]).filter(x=>String(x.itemId)===String(it.itemId)).reduce((z,x)=>z+(Number(x.qty)||0),0),0);const thisReturn=returnedItems.filter(x=>String(x.itemId)===String(it.itemId)).reduce((n,x)=>n+x.qty,0);if(thisReturn+already>sold+0.000001){alert(`Return quantity for ${saleItemName(it.itemId)} exceeds the quantity sold on ${inv.invoiceNo}. Remaining returnable quantity: ${Math.max(0,sold-already)}.`);return;}}} const total=Math.round(returnedItems.reduce((n,it)=>{const base=it.qty*it.rate;const tx=base-base*it.discount/100;return n+tx+tx*it.gst/100;},0)); const parties=JSON.parse(localStorage.getItem('mviapps_parties')||'[]'),party=parties.find(x=>String(x.id||x.name)===String(customer));const arr=JSON.parse(localStorage.getItem('mviapps_sales_returns')||'[]');if(arr.some(x=>String(x.number||x.invoiceNo||'').trim().toUpperCase()===String(number).trim().toUpperCase()&&String(x.id)!==String(editingSalesReturnId||''))){alert('This Sales Return No. already exists.');return;} const previous=editingSalesReturnId?arr.find(x=>String(x.id)===String(editingSalesReturnId)):null;const record={id:previous?.id||Date.now(),number,invoiceNo:number,originalInvoiceId:inv?.id||'',originalInvoiceNo:inv?.invoiceNo||String(document.getElementById('salesReturnReference')?.value||'').trim(),customer,customerName:party?.name||inv?.customerName||customer,partyId:customer,partyName:party?.name||inv?.customerName||customer,date,returnMode:mode,reference:String(document.getElementById('salesReturnReference')?.value||'').trim(),notes:String(document.getElementById('salesReturnNotes')?.value||'').trim(),items:returnedItems,total:'₹ '+total.toFixed(2),adjustmentType:'Credit Adjustment'}; if(previous){const idx=arr.findIndex(x=>String(x.id)===String(editingSalesReturnId));if(idx>=0)arr[idx]=record;}else arr.push(record);localStorage.setItem('mviapps_sales_returns',JSON.stringify(arr));let moves=JSON.parse(localStorage.getItem('mviapps_stock_movements')||'[]');if(previous)moves=moves.filter(m=>!(m.type==='sales-return'&&String(m.ref||'')===String(previous.number||previous.invoiceNo||'')));returnedItems.forEach(it=>{if(!isServiceSaleItem(items.find(x=>String(x.id)===String(it.itemId))))moves.push({id:Date.now()+Math.random(),date,itemId:it.itemId,qty:it.qty,type:'sales-return',ref:number,rate:Number(items.find(x=>String(x.id)===String(it.itemId))?.purchase)||0,godownId:it.godownId});});localStorage.setItem('mviapps_stock_movements',JSON.stringify(moves)); const returnGodowns=getGodowns();[...new Set(returnedItems.map(it=>String(it.itemId)))].forEach(itemId=>{const item=items.find(x=>String(x.id)===itemId);if(item&&!isServiceSaleItem(item))syncGodownStockWithClosing(item,returnGodowns);}); const wasEditing=!!previous;editingSalesReturnId=null;alert(wasEditing?'Sales Return modified successfully. Stock return and customer credit adjustment have been updated.':'Sales Return saved successfully. Customer credit adjustment and stock return have been recorded.');show('sales-returns'); } function deleteSalesReturn(id){const arr=JSON.parse(localStorage.getItem('mviapps_sales_returns')||'[]'),x=arr.find(v=>String(v.id)===String(id));if(!x)return;if(!confirm(`Delete Sales Return ${x.number||x.invoiceNo||''}? This will remove its credit adjustment and stock-return record.`))return;localStorage.setItem('mviapps_sales_returns',JSON.stringify(arr.filter(v=>String(v.id)!==String(id))));const moves=JSON.parse(localStorage.getItem('mviapps_stock_movements')||'[]');localStorage.setItem('mviapps_stock_movements',JSON.stringify(moves.filter(m=>!(m.type==='sales-return'&&String(m.ref)===String(x.number||x.invoiceNo||'')))));const items=JSON.parse(localStorage.getItem('mviapps_items')||'[]'),gs=getGodowns();[...new Set((x.items||[]).map(it=>String(it.itemId)))].forEach(itemId=>{const item=items.find(i=>String(i.id)===itemId);if(item&&!isServiceSaleItem(item))syncGodownStockWithClosing(item,gs);});renderSalesReturns();} function renderSalesReturns(){if(!editingSalesReturnId){const h=document.querySelector('#sales-returns .page-head h1');if(h)h.textContent='Sales Return';const save=document.querySelector('#sales-returns .page-head .btn:not(.secondary)');if(save)save.textContent='Save Sales Return';}const body=document.getElementById('salesReturnRows');if(!body)return;const q=String(document.getElementById('salesReturnSearch')?.value||'').toLowerCase();const arr=filterByActiveFinancialYear(JSON.parse(localStorage.getItem('mviapps_sales_returns')||'[]')).filter(x=>!q||String(x.number||x.invoiceNo||'').toLowerCase().includes(q)||String(x.customerName||x.partyName||'').toLowerCase().includes(q)).sort((a,b)=>String(b.date||'').localeCompare(String(a.date||'')));body.innerHTML=arr.length?arr.map(x=>`${escapeHtml(x.date||'')}${escapeHtml(x.number||x.invoiceNo||'')}${escapeHtml(x.customerName||x.partyName||'')}${escapeHtml(x.originalInvoiceNo||'—')}${(x.items||[]).length}${escapeHtml(x.total||'₹ 0.00')} `).join(''):'No Sales Return entries found.';} function editSalesReturn(id){const x=JSON.parse(localStorage.getItem('mviapps_sales_returns')||'[]').find(v=>String(v.id)===String(id));if(!x)return;editingSalesReturnId=x.id;show('sales-returns');setTimeout(()=>{const set=(id,v)=>{const el=document.getElementById(id);if(el)el.value=v??'';};set('salesReturnMode',x.returnMode|| (x.originalInvoiceId?'with':'without'));set('salesReturnOriginalInvoice',x.originalInvoiceId||'');set('salesReturnCustomer',x.customer||x.partyId||'');set('salesReturnDate',x.date||'');syncSalesReturnDateDisplay();set('salesReturnNo',x.number||x.invoiceNo||'');set('salesReturnReference',x.reference||'');set('salesReturnNotes',x.notes||'');salesReturnModeChanged();const body=document.getElementById('salesReturnItems');if(body)body.innerHTML='';(x.items||[]).forEach(it=>addSalesReturnItemRow({...it,originalItemId:it.itemId}));calculateSalesReturn();const h=document.querySelector('#sales-returns .page-head h1');if(h)h.textContent='Modify Sales Return';const save=document.querySelector('#sales-returns .page-head .btn:not(.secondary)');if(save)save.textContent='Update Sales Return';window.scrollTo({top:0,behavior:'smooth'});},0);} function viewSalesReturn(id){const x=JSON.parse(localStorage.getItem('mviapps_sales_returns')||'[]').find(v=>String(v.id)===String(id));if(!x)return;const old=document.getElementById('salesReturnViewModal');if(old)old.remove();const lines=(x.items||[]).map(it=>`${escapeHtml(saleItemName(it.itemId))}${escapeHtml(getGodowns().find(g=>String(g.id)===String(it.godownId))?.name||'—')}${it.qty}₹ ${Number(it.rate||0).toFixed(2)}${it.discount||0}%${it.gst||0}%`).join('');document.body.insertAdjacentHTML('beforeend',`

Sales Return ${escapeHtml(x.number||x.invoiceNo||'')}

${escapeHtml(x.date||'')} · ${escapeHtml(x.customerName||x.partyName||'')}

Original Invoice: ${escapeHtml(x.originalInvoiceNo||'—')} · ${escapeHtml(x.adjustmentType||'Credit Adjustment')}

${lines}
ItemGodownQtyRateDiscountGST
Return Total: ${escapeHtml(x.total||'₹ 0.00')}
${x.notes?`

Notes: ${escapeHtml(x.notes)}

`:''}
`);} function exportItemsPage(){ return `

Export Items to Excel

Export your saved item data to an Excel file on your system.

▤

Export Items to Excel

Export item data to an Excel file on your system

`; } function exportItemsMaster(){ const items=typeof getSortedItems==='function'?getSortedItems():JSON.parse(localStorage.getItem('mviapps_items')||'[]'); if(!Array.isArray(items)||!items.length){alert('Export karne ke liye koi item record nahi mila.');return;} const headers=['Item Name','Item Code','Category','Brand','Unit','HSN/SAC','Weight','Weight Unit','Dimension','Dimension Unit','GST Rate','Opening Quantity','Opening Value','Purchase Rate','Sale Rate','Wholesale Rate','Retail Rate','Minimum Stock Level','Source']; const rows=items.map(x=>[x.name??'',x.code??'',x.category??'',x.brand??'',x.unit??'',x.hsn??'',x.weight??'0',x.weightUnit??'KG',x.dimension??'',x.dimensionUnit??'CM',x.gst??'0',x.qty??'0',x.value??'0',x.purchase??'0',x.sale??'0',x.wholesale??'0',x.retail??'0',x.min??'0',x.source??'']); const stamp=new Date().toISOString().slice(0,10); if(window.ExcelJS&&window.ExcelJS.Workbook){ try{ const wb=new ExcelJS.Workbook();wb.creator='MVIApps';wb.subject='Item Master Export'; const ws=wb.addWorksheet('Items');ws.addRow(headers);rows.forEach(r=>ws.addRow(r)); ws.views=[{state:'frozen',ySplit:1}];ws.autoFilter={from:{row:1,column:1},to:{row:1,column:headers.length}}; ws.columns=headers.map(h=>({width:Math.max(14,Math.min(28,h.length+3))})); const header=ws.getRow(1);header.font={bold:true,color:{argb:'FFFFFFFF'}};header.fill={type:'pattern',pattern:'solid',fgColor:{argb:'FF2457A7'}};header.alignment={vertical:'middle',horizontal:'center'};header.height=24; wb.xlsx.writeBuffer().then(buffer=>{const blob=new Blob([buffer],{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download='MVIApps_Items_Export_'+stamp+'.xlsx';document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),1000);}).catch(()=>exportItemsMasterCSV(headers,rows,stamp)); return; }catch(e){} } if(window.XLSX&&XLSX.utils&&typeof XLSX.writeFile==='function'){ try{const wb=XLSX.utils.book_new(),ws=XLSX.utils.aoa_to_sheet([headers,...rows]);ws['!cols']=headers.map(h=>({wch:Math.max(14,Math.min(28,h.length+3))}));XLSX.utils.book_append_sheet(wb,ws,'Items');XLSX.writeFile(wb,'MVIApps_Items_Export_'+stamp+'.xlsx');return;}catch(e){} } exportItemsMasterCSV(headers,rows,stamp); } function exportItemsMasterCSV(headers,rows,stamp){ const csv='\uFEFF'+[headers,...rows].map(row=>row.map(v=>'"'+String(v??'').replace(/"/g,'""')+'"').join(',')).join('\r\n'); const blob=new Blob([csv],{type:'text/csv;charset=utf-8;'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='MVIApps_Items_Export_'+stamp+'.csv';document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),1000); } function importItemsPage(){ return `

Import Items from Excel

Choose an Excel file. The first row must contain column headings and the rows below it must contain item data.

1. Select Excel File

Required column: Item Name. Optional columns include Item Code, Category, Brand, Unit, HSN/SAC, Weight, Weight Unit, Dimension, Dimension Unit, GST Rate, Opening Quantity, Opening Value, Purchase Rate, Sale Rate, Wholesale Rate, Retail Rate, Minimum Stock Level and Source. Column names may be in any order.

2. Preview
Select a file to preview its rows before importing.
`; } async function downloadItemsImportTemplate(){ const headers=['Item Name','Item Code','Category','Brand','Unit','HSN/SAC','Weight','Weight Unit','Dimension','Dimension Unit','GST Rate','Opening Quantity','Opening Value','Purchase Rate','Sale Rate','Wholesale Rate','Retail Rate','Minimum Stock Level','Source']; const safeName='MVIApps_Import_Items_Blank_Format'; const categories=[...new Set((typeof getItemCategories==='function'?getItemCategories():[]).map(c=>String(c?.c??c??'').trim()).filter(Boolean))]; const weightUnits=['KG','G','MG','TON']; const dimensionUnits=['CM','MM','M','IN']; const units=['Pcs','Box','Set','Pack','Nos','Pair','Dozen','Kg','Gm','Litre','Meter']; if(window.ExcelJS&&window.ExcelJS.Workbook){ try{ const wb=new ExcelJS.Workbook();wb.creator='MVIApps';wb.subject='Blank Item Import Template'; const ws=wb.addWorksheet('Items');ws.addRow(headers); ws.views=[{state:'frozen',ySplit:1}]; ws.autoFilter={from:{row:1,column:1},to:{row:1,column:headers.length}}; ws.columns=headers.map(h=>({width:Math.max(14,h.length+2)})); const header=ws.getRow(1);header.font={bold:true,color:{argb:'FFFFFFFF'}};header.fill={type:'pattern',pattern:'solid',fgColor:{argb:'FF2457A7'}};header.alignment={vertical:'middle',horizontal:'center'};header.height=24; const listRule=(values,prompt)=>({type:'list',allowBlank:true,formulae:['"'+values.map(v=>String(v).replace(/"/g,'""')).join(',')+'"'],showErrorMessage:true,errorTitle:'Invalid value',error:'Please select a value from the dropdown list.',showInputMessage:true,promptTitle:'Choose a value',prompt}); const maxRows=501; if(categories.length&&categories.join(',').length<240){for(let r=2;r<=maxRows;r++)ws.getCell(r,3).dataValidation=listRule(categories,'Select an existing MVIApps category.');} for(let r=2;r<=maxRows;r++){ ws.getCell(r,5).dataValidation=listRule(units,'Select the item unit.'); ws.getCell(r,8).dataValidation=listRule(weightUnits,'Select the weight unit.'); ws.getCell(r,10).dataValidation=listRule(dimensionUnits,'Select the dimension unit.'); } ws.getCell('A2').note='Enter one item per row. Keep the header row unchanged. Dropdowns are available in Category, Unit, Weight Unit and Dimension Unit.'; const buffer=await wb.xlsx.writeBuffer();const blob=new Blob([buffer],{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=safeName+'.xlsx';document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),1500);return; }catch(err){console.warn('Excel template with dropdowns could not be generated:',err);} } alert('Dropdown वाला Excel template बनाने के लिए Excel library load नहीं हुई। कृपया internet connection जाँचकर पेज reload करें और फिर कोशिश करें।'); } function importHeaderKey(v){return String(v??'').trim().toLowerCase().replace(/[\s_\-./()]+/g,'').replace(/[^a-z0-9]/g,'');} function importCell(row,aliases){const keys=Object.keys(row||{});for(const a of aliases){const target=importHeaderKey(a);const k=keys.find(x=>importHeaderKey(x)===target);if(k!==undefined&&row[k]!==null&&row[k]!==undefined)return String(row[k]).trim();}return '';} function importNumber(v,def='0'){if(v===null||v===undefined||String(v).trim()==='')return def;const n=Number(String(v).replace(/[,₹\s]/g,''));return Number.isFinite(n)&&n>=0?String(n):null;} function normalizeImportedItem(row,index){ const name=importCell(row,['Item Name','Item','Name','Product Name','Item Description']); const code=importCell(row,['Item Code','Code','SKU','Product Code']); const qty=importNumber(importCell(row,['Opening Quantity','Opening Qty','Opening Stock','Quantity','Qty'])); const value=importNumber(importCell(row,['Opening Value','Opening Stock Value','Stock Value'])); const purchase=importNumber(importCell(row,['Purchase Rate','Purchase Price','Purchase','Cost Price'])); const sale=importNumber(importCell(row,['Sale Rate','Sale Price','Selling Price','MRP'])); const wholesale=importNumber(importCell(row,['Wholesale Rate','Wholesale Price','Wholesale'])); const retail=importNumber(importCell(row,['Retail Rate','Retail Price','Retail'])); const min=importNumber(importCell(row,['Minimum Stock Level','Min Stock','Minimum Stock','Reorder Level'])); const weight=importNumber(importCell(row,['Weight','Item Weight'])); const gst=importNumber(importCell(row,['GST Rate','GST','GST Percent','Tax Rate'])); const errors=[];if(!name)errors.push('Item Name is required'); for(const [label,val] of [['Opening Quantity',qty],['Opening Value',value],['Purchase Rate',purchase],['Sale Rate',sale],['Wholesale Rate',wholesale],['Retail Rate',retail],['Minimum Stock Level',min],['Weight',weight],['GST Rate',gst]])if(val===null)errors.push(label+' must be a non-negative number'); return {rowNumber:index+2,name,code,category:importCell(row,['Category','Item Category','Group']),brand:importCell(row,['Brand','Manufacturer']),unit:importCell(row,['Unit','UOM','Unit of Measure']),hsn:importCell(row,['HSN/SAC','HSN','SAC','HSN Code']),weight:weight??'0',weightUnit:importCell(row,['Weight Unit'])||'KG',dimension:importCell(row,['Dimension','Dimensions']),dimensionUnit:importCell(row,['Dimension Unit'])||'CM',gst:gst??'0',source:importCell(row,['Source','Supplier','Item Source']),qty:qty??'0',value:value??'0',purchase:purchase??'0',sale:sale??'0',wholesale:wholesale??'0',retail:retail??'0',min:min??'0',errors}; } async function readItemsImportFile(event){ const file=event?.target?.files?.[0];window._mviappsImportRows=[];const status=document.getElementById('importItemsStatus'),preview=document.getElementById('importItemsPreview'),actions=document.getElementById('importItemsActions');if(!file||!status||!preview)return; try{let rawRows=[];const ext=(file.name.split('.').pop()||'').toLowerCase();if(ext==='csv'){const text=await file.text();rawRows=parseItemsCSV(text);}else{if(!window.XLSX){status.innerHTML='Excel reader library did not load. Check your internet connection and reload MVIApps, or save the sheet as CSV and import it.';preview.innerHTML='';actions.style.display='none';return;}const data=await file.arrayBuffer();const wb=XLSX.read(data,{type:'array',cellDates:false});const ws=wb.Sheets[wb.SheetNames[0]];rawRows=XLSX.utils.sheet_to_json(ws,{defval:'',raw:false});} if(!rawRows.length){throw new Error('No item rows found. Make sure the first row contains column headings and data starts on the second row.');} const headers=Object.keys(rawRows[0]||{});if(!headers.some(h=>['itemname','item','name','productname','itemdescription'].includes(importHeaderKey(h))))throw new Error('Required “Item Name” column was not found in the first row.'); window._mviappsImportRows=rawRows.map((r,i)=>normalizeImportedItem(r,i));renderItemsImportPreview(); }catch(err){status.innerHTML=''+escapeHtml(err?.message||'Could not read this file.')+'';preview.innerHTML='';actions.style.display='none';} } function parseItemsCSV(text){const rows=[];let row=[],cell='',quoted=false;for(let i=0;iString(v).trim()))rows.push(row);row=[];cell='';}else cell+=c;}if(cell.length||row.length){row.push(cell);rows.push(row);}if(rows.length<2)return [];const heads=rows.shift().map(x=>String(x).trim());return rows.filter(r=>r.some(x=>String(x).trim())).map(r=>Object.fromEntries(heads.map((h,i)=>[h,r[i]??''])));} function renderItemsImportPreview(){const rows=window._mviappsImportRows||[],status=document.getElementById('importItemsStatus'),preview=document.getElementById('importItemsPreview'),actions=document.getElementById('importItemsActions');if(!status||!preview)return;const existing=JSON.parse(localStorage.getItem('mviapps_items')||'[]');let valid=0,duplicate=0,invalid=0;const seenCodes=new Set(existing.map(x=>String(x.code||'').trim().toLowerCase()).filter(Boolean));const seenNames=new Set(existing.map(x=>String(x.name||'').trim().toLowerCase()).filter(Boolean));rows.forEach(r=>{const dup=(r.code&&seenCodes.has(r.code.toLowerCase()))||(!r.code&&seenNames.has(r.name.toLowerCase()));if(dup){r.importStatus='Duplicate — will skip';duplicate++;}else if(r.errors.length){r.importStatus='Invalid — will skip';invalid++;}else{r.importStatus='Ready to import';valid++;if(r.code)seenCodes.add(r.code.toLowerCase());else seenNames.add(r.name.toLowerCase());}});status.textContent=`${rows.length} data row(s) found · ${valid} ready · ${duplicate} duplicate(s) · ${invalid} invalid row(s). Existing Item Codes will not be duplicated.`;const show=rows.slice(0,100);preview.innerHTML=show.length?`${show.map(r=>``).join('')}
Excel RowItem NameItem CodeCategoryOpening QtyPurchase RateSale RateStatus
${r.rowNumber}${escapeHtml(r.name||'—')}${escapeHtml(r.code||'—')}${escapeHtml(r.category||'—')}${escapeHtml(r.qty)}${escapeHtml(r.purchase)}${escapeHtml(r.sale)}${escapeHtml(r.importStatus+(r.errors.length?': '+r.errors.join(', '):''))}
${rows.length>100?`

Showing first 100 rows of ${rows.length}.

`:''}`:'

No data rows found.

';if(actions)actions.style.display=rows.length?'flex':'none';} function clearItemsImportPreview(){window._mviappsImportRows=[];const f=document.getElementById('importItemsFile');if(f)f.value='';const s=document.getElementById('importItemsStatus');if(s)s.textContent='Select a file to preview its rows before importing.';const p=document.getElementById('importItemsPreview');if(p)p.innerHTML='';const a=document.getElementById('importItemsActions');if(a)a.style.display='none';} async function commitItemsImport(){const rows=window._mviappsImportRows||[];if(!rows.length){alert('Please select an Excel file first.');return;}const ready=rows.filter(r=>r.importStatus==='Ready to import');if(!ready.length){alert('There are no valid new items to import. Please check the preview.');return;}if(!confirm(`Import ${ready.length} item(s) into MVIApps? Duplicate and invalid rows will be skipped.`))return;const existing=JSON.parse(localStorage.getItem('mviapps_items')||'[]');const codes=new Set(existing.map(x=>String(x.code||'').trim().toLowerCase()).filter(Boolean));const names=new Set(existing.map(x=>String(x.name||'').trim().toLowerCase()).filter(Boolean));const add=[],stockAdds=[];let skipped=0;for(const r of ready){if((r.code&&codes.has(r.code.toLowerCase()))||(!r.code&&names.has(r.name.toLowerCase()))){skipped++;continue;}const item={id:Date.now()+Math.random(),createdAt:new Date().toISOString().slice(0,10),name:r.name,code:r.code,category:r.category,brand:r.brand,unit:r.unit,hsn:r.hsn,weight:r.weight,weightUnit:r.weightUnit,dimension:r.dimension,dimensionUnit:r.dimensionUnit,gst:r.gst,source:r.source,qty:r.qty,value:r.value,purchase:r.purchase,sale:r.sale,wholesale:r.wholesale,retail:r.retail,min:r.min};try{add.push(await prepareItemForStorage(item,''));if(r.code)codes.add(r.code.toLowerCase());else names.add(r.name.toLowerCase());if(Number(r.qty)>0)stockAdds.push({itemId:item.id,qty:Number(r.qty)});}catch(e){alert('Import rok diya gaya: item storage prepare nahi ho paya. Koi imported item save nahi kiya gaya.');return;}} const saved=await saveItemsWithRecovery(existing.concat(add));if(!saved){alert('Import save nahi ho paya. Browser storage space check karein.');return;}if(stockAdds.length){let gs=getGodowns();if(!gs.length){gs=[{id:Date.now()+Math.random(),name:'Main Godown',location:'',createdAt:new Date().toISOString().slice(0,10)}];saveGodowns(gs);}const main=gs.find(g=>String(g.name||'').trim().toLowerCase()==='main godown')||gs[0];const stocks=getGodownStock();for(const x of stockAdds){const old=stocks.find(y=>String(y.itemId)===String(x.itemId)&&String(y.godownId)===String(main.id));if(old)old.qty=(Number(old.qty)||0)+x.qty;else stocks.push({id:Date.now()+Math.random(),itemId:x.itemId,godownId:main.id,qty:x.qty});}saveGodownStock(stocks);}alert(`Import complete. ${add.length} item(s) imported.${skipped?` ${skipped} duplicate row(s) skipped during final check.`:''} Opening quantities were added to Main Godown.`);clearItemsImportPreview();show('item-details');} function mviappsStaffPagePermission(id){ const rules={ // Parties 'party-details':['parties','view'],'party-ledger':['parties','view'], 'receivable':['parties','view'],'payable':['parties','view'], // Items, inventory and godowns 'item-details':['items','view'],'item-barcode-print':['items','view'], 'add-item':['items','create'],'item-categories':['items','view'], 'item-settings':['items','view'],'import-items':['items','create'], 'export-items':['items','view'],'stock-summary':['stock','view'], 'stock-ledger':['stock','view'],'godown-management':['godowns','view'], 'godown-transfer':['stock','create'], // Sales and POS 'sale-invoices':['sales','view'],'sales-returns':['sales','view'], 'point-of-sale':['sales','create'], // Purchases 'purchase-invoices':['purchases','view'],'purchase-returns':['purchases','view'], // Expenses, payments and income 'expenses':['expenses','view'],'expense-categories':['expenses','view'], 'payment-in':['payments','view'],'payment-out':['payments','view'], 'other-income':['income','view'],'income-heads':['income','view'], // Bank and cash 'bank-accounts':['bankCash','view'],'cash':['bankCash','view'], // Application settings and informational pages 'help':['settings','view'],'plans-pricing':['settings','view'], 'account-settings':['settings','view'],'appearance':['settings','view'], 'company':['settings','view'],'invoice-settings':['settings','view'], 'security':['settings','view'],'shipping-rates':['settings','view'], 'tax-settings':['settings','view'],'utilities':['settings','view'], // Owner-only pages: no Staff permission can grant access to these controls 'data-safety':['ownerOnly','view'],'delete-all-data':['ownerOnly','view'],'reset-production-cloud':['ownerOnly','view'], 'drive-sync':['ownerOnly','view'], // Reports 'report-all-parties':['reports','view'],'report-all-transactions':['reports','view'], 'report-balance-sheet':['reports','view'],'report-bank-statement':['reports','view'], 'report-day-book':['reports','view'],'report-expense':['reports','view'], 'report-item-details':['reports','view'],'report-other-income':['reports','view'], 'report-party-statement':['reports','view'],'report-pos':['reports','view'], 'report-profit-loss':['reports','view'],'report-purchase':['reports','view'], 'report-sale':['reports','view'],'report-sale-purchase-party':['reports','view'], 'report-stock-details':['reports','view'],'report-stock-summary':['reports','view'], 'report-stock-transfer-details':['reports','view'],'report-cloud-readonly':['reports','view'] }; return id==='dashboard'?null:(rules[id]||['ownerOnly','view']); } function show(id,btn){ window._mviappsCurrentPage=id; window._mviappsCurrentBtn=btn||window._mviappsCurrentBtn||null; const staffIdentity=window.mviappsProductionCloud?.getIdentity?.(); const staffPermission=staffIdentity?.mode==='staff'?mviappsStaffPagePermission(id):null; // Fail closed: every Staff destination except Dashboard must be explicitly mapped. if(staffIdentity?.mode==='staff'&&id!=='dashboard'&&(!staffPermission||!window.mviappsProductionCloud?.hasStaffPermission?.(staffPermission[0],staffPermission[1]))){ const content=document.getElementById('content'); if(content){ content.innerHTML='

Access Denied

Your Staff account does not have permission to open this section ('+escapeHtml(staffPermission[0]+'.'+staffPermission[1])+'). Contact the Business Owner if access is required.

'; } document.querySelectorAll('.nav button').forEach(b=>b.classList.remove('active')); if(btn)btn.classList.add('active'); window.scrollTo(0,0); return; } // Dashboard is a top-level destination: close every open main-menu dropdown when it is selected. if(id==='dashboard') document.querySelectorAll('.nav > .group.open').forEach(g=>g.classList.remove('open')); const p=pages[id]||pages.dashboard; const content=document.getElementById('content'); if(!content)return; content.innerHTML=(id==='import-items'?importItemsPage():(id==='export-items'?exportItemsPage():(id==='plans-pricing'?`
₹
MVIApps

Plans & Pricing

Will be available soon

We’re preparing something useful for your business.

`:(id==='dashboard'?dashboard():(id==='bank-accounts'?bankAccountsPage():(id==='cash'?cashPage():(id==='sales-returns'?salesReturnPage():(p.html||'')))))))); if(id==='party-details') setTimeout(()=>{ const button=document.getElementById('mviapps-add-party-button'); if(button){ const identity=window.mviappsProductionCloud?.getIdentity?.(); const allowed=identity?.mode!=='staff'||window.mviappsProductionCloud?.hasStaffPermission?.('parties','create')===true; button.style.display=allowed?'':'none'; } },0); if(id==='import-items') setTimeout(clearItemsImportPreview,0); if(id==='cash') setTimeout(renderCashTransactions,0); if(id==='security') setTimeout(()=>{if(typeof mviappsRenderUserList==='function')mviappsRenderUserList();},0); if(id==='shipping-rates') setTimeout(()=>{renderShippingPlugin();compareShippingRates();},0); // Negative/loss highlighting is intentionally limited to the Profit & Loss report. // Do not scan other reports, because dates, item names and references may contain '-'. if(id==='report-profit-loss') setTimeout(()=>{const fy=document.getElementById('plFinancialYear')?.value||getSelectedFinancialYear(); const start=Number(String(fy).split('-')[0])||new Date().getFullYear(); setProfitLossDateValues(start+'-04-01',(start+1)+'-03-31'); highlightProfitLossNegatives(content);},0); if(['report-all-transactions','report-day-book','report-balance-sheet','report-party-statement'].includes(id)) setTimeout(()=>{const prefix=id==='report-all-transactions'?'at':id==='report-day-book'?'db':id==='report-balance-sheet'?'bs':'ps'; const fy=document.getElementById(prefix+'FinancialYear')?.value||getSelectedFinancialYear(); const start=Number(String(fy).split('-')[0])||new Date().getFullYear(); setReportDateValues(prefix,start+'-04-01',(start+1)+'-03-31'); if(prefix==='ps'){const month=document.getElementById('psMonth');if(month)month.value='all';}},0); document.querySelectorAll('.nav button').forEach(b=>b.classList.remove('active')); if(btn)btn.classList.add('active'); window.scrollTo(0,0); if(id==='company' && typeof loadCompanySettings==='function')loadCompanySettings(); if(id==='account-settings' && typeof renderAccountHeads==='function')setTimeout(renderAccountHeads,0); if(id==='item-categories' && typeof renderItemCategories==='function')renderItemCategories(); if(id==='report-all-parties' && typeof renderAllPartiesList==='function') setTimeout(renderAllPartiesList,0); if(id==='report-stock-summary' && typeof renderReportStockSummary==='function') setTimeout(renderReportStockSummary,0); if(id==='report-stock-details' && typeof renderStockDetailsReport==='function') setTimeout(renderStockDetailsReport,0); if(id==='report-item-details' && typeof renderItemDetailsReport==='function') setTimeout(renderItemDetailsReport,0); if(id==='report-stock-transfer-details' && typeof initStockTransferReport==='function') setTimeout(initStockTransferReport,0); if(id==='report-expense' && typeof initExpenseReport==='function') setTimeout(initExpenseReport,0); if(id==='report-pos' && typeof initPOSReport==='function') setTimeout(initPOSReport,0); if(id==='sales-returns' && typeof renderSalesReturns==='function') setTimeout(renderSalesReturns,0); if(id==='report-other-income' && typeof initOtherIncomeReport==='function') setTimeout(initOtherIncomeReport,0); if(id==='report-sale' && typeof saleReportInit==='function') setTimeout(saleReportInit,0); if(id==='report-purchase' && typeof purchaseReportInit==='function') setTimeout(purchaseReportInit,0); if(id==='report-sale-purchase-party'){ setTimeout(()=>{ const now=new Date(), first=new Date(now.getFullYear(),now.getMonth(),1), last=new Date(now.getFullYear(),now.getMonth()+1,0); const f=document.getElementById('spFrom'), t=document.getElementById('spTo'); if(f&&!f.value)f.value=first.toISOString().slice(0,10); if(t&&!t.value)t.value=last.toISOString().slice(0,10); syncReportDateDisplay('sp','from'); syncReportDateDisplay('sp','to'); renderSalePurchasePartyReport(); },0); } if(id==='party-details'){ const panel=document.getElementById('party-form-panel'); if(panel){ const f=[...panel.querySelectorAll('.field')].find(x=>x.querySelector('label')?.textContent==='Party Type'); if(f)f.innerHTML=''; panel.style.display='none'; } if(typeof renderParties==='function')renderParties(); } if(id==='check-item-availability'){setTimeout(()=>{if(typeof initQuickItemAvailability==='function')initQuickItemAvailability();},0);} if(id==='item-details' && typeof renderItems==='function')renderItems(); if(id==='item-barcode-print' && typeof renderMVIBarcodeItems==='function')setTimeout(renderMVIBarcodeItems,0); if(id==='point-of-sale'){setTimeout(()=>{if(typeof initPointOfSale==='function')initPointOfSale();},0);} if(id==='stock-summary' && typeof renderStockSummary==='function')renderStockSummary(); if(id==='stock-ledger' && typeof renderStockLedger==='function')renderStockLedger(); if(id==='godown-management' && typeof initGodownPage==='function')initGodownPage();if(id==='receivable' && typeof renderReceivable==='function')setTimeout(renderReceivable,0);if(id==='payable' && typeof renderPayable==='function')setTimeout(renderPayable,0); if(id==='expenses' && typeof renderExpenses==='function'){renderExpenses();setTimeout(()=>{if(typeof mviappsLoadExpenseCloudMasters==='function')mviappsLoadExpenseCloudMasters();},0);} if((id==='payment-in'||id==='other-income'||id==='payment-out') && typeof renderAccountEntries==='function')setTimeout(()=>renderAccountEntries(id==='payment-in'?'Payment-In':(id==='other-income'?'Other Income':'Payment-Out')),0); if(id==='payment-in'&&window.mviappsProductionCloud?.getIdentity?.())setTimeout(()=>mviappsPreparePaymentInCloudForm(),0); if(id==='payment-out'&&window.mviappsProductionCloud?.getIdentity?.())setTimeout(()=>mviappsPreparePaymentOutCloudForm(),0); if(id==='purchase-returns' && typeof renderPurchaseReturns==='function')setTimeout(renderPurchaseReturns,0); if(id==='expense-categories' && typeof renderExpenseCategories==='function')renderExpenseCategories(); if(id==='income-heads' && typeof renderIncomeHeads==='function')renderIncomeHeads(); if(id==='sale-invoices'){ const now=new Date(), y=now.getFullYear(), m=now.getMonth(); const first=new Date(y,m,1), last=new Date(y,m+1,0); const fmt=d=>d.toISOString().slice(0,10); const from=document.getElementById('saleInvoiceFrom'), to=document.getElementById('saleInvoiceTo'); if(from)from.value=fmt(first); if(to)to.value=fmt(last); if(typeof renderSaleInvoices==='function')renderSaleInvoices(); } if(id==='purchase-invoices'){ const now=new Date(), y=now.getFullYear(), m=now.getMonth(); const first=new Date(y,m,1), last=new Date(y,m+1,0); const fmt=d=>d.toISOString().slice(0,10); const from=document.getElementById('purchaseInvoiceFrom'), to=document.getElementById('purchaseInvoiceTo'); if(from)from.value=fmt(first); if(to)to.value=fmt(last); if(typeof syncPurchaseInvoiceFilterDateDisplays==='function')syncPurchaseInvoiceFilterDateDisplays(); if(typeof renderPurchaseInvoices==='function')renderPurchaseInvoices(); } } function highlightProfitLossNegatives(root=document){ try{ const RED='#dc2626'; const report=root.querySelector('#profitLossResult') || root; // Only inspect numeric amount cells inside the Profit & Loss report. report.querySelectorAll('.pl-pdf-statement td.num, .pl-summary b, .pl-cogs-grid b').forEach(el=>{ const txt=(el.textContent||'').trim(); if(/(?:-\s*₹|₹\s*-|-\s*(?:Rs\.?|INR)|(?:Rs\.?|INR)\s*-)/i.test(txt) || /^-/.test(txt)){ el.style.color=RED; el.classList.add('negative'); } }); // Gross Loss / Net Loss are displayed as positive absolute figures, so their // row receives the red treatment explicitly. Gross/Net Profit remains normal. report.querySelectorAll('.pl-loss-red').forEach(row=>{ row.style.color=RED; row.querySelectorAll('td,td *,th,th *').forEach(el=>el.style.color=RED); }); }catch(e){ console.warn('P&L negative/loss highlighting failed',e); } } function globalSearch(q){ const input=document.querySelector('.topbar .search'); if(!input)return; let box=document.getElementById('mviappsGlobalSearchResults'); if(!box){ box=document.createElement('div'); box.id='mviappsGlobalSearchResults'; box.className='mvi-global-search-results'; input.parentElement.style.position='relative'; input.parentElement.appendChild(box); } const term=String(q||'').trim().toLowerCase(); if(term.length<2){box.innerHTML='';box.style.display='none';return;} const read=(key)=>{try{const v=JSON.parse(localStorage.getItem(key)||'[]');return Array.isArray(v)?v:[];}catch(e){return [];}}; const esc=typeof escapeHtml==='function'?escapeHtml:(v)=>String(v??'').replace(/[&<>\"']/g,c=>({'&':'&','<':'<','>':'>','\"':'"',"'":'''}[c])); const results=[]; const add=(type,title,detail,page,icon)=>{ const hay=(String(title||'')+' '+String(detail||'')).toLowerCase(); if(hay.includes(term))results.push({type,title,detail,page,icon}); }; read('mviapps_items').forEach(x=>add('Item',x.name||x.itemName||'Unnamed Item',[x.code?'Code: '+x.code:'',x.category?'Category: '+x.category:''].filter(Boolean).join(' • '),'items','📦')); read('mviapps_parties').forEach(x=>add('Party',x.name||'Unnamed Party',[x.phone,x.email,x.type].filter(Boolean).join(' • '),'parties','👤')); read('mviapps_sales_invoices').forEach(x=>add('Sale Invoice',x.invoiceNo||x.number||'Unnamed Invoice',[x.customerName||x.customer||'',x.date||''].filter(Boolean).join(' • '),'sale-invoices','🧾')); read('mviapps_purchase_invoices').forEach(x=>add('Purchase Invoice',x.invoiceNo||x.number||'Unnamed Invoice',[x.supplierName||x.supplier||'',x.date||''].filter(Boolean).join(' • '),'purchase-invoices','🧾')); read('mviapps_expenses').forEach(x=>add('Expense',x.expenseNo||x.number||x.category||'Expense',[x.category||'',x.date||''].filter(Boolean).join(' • '),'expenses','💳')); read('mviapps_other_income').forEach(x=>add('Other Income',x.incomeNo||x.number||x.head||'Income',[x.head||x.incomeHead||'',x.date||''].filter(Boolean).join(' • '),'other-income','💰')); read('mviapps_shipping_rate_sheets').forEach(x=>add('Shipping Rate Sheet',x.shipper||'Shipper',[x.effectiveFrom?'Effective: '+x.effectiveFrom:''].filter(Boolean).join(' • '),'shipping-rates','🚚')); const limited=results.slice(0,12); if(!limited.length){ box.innerHTML='
No matching item, party, invoice or record found.
'; box.style.display='block'; return; } box.innerHTML=limited.map((r,i)=>``).join(''); box._results=limited; box.style.display='block'; } function openGlobalSearchResult(index){ const box=document.getElementById('mviappsGlobalSearchResults'); const r=box?box._results?.[index]:null; if(!r)return; if(box){box.innerHTML='';box.style.display='none';} const input=document.querySelector('.topbar .search');if(input)input.value=''; if(typeof show==='function')show(r.page,null); } document.addEventListener('click',function(e){ const box=document.getElementById('mviappsGlobalSearchResults'); const input=document.querySelector('.topbar .search'); if(box&&input&&!box.contains(e.target)&&e.target!==input){box.style.display='none';} }); migrateItemsToIndexedDB().catch(()=>{}); function mviappsRenderDashboardOnReady(){try{mviappsBindBankModeSelector();}catch(e){} try{const content=document.getElementById('content');if(content && !content.innerHTML.trim()){content.innerHTML=dashboard();document.querySelectorAll('.nav button').forEach(b=>b.classList.remove('active'));const db=[...document.querySelectorAll('.nav button')].find(b=>String(b.getAttribute('onclick')||'').includes("show('dashboard'"));if(db)db.classList.add('active');}}catch(e){console.error('Dashboard rendering failed:',e);}} window.addEventListener('DOMContentLoaded',mviappsRenderDashboardOnReady); window.addEventListener('load',mviappsRenderDashboardOnReady);