« Back to History
machine_wise_production_export_debug.php
|
20260723_000646.php
Initial Domain Snapshot
Copy Code
<?php /* machine_wise_production_export_debug.php Debug-ready page: restores controls + Export All + improved diagnostics. Replace your current page with this (keep a backup). Note: uses same endpoints (?act=...) already present in your backend. */ ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); require __DIR__ . '/modules/auth/auth.php'; require_login(); $u = auth_user(); $COMPANY_ID = (int)$u['company_id']; $USER_ID = (int)$u['id']; function jexit($arr,$code=200){ if (!headers_sent()){ header('Content-Type: application/json; charset=utf-8'); http_response_code($code); } echo json_encode($arr, JSON_UNESCAPED_UNICODE); exit; } /* ensure $pdo exists */ $pdo = $GLOBALS['pdo'] ?? null; if (!$pdo) { require __DIR__ . '/core/db.php'; } $pdo = $GLOBALS['pdo'] ?? null; /* Minimal helpers just to avoid fatal if missing — real ones live in your original file */ if (!function_exists('fetch_khata_by_code')) { function fetch_khata_by_code($pdo,$company_id,$code){ $st=$pdo->prepare("SELECT id,code,machine_from,machine_to FROM khatas WHERE company_id=? AND code=? LIMIT 1"); $st->execute([$company_id,$code]); return $st->fetch(PDO::FETCH_ASSOC); } } ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Machine Export — Debug</title> <meta name="viewport" content="width=device-width,initial-scale=1"> <style> body{font-family:Arial,Helvetica,sans-serif;padding:16px;background:#f4f6f8;color:#0b1220} .card{background:#fff;padding:12px;border-radius:8px;border:1px solid #e2e8f0;max-width:1100px} label{font-size:13px;color:#374151} .controls{display:flex;gap:10px;flex-wrap:wrap;align-items:end} select,input{padding:8px;border-radius:6px;border:1px solid #cbd5e1} button{padding:8px 12px;border-radius:6px;background:#2563eb;color:#fff;border:none;cursor:pointer} .btn-ghost{background:#fff;color:#111;border:1px solid #cbd5e1} pre{background:#0b1220;color:#d1fae5;padding:8px;border-radius:6px;overflow:auto} </style> </head> <body> <div class="card"> <h2>Machine Production — Debug Export</h2> <div style="margin-bottom:8px;color:#374151">This debug page restores the controls and gives verbose client/server feedback. Open DevTools → Console & Network.</div> <div class="controls" style="margin-bottom:8px"> <div> <label>Khata</label><br> <select id="khata"><option>Loading…</option></select> </div> <div> <label>Machine</label><br> <select id="machine"><option value="">—</option></select> </div> <div> <label>Quality</label><br> <select id="quality_select"><option value="">Loading…</option></select> </div> <div> <label>Month</label><br> <input id="month" type="month" /> </div> <div> <label>Period</label><br> <select id="period"><option>H1</option><option>H2</option></select> </div> <div style="display:flex;gap:8px;align-items:center"> <button id="btnLoad">Load</button> <button id="btnExportAll">Export All</button> <button id="btnFetchTest" class="btn-ghost">Server test</button> </div> </div> <div style="margin-top:10px"> <strong>Client logs (console also):</strong> <pre id="clog">Ready.</pre> </div> <div style="margin-top:10px"> <strong>Last server response (Network):</strong> <pre id="slog">—</pre> </div> <div style="margin-top:10px"> <strong>Notes:</strong> <ul> <li>If Export returns nothing, open Network & click the export request — inspect the Response tab.</li> <li>If you see PHP errors, they will appear in Response or server logs when debug enabled.</li> </ul> </div> </div> <script> const clog = id=>document.getElementById('clog').textContent = id; const slog = id=>document.getElementById('slog').textContent = id; function appendLog(txt){ console.log(txt); const cur = document.getElementById('clog').textContent; document.getElementById('clog').textContent = (cur + "\n" + String(txt)).trim(); } /* small wrapper for fetch that logs */ async function myFetch(url, opts){ appendLog('FETCH -> ' + url + (opts && opts.method ? ' ['+opts.method+']' : '')); try{ const r = await fetch(url, opts); const txt = await r.text(); appendLog('Response status: ' + r.status); slog(txt.slice(0,4000)); // try to parse JSON for convenience try{ const j = JSON.parse(txt); appendLog('Parsed JSON: ' + (j.ok ? 'ok' : (j.msg||'no ok'))); return { ok:true, code:r.status, body:j, raw:txt }; }catch(e){ appendLog('Response not JSON (first 4000 chars shown)'); return { ok:false, code:r.status, body:null, raw:txt }; } }catch(err){ appendLog('Fetch error: ' + err.message); slog('Fetch error: ' + err.message); return { ok:false, error:err }; } } /* load khata list & qualities */ async function loadInit(){ appendLog('Loading khata list...'); const a = await myFetch('?act=khata_list'); if(a.ok && a.body && a.body.khatas){ const sel = document.getElementById('khata'); sel.innerHTML = '<option value="">(select)</option>'; a.body.khatas.forEach(k=>{ const o = document.createElement('option'); o.value = k.code; o.dataset.kid = k.id; o.dataset.from = k.machine_from; o.dataset.to = k.machine_to; o.textContent = k.code + (k.machine_from && k.machine_to ? ` — ${k.machine_from}-${k.machine_to}` : ''); sel.appendChild(o); }); appendLog('Khata loaded: ' + a.body.khatas.length); } else { appendLog('khata_list failed. Response: ' + (a.raw||JSON.stringify(a))); } appendLog('Loading quality list...'); const q = await myFetch('?act=quality_list'); if(q.ok && q.body && q.body.qualities){ const s = document.getElementById('quality_select'); s.innerHTML = '<option value="">(select)</option>'; q.body.qualities.forEach(qi=>{ const o=document.createElement('option'); o.value=qi.quality_id; o.textContent = qi.quality_name; s.appendChild(o); }); appendLog('Qualities loaded: ' + q.body.qualities.length); } else { appendLog('quality_list failed. Response: ' + (q.raw||JSON.stringify(q))); } } /* when khata changes, populate machine range */ document.getElementById('khata').addEventListener('change', (e)=>{ const opt = e.target.selectedOptions[0]; const ms = document.getElementById('machine'); ms.innerHTML = '<option value="">—</option>'; if(!opt) return; const from = parseInt(opt.dataset.from||0), to = parseInt(opt.dataset.to||0); if(from && to && to>=from){ for(let i=from;i<=to;i++){ const o=document.createElement('option'); o.value=i; o.textContent=i; ms.appendChild(o); } } }); /* load summary (to ensure data exists) */ document.getElementById('btnLoad').addEventListener('click', async ()=>{ const kh = document.getElementById('khata').value, m = document.getElementById('machine').value, mon = document.getElementById('month').value, per = document.getElementById('period').value; if(!kh || !m || !mon) return alert('Select khata, machine, month'); appendLog('Load summary for '+kh+' machine '+m+' month '+mon+' period '+per); const res = await myFetch(`?act=fetch_summary&khata=${encodeURIComponent(kh)}&machine=${encodeURIComponent(m)}&month=${encodeURIComponent(mon)}&period=${encodeURIComponent(per)}`); if(res.ok && res.body && res.body.karigars){ appendLog('Summary rows: ' + res.body.karigars.length); document.getElementById('summaryWrap').innerHTML = '<pre>' + JSON.stringify(res.body, null, 2).slice(0,5000) + '</pre>'; } else { appendLog('fetch_summary failed: ' + JSON.stringify(res)); document.getElementById('summaryWrap').innerHTML = '<pre>fetch_summary failed. See logs.</pre>'; } }); /* Server test (simple GET) */ document.getElementById('btnFetchTest').addEventListener('click', async ()=>{ appendLog('Server test -> khata_list'); const r = await myFetch('?act=khata_list'); appendLog('Server test done.'); }); /* exportAll (debug-enhanced) */ async function exportAllMachines(){ appendLog('ExportAll start'); const khata = document.getElementById('khata').value.trim(); const machine = document.getElementById('machine').value || ''; const month = document.getElementById('month').value; const period = document.getElementById('period').value; const qualityText = (document.getElementById('quality_select').selectedOptions[0]?.textContent || '').trim(); if(!khata || !month || !period){ alert('Select khata, month & period first'); appendLog('missing params for export'); return; } // Need summary loaded so we can gather cards; if not loaded, call fetch_summary now. let firstCard = document.querySelector('.card-kg'); if(!firstCard){ appendLog('No cards loaded — attempting fetch_summary automatically'); const q = await myFetch(`?act=fetch_summary&khata=${encodeURIComponent(khata)}&machine=${encodeURIComponent(machine)}&month=${encodeURIComponent(month)}&period=${encodeURIComponent(period)}`); if(!(q.ok && q.body && q.body.karigars)){ appendLog('fetch_summary returned no karigars; abort export'); alert('No data loaded for export; press Load first and verify.'); return; } // We will build production structure from q.body rather than DOM (safer in debug) const prod = {}; (q.body.dates || []).forEach(d=>prod[d] = {}); q.body.karigars.forEach(k=>{ const kid = String(k.karigar_id || k.karigar_id); (k.dates || []).forEach(dd=>{ const dt = dd.date; // build string same as UI: if has -> use takas (taka_display) or details -> sum let val = ''; if(dd.has){ if(dd.taka_display && dd.taka_display !== '') val = dd.taka_display; else if(dd.details && dd.details.length){ val = dd.details.map(x=> (x.meter||0) ).join('+'); } } if(val !== ''){ prod[dt][kid] = val; } }); }); // compute total_meters let total=0; Object.values(prod).forEach(day=>{ Object.values(day).forEach(cell=>{ cell.split('+').forEach(p=>{ const n=parseFloat(p); if(!isNaN(n)) total+=n; }); }); }); total = Math.round(total*100)/100; // ready payload const rows = [{ khata: khata, machine_no: machine, quality: qualityText||'UNKNOWN', production: prod, total_meters: total }]; if(!confirm('Continue to export (server call)?')) return; // send const resp = await myFetch('?act=export_bulk', { method:'POST', headers:{ 'Content-Type':'application/json' }, body: JSON.stringify({ month_year: month, period: period, rows: rows }) }); if(resp.ok && resp.body){ appendLog('Export response JSON: ' + JSON.stringify(resp.body).slice(0,1000)); alert('Export result: ' + (resp.body.saved_count ?? JSON.stringify(resp.body))); } else { appendLog('Export failed (non-json or error). See server response.'); alert('Export failed — check Network & server logs'); } return; } appendLog('ExportAll end'); } /* Attach events */ document.getElementById('btnExportAll').addEventListener('click', exportAllMachines); /* init */ loadInit(); </script> </body> </html>