« Back to History
mesr_warping.php
|
20260722_120325.php
Initial Domain Snapshot
Copy Code
<?php /* mesr_warping.php - Warping Machine entry page - Sections: Open Box, Closed Box, Yarn In Machine - Denier defaults: 110 ATY, 105/36, 75/36, 136 (with +Add) - Uses mesr_matrix for cone_weight and to persist lookups */ error_reporting(E_ALL); ini_set('display_errors',1); require_once __DIR__ . '/modules/auth/page_acl.php'; $ctx = page_require_access('mesr_warping'); $u = $ctx['user'] ?? null; $company_id = (int)($ctx['company_id'] ?? 0); $pdo = $ctx['pdo'] ?? null; if (!$pdo) require_once __DIR__ . '/core/db.php'; /* ------------------ AJAX HANDLERS (must run BEFORE header include) ------------------ */ /* cone_lookup: return cone_weight for denier+color */ if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'cone_lookup') { header('Content-Type: application/json; charset=utf-8'); $den = trim($_POST['denier'] ?? ''); $col = trim($_POST['color'] ?? ''); try { $q = $pdo->prepare("SELECT cone_weight FROM mesr_matrix WHERE company_id = :cid AND matrix_type = 'cone_weight' AND LOWER(TRIM(denier)) = LOWER(TRIM(:denier)) AND LOWER(TRIM(color)) = LOWER(TRIM(:color)) LIMIT 1"); $q->execute([':cid'=>$company_id, ':denier'=>$den, ':color'=>$col]); $r = $q->fetch(PDO::FETCH_ASSOC); if ($r && $r['cone_weight'] !== null) { echo json_encode(['success'=>true,'cone_weight'=>(float)$r['cone_weight']]); exit; } // fallback: color-only $q2 = $pdo->prepare("SELECT cone_weight FROM mesr_matrix WHERE company_id = :cid AND matrix_type = 'cone_weight' AND (denier IS NULL OR TRIM(denier) = '') AND LOWER(TRIM(color)) = LOWER(TRIM(:color)) LIMIT 1"); $q2->execute([':cid'=>$company_id, ':color'=>$col]); $r2 = $q2->fetch(PDO::FETCH_ASSOC); if ($r2 && $r2['cone_weight'] !== null) { echo json_encode(['success'=>true,'cone_weight'=>(float)$r2['cone_weight']]); exit; } echo json_encode(['success'=>false,'msg'=>'not_found']); exit; } catch (Exception $e) { echo json_encode(['success'=>false,'msg'=>'error','error'=>$e->getMessage()]); exit; } } /* add_lookup: persist denier or color as lookup in mesr_matrix */ if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_lookup') { header('Content-Type: application/json; charset=utf-8'); $type = trim($_POST['type'] ?? ''); $value = trim($_POST['value'] ?? ''); if (!$type || !$value) { echo json_encode(['success'=>false,'msg'=>'missing']); exit; } try { if ($type === 'denier') { $ins = $pdo->prepare("INSERT INTO mesr_matrix (company_id, matrix_type, denier, created_by, created_at) VALUES (:cid,'denier',:val,:uid,NOW())"); $ins->execute([':cid'=>$company_id, ':val'=>$value, ':uid'=>$u['id'] ?? null]); echo json_encode(['success'=>true]); exit; } elseif ($type === 'color') { $ins = $pdo->prepare("INSERT INTO mesr_matrix (company_id, matrix_type, color, created_by, created_at) VALUES (:cid,'color',:val,:uid,NOW())"); $ins->execute([':cid'=>$company_id, ':val'=>$value, ':uid'=>$u['id'] ?? null]); echo json_encode(['success'=>true]); exit; } else { echo json_encode(['success'=>false,'msg'=>'unknown']); exit; } } catch (Exception $e) { echo json_encode(['success'=>false,'msg'=>'db','error'=>$e->getMessage()]); exit; } } /* Save final month entry */ if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save') { $token = $_POST['csrf_token'] ?? ''; if (!$token || !hash_equals($_SESSION['csrf_token'] ?? '', $token)) { echo "<div style='color:red;padding:10px;'>CSRF token mismatch.</div>"; exit; } $month = trim($_POST['month'] ?? ''); $location = trim($_POST['location'] ?? ''); $remark = trim($_POST['remark'] ?? ''); $sections_json = $_POST['sections_json'] ?? '[]'; if (!$month || !$location) { echo "<div style='color:orange;padding:10px;'>Please provide month and location.</div>"; exit; } $stock_type = $location . ' Warping Machine'; try { $ins = $pdo->prepare("INSERT INTO month_end_stock_report (company_id, month, stock_type, yarns_json, remark, created_by, created_at) VALUES (:cid, :month, :st, :yj, :remark, :uid, NOW())"); $ins->execute([ ':cid'=>$company_id, ':month'=>$month, ':st'=>$stock_type, ':yj'=>$sections_json, ':remark'=>$remark, ':uid'=>$u['id'] ?? null ]); echo "<div style='color:green;padding:10px;'>Saved successfully.</div>"; } catch (PDOException $ex) { echo "<div style='color:red;padding:10px;'>DB error: " . htmlspecialchars($ex->getMessage()) . "</div>"; } exit; } /* ------------------ END AJAX (now include header for page) ------------------ */ $header_paths = [ __DIR__ . '/erp/partials/header.php', __DIR__ . '/partials/header.php', __DIR__ . '/header.php' ]; foreach ($header_paths as $hp) { if (file_exists($hp)) { require_once $hp; break; } } /* CSRF token */ $csrf = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(16)); $_SESSION['csrf_token'] = $csrf; /* Load colors and deniers from mesr_matrix, but keep our default deniers (user asked) */ $colors = []; $deniers_db = []; try { $q = $pdo->prepare("SELECT DISTINCT TRIM(color) AS color FROM mesr_matrix WHERE company_id = :cid AND color IS NOT NULL AND TRIM(color) <> '' ORDER BY color"); $q->execute([':cid'=>$company_id]); $colors = array_column($q->fetchAll(PDO::FETCH_ASSOC), 'color'); $q2 = $pdo->prepare("SELECT DISTINCT TRIM(denier) AS denier FROM mesr_matrix WHERE company_id = :cid AND denier IS NOT NULL AND TRIM(denier) <> '' ORDER BY denier"); $q2->execute([':cid'=>$company_id]); $deniers_db = array_column($q2->fetchAll(PDO::FETCH_ASSOC), 'denier'); } catch (Exception $e) { /* ignore */ } /* Your required default deniers for Warping */ $DEFAULT_DENIERS = ['110 ATY', '105/36', '75/36', '136']; // merge db deniers but ensure defaults are first and unique $deniers = $DEFAULT_DENIERS; foreach ($deniers_db as $d) { if (!in_array($d, $deniers)) $deniers[] = $d; } ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>MESR - Warping Machine Entry</title> <meta name="viewport" content="width=device-width,initial-scale=1"> <style> body{font-family:Arial,Helvetica,sans-serif;background:#fff;padding:18px;} .card{border:1px solid #ddd;border-radius:6px;padding:16px;max-width:1200px;margin:8px auto;} .form-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;} .form-group{display:flex;flex-direction:column;margin-bottom:8px;} label{font-weight:600;margin-bottom:6px;} input.form-control, select.form-control, textarea.form-control{padding:8px;border:1px solid #ccc;border-radius:4px;} .btn{display:inline-block;padding:8px 12px;border-radius:6px;border:0;cursor:pointer;background:#2d6cdf;color:#fff;} .small-btn{padding:6px 8px;font-size:12px;margin-left:6px;} .table{width:100%;border-collapse:collapse;margin-top:8px;} .table th,.table td{border:1px solid #eee;padding:8px;font-size:13px;text-align:left;} .section{border:1px dashed #ccc;padding:10px;margin:12px 0;border-radius:6px;background:#fbfbfb;} .total{font-weight:700;} </style> </head> <body> <div class="card"> <h3>Warping Machine Entry</h3> <form id="mainForm" method="post" action=""> <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>"> <input type="hidden" name="action" value="save"> <div class="form-grid"> <div class="form-group"> <label for="month">Month</label> <input id="month" name="month" type="month" class="form-control" required> </div> <div class="form-group"> <label for="location">Location</label> <select id="location" name="location" class="form-control" required> <option value="">-- Select --</option> <option value="MST1">MST1</option> <option value="MST2A">MST2A</option> <option value="MST2B">MST2B</option> <option value="MST2-TOP">MST2-TOP</option> </select> </div> <div class="form-group"> <label for="remark">Remark</label> <input id="remark" name="remark" class="form-control"> </div> </div> <!-- OPEN BOX --> <div class="section"> <h4>Open Box</h4> <button type="button" id="add_open_box" class="small-btn">+ Add Row</button> <table class="table" id="tbl_open_box"> <thead> <tr><th>#</th> <th>Denier <button type="button" class="small-btn denier-add">+Add</button></th> <th>Color <button type="button" class="small-btn color-add">+Add</button></th> <th>Total Cones</th><th>Weight (kg)</th><th>Action</th></tr> </thead> <tbody></tbody> <tfoot><tr><td colspan="4" style="text-align:right;">Total Kg</td><td id="total_open_box" class="total">0</td><td></td></tr></tfoot> </table> </div> <!-- CLOSED BOX --> <div class="section"> <h4>Closed Box</h4> <button type="button" id="add_closed_box" class="small-btn">+ Add Row</button> <table class="table" id="tbl_closed_box"> <thead> <tr><th>#</th> <th>Denier <button type="button" class="small-btn denier-add">+Add</button></th> <th>Color <button type="button" class="small-btn color-add">+Add</button></th> <th>Box/ID</th><th>Weight (kg)</th><th>Action</th></tr> </thead> <tbody></tbody> <tfoot><tr><td colspan="4" style="text-align:right;">Total Kg</td><td id="total_closed_box" class="total">0</td><td></td></tr></tfoot> </table> </div> <!-- YARN IN MACHINE --> <div class="section"> <h4>Yarn In Machine</h4> <button type="button" id="add_in_machine" class="small-btn">+ Add Row</button> <table class="table" id="tbl_in_machine"> <thead> <tr><th>#</th> <th>Denier <button type="button" class="small-btn denier-add">+Add</button></th> <th>Color <button type="button" class="small-btn color-add">+Add</button></th> <th>Filled %</th><th>Total Cones</th><th>Weight (kg)</th><th>Action</th></tr> </thead> <tbody></tbody> <tfoot><tr><td colspan="5" style="text-align:right;">Total Kg</td><td id="total_in_machine" class="total">0</td><td></td></tr></tfoot> </table> </div> <input type="hidden" name="sections_json" id="sections_json"> <div style="margin-top:12px;"> <button type="submit" class="btn">SAVE</button> </div> </form> </div> <script> /* Client script for Warping Machine page */ /* deniers: defaults + any db deniers merged server-side */ const PRELOADED_DENIERS = <?= json_encode($deniers, JSON_UNESCAPED_UNICODE) ?>; const PRELOADED_COLORS = <?= json_encode($colors, JSON_UNESCAPED_UNICODE) ?>; function $(id){ return document.getElementById(id); } function escapeHtml(s){ return (s===null||s===undefined)?'':String(s).replaceAll('&','&').replaceAll('<','<').replaceAll('>','>'); } function renumber(tbody){ Array.from(tbody.querySelectorAll('tr')).forEach((tr,i)=> { tr.children[0].textContent = i+1; }); } /* get cone weight via AJAX */ function getConeWeightRemote(denier, color){ const fd = new FormData(); fd.append('action','cone_lookup'); fd.append('denier', denier); fd.append('color', color); return fetch('', { method:'POST', body: fd }).then(r => r.json()).then(j => { if (j && j.success) return parseFloat(j.cone_weight || 0); return null; }).catch(()=> null); } /* compute row weight */ function computeRow(tr, tblId){ const weightCell = tr.querySelector('.item_weight'); if (tblId === 'tbl_closed_box') { const w = parseFloat(tr.querySelector('.item_box_weight')?.value || 0); weightCell.textContent = w.toFixed(3); recalcTotals(); return; } const denier = tr.querySelector('.item_denier')?.value || ''; const color = tr.querySelector('.item_color')?.value || ''; if (!denier || !color) { weightCell.textContent = '0'; recalcTotals(); return; } if (tblId === 'tbl_open_box') { const cones = parseFloat(tr.querySelector('.item_total_cone')?.value || 0); if (cones <= 0) { weightCell.textContent = '0'; recalcTotals(); return; } getConeWeightRemote(denier, color).then(cw => { if (cw) weightCell.textContent = (cw * cones).toFixed(3); else weightCell.textContent = '0'; recalcTotals(); }); return; } if (tblId === 'tbl_in_machine') { const filled = parseFloat(tr.querySelector('.item_filled')?.value || 0); const cones = parseFloat(tr.querySelector('.item_total_cones')?.value || 0); if (cones <= 0) { weightCell.textContent = '0'; recalcTotals(); return; } getConeWeightRemote(denier, color).then(cw => { if (cw) { const w = cw * (filled/100.0) * cones; weightCell.textContent = w.toFixed(3); } else weightCell.textContent = '0'; recalcTotals(); }); return; } weightCell.textContent = '0'; recalcTotals(); } function recalcTotals(){ function sum(sel){ let s=0; document.querySelectorAll(sel).forEach(el=> { const v=parseFloat(el.textContent||0); if(!isNaN(v)) s+=v; }); return s.toFixed(3); } $('total_open_box').textContent = sum('#tbl_open_box .item_weight'); $('total_closed_box').textContent = sum('#tbl_closed_box .item_weight'); $('total_in_machine').textContent = sum('#tbl_in_machine .item_weight'); } /* addRow helper */ function addRowTo(tblId, rowHtml){ const tbody = document.querySelector('#'+tblId+' tbody'); const tr = document.createElement('tr'); tr.innerHTML = '<td></td>' + rowHtml + '<td><button type="button" class="remove-row small-btn">X</button></td>'; tbody.appendChild(tr); renumber(tbody); tr.querySelectorAll('input,select').forEach(el=>{ el.addEventListener('input', ()=> computeRow(tr, tblId)); el.addEventListener('change', ()=> computeRow(tr, tblId)); }); tr.querySelector('.remove-row').addEventListener('click', ()=>{ tr.remove(); renumber(tbody); recalcTotals(); }); // initial compute computeRow(tr, tblId); return tr; } /* build denier select from PRELOADED_DENIERS */ function denierSelectHtml(){ let s = '<select class="form-control item_denier">'; s += '<option value=""></option>'; PRELOADED_DENIERS.forEach(d => s += '<option>'+escapeHtml(d)+'</option>'); s += '</select>'; return s; } function colorOptionsHtml(){ let s = '<option value=""></option>'; PRELOADED_COLORS.forEach(c => s += '<option>'+escapeHtml(c)+'</option>'); return s; } /* --- ADD ROW handlers --- */ document.getElementById('add_open_box').addEventListener('click', function(e){ e.preventDefault(); const row = [ '<td>'+ denierSelectHtml() +'</td>', '<td><select class="form-control item_color">'+ colorOptionsHtml() +'</select></td>', '<td><input type="number" class="form-control item_total_cone" value="0" min="0"></td>', '<td class="item_weight">0</td>' ].join(''); addRowTo('tbl_open_box', row); }); document.getElementById('add_closed_box').addEventListener('click', function(e){ e.preventDefault(); const row = [ '<td>'+ denierSelectHtml() +'</td>', '<td><select class="form-control item_color">'+ colorOptionsHtml() +'</select></td>', '<td><input type="text" class="form-control item_box" /></td>', '<td><input type="number" step="0.001" class="form-control item_box_weight" value="0"></td>', '<td class="item_weight">0</td>' ].join(''); addRowTo('tbl_closed_box', row); }); document.getElementById('add_in_machine').addEventListener('click', function(e){ e.preventDefault(); const row = [ '<td>'+ denierSelectHtml() +'</td>', '<td><select class="form-control item_color">'+ colorOptionsHtml() +'</select></td>', '<td><input type="number" class="form-control item_filled" value="100" min="0" max="100"></td>', '<td><input type="number" class="form-control item_total_cones" value="0" min="0"></td>', '<td class="item_weight">0</td>' ].join(''); addRowTo('tbl_in_machine', row); }); /* --- Add Lookup buttons (delegated) --- */ document.body.addEventListener('click', function(e){ if (e.target && e.target.classList.contains('denier-add')) { const val = prompt('Enter new denier (e.g. 110 ATY)'); if (!val) return; if (!PRELOADED_DENIERS.includes(val)) PRELOADED_DENIERS.push(val); // update selects document.querySelectorAll('.item_denier').forEach(s=>{ const exists = Array.from(s.options).some(o=>o.value.trim().toLowerCase()===val.trim().toLowerCase()); if (!exists) { const o = document.createElement('option'); o.value = val; o.text = val; s.appendChild(o); } }); const fd = new FormData(); fd.append('action','add_lookup'); fd.append('type','denier'); fd.append('value', val); fetch('', { method:'POST', body: fd }).then(r=>r.json()).then(j=>{ if(!j.success) console.warn('denier save failed', j); }).catch(()=>{}); } if (e.target && e.target.classList.contains('color-add')) { const val = prompt('Enter new color (e.g. Gold)'); if (!val) return; if (!PRELOADED_COLORS.includes(val)) PRELOADED_COLORS.push(val); document.querySelectorAll('.item_color').forEach(s=>{ const exists = Array.from(s.options).some(o=>o.value.trim().toLowerCase()===val.trim().toLowerCase()); if (!exists) { const o = document.createElement('option'); o.value = val; o.text = val; s.appendChild(o); } }); const fd = new FormData(); fd.append('action','add_lookup'); fd.append('type','color'); fd.append('value', val); fetch('', { method:'POST', body: fd }).then(r=>r.json()).then(j=>{ if(!j.success) console.warn('color save failed', j); }).catch(()=>{}); } }); /* --- Enter-key behavior: go to NEXT ROW's first field (not next input). If last row, add new row and focus it. --- */ document.addEventListener('keydown', function(e){ if (e.key !== 'Enter') return; const el = e.target; if (!el) return; const tbl = el.closest('table'); if (!tbl) return; e.preventDefault(); const row = el.closest('tr'); const tbody = row.parentElement; const nextRow = row.nextElementSibling; if (nextRow) { const first = nextRow.querySelector('input, select'); if (first) first.focus(); return; } // no next row: add and focus const tid = tbody.closest('table').id; if (tid === 'tbl_open_box') document.getElementById('add_open_box').click(); if (tid === 'tbl_closed_box') document.getElementById('add_closed_box').click(); if (tid === 'tbl_in_machine') document.getElementById('add_in_machine').click(); setTimeout(()=> { const newRow = tbody.lastElementChild; const first = newRow.querySelector('input, select'); if (first) first.focus(); }, 80); }); /* --- Save: collect data into sections_json --- */ document.getElementById('mainForm').addEventListener('submit', function(e){ function collect(tblId, mapping){ const out = []; document.querySelectorAll('#'+tblId+' tbody tr').forEach(tr=>{ const obj = {}; mapping.forEach(m=>{ const sel = tr.querySelector('.item_' + m); if (m === 'weight') obj[m] = parseFloat(tr.querySelector('.item_weight')?.textContent || 0); else obj[m] = sel ? sel.value : ''; }); out.push(obj); }); return out; } const data = { open_box: collect('tbl_open_box', ['denier','color','total_cone','weight']), closed_box: collect('tbl_closed_box', ['denier','color','box','box_weight','weight']), in_machine: collect('tbl_in_machine', ['denier','color','filled','total_cones','weight']) }; document.getElementById('sections_json').value = JSON.stringify(data); // allow default submit }); /* Initialize with one row each for speed */ document.getElementById('add_open_box').click(); document.getElementById('add_closed_box').click(); document.getElementById('add_in_machine').click(); </script> </body> </html>