AMCON DEVELOPMENT
Registration No.: 201401032075 (1108159-H)

Dashboard

公司项目与财务总览 · 汇总已核实收款及未收余额
Total Projects
12
All projects
Ongoing Projects
8
Currently active
Total Collected
RM 340,000
Verified payments
Outstanding
RM 330,000
Unpaid invoices / claims

Company Payment Overview

公司项目收款分布 · Verified / Due / Future Billing
Demo data
Collected · 已收款
Finance 已确认到账
——
Due Now · 当前应收
已批准、尚未收取的款项
——
Future Billing · 未来收费
尚未到付款阶段的余额
——

此圆环显示客户向 AMCON 的项目付款情况,不代表公司对供应商或员工的支出。正式版将根据项目合约、已批准应收账款及核实收款自动更新。

Project Overview

Director view · demo
ProjectContract ValueWork ProgressCollectedDue NowFuture BillingUncollected BalanceStatus
Residential Renovation A
AM-2026-001
RM 200,000
55% completed
RM 80,000
40% collected
RM 60,000
Claim 1 · 30%
RM 60,000
20% + 10% retention
RM 120,000Ongoing
Commercial Unit B
AM-2026-002
RM 350,000
40% completed
RM 140,000
40% collected
RM 105,000
Claim 1 · 30%
RM 105,000
20% + 10% retention
RM 210,000Ongoing
House Extension C
AM-2026-003
RM 120,000
100% completed
RM 120,000
100% collected
RM 0RM 0RM 0Completed
收费计算示例(合约 RM100,000)
工程进度达到 40%:已收 Deposit RM40,000(40%);当前触发 Progress Claim 1:应收 RM30,000(30%);之后尚有 RM30,000(Progress Claim 2 的 20% + Retention 10%)。
Current due = 当前阶段已触发但尚未收取的金额;Future billing = 尚未达到触发条件的阶段金额;Uncollected balance = 合约总额减去已核实收款。

Financial Snapshot

Contract Value
RM 670,000
Recorded Expenses
RM 298,000
Estimated Gross Profit
RM 372,000
Pending Approval
3 claims

示例数据仅用于界面预览。正式利润报表需纳入已发生及应计成本、变更单、税务和其他调整。

`; const w=window.open('','_blank');if(!w){message.textContent='Please allow pop-ups to preview the invoice.';return;}w.document.open();w.document.write(html);w.document.close();recordGeneratedDocument('Invoice',invoiceNo,get('invoiceCustomer'),get('invoiceProject'),get('invoiceAmount'),html);message.textContent='Invoice '+invoiceNo+' generated and saved in this browser. Use Print / Save as PDF.';refreshInvoiceNumber(); } document.getElementById('roleSwitch').addEventListener('change',e=>setRole(e.target.value)); function setRole(role){ currentRole=role; document.querySelectorAll('nav button[data-page],.nav-group').forEach(b=>{const roles=(b.dataset.roles||'director,sales_manager,finance').split(',');b.classList.toggle('hidden',!roles.includes(role));}); document.querySelectorAll('.director-only').forEach(b=>b.classList.toggle('hidden',role!=='director')); document.querySelectorAll('.non-director-approval').forEach(b=>b.classList.toggle('hidden',role==='director')); document.querySelectorAll('.finance-sensitive').forEach(el=>el.classList.toggle('hidden',role==='site'||role==='sales'||role==='operation_manager')); document.getElementById('projectRegister').classList.toggle('hidden',role==='operation_manager'); document.querySelectorAll('[data-manual]').forEach(el=>el.classList.toggle('hidden',!['director','sales_manager'].includes(role)));resetProjectMode(); document.querySelectorAll('.billing-config').forEach(el=>el.classList.toggle('hidden',!['director','sales_manager'].includes(role))); if(role==='site')showPage('siteview');else if(role==='operation_manager')showPage('supervisors');else if(role==='sales')showPage('projects');else if(role==='sales_manager')showPage('projectapprovals');else showPage('dashboard'); document.getElementById('projectSubmitButton').textContent=role==='sales'?'Submit for Approval':'Create Project'; renderReceipts();renderSupervisors();renderExpenseClaims();renderPurchaseRequests();renderQuotations();renderProjectApprovals();renderQuotations(); } // Expense claim demo ledger: approved but unpaid claims are liabilities, not customer receivables. const expenseClaims=[ {id:'EC-2026-001',project:'Residential Renovation A',supervisor:'Supervisor 01',category:'Materials',amount:185.50,expenseDate:'2026-11-17',submitted:'2026-11-18',description:'Cement and site consumables',attachment:'receipt-cement.jpg',status:'Approved / Unpaid',approvedAt:'2026-11-19',paidAt:'',paymentRef:''}, {id:'EC-2026-002',project:'Commercial Unit B',supervisor:'Supervisor 02',category:'Transport',amount:65,expenseDate:'2026-11-19',submitted:'2026-11-20',description:'Delivery transport',attachment:'transport-slip.pdf',status:'Pending Review',approvedAt:'',paidAt:'',paymentRef:''}, {id:'EC-2026-003',project:'Residential Renovation A',supervisor:'Supervisor 01',category:'Tools & Equipment',amount:90,expenseDate:'2026-11-11',submitted:'2026-11-12',description:'Small hand tools',attachment:'tools.jpg',status:'Reimbursed',approvedAt:'2026-11-13',paidAt:'2026-11-14',paymentRef:'TRF-DEMO-01'} ]; const PURCHASE_REQUEST_KEY='amcon_purchase_requests_v2'; const purchaseRequests=(()=>{try{return JSON.parse(localStorage.getItem(PURCHASE_REQUEST_KEY)||'[]')||[]}catch(e){return []}})(); function persistPurchaseRequests(){try{localStorage.setItem(PURCHASE_REQUEST_KEY,JSON.stringify(purchaseRequests));return true}catch(e){alert('Browser storage full; purchase record could not be saved.');return false}} function todayISO(){return new Date().toLocaleDateString('en-CA');} function submitExpenseClaim(){if(currentRole!=='site')return;const amount=Number(document.getElementById('claimAmount').value),desc=document.getElementById('claimDescription').value.trim(),date=document.getElementById('claimExpenseDate').value,supervisor=document.getElementById('claimSupervisor').value.trim(),file=document.getElementById('claimAttachment').files[0],msg=document.getElementById('claimFormMessage');if(!amount||amount<=0||!desc||!date||!supervisor||!file){msg.textContent='请填写所有必填资料,并上传收据。';return;}expenseClaims.push({id:'EC-2026-'+String(expenseClaims.length+1).padStart(3,'0'),project:document.getElementById('claimProject').value,supervisor,category:document.getElementById('claimCategory').value,amount,expenseDate:date,submitted:todayISO(),description:desc,attachment:file.name,status:'Pending Review',approvedAt:'',paidAt:'',paymentRef:''});msg.textContent='Claim submitted for Operation Manager review. (Demo: attachment name only; no upload storage.)';document.getElementById('claimAmount').value='';document.getElementById('claimDescription').value='';document.getElementById('claimAttachment').value='';renderExpenseClaims();} function renderExpenseClaims(){const unpaid=expenseClaims.filter(x=>x.status==='Approved / Unpaid'),pending=expenseClaims.filter(x=>x.status==='Pending Review'),paid=expenseClaims.filter(x=>x.status==='Reimbursed');document.getElementById('claimUnpaid').textContent=money(unpaid.reduce((a,x)=>a+x.amount,0));document.getElementById('claimPending').textContent=money(pending.reduce((a,x)=>a+x.amount,0));document.getElementById('claimPaid').textContent=money(paid.reduce((a,x)=>a+x.amount,0));document.getElementById('claimUnpaidCount').textContent=unpaid.length;document.getElementById('newClaimPanel').classList.toggle('hidden',currentRole!=='site');const filter=document.getElementById('claimFilter').value;const rows=expenseClaims.map((x,i)=>({x,i})).filter(({x})=>filter==='all'||x.status===filter).filter(({x})=>currentRole!=='site'||x.supervisor==='Supervisor 01');document.getElementById('claimRows').innerHTML=rows.map(({x,i})=>`${safeText(x.id)}${safeText(x.supervisor)}
${safeText(x.project)}
${safeText(x.expenseDate)}${safeText(x.submitted)}${money(x.amount)}${safeText(x.status)}${safeText(x.approvedAt||'—')}${safeText(x.paidAt||'—')}`).join('')||'No claims found.';} function viewExpenseClaim(i){const x=expenseClaims[i];if(!x)return;if(currentRole==='site'&&x.supervisor!=='Supervisor 01')return;const actions=x.status==='Pending Review'&¤tRole==='operation_manager'?` `:x.status==='Approved / Unpaid'&¤tRole==='finance'?``:'';document.getElementById('claimDetails').innerHTML=`${safeText(x.id)} — ${safeText(x.category)}

${safeText(x.description)}

