« Back to History
machine_wise_production_export.php
|
20260721_154033.php
Initial Bulk Import
Copy Code
<?php /* machine_wise_production.php Updated with export_bulk (karigar-wise JSON). */ header('X-Frame-Options: SAMEORIGIN'); error_reporting(E_ALL); ini_set('display_errors','0'); if (isset($_GET['debug']) && $_GET['debug']=='1') ini_set('display_errors','1'); 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; } $pdo = $GLOBALS['pdo'] ?? null; if (!$pdo) { require __DIR__ . '/core/db.php'; } $pdo = $GLOBALS['pdo']; if (!$pdo) jexit(['ok'=>false,'msg'=>'DB connect fail'],500); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /* ---------------- Existing helpers skipped (same as your file) ---------------- */ /* keep all your fetch_khata_by_code, fetch_assigned_karigars, fetch_all_karigars_in_khata, etc. */ /* ---------------- AJAX router ---------------- */ $act = $_GET['act'] ?? ''; if($act){ try { switch($act){ /* ---- your existing cases stay unchanged (khata_list, fetch_summary, etc.) ---- */ /* ---------------- NEW EXPORT_BULK CASE ---------------- */ case 'export_bulk': { // Payload: { month_year, period, rows: [ { khata, machine_no, quality, production:{date:{kid:"meterString"}}, total_meters } ] } $in = json_decode(file_get_contents('php://input'), true); if(!$in || !isset($in['rows']) || !is_array($in['rows'])) jexit(['ok'=>false,'msg'=>'Bad JSON/rows'],400); $month_year = trim($in['month_year'] ?? ''); $period = trim($in['period'] ?? ''); if($month_year==='' || $period==='') jexit(['ok'=>false,'msg'=>'Missing month_year/period'],400); try{ $pdo->beginTransaction(); $ins = $pdo->prepare("INSERT INTO machine_production_export (company_id, khata, machine_no, quality, month_year, period, production_json, total_meters, created_by) VALUES (:cid,:khata,:mno,:quality,:my,:period,:prod,:total,:user) ON DUPLICATE KEY UPDATE production_json=VALUES(production_json), total_meters=VALUES(total_meters), updated_at=NOW()"); $aud = $pdo->prepare("INSERT INTO machine_production_export_audit (export_id, company_id, action, payload, user_id) VALUES (:export_id, :cid, :action, :payload, :user)"); $saved = 0; foreach($in['rows'] as $r){ $kh = trim($r['khata'] ?? ''); $mno = (string)($r['machine_no'] ?? ''); $quality = trim($r['quality'] ?? ($in['quality'] ?? 'UNKNOWN')); if($kh==='' || $mno==='' || $quality==='') continue; // production JSON is already in new {date:{kid:meters}} format $prod = is_array($r['production']) ? $r['production'] : []; $prod_json = json_encode($prod, JSON_UNESCAPED_UNICODE); $total = isset($r['total_meters']) ? (float)$r['total_meters'] : 0.0; $ins->execute([ ':cid'=>$COMPANY_ID, ':khata'=>$kh, ':mno'=>$mno, ':quality'=>$quality, ':my'=>$month_year, ':period'=>$period, ':prod'=>$prod_json, ':total'=>$total, ':user'=>$USER_ID ]); $export_id = $pdo->lastInsertId() ?: null; $aud->execute([':export_id'=>$export_id, ':cid'=>$COMPANY_ID, ':action'=>'bulk_import', ':payload'=>$prod_json, ':user'=>$USER_ID]); $saved++; } $pdo->commit(); jexit(['ok'=>true,'saved_count'=>$saved]); } catch(Throwable $e){ $pdo->rollBack(); jexit(['ok'=>false,'msg'=>'Export failed','detail'=>$e->getMessage()],500); } } default: jexit(['ok'=>false,'msg'=>'Unknown act'],404); } } catch(Throwable $e){ jexit(['ok'=>false,'msg'=>'Server error','detail'=>$e->getMessage()],500); } } /* ---------------- FRONTEND (HTML + JS) ---------------- */ ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Machine Production Export</title> </head> <body> <div class="container"> <h3>Machine Production — Export Demo</h3> <!-- your existing khata/machine/month/period controls here --> <!-- Export button --> <button id="btnExportAll">Export All</button> <div id="summaryWrap"></div> </div> <script> const $ = id=>document.getElementById(id); // --- NEW EXPORT FUNCTION --- async function exportAllMachines(opts={confirm:true}) { const khata = $('khata').value.trim(); const machine = $('machine').value || ''; const month = $('month').value; const period = $('period').value; const qualityText = (document.getElementById('quality_select').selectedOptions[0]?.textContent || '').trim(); if(!khata||!month||!period){ return alert('Select khata, month & period first'); } // Build production map: {date:{kid:metersString}} const production = {}; const firstCard = document.querySelector('.card-kg'); if(!firstCard) return alert('Nothing loaded'); const dateRows = Array.from(firstCard.querySelectorAll('.kg-row')).map(r => r.dataset.date || r.querySelector('.date')?.textContent?.trim()).filter(Boolean); dateRows.forEach(d=>production[d]={}); const cards = Array.from(document.querySelectorAll('.card-kg')); cards.forEach(card=>{ const kid = card.dataset.kg; const rows = Array.from(card.querySelectorAll('.kg-row')); rows.forEach(r=>{ const dt = r.dataset.date || r.querySelector('.date')?.textContent?.trim(); if(!dt) return; let val = ''; const takaDiv = r.querySelector('.taka'); if(takaDiv) val = takaDiv.textContent.trim(); else { const inp = r.querySelector('input.inlineMeter'); if(inp) val = (inp.value||'').trim(); } if(val) { if(!production[dt][kid]) production[dt][kid] = val; else production[dt][kid] += '+'+val; } }); }); // total meters calc let totalMeters=0; Object.values(production).forEach(day=>{ Object.values(day).forEach(cell=>{ cell.split('+').forEach(p=>{ const n=parseFloat(p); if(!isNaN(n)) totalMeters+=n; }); }); }); totalMeters = Math.round(totalMeters*100)/100; const rows=[{ khata:khata, machine_no:machine, quality:qualityText||'UNKNOWN', production:production, total_meters:totalMeters }]; if(opts.confirm && !confirm('Export all visible data karigar-wise?')) return; try{ const resp = await fetch('?act=export_bulk',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({month_year:month,period:period,rows:rows})}); const j=await resp.json(); if(!j.ok) throw new Error(j.msg||'Export failed'); alert('Export successful: '+j.saved_count+' row(s).'); }catch(err){ alert('Export failed: '+err.message); } } document.addEventListener('DOMContentLoaded',()=>{ const be=$('btnExportAll'); if(be) be.addEventListener('click',()=>exportAllMachines({confirm:true})); }); </script> </body> </html>