Receipt: ${safeText(x.attachment)} (demo filename only)
Submitted: ${safeText(x.submitted)} · Approved: ${safeText(x.approvedAt||'—')} · Paid: ${safeText(x.paidAt||'—')}
Payment reference: ${safeText(x.paymentRef||'—')}
${actions}
`;} function reviewExpenseClaim(i,approve){if(currentRole!=='operation_manager')return;const x=expenseClaims[i];if(!x||x.status!=='Pending Review')return;x.status=approve?'Approved / Unpaid':'Returned';x.approvedAt=approve?todayISO():'';renderExpenseClaims();viewExpenseClaim(i);} function payExpenseClaim(i){if(currentRole!=='finance')return;const x=expenseClaims[i],ref=document.getElementById('claimPaymentRef')?.value.trim();if(!x||x.status!=='Approved / Unpaid'||!ref){alert('Please enter bank payment reference.');return;}x.status='Reimbursed';x.paidAt=todayISO();x.paymentRef=ref;renderExpenseClaims();viewExpenseClaim(i);} function submitPurchaseRequest(){ if(!['site','operation_manager','director'].includes(currentRole))return; const amount=Number(document.getElementById('purchaseAmount').value),reason=document.getElementById('purchaseReason').value.trim(),supplier=document.getElementById('purchaseSupplier').value.trim(),file=document.getElementById('purchaseFile').files[0],msg=document.getElementById('purchaseMessage'); if(!Number.isFinite(amount)||amount<=0||!reason||!supplier){msg.textContent='Please enter supplier, amount and reason.';return;} const r={id:'PRQ-'+String(Math.max(0,...purchaseRequests.map(x=>Number(x.id.split('-').pop())||0))+1).padStart(4,'0'),project:document.getElementById('purchaseProject').value,supplier,amount,reason,date:todayISO(),requestedAt:new Date().toISOString(),requestedBy:currentRole,attachment:file?.name||'',status:'Pending Operation Review',reviewedAt:'',approvedAt:'',paidAt:'',paymentReference:'',paymentDate:'',paymentProof:'',approvedBy:'',paidBy:''}; purchaseRequests.push(r);if(!persistPurchaseRequests()){purchaseRequests.pop();return;} amconLog('Purchase Request Submitted',`${r.id} | ${r.project} | ${r.supplier} | RM ${r.amount} | ${r.attachment||'No attachment'}`); msg.textContent=r.id+' submitted. Operation review and Director approval required before Finance transfer.';renderPurchaseRequests(); } function renderPurchaseRequests(){ const t=document.getElementById('purchaseRows');if(!t)return; t.innerHTML=purchaseRequests.map((r,i)=>`${safeText(r.id)}
${safeText(r.requestedBy||'')}
${safeText(r.project)}${safeText(r.supplier)}
${safeText(r.reason||'')}
${money(r.amount)}${safeText(r.date)}
${safeText(r.attachment||'')}
${safeText(r.status)}${r.approvedAt?`
Approved: ${safeText(new Date(r.approvedAt).toLocaleString('en-MY'))}
`:''}${r.paidAt?`
Paid: ${safeText(r.paymentDate||'')} · ${safeText(r.paymentReference||'')}
`:''}${currentRole==='operation_manager'&&r.status==='Pending Operation Review'?` `:currentRole==='director'&&r.status==='Pending Director Approval'?` `:currentRole==='finance'&&r.status==='Approved for Payment'?``:'—'} `).join('')||'No purchase requests yet.'; const pending=purchaseRequests.filter(x=>x.status==='Approved for Payment').reduce((a,x)=>a+Number(x.amount),0);const stats=document.getElementById('purchaseStats');if(stats)stats.textContent='Finance approved but unpaid: '+money(pending)+' · '+purchaseRequests.filter(x=>x.status==='Approved for Payment').length+' request(s)'; const panel=document.getElementById('purchaseTransferPanel');if(panel&&!panel.classList.contains('hidden')&¤tRole!=='finance')panel.classList.add('hidden'); } function reviewPurchase(i,action='approve'){ const r=purchaseRequests[i];if(!r)return; const allowed=(currentRole==='operation_manager'&&r.status==='Pending Operation Review')||(currentRole==='director'&&r.status==='Pending Director Approval');if(!allowed)return; const previous=r.status; if(currentRole==='director'){ const note=prompt(action==='reject'?'Director rejection reason (required):':'Director approval note / authorization reference (required):'); if(!note||!note.trim())return; if(action!=='reject'&&!confirm(`Authorize Finance to transfer ${money(r.amount)} to ${r.supplier} for ${r.id}?`))return; r.directorDecisionNote=note.trim();r.directorDecisionAt=new Date().toISOString();r.directorDecisionBy='director'; } if(action==='reject')r.status='Rejected';else if(currentRole==='operation_manager'){r.status='Pending Director Approval';r.reviewedAt=new Date().toISOString();r.reviewedBy=currentRole;}else{r.status='Approved for Payment';r.approvedAt=new Date().toISOString();r.approvedBy=currentRole;} if(!persistPurchaseRequests()){r.status=previous;return;} amconLog(action==='reject'?'Purchase Request Rejected':'Purchase Request Approved',`${r.id} | ${previous} → ${r.status} | RM ${r.amount} | ${r.supplier} | Director note: ${r.directorDecisionNote||'—'}`);renderPurchaseRequests(); } let purchaseTransferIndex=-1; function openPurchaseTransfer(i){const r=purchaseRequests[i];if(currentRole!=='finance'||r?.status!=='Approved for Payment')return;purchaseTransferIndex=i;document.getElementById('purchaseTransferPanel').classList.remove('hidden');document.getElementById('purchaseTransferInfo').textContent=`${r.id} · ${r.supplier} · ${money(r.amount)} · Director approved ${new Date(r.approvedAt).toLocaleString('en-MY')}`;document.getElementById('purchaseTransferAmount').value=r.amount;document.getElementById('purchaseTransferDate').value=todayISO();document.getElementById('purchaseTransferReference').value='';document.getElementById('purchaseTransferProof').value='';document.getElementById('purchaseTransferMessage').textContent='';document.getElementById('purchaseTransferPanel').scrollIntoView({behavior:'smooth',block:'center'});} function confirmPurchaseTransfer(){ const r=purchaseRequests[purchaseTransferIndex];if(currentRole!=='finance'||r?.status!=='Approved for Payment')return; const date=document.getElementById('purchaseTransferDate').value,reference=document.getElementById('purchaseTransferReference').value.trim(),amount=Number(document.getElementById('purchaseTransferAmount').value),proof=document.getElementById('purchaseTransferProof').files[0],msg=document.getElementById('purchaseTransferMessage'); if(!date||!reference||!proof||Math.abs(amount-r.amount)>0.005){msg.textContent='Enter payment date, exact approved amount, bank reference and upload transfer proof.';return;} const previous={...r};Object.assign(r,{status:'Paid',paidAt:new Date().toISOString(),paymentDate:date,paymentReference:reference,paymentProof:proof.name,paidAmount:amount,paidBy:currentRole,reconciliationStatus:'Unreconciled'});if(!persistPurchaseRequests()){Object.assign(r,previous);return;} amconLog('Purchase Bank Transfer Recorded',`${r.id} | ${r.project} | ${r.supplier} | ${money(amount)} | Transfer date ${date} | Bank ref ${reference} | Proof ${proof.name} | Director approval ${r.approvedAt}`); msg.textContent='Transfer recorded with audit trail. Keep original bank proof for official audit.';document.getElementById('purchaseTransferPanel').classList.add('hidden');renderPurchaseRequests(); } function viewPurchaseAudit(i){ const r=purchaseRequests[i],el=document.getElementById('purchaseAuditDetails');if(!r||!el)return; el.innerHTML=`${safeText(r.id)} — ${safeText(r.status)}

Project: ${safeText(r.project)} | Supplier: ${safeText(r.supplier)} | Amount: ${money(r.amount)}

Requested: ${safeText(r.requestedAt||r.date)} by ${safeText(r.requestedBy||'—')}
Operation reviewed: ${safeText(r.reviewedAt||'—')}
Director decision: ${safeText(r.directorDecisionAt||r.approvedAt||'—')} by ${safeText(r.directorDecisionBy||r.approvedBy||'—')}
Director note: ${safeText(r.directorDecisionNote||'—')}
Finance paid: ${safeText(r.paidAt||'—')} | Date: ${safeText(r.paymentDate||'—')} | Ref: ${safeText(r.paymentReference||'—')}
Proof file: ${safeText(r.paymentProof||'—')} (filename only)
Reconciliation: ${safeText(r.reconciliationStatus||'—')} | ${safeText(r.reconciledAt||'—')} | Bank statement: ${safeText(r.bankStatementRef||'—')}

This demo does not retain actual file bytes, verified employee identities or tamper-proof audit evidence.

`; el.scrollIntoView({behavior:'smooth',block:'nearest'}); } function renderBankReconciliation(){ const t=document.getElementById('reconciliationRows');if(!t)return; const rows=purchaseRequests.map((r,i)=>({r,i})).filter(({r})=>r.status==='Paid'); const unmatched=rows.filter(({r})=>r.reconciliationStatus!=='Reconciled'); document.getElementById('reconciliationStats').textContent=`Paid transfers: ${rows.length} · Unreconciled: ${unmatched.length} (${money(unmatched.reduce((n,{r})=>n+(Number(r.paidAmount)||0),0))})`; t.innerHTML=rows.map(({r,i})=>`${safeText(r.id)}${safeText(r.supplier)}
${safeText(r.project)}
${money(r.paidAmount)}
${safeText(r.paymentDate||'')}
${safeText(r.paymentReference||'')}${safeText(r.reconciliationStatus||'Unreconciled')}
${safeText(r.bankStatementRef||'')}
${currentRole==='finance'&&r.reconciliationStatus!=='Reconciled'?``:'—'}`).join('')||'No paid purchase transfers to reconcile.'; } function reconcilePurchase(i){ const r=purchaseRequests[i];if(currentRole!=='finance'||r?.status!=='Paid'||r.reconciliationStatus==='Reconciled')return; const bankRef=prompt(`Enter bank statement transaction reference matching ${r.id} / ${money(r.paidAmount)}:`);if(!bankRef||!bankRef.trim())return; if(!confirm(`Confirm bank statement matches supplier ${r.supplier}, amount ${money(r.paidAmount)} and transfer reference ${r.paymentReference}?`))return; const old={...r};Object.assign(r,{reconciliationStatus:'Reconciled',bankStatementRef:bankRef.trim(),reconciledAt:new Date().toISOString(),reconciledBy:currentRole}); if(!persistPurchaseRequests()){Object.assign(r,old);return;} amconLog('Bank Transfer Reconciled',`${r.id} | ${r.supplier} | ${money(r.paidAmount)} | Bank statement ${bankRef.trim()} | Transfer ${r.paymentReference}`);renderBankReconciliation();renderPurchaseRequests(); } function exportReconciliationCSV(){ const rows=[['Purchase No','Project','Supplier','Amount','Transfer Date','Transfer Reference','Director Approved At','Director Note','Bank Status','Bank Statement Reference','Reconciled At'],...purchaseRequests.filter(r=>r.status==='Paid').map(r=>[r.id,r.project,r.supplier,r.paidAmount,r.paymentDate,r.paymentReference,r.approvedAt,r.directorDecisionNote,r.reconciliationStatus||'Unreconciled',r.bankStatementRef||'',r.reconciledAt||''])]; const csv=rows.map(row=>row.map(x=>'"'+String(x??'').replace(/"/g,'""')+'"').join(',')).join('\r\n');const a=document.createElement('a');a.href=URL.createObjectURL(new Blob(['\ufeff'+csv],{type:'text/csv;charset=utf-8'}));a.download='amcon-bank-reconciliation.csv';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),1000); } const pendingReceipts=[]; const projectNames=['Residential Renovation A','Commercial Unit B','House Extension C']; function safeText(s){return String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));} function uploadReceipt(){ if(!['sales','sales_manager','finance','director'].includes(currentRole))return; const amount=Number(document.getElementById('receiptAmount').value); const file=document.getElementById('receiptFile').files[0]; if(!amount||amount<=0||!file){document.getElementById('receiptMessage').textContent='请填写有效金额并选择收据文件。';return;} const project=Number(document.getElementById('receiptProject').value); pendingReceipts.push({project,amount,file:file.name,ref:document.getElementById('receiptReference').value,status:'Pending Verification'}); document.getElementById('receiptMessage').textContent='Receipt submitted. Pending Finance verification (demo only; file is not stored).'; document.getElementById('receiptAmount').value=''; document.getElementById('receiptFile').value=''; renderReceipts(); } function renderReceipts(){ const body=document.getElementById('receiptRows');if(!body)return; body.innerHTML=pendingReceipts.length?pendingReceipts.map((r,i)=>`${safeText(projectNames[r.project]||'New Project')}${money(r.amount)}${safeText(r.ref)}${safeText(r.file)}${r.status}${currentRole==='finance'&&r.status!=='Verified'?``:'—'}`).join(''):'No receipts submitted yet.'; } function verifyReceipt(i){ if(currentRole!=='finance')return; const r=pendingReceipts[i];if(!r||r.status==='Verified')return; r.status='Verified';projectLedger[r.project].verifiedReceipts+=r.amount; updateDashboardTotals();renderReceipts(); } function openApproval(){if(currentRole!=='director'){alert('No permission. Only Director can approve this submission.');return;}document.getElementById('approvalDetail').classList.remove('hidden');} function decision(result){if(currentRole!=='director'){alert('No permission');return;}document.getElementById('approvalResult').innerHTML=''+result+' · Director decision recorded in this demo.';document.getElementById('approvalDetail').classList.add('hidden');} const projectRequests=[]; let selectedProjectRequest=-1; let manualEntry=false; const bqCategories=['Preliminaries','Demolition','Earthworks','Concrete','Masonry / Brickwork','Plastering','Waterproofing','Tiling','Ceiling','Painting','Carpentry','Doors & Windows','Electrical','Plumbing','Roofing','External Works','Others']; const defaultBQTemplates=[ {name:'Full House Renovation',items:[{category:'Preliminaries',description:'Site protection, setting out and general preliminaries',unit:'lot',qty:1,rate:0},{category:'Demolition',description:'Hack and remove existing finishes including disposal',unit:'m²',qty:1,rate:0},{category:'Masonry / Brickwork',description:'Supply and construct brick wall including mortar',unit:'m²',qty:1,rate:0},{category:'Plastering',description:'Cement sand plaster to wall surfaces',unit:'m²',qty:1,rate:0},{category:'Waterproofing',description:'Apply waterproofing system to wet areas',unit:'m²',qty:1,rate:0},{category:'Tiling',description:'Supply and lay floor tiles with adhesive and grout',unit:'m²',qty:1,rate:0},{category:'Painting',description:'Prepare surfaces, undercoat and finishing coats',unit:'m²',qty:1,rate:0},{category:'Electrical',description:'Supply and install power socket point',unit:'point',qty:1,rate:0},{category:'Plumbing',description:'Supply and install water piping',unit:'m',qty:1,rate:0}]}, {name:'Office Renovation',items:[{category:'Preliminaries',description:'Site setup and protection',unit:'lot',qty:1,rate:0},{category:'Ceiling',description:'Supply and install suspended ceiling',unit:'m²',qty:1,rate:0},{category:'Electrical',description:'Supply and install lighting point',unit:'point',qty:1,rate:0},{category:'Painting',description:'Wall preparation and emulsion paint',unit:'m²',qty:1,rate:0}]} ]; let bqTemplates; try{const stored=JSON.parse(localStorage.getItem('amcon_bq_templates_v1'));bqTemplates=Array.isArray(stored)?stored:structuredClone(defaultBQTemplates);}catch(e){bqTemplates=JSON.parse(JSON.stringify(defaultBQTemplates));} function persistBQTemplates(){try{localStorage.setItem('amcon_bq_templates_v1',JSON.stringify(bqTemplates));}catch(e){document.getElementById('bqLibraryMessage').textContent='Browser storage unavailable; templates will not persist after refresh.';}} function renderBQTemplates(){const select=document.getElementById('projectBQTemplate');select.innerHTML=bqTemplates.map((t,i)=>``).join('');document.getElementById('bqLibraryRows').innerHTML=bqTemplates.map((t,i)=>`${safeText(t.name)}${t.items.length} `).join('')||'No templates';} function replaceProjectBQ(items){document.getElementById('bqRows').innerHTML='';items.forEach(x=>addBQRow({...x}));updateBQ();} function loadBQTemplate(){const i=Number(document.getElementById('projectBQTemplate').value);if(!bqTemplates[i])return;if(readBQ().some(x=>x.description.trim())&&!confirm('Replace the current project BQ with a copy of this template?'))return;replaceProjectBQ(bqTemplates[i].items);} function editBQTemplate(i){if(!['director','sales_manager'].includes(currentRole))return;const t=bqTemplates[i];if(!t)return;replaceProjectBQ(t.items);document.getElementById('bqTemplateName').value=t.name;showPage('projects');document.getElementById('addProjectForm').classList.remove('hidden');} function saveBQTemplate(){if(!['director','sales_manager'].includes(currentRole))return;const name=document.getElementById('bqTemplateName').value.trim(),items=readBQ();if(!name||!items.length||items.some(x=>!x.description.trim())){document.getElementById('bqLibraryMessage').textContent='Please enter a template name and complete the BQ rows in Add Project.';return;}const i=bqTemplates.findIndex(t=>t.name.toLowerCase()===name.toLowerCase());if(i>=0&&!confirm('Overwrite existing template '+name+'?'))return;const data={name,items:JSON.parse(JSON.stringify(items))};if(i>=0)bqTemplates[i]=data;else bqTemplates.push(data);persistBQTemplates();renderBQTemplates();document.getElementById('bqLibraryMessage').textContent='Template saved: '+name;} function deleteBQTemplate(i){if(!['director','sales_manager'].includes(currentRole)||!bqTemplates[i])return;if(!confirm('Delete template '+bqTemplates[i].name+'? Existing project BQs will not change.'))return;bqTemplates.splice(i,1);persistBQTemplates();renderBQTemplates();} function addBQRow(item={}){ const tr=document.createElement('tr'); tr.innerHTML=`RM 0`; document.getElementById('bqRows').appendChild(tr); tr.querySelectorAll('input').forEach(el=>el.addEventListener('input',updateBQ));updateBQ(); } function readBQ(){return [...document.querySelectorAll('#bqRows tr')].map(tr=>({category:tr.querySelector('.bq-category').value,description:tr.querySelector('.bq-description').value,unit:tr.querySelector('.bq-unit').value,qty:Number(tr.querySelector('.bq-qty').value),rate:Number(tr.querySelector('.bq-rate').value)}));} function updateBQ(){let total=0;document.querySelectorAll('#bqRows tr').forEach(tr=>{const amount=(Number(tr.querySelector('.bq-qty').value)||0)*(Number(tr.querySelector('.bq-rate').value)||0);tr.querySelector('.bq-amount').textContent=money(amount);total+=amount;});document.getElementById('bqTotal').textContent=money(total);} function openManualProject(){if(!['director','sales_manager'].includes(currentRole))return;manualEntry=true;document.getElementById('addProjectForm').classList.remove('hidden');document.getElementById('projectFormTitle').textContent='Manual Project Entry';document.getElementById('manualEntryNotice').classList.remove('hidden');document.getElementById('projectSubmitButton').textContent='Create Project Directly';} function resetProjectMode(){manualEntry=false;document.getElementById('projectFormTitle').textContent='New Project';document.getElementById('manualEntryNotice').classList.add('hidden');document.getElementById('projectSubmitButton').textContent=currentRole==='sales'?'Submit for Approval':'Create Project';} function generateQuotationPDF(quoteData=null){ const items=(quoteData?quoteData.bq:readBQ()).filter(x=>x.description.trim()); if(!items.length){alert('Please add at least one BQ item.');return;} const name=quoteData?quoteData.name:document.getElementById('newProjectName').value.trim()||'Project'; const client=quoteData?quoteData.client:document.getElementById('newClient').value.trim()||'Customer'; const address=quoteData?quoteData.location:document.getElementById('newLocation').value.trim(); const mode=confirm('OK = Detailed Quotation (item rates). Cancel = Summary Quotation (category totals).'); const byCategory={};items.forEach(x=>{(byCategory[x.category]??=[]).push(x);}); const total=items.reduce((v,x)=>v+x.qty*x.rate,0); const rows=Object.entries(byCategory).map(([cat,list])=>{ const subtotal=list.reduce((v,x)=>v+x.qty*x.rate,0); return `${safeText(cat)}`+ (mode?list.map(x=>`${safeText(x.description)}${safeText(x.unit)}${x.qty}${money(x.rate)}${money(x.qty*x.rate)}`).join(''):'')+ `${mode?'Subtotal':'Category Total'}${money(subtotal)}`; }).join(''); const doc=`AMCON Quotation - ${safeText(name)}
Amcon Development Sdn Bhd
Registration No.: 201401032075 (1108159-H)
${mode?'DETAILED':'SUMMARY'} QUOTATION
Client Name:${safeText(client)}
Quotation No.:${safeText(quoteData?.number||'DRAFT')}
Project:${safeText(name)}
Date:${safeText(quoteData?.date||new Date().toLocaleDateString('en-MY'))}
Project Location:${safeText(address)}
Validity:${safeText(quoteData?.validity||30)} days
${(mode?['Work Description','Unit','Qty','Rate','Amount']:['Category / Description','Amount']).map(x=>'').join('')}${rows}
'+x+'
GRAND TOTAL${money(total)}
Payment Terms
${safeText(quoteData?.terms||'Subject to final agreed contract and billing schedule.')}

PAYMENT / BANK DETAILS

Account Name: Amcon Development Sdn Bhd

Registration No.: 201401032075 (1108159-H)

Bank: CIMB

Account No.: 8008242443

For AMCON DEVELOPMENT SDN. BHD.
Authorized Signature / Company Stamp
Name: ___________________
Date: ___________________
Customer Acceptance
Customer Signature
Name: ___________________
Date: ___________________
AMCON DEVELOPMENT SDN. BHD.${safeText(quoteData?.number||'DRAFT')} · Customer Quotation
`; const w=window.open('','_blank');if(!w){alert('Please allow pop-ups to generate the quotation.');return;}w.document.write(doc);w.document.close();recordGeneratedDocument('Quotation',quoteData?.number||'DRAFT',client,name,total,doc); } function clearValidation(scope){ const root=document.querySelector(scope);if(!root)return; root.querySelectorAll('.validation-error').forEach(e=>e.classList.remove('validation-error')); root.querySelectorAll('.validation-hint').forEach(e=>e.remove()); } function flagRequired(el,message){ if(!el)return false; el.classList.add('validation-error'); const hint=document.createElement('span');hint.className='validation-hint';hint.textContent=message; el.insertAdjacentElement('afterend',hint); return true; } function validateFields(scope,fields,output){ clearValidation(scope);let first=null,errors=[]; fields.forEach(([id,label,check])=>{const el=document.getElementById(id);if(!el)return; const valid=check?check(el):!!String(el.value).trim(); if(!valid){flagRequired(el,label+' 为必填或格式不正确');first=first||el;errors.push(label);} }); if(errors.length){document.getElementById(output).textContent='请填写红色标示的必填资料:'+errors.join('、');first.focus();first.scrollIntoView({block:'center',behavior:'smooth'});return false;} return true; } function validateBQRows(selector,output){ let first=null,errors=0; document.querySelectorAll(selector+' tr').forEach((tr,i)=>{ const desc=tr.querySelector('input[class*="desc"],textarea[class*="desc"]')||tr.querySelectorAll('input')[1]; const qty=tr.querySelector('input[class*="qty"]'); const rate=tr.querySelector('input[class*="rate"]'); [[desc,el=>!!el.value.trim(),'施工内容'],[qty,el=>Number(el.value)>0,'数量'],[rate,el=>el.value.trim()!==''&&Number(el.value)>=0,'单价']].forEach(([el,test,label])=>{ if(el&&!test(el)){flagRequired(el,'第 '+(i+1)+' 行 '+label+' 必填');first=first||el;errors++;} }); }); if(errors){document.getElementById(output).textContent='BQ 有 '+errors+' 项未填写或无效,请检查红色格子。';first.focus();return false;} return true; } function createProject(){ if(!['sales','director','sales_manager'].includes(currentRole))return; const name=document.getElementById('newProjectName').value.trim(),client=document.getElementById('newClient').value.trim(); const value=Number(document.getElementById('newValue').value); if(!validateFields('#addProjectForm',[ ['newProjectName','Project Name'],['newClient','Client'],['newLocation','Project Location'], ['newValue','Contract Value',e=>e.value.trim()!==''&&Number(e.value)>0] ],'newProjectMsg'))return; if(!validateBQRows('#bqRows','newProjectMsg'))return; if(!name||!client||!Number.isFinite(value)||value<=0){document.getElementById('newProjectMsg').textContent='请填写项目名称、客户和有效合约金额。';return;} const billing=['bDeposit','bClaim1','bClaim2','bRetention'].map(id=>Number(document.getElementById(id).value)); if(billing.some(n=>!Number.isFinite(n)||n<0)||billing.reduce((a,b)=>a+b,0)!==100){document.getElementById('newProjectMsg').textContent='收费比例必须合计 100%。';return;} const bq=readBQ();if(bq.some(x=>!x.description.trim()||x.qty<=0||x.rate<0)){document.getElementById('newProjectMsg').textContent='请填写每个 BQ 项目的施工内容、有效数量及单价。';return;} const req={name,client,value,bq,location:document.getElementById('newLocation').value,scope:document.getElementById('newScope').value,supervisor:document.getElementById('newSupervisor').value,billing:currentRole==='sales'?[40,30,20,10]:billing,status:currentRole==='sales'?'Pending Approval':'Approved',note:'',submittedBy:currentRole}; projectRequests.push(req); document.getElementById('newProjectMsg').textContent=req.status==='Pending Approval'?'已提交 Sales Manager 审批,批准前不会加入正式项目。':'项目已建立(演示)。'; renderProjectApprovals(); } function renderProjectApprovals(){ const rows=document.getElementById('projectApprovalRows');if(!rows)return; rows.innerHTML=projectRequests.length?projectRequests.map((r,i)=>`${safeText(r.name)}${safeText(r.client)}${money(r.value)}${safeText(r.status)}${currentRole==='sales_manager'?``:'—'}`).join(''):'No submissions yet. Switch to Sales to submit a project.'; const approved=document.getElementById('approvedNewProjects');approved.innerHTML=projectRequests.filter(r=>r.status==='Approved').map((r,i)=>`NEW-${i+1}${safeText(r.client)}${money(r.value)}0%${r.billing.join('/')}`).join(''); } function viewProjectRequest(i){if(currentRole!=='sales_manager')return;const r=projectRequests[i];if(!r)return;selectedProjectRequest=i; const detail=document.getElementById('projectApprovalDetail');detail.classList.remove('hidden');detail.innerHTML=`

${safeText(r.name)} · ${safeText(r.status)}

Client: ${safeText(r.client)} · Contract: ${money(r.value)}

Location: ${safeText(r.location)}

Scope: ${safeText(r.scope)}

BQ Work Items

${(r.bq||[]).map(x=>``).join('')}
CategoryDescriptionQtyUnitRateAmount
${safeText(x.category)}${safeText(x.description)}${x.qty}${safeText(x.unit)}${money(x.rate)}${money(x.qty*x.rate)}

Supervisor: ${safeText(r.supervisor)}

Billing: ${r.billing.join('% / ')}%

`; } function decideProject(status){if(currentRole!=='sales_manager'||selectedProjectRequest<0)return;const r=projectRequests[selectedProjectRequest];if(r.status==='Approved'||r.status==='Rejected')return;r.status=status;r.note=document.getElementById('projectReviewNote').value;document.getElementById('projectApprovalDetail').classList.add('hidden');selectedProjectRequest=-1;renderProjectApprovals();} function submitSiteProgress(){const pct=Number(document.getElementById('siteProgress').value);if(pct<0||pct>100){document.getElementById('siteSubmitMsg').textContent='进度必须介于 0 至 100%。';return;}document.getElementById('siteSubmitMsg').textContent='进度 '+pct+'% 已提交至待审批队列(演示)。照片及记录在正式版本会上传至项目档案。';} renderBQTemplates();addBQRow({category:'Demolition',description:'Hack and remove existing wall finishes including disposal',unit:'m²',qty:1,rate:0}); let activeProjectDetail=null; const demoProjectData=[ {name:'Residential Renovation A',client:'Tan Family',location:'Kuala Lumpur',value:200000,bq:[{category:'Masonry / Brickwork',description:'Brickwork and cement mortar',unit:'m²',qty:100,rate:80},{category:'Painting',description:'Interior painting',unit:'m²',qty:300,rate:12}]}, {name:'Commercial Unit B',client:'ABC Sdn Bhd',location:'Selangor',value:350000,bq:[{category:'Ceiling',description:'Suspended ceiling',unit:'m²',qty:150,rate:65}]}, {name:'House Extension C',client:'Lee Family',location:'Selangor',value:120000,bq:[{category:'Concrete',description:'Reinforced concrete works',unit:'m³',qty:20,rate:550}]} ]; function approvedProjects(){return [...demoProjectData,...projectRequests.filter(r=>r.status==='Approved')];} function openProjectDetail(index){if(currentRole==='site'||currentRole==='operation_manager')return;activeProjectDetail=approvedProjects()[index];if(!activeProjectDetail)return;const p=activeProjectDetail;document.getElementById('detailTitle').textContent=p.name;document.getElementById('detailInfo').innerHTML=`

Client: ${safeText(p.client)}   Location: ${safeText(p.location||'—')}

`;document.getElementById('detailBQRows').innerHTML=p.bq.map((x,i)=>`${bqItemCode(i)}${safeText(x.category)}${safeText(x.description)}${safeText(x.unit)}${x.qty}${money(x.rate)}${money(x.qty*x.rate)}`).join('');document.getElementById('detailBQTotal').textContent='BQ Total: '+money(p.bq.reduce((a,x)=>a+x.qty*x.rate,0));showPage('projectdetail');renderProjectFinance();} const PROJECT_EXPENSE_KEY='amcon_project_expenses_v1'; function getProjectExpenses(){try{return JSON.parse(localStorage.getItem(PROJECT_EXPENSE_KEY)||'[]')||[];}catch(e){return [];}} function projectFinanceKey(p){return p?.id||p?.name||'';} function currentProjectExpenses(){return getProjectExpenses().filter(e=>e.projectKey===projectFinanceKey(activeProjectDetail));} function financeCurrency(n){return 'RM '+(Number(n)||0).toLocaleString('en-MY',{minimumFractionDigits:2,maximumFractionDigits:2});} const SUPPLIER_PAYMENTS_KEY='amcon_supplier_payments_v1'; function getSupplierPayments(){try{return JSON.parse(localStorage.getItem(SUPPLIER_PAYMENTS_KEY)||'[]')||[];}catch(e){return [];}} function expensePayments(e){return getSupplierPayments().filter(x=>x.expenseId===e.id);} function expensePaidTotal(e){return Number(e.paid||0)+expensePayments(e).reduce((a,x)=>a+Number(x.amount||0),0);} function renderProjectFinance(){ const p=activeProjectDetail,stats=document.getElementById('projectFinanceStats'),rows=document.getElementById('projectExpenseRows');if(!p||!stats||!rows)return; const records=currentProjectExpenses(),cost=records.reduce((a,e)=>a+Number(e.amount||0),0),paid=records.reduce((a,e)=>a+expensePaidTotal(e),0); const vo=typeof getVORecords==='function'?getVORecords().filter(v=>v.project===p.name&&v.status==='Approved').reduce((a,v)=>a+Number(v.amount||0),0):0; const contract=Number(p.value||0)+vo; const ledger=typeof projectLedger!=='undefined'?projectLedger.find(x=>x.name===p.name):null; const collected=ledger?Number(ledger.verifiedReceipts||0):null; const boxes=[['Revised Contract',financeCurrency(contract)],['Verified Collected',collected===null?'Not linked':financeCurrency(collected)],['Uncollected Contract',collected===null?'Not linked':financeCurrency(Math.max(0,contract-collected))],['Committed / Recorded Costs',financeCurrency(cost)],['Supplier Paid To Date',financeCurrency(paid)],['Supplier Still To Pay',financeCurrency(Math.max(0,cost-paid))],['Expected Gross Profit',financeCurrency(contract-cost)],['Cash Position (Collected − Paid)',collected===null?'Not linked':financeCurrency(collected-paid)]]; stats.innerHTML=boxes.map(([label,value])=>`
${label}
${value}
`).join(''); const chart=document.getElementById('projectFinanceChart');if(chart){ const profit=contract-cost,unpaid=Math.max(0,cost-paid),remaining=Math.max(0,contract-cost); const donut=(title,centerValue,parts,note)=>{ const positive=parts.map(x=>({...x,value:Math.max(0,x.value)}));const total=positive.reduce((n,x)=>n+x.value,0); let offset=0;const stops=positive.map(x=>{const from=offset;offset+=total?x.value/total*100:0;return `${x.color} ${from.toFixed(3)}% ${offset.toFixed(3)}%`;}); const bg=total>0?`conic-gradient(${stops.join(',')})`:'#e4eaf0'; return `
${title}
${title==='Contract Allocation'?'Contract Value':'Committed Costs'}${financeCurrency(centerValue)}
${positive.map(x=>`
${x.label}${financeCurrency(x.value)}
`).join('')}

${note}

`; }; chart.innerHTML=`
${donut('Contract Allocation',contract,[{label:'Committed Costs',value:cost,color:'#d18b25'},{label:'Expected Gross Profit',value:remaining,color:'#238568'}],'Expected profit = revised contract − committed costs. '+(profit<0?'Cost exceeds contract by '+financeCurrency(-profit)+'.':''))}${donut('Supplier Payments',cost,[{label:'Paid',value:paid,color:'#1b4b77'},{label:'Unpaid',value:unpaid,color:'#bc5360'}],'Supplier payments reduce unpaid balance, not the committed cost again.')}
`; } rows.innerHTML=records.map(e=>{const paidAmount=expensePaidTotal(e),unpaid=Math.max(0,Number(e.amount)-paidAmount);return `${safeText(e.date)}
${safeText(e.invoice)}
${safeText(e.supplier)}
${safeText(e.category)}
${financeCurrency(e.amount)}${financeCurrency(paidAmount)}${financeCurrency(unpaid)}${unpaid<0.005?'Paid':paidAmount>0?'Partially Paid':'Unpaid'}
${expensePayments(e).length} payment(s)
${e.fileData?``:'—'}`}).join('')||'No expenses recorded for this project.'; const sel=document.getElementById('supplierPaymentExpense');if(sel){const previous=sel.value;sel.innerHTML=records.filter(e=>Number(e.amount)-expensePaidTotal(e)>0.005).map(e=>``).join('');if([...sel.options].some(o=>o.value===previous))sel.value=previous;} const history=document.getElementById('supplierPaymentRows');if(history)history.innerHTML=getSupplierPayments().filter(x=>records.some(e=>e.id===x.expenseId)).map(x=>{const e=records.find(e=>e.id===x.expenseId);return `${safeText(x.date)}${safeText(e.supplier)}
${safeText(e.invoice)}
${safeText(x.stage)}${financeCurrency(x.amount)}${safeText(x.reference||'—')}${x.fileData?``:'—'}`}).join('')||'No supplier payments recorded.'; const canEdit=['director','finance'].includes(currentRole);document.querySelectorAll('#projectFinancePanel input,#projectFinancePanel select,#projectFinancePanel textarea,#projectFinancePanel button.primary').forEach(x=>x.disabled=!canEdit); } function openSupplierPaymentProof(id){const x=getSupplierPayments().find(x=>x.id===id);if(!x?.fileData)return;const w=window.open('','_blank');if(!w){alert('Allow pop-ups to view proof.');return;}w.document.write('Payment Proof');w.document.close();} function addSupplierPayment(){ if(!['director','finance'].includes(currentRole))return; const get=id=>document.getElementById(id).value.trim(),expense=currentProjectExpenses().find(x=>x.id===get('supplierPaymentExpense')),amount=Number(get('supplierPaymentAmount')),msg=document.getElementById('supplierPaymentMessage'); if(!expense||!(amount>0)||!get('supplierPaymentDate')||amount>Number(expense.amount)-expensePaidTotal(expense)+0.001){msg.textContent='Select a bill, enter date and an amount not exceeding its outstanding balance.';return;} const file=document.getElementById('supplierPaymentProof').files[0];if(file&&file.size>700000){msg.textContent='Demo proof limit: 700 KB.';return;} const save=fileData=>{const list=getSupplierPayments();list.unshift({id:String(Date.now())+'-'+Math.random().toString(36).slice(2,7),expenseId:expense.id,amount,date:get('supplierPaymentDate'),stage:get('supplierPaymentStage'),reference:get('supplierPaymentReference'),fileData,createdAt:new Date().toISOString()});try{localStorage.setItem(SUPPLIER_PAYMENTS_KEY,JSON.stringify(list));['supplierPaymentAmount','supplierPaymentDate','supplierPaymentReference','supplierPaymentProof'].forEach(id=>document.getElementById(id).value='');msg.textContent='Payment recorded. Supplier outstanding and project chart updated.';renderProjectFinance();}catch(e){msg.textContent='Browser storage full; payment not saved.';}}; if(file){const r=new FileReader();r.onload=()=>save(r.result);r.onerror=()=>msg.textContent='Cannot read payment proof.';r.readAsDataURL(file);}else save(''); } function openExpenseAttachment(id){const e=currentProjectExpenses().find(x=>x.id===id);if(e?.fileData){const w=window.open('','_blank');if(!w){alert('Allow pop-ups to view attachment.');return;}w.document.write('Supplier Document');w.document.close();}} function addProjectExpense(){ if(!['director','finance'].includes(currentRole)){alert('Finance or Director permission required.');return;} const val=id=>document.getElementById(id).value.trim(),amount=Number(val('expenseAmount')),paid=Number(val('expensePaid')||0),msg=document.getElementById('expenseMessage'); if(!activeProjectDetail||!val('expenseSupplier')||!val('expenseInvoice')||!val('expenseDate')||!(amount>0)||paid<0||paid>amount){msg.textContent='Fill required fields; paid amount must be between zero and invoice amount.';return;} const records=getProjectExpenses();if(records.some(e=>e.projectKey===projectFinanceKey(activeProjectDetail)&&e.supplier.toLowerCase()===val('expenseSupplier').toLowerCase()&&e.invoice.toLowerCase()===val('expenseInvoice').toLowerCase())){msg.textContent='This supplier invoice number is already recorded for this project.';return;} const file=document.getElementById('expenseFile').files[0];if(file&&file.size>700000){msg.textContent='Demo attachment limit: 700 KB. Please use a smaller file.';return;} const save=fileData=>{records.unshift({id:String(Date.now()),projectKey:projectFinanceKey(activeProjectDetail),category:val('expenseCategory'),supplier:val('expenseSupplier'),invoice:val('expenseInvoice'),date:val('expenseDate'),due:val('expenseDue'),amount,paid,paidDate:val('expensePaidDate'),reference:val('expenseReference'),notes:val('expenseNotes'),fileName:file?.name||'',fileData,createdAt:new Date().toISOString()});try{localStorage.setItem(PROJECT_EXPENSE_KEY,JSON.stringify(records));msg.textContent='Expense saved to this browser.';['expenseSupplier','expenseInvoice','expenseAmount','expenseDate','expenseDue','expensePaidDate','expenseReference','expenseNotes'].forEach(id=>document.getElementById(id).value='');document.getElementById('expensePaid').value='0';document.getElementById('expenseFile').value='';renderProjectFinance();}catch(e){msg.textContent='Browser storage full. Expense was not saved. Please export existing records or use smaller attachments.';}}; if(file){const reader=new FileReader();reader.onload=()=>save(reader.result);reader.onerror=()=>msg.textContent='Unable to read attachment.';reader.readAsDataURL(file);}else save(''); } function exportProjectExpenses(){const rows=[['Date','Supplier','Category','Invoice No','Amount','Paid','Unpaid','Due Date','Payment Date','Payment Reference','Notes'],...currentProjectExpenses().map(e=>[e.date,e.supplier,e.category,e.invoice,e.amount,expensePaidTotal(e),e.amount-expensePaidTotal(e),e.due,e.paidDate,e.reference,e.notes])];const csv='\uFEFF'+rows.map(r=>r.map(x=>'"'+String(x??'').replace(/"/g,'""')+'"').join(',')).join('\r\n');const a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv;charset=utf-8'}));a.href=url;a.download=(activeProjectDetail?.name||'project').replace(/[^a-z0-9_-]/gi,'_')+'_expenses.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function downloadProjectBQ(){if(!activeProjectDetail)return;const p=activeProjectDetail;const data=[['Category','Work Description','Unit','Qty','Rate (RM)','Amount (RM)'],...p.bq.map(x=>[x.category,x.description,x.unit,x.qty,x.rate,x.qty*x.rate])];const csv='\uFEFF'+data.map(r=>r.map(v=>'"'+String(v).replace(/"/g,'""')+'"').join(',')).join('\r\n');const url=URL.createObjectURL(new Blob([csv],{type:'text/csv;charset=utf-8'}));const a=document.createElement('a');a.href=url;a.download=p.name.replace(/[^a-z0-9_-]/gi,'_')+'_BQ.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function printProjectBQ(){ if(!activeProjectDetail)return; const p=activeProjectDetail; const bqTotal=p.bq.reduce((a,x)=>a+Number(x.qty)*Number(x.rate),0); const vos=getVORecords().filter(v=>v.project===p.name); const approvedVOs=vos.filter(v=>v.status==='Approved'); const voTotal=approvedVOs.reduce((a,v)=>a+Number(v.amount||0),0); const fmt=x=>money(x); const bqRows=p.bq.map((x,i)=>`${bqItemCode(i)}${safeText(x.category)}${safeText(x.description)}${safeText(x.unit)}${safeText(x.qty)}${fmt(x.rate)}${fmt(Number(x.qty)*Number(x.rate))}`).join(''); const voRows=vos.map(v=>`${safeText(v.number)}${safeText(v.bqCode)}${safeText(v.description)}${safeText(v.status||'Pending Approval')}${fmt(v.amount)}`).join(''); const doc=`${safeText(p.name)} - BQ with VO

AMCON DEVELOPMENT SDN BHD

Registration No.: 201401032075 (1108159-H)

PROJECT BILL OF QUANTITIES (BQ)

Project: ${safeText(p.name)}
Client: ${safeText(p.client)}
Location: ${safeText(p.location||'—')}

${bqRows}
BQ CodeCategoryDescriptionUnitQtyRate (RM)Amount (RM)
Original BQ Total${fmt(bqTotal)}

VARIATION ORDERS (VO) — ${vos.length} record(s)

${vos.length?`${voRows}
VO No.Original BQ CodeVariation DescriptionStatusVO Amount (RM)
`:'

No Variation Orders recorded for this project.

'}
Original BQ Total${fmt(bqTotal)}
Approved VO Total (+/-)${fmt(voTotal)}
Revised Total (BQ + Approved VO)${fmt(bqTotal+voTotal)}

Only Approved VOs are included in the revised total. Pending Approval and Rejected VOs are shown for reference only.

`; const w=window.open('','_blank');if(!w){alert('Please allow pop-ups to print the BQ.');return;} w.document.open();w.document.write(doc);w.document.close(); } function loadExampleQuotation(){ clearQuotationEditor(); document.getElementById('quoteName').value='Quotation for Wet Works – Epoxy Flooring'; document.getElementById('quoteClient').value='Teh (Sample)'; document.getElementById('quoteLocation').value='Sample project location'; document.getElementById('quoteTerms').value='Quotation valid for 30 days. Payment schedule subject to written agreement.'; replaceQuoteBQ([{category:'Flooring / Epoxy Works',description:'To supply labour, tools and materials to apply Outdoor UV-Resistant Epoxy & PU Flooring System (Smooth Finish, 3-Color Linear Zoning, without anti-slip aggregates) for approx. 3,610 sq. ft.',unit:'Sqft',qty:3610,rate:10.5}]); document.getElementById('quoteMessage').textContent='Sample quotation loaded. Edit any field or click Generate PDF Preview. Sample data only.'; } function previewQuotationEditor(){ const items=readQuoteBQ(), name=document.getElementById('quoteName').value.trim(), client=document.getElementById('quoteClient').value.trim(); if(!name||!client||!items.length||items.some(x=>!x.description.trim()||!(x.qty>0)||x.rate<0||!Number.isFinite(x.rate))){document.getElementById('quoteMessage').textContent='Please complete Project Name, Customer and valid BQ items before generating PDF.';return;} generateQuotationPDF({name,client,location:document.getElementById('quoteLocation').value,bq:items,number:editingQuoteIndex===null?(pendingQuotationNumber||(pendingQuotationNumber=nextDocumentNumber('Quotation'))):quotations[editingQuoteIndex].number,date:document.getElementById('quoteDate').value,validity:document.getElementById('quoteValidity').value,terms:document.getElementById('quoteTerms').value}); } const quotations=[];let editingQuoteIndex=null; function quotationTotal(items){return items.reduce((sum,x)=>sum+Number(x.qty)*Number(x.rate),0);} function renderQuoteSources(){const sel=document.getElementById('quoteProject');if(!sel)return;const old=sel.value;sel.innerHTML=''+approvedProjects().map((p,i)=>``).join('');if([...sel.options].some(o=>o.value===old))sel.value=old;} function prefillQuotationSource(){const v=document.getElementById('quoteProject').value;if(v==='')return;const p=approvedProjects()[Number(v)];if(!p)return;document.getElementById('quoteName').value=p.name;document.getElementById('quoteClient').value=p.client;document.getElementById('quoteLocation').value=p.location||'';replaceQuoteBQ(p.bq);} function addQuoteBQRow(item={}){const tr=document.createElement('tr');tr.innerHTML=`RM 0`;document.getElementById('quoteBQRows').appendChild(tr);tr.querySelectorAll('input,textarea,select').forEach(el=>el.addEventListener('input',updateQuoteBQ));updateQuoteBQ();} function readQuoteBQ(){return [...document.querySelectorAll('#quoteBQRows tr')].map(tr=>({category:tr.querySelector('.qb-category').value,description:tr.querySelector('.qb-description').value,unit:tr.querySelector('.qb-unit').value,qty:Number(tr.querySelector('.qb-qty').value),rate:Number(tr.querySelector('.qb-rate').value)}));} function updateQuoteBQ(){document.querySelectorAll('#quoteBQRows tr').forEach(tr=>tr.querySelector('.qb-amount').textContent=money(Number(tr.querySelector('.qb-qty').value)*Number(tr.querySelector('.qb-rate').value)));document.getElementById('quoteBQTotal').textContent='BQ Total: '+money(quotationTotal(readQuoteBQ()));} function replaceQuoteBQ(items){document.getElementById('quoteBQRows').innerHTML='';(items||[]).forEach(x=>addQuoteBQRow(x));updateQuoteBQ();} function clearQuotationEditor(){editingQuoteIndex=null;pendingQuotationNumber=null;document.getElementById('quoteProject').value='';['quoteName','quoteClient','quoteLocation'].forEach(id=>document.getElementById(id).value='');document.getElementById('quoteDate').value=new Date().toISOString().slice(0,10);document.getElementById('quoteValidity').value='30';document.getElementById('quoteTerms').value='Subject to agreed contract terms.';document.getElementById('saveQuoteButton').textContent='Save Quotation';document.getElementById('quoteMessage').textContent='';replaceQuoteBQ([]);addQuoteBQRow();} function editQuotation(i){pendingQuotationNumber=null;const q=quotations[i];if(!q)return;editingQuoteIndex=i;document.getElementById('quoteProject').value='';document.getElementById('quoteName').value=q.name;document.getElementById('quoteClient').value=q.client;document.getElementById('quoteLocation').value=q.location||'';document.getElementById('quoteDate').value=q.date;document.getElementById('quoteValidity').value=q.validity;document.getElementById('quoteTerms').value=q.terms;replaceQuoteBQ(q.bq);document.getElementById('saveQuoteButton').textContent='Update '+q.number;document.getElementById('quoteMessage').textContent='Editing '+q.number;showPage('quotations');} function createQuotation(){if(!['director','sales_manager','sales','finance'].includes(currentRole))return;const name=document.getElementById('quoteName').value.trim(),client=document.getElementById('quoteClient').value.trim(),bq=readQuoteBQ();if(!name||!client||!bq.length||bq.some(x=>!x.description.trim()||!Number.isFinite(x.qty)||x.qty<=0||!Number.isFinite(x.rate)||x.rate<0)){document.getElementById('quoteMessage').textContent='请填写项目、客户及有效 BQ 项目。';return;}if(!validateFields('#quotations',[ ['quoteName','Project Name'],['quoteClient','Customer'],['quoteLocation','Project Location'], ['quoteDate','Quotation Date'],['quoteValidity','Validity',e=>e.value.trim()!==''&&Number(e.value)>0] ],'quoteMessage'))return; if(!validateBQRows('#quoteBQRows','quoteMessage'))return; const prior=editingQuoteIndex===null?null:quotations[editingQuoteIndex];const q={name,client,location:document.getElementById('quoteLocation').value,bq:bq.map(x=>({...x})),number:prior?.number||pendingQuotationNumber||nextDocumentNumber('Quotation'),date:document.getElementById('quoteDate').value||new Date().toISOString().slice(0,10),validity:document.getElementById('quoteValidity').value,terms:document.getElementById('quoteTerms').value,status:prior?.status||'Draft'};if(editingQuoteIndex===null){quotations.push(q);editingQuoteIndex=quotations.length-1;}else quotations[editingQuoteIndex]=q;document.getElementById('quoteMessage').textContent=q.number+' saved (demo).';renderQuotations();} function setQuotationStatus(i,status){if(!['director','sales_manager'].includes(currentRole))return;quotations[i].status=status;renderQuotations();} function convertQuotationToProject(i){if(!['director','sales_manager','sales'].includes(currentRole))return;const q=quotations[i];if(!q||q.status!=='Accepted'){alert('Quotation must be marked Accepted by Sales Manager before conversion.');return;}document.getElementById('newProjectName').value=q.name;document.getElementById('newClient').value=q.client;document.getElementById('newLocation').value=q.location||'';document.getElementById('newValue').value=quotationTotal(q.bq);replaceProjectBQ(q.bq.map(x=>({...x})));document.getElementById('addProjectForm').classList.remove('hidden');document.getElementById('newProjectMsg').textContent='Imported from '+q.number+'. Please review details and submit. Sales submissions still require Sales Manager approval.';showPage('projects');document.getElementById('addProjectForm').scrollIntoView({behavior:'smooth',block:'start'});} function renderQuotations(){renderQuoteSources();const body=document.getElementById('quotationRows');if(!body)return;body.innerHTML=quotations.length?quotations.map((q,i)=>`${safeText(q.number)}${safeText(q.client)}
${safeText(q.name)}
${safeText(q.date)}${money(quotationTotal(q.bq))}${safeText(q.status)} ${['director','sales_manager'].includes(currentRole)?``:''} ${q.status==='Accepted'&&['director','sales_manager','sales'].includes(currentRole)?``:''}`).join(''):'No quotations created yet.';} // Only show actionable pending approvals to the role responsible for them. let demoProgressApprovalPending=true; function pendingApprovalCounts(role){ const count=(items,predicate)=>items.filter(predicate).length; const pendingVO=count(getVORecords(),v=>(v.status||'Pending Approval')==='Pending Approval'); const pendingProject=count(projectRequests,r=>r.status==='Pending Approval'||r.status==='Pending'||r.status==='Submitted'||r.status==='Pending Sales Manager Approval'); const pendingClaims=count(expenseClaims,x=>x.status==='Pending Review'); const unpaidClaims=count(expenseClaims,x=>x.status==='Approved / Unpaid'); const counts={}; if(role==='director'){ counts.variationorders=pendingVO; counts.workflow=demoProgressApprovalPending?1:0; counts.purchaserequests=count(purchaseRequests,x=>x.status==='Pending Director Approval'); }else if(role==='sales_manager'){ counts.projectapprovals=pendingProject; counts.variationorders=pendingVO; }else if(role==='operation_manager'){ counts.expenseclaims=pendingClaims; counts.purchaserequests=count(purchaseRequests,x=>x.status==='Pending Operation Review'); }else if(role==='finance'){ counts.receipts=count(pendingReceipts,x=>x.status!=='Verified'); counts.expenseclaims=unpaidClaims; counts.purchaserequests=count(purchaseRequests,x=>x.status==='Approved for Payment'); } return counts; } function refreshApprovalBadges(){ const counts=pendingApprovalCounts(currentRole); document.querySelectorAll('#sideNav button[data-page]').forEach(btn=>{ const page=btn.dataset.page,n=counts[page]||0; let badge=btn.querySelector('.approval-count'); if(n>0&&!btn.classList.contains('hidden')){ if(!badge){badge=document.createElement('span');badge.className='approval-count';btn.appendChild(badge);} badge.textContent=n;badge.title=n+' item(s) require your action';badge.setAttribute('aria-label',n+' pending approvals or payments'); }else if(badge)badge.remove(); }); document.querySelectorAll('#sideNav .nav-group').forEach(group=>{ const total=Array.from(group.querySelectorAll('button[data-page]')).reduce((sum,b)=>sum+(b.classList.contains('hidden')?0:(counts[b.dataset.page]||0)),0); const parent=group.querySelector('.nav-parent');if(!parent)return; let badge=parent.querySelector('.approval-count'); if(total>0&&!group.classList.contains('hidden')){ if(!badge){badge=document.createElement('span');badge.className='approval-count';const arrow=parent.querySelector('span');parent.insertBefore(badge,arrow||null);} badge.textContent=total;badge.title=total+' items require your attention'; }else if(badge)badge.remove(); }); } // Refresh counts whenever an approval, receipt, or purchase changes status. ['setRole','setVOStatus','createVO','renderProjectApprovals','renderExpenseClaims','renderPurchaseRequests','renderReceipts','verifyReceipt','decision'].forEach(name=>{ const original=window[name];if(typeof original!=='function')return; window[name]=function(...args){const result=original.apply(this,args);if(name==='decision')demoProgressApprovalPending=false;refreshApprovalBadges();return result;}; }); const AMCON_FORECAST_KEY='amcon_cash_forecasts_v1',AMCON_BUDGET_KEY='amcon_budget_targets_v1',AMCON_DAILY_KEY='amcon_daily_reports_v1',AMCON_DEFECT_KEY='amcon_defect_tracker_v1',AMCON_DIRECTORY_KEY='amcon_supplier_directory_v1',AMCON_AUDIT_KEY='amcon_audit_log_v1'; function amconRead(key){try{const v=JSON.parse(localStorage.getItem(key)||'[]');return Array.isArray(v)?v:[];}catch(e){return [];}} function amconWrite(key,data){try{localStorage.setItem(key,JSON.stringify(data));return true;}catch(e){alert('Browser storage is full; changes were not saved.');return false;}} function amconLog(action,details){const a=amconRead(AMCON_AUDIT_KEY);a.unshift({at:new Date().toISOString(),role:currentRole,action,details:String(details)});amconWrite(AMCON_AUDIT_KEY,a.slice(0,500));renderAuditLog();} function exportAuditLog(){const rows=amconRead(AMCON_AUDIT_KEY),csv=[['Timestamp','Role','Action','Details'],...rows.map(x=>[x.at,x.role,x.action,x.details])].map(row=>row.map(v=>'"'+String(v??'').replace(/"/g,'""')+'"').join(',')).join('\r\n');const a=document.createElement('a');a.href=URL.createObjectURL(new Blob(['\ufeff'+csv],{type:'text/csv;charset=utf-8'}));a.download='amcon-audit-log.csv';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),1000);} function renderAuditLog(){const t=document.getElementById('auditRows');if(t)t.innerHTML=amconRead(AMCON_AUDIT_KEY).map(x=>`${safeText(new Date(x.at).toLocaleString('en-MY'))}${safeText(x.role)}${safeText(x.action)}${safeText(x.details)}`).join('')||'No recorded changes yet.';} function amconProjectsSelect(id){const sel=document.getElementById(id);if(!sel)return;const old=sel.value;sel.innerHTML=approvedProjects().map((p,i)=>``).join('');if([...sel.options].some(o=>o.value===old))sel.value=old;} function amconProjectCost(p){return getProjectExpenses().filter(e=>e.projectKey===projectFinanceKey(p)).reduce((a,e)=>a+Number(e.amount||0),0);} function amconContract(p){return Number(p.value||0)+getVORecords().filter(v=>v.project===p.name&&v.status==='Approved').reduce((a,v)=>a+Number(v.amount||0),0);} function amconDonut(title,center,segments,note){const total=segments.reduce((a,x)=>a+Math.max(0,x.value),0);let pos=0;const stops=segments.map(x=>{const st=pos;pos+=total?Math.max(0,x.value)/total*100:0;return `${x.color} ${st}% ${pos}%`});return `
${title}
${safeText(title)}${financeCurrency(center)}
${segments.map(x=>`
${safeText(x.name)}${financeCurrency(x.value)}
`).join('')}

${note}

`;} function amconWithin(date,days){if(!date)return false;const now=new Date();now.setHours(0,0,0,0);const end=new Date(now);end.setDate(end.getDate()+days);const d=new Date(date+'T00:00:00');return d<=end;} function renderCashFlow(){const days=Number(document.getElementById('cashHorizon')?.value||30);amconProjectsSelect('forecastProject');const all=getProjectExpenses(),payments=getSupplierPayments();const entries=all.map(e=>{const p=approvedProjects().find(p=>projectFinanceKey(p)===e.projectKey);const paid=Number(e.paid||0)+payments.filter(x=>x.expenseId===e.id).reduce((a,x)=>a+Number(x.amount||0),0);return {...e,project:p?.name||e.projectKey,paid,unpaid:Math.max(0,Number(e.amount||0)-paid)};});const due=entries.filter(x=>x.unpaid>0.005&&amconWithin(x.due,days));const dueTotal=due.reduce((a,x)=>a+x.unpaid,0);const forecasts=amconRead(AMCON_FORECAST_KEY);const incoming=forecasts.filter(x=>amconWithin(x.date,days)).reduce((a,x)=>a+Number(x.amount||0),0);const allUnpaid=entries.reduce((a,x)=>a+x.unpaid,0);const overdue=entries.filter(x=>x.unpaid>0.005&&x.due&&new Date(x.due+'T00:00:00')a+x.unpaid,0);document.getElementById('cashFlowSummary').innerHTML=[['Expected Customer Receipts',incoming],['Supplier Payments Due',dueTotal],['Net Forecast (Expected − Due)',incoming-dueTotal],['All Supplier Unpaid',allUnpaid],['Already Overdue',overdue]].map(([label,val])=>`
${label}${financeCurrency(val)}
`).join('');document.getElementById('cashFlowDonut').innerHTML=amconDonut('Next '+days+' Days',incoming+dueTotal,[{name:'Expected Inflow',value:incoming,color:'#238568'},{name:'Supplier Due',value:dueTotal,color:'#bf5661'}],'Forecast is based on manual expected receipts and supplier due dates; not bank balance.');document.getElementById('cashFlowRows').innerHTML=entries.filter(x=>x.unpaid>0.005).sort((a,b)=>(a.due||'9999').localeCompare(b.due||'9999')).map(x=>`${safeText(x.project)}${safeText(x.supplier)}
${safeText(x.invoice)}
${safeText(x.due||'Not set')}${financeCurrency(x.amount)}${financeCurrency(x.paid)}${financeCurrency(x.unpaid)}${!x.due?'No due date':new Date(x.due+'T00:00:00')Overdue':amconWithin(x.due,days)?'Due in window':'Later'}`).join('')||'No outstanding supplier bills.';document.getElementById('forecastRows').innerHTML=forecasts.map(x=>`${safeText(x.project)}${safeText(x.date)}${financeCurrency(x.amount)}${safeText(x.notes)}`).join('')||'No forecasts recorded.';} function addCashForecast(){if(!['director','finance'].includes(currentRole))return;const p=approvedProjects()[Number(document.getElementById('forecastProject').value)],date=document.getElementById('forecastDate').value,amount=Number(document.getElementById('forecastAmount').value),notes=document.getElementById('forecastNotes').value.trim();if(!p||!date||!(amount>0)){document.getElementById('forecastMessage').textContent='Project, date and positive amount required.';return;}const a=amconRead(AMCON_FORECAST_KEY);a.unshift({id:String(Date.now()),project:p.name,date,amount,notes});if(amconWrite(AMCON_FORECAST_KEY,a)){amconLog('Customer receipt forecast',p.name+' / '+financeCurrency(amount));renderCashFlow();document.getElementById('forecastMessage').textContent='Forecast saved (not counted as collected).';}} function removeCashForecast(id){if(!['director','finance'].includes(currentRole))return;const a=amconRead(AMCON_FORECAST_KEY);const item=a.find(x=>x.id===id);if(amconWrite(AMCON_FORECAST_KEY,a.filter(x=>x.id!==id))){amconLog('Removed forecast',item?.project||id);renderCashFlow();}} function exportCashFlowCSV(){const headers=['Project','Supplier','Invoice','Due Date','Committed','Paid','Unpaid'];const data=getProjectExpenses().map(e=>{const paid=expensePaidTotal(e);return [e.projectKey,e.supplier,e.invoice,e.due,e.amount,paid,Math.max(0,e.amount-paid)]});const csv=[headers,...data].map(r=>r.map(v=>'"'+String(v??'').replace(/"/g,'""')+'"').join(',')).join('\r\n');const a=document.createElement('a');a.href=URL.createObjectURL(new Blob(['\ufeff'+csv],{type:'text/csv'}));a.download='amcon-supplier-due-payments.csv';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),1000);} function budgetFor(p){return amconRead(AMCON_BUDGET_KEY).find(x=>x.projectKey===projectFinanceKey(p));} function renderBudgets(){amconProjectsSelect('budgetProject');const t=document.getElementById('budgetRows');if(!t)return;t.innerHTML=approvedProjects().map(p=>{const target=budgetFor(p)?.amount,cost=amconProjectCost(p),variance=target==null?null:target-cost;return `${safeText(p.name)}${financeCurrency(amconContract(p))}${target==null?'Not set':financeCurrency(target)}${financeCurrency(cost)}${variance==null?'—':financeCurrency(variance)}${financeCurrency(amconContract(p)-cost)}${variance==null?'Set target':variance<0?'Over Budget':'Within Budget'}`}).join('');} function saveProjectBudget(){if(!['director','finance'].includes(currentRole))return;const p=approvedProjects()[Number(document.getElementById('budgetProject').value)],raw=document.getElementById('budgetAmount').value,amount=Number(raw),reason=document.getElementById('budgetReason').value.trim();if(!p||raw===''||!Number.isFinite(amount)||amount<0||!reason){document.getElementById('budgetMessage').textContent='Enter nonnegative budget and reason.';return;}const a=amconRead(AMCON_BUDGET_KEY).filter(x=>x.projectKey!==projectFinanceKey(p));a.push({projectKey:projectFinanceKey(p),amount,reason,updatedAt:new Date().toISOString()});if(amconWrite(AMCON_BUDGET_KEY,a)){amconLog('Budget updated',p.name+' / '+financeCurrency(amount)+' / '+reason);renderBudgets();if(activeProjectDetail)renderProjectFinance();document.getElementById('budgetMessage').textContent='Budget saved.';}} function renderDailyReports(){amconProjectsSelect('dailyProject');const t=document.getElementById('dailyRows');if(t)t.innerHTML=amconRead(AMCON_DAILY_KEY).map(x=>`${safeText(x.date)}${safeText(x.project)}${safeText(x.role)}${x.workers}${x.progress===''?'—':x.progress+'%'}${safeText(x.notes)}${x.photo?``:'—'}`).join('')||'No daily reports yet.';} function saveDailyReport(){if(!['site','operation_manager'].includes(currentRole))return;const p=approvedProjects()[Number(document.getElementById('dailyProject').value)],date=document.getElementById('dailyDate').value,workers=Number(document.getElementById('dailyWorkers').value),progress=document.getElementById('dailyProgress').value,notes=document.getElementById('dailyNotes').value.trim(),msg=document.getElementById('dailyMessage');if(!p||!date||!notes||workers<0||!Number.isFinite(workers)||(progress!==''&&(Number(progress)<0||Number(progress)>100))){msg.textContent='Project, date, notes and valid workers/progress required.';return;}const file=document.getElementById('dailyPhoto').files[0];if(file&&file.size>350000){msg.textContent='Demo photo limit is 350 KB.';return;}const save=photo=>{const a=amconRead(AMCON_DAILY_KEY);a.unshift({id:String(Date.now()),project:p.name,date,workers,progress,notes,role:currentRole,photo});if(amconWrite(AMCON_DAILY_KEY,a)){amconLog('Daily site report',p.name+' / '+date);renderDailyReports();msg.textContent='Daily report saved in this browser.';}};if(file){const r=new FileReader();r.onload=()=>save(r.result);r.readAsDataURL(file);}else save('');} function openDailyPhoto(id){const x=amconRead(AMCON_DAILY_KEY).find(x=>x.id===id);if(x?.photo){const w=window.open('','_blank');if(w){w.document.write('');w.document.close();}}} function renderDefects(){amconProjectsSelect('defectProject');const t=document.getElementById('defectRows');if(t)t.innerHTML=amconRead(AMCON_DEFECT_KEY).map(x=>`${safeText(x.project)}${safeText(x.date)}${safeText(x.due||'—')}${safeText(x.description)}${safeText(x.assignee||'—')}`).join('')||'No defects logged.';} function addDefect(){const p=approvedProjects()[Number(document.getElementById('defectProject').value)],date=document.getElementById('defectDate').value,due=document.getElementById('defectDue').value,assignee=document.getElementById('defectAssignee').value.trim(),description=document.getElementById('defectDescription').value.trim();if(!p||!date||!description){document.getElementById('defectMessage').textContent='Project, reported date and description required.';return;}const a=amconRead(AMCON_DEFECT_KEY);a.unshift({id:String(Date.now()),project:p.name,date,due,assignee,description,status:'Open'});if(amconWrite(AMCON_DEFECT_KEY,a)){amconLog('Defect logged',p.name+' / '+description);renderDefects();document.getElementById('defectMessage').textContent='Defect saved.';}} function changeDefectStatus(id,status){const a=amconRead(AMCON_DEFECT_KEY),x=a.find(x=>x.id===id);if(!x)return;x.status=status;if(amconWrite(AMCON_DEFECT_KEY,a))amconLog('Defect status',x.project+' / '+status);} function renderSupplierDirectory(){const t=document.getElementById('dirRows');if(!t)return;t.innerHTML=amconRead(AMCON_DIRECTORY_KEY).map(x=>{const commitments=getProjectExpenses().filter(e=>e.supplier.toLowerCase()===x.name.toLowerCase()).reduce((a,e)=>a+Number(e.amount||0),0);return `${safeText(x.name)}${safeText(x.category)}${safeText(x.contact)}${safeText(x.terms)}${financeCurrency(commitments)}`}).join('')||'No suppliers registered.';} function addSupplierDirectory(){if(!['director','finance'].includes(currentRole))return;const name=document.getElementById('dirName').value.trim(),category=document.getElementById('dirCategory').value,contact=document.getElementById('dirContact').value.trim(),terms=document.getElementById('dirTerms').value.trim(),a=amconRead(AMCON_DIRECTORY_KEY);if(!name||a.some(x=>x.name.toLowerCase()===name.toLowerCase())){document.getElementById('dirMessage').textContent='Enter a unique supplier name.';return;}a.unshift({name,category,contact,terms});if(amconWrite(AMCON_DIRECTORY_KEY,a)){amconLog('Supplier added',name);renderSupplierDirectory();document.getElementById('dirMessage').textContent='Supplier saved.';}} // Wrap existing successful saves: a change is logged only if the original action changes stored data. ['addProjectExpense','addSupplierPayment','setVOStatus','createVO','verifyReceipt','addCashForecast'].forEach(name=>{if(name==='addCashForecast')return;const old=window[name];if(typeof old!=='function')return;window[name]=function(...args){const before=JSON.stringify([getProjectExpenses(),getSupplierPayments(),getVORecords()]);const out=old.apply(this,args);const after=JSON.stringify([getProjectExpenses(),getSupplierPayments(),getVORecords()]);if(before!==after){amconLog(name,'Financial / approval record changed');if(document.getElementById('cashflow')&&!document.getElementById('cashflow').classList.contains('hidden'))renderCashFlow();}return out;};}); const amconOriginalShowPage=showPage;showPage=function(page){amconOriginalShowPage(page);if(page==='cashflow')renderCashFlow();if(page==='budgetcontrol')renderBudgets();if(page==='dailyreports')renderDailyReports();if(page==='defects')renderDefects();if(page==='supplierdirectory')renderSupplierDirectory();if(page==='auditlog')renderAuditLog();}; const amconOriginalRenderFinance=renderProjectFinance;renderProjectFinance=function(){amconOriginalRenderFinance();const p=activeProjectDetail,el=document.getElementById('projectBudgetAlert');if(!p||!el)return;const target=budgetFor(p)?.amount,cost=amconProjectCost(p);el.innerHTML=target==null?'Budget target not set. Finance / Director can set it in Budget vs Actual.':`Budget Target: ${financeCurrency(target)}   Committed Cost: ${financeCurrency(cost)}   Variance: ${financeCurrency(target-cost)} ${cost>target?'— OVER BUDGET':'— Within budget'}`;}; clearQuotationEditor(); refreshInvoiceNumber(); renderDocumentHistory(); updateDashboardTotals();setRole('director'); document.addEventListener('input',e=>{if(e.target.classList&&e.target.classList.contains('validation-error')){e.target.classList.remove('validation-error');const n=e.target.nextElementSibling;if(n&&n.classList.contains('validation-hint'))n.remove();}});