« Back to History
saree_out_add.php
|
20261118_125741.php
Initial Domain Snapshot
Copy Code
<?php /* ============================================================================= File: /erp/saree_out_add.php Title: Saree Out — Manual Entry (dropdown from saree_in/out + stock guard) ============================================================================= */ header('X-Frame-Options: SAMEORIGIN'); error_reporting(E_ALL); ini_set('display_errors','1'); require __DIR__ . '/modules/auth/auth.php'; require_login(); $u = auth_user(); $company_id = (int)($u['company_id'] ?? 0); $user_id = (int)($u['id'] ?? 0); $pdo = $GLOBALS['pdo'] ?? null; if (!$pdo) { require __DIR__ . '/core/db.php'; } /* ---------- Helpers ---------- */ function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); } function pv($k,$d=null){ return isset($_POST[$k])? (is_array($_POST[$k])?$_POST[$k]:trim((string)$_POST[$k])) : $d; } function gv($k,$d=null){ return isset($_GET[$k]) ? trim((string)$_GET[$k]) : $d; } function table_exists(PDO $pdo, string $t): bool { try { $pdo->query("SELECT 1 FROM `$t` LIMIT 1"); return true; } catch(Throwable $e){ return false; } } function col_exists(PDO $pdo, string $t, string $col): bool { try { foreach($pdo->query("DESCRIBE `$t`") as $r){ if(($r['Field']??'')===$col) return true; } } catch(Throwable $e){} return false; } /* ---------- Schema fix ---------- */ function schema_heal_saree_out(PDO $pdo){ try { $res = $pdo->query("DESCRIBE `saree_out`")->fetchAll(PDO::FETCH_ASSOC); $has = array_column($res,'Field'); if (!in_array('total_saree',$has)) { $pdo->exec("ALTER TABLE `saree_out` ADD COLUMN `total_saree` INT DEFAULT 0 AFTER `second`"); } } catch(Throwable $e){} } if (table_exists($pdo,'saree_out')) schema_heal_saree_out($pdo); /* ---------- Build master list + other names ---------- */ $saree_names = []; // rows with ['id'=>int|null, 'name'=>string] $map_by_id = []; // id => name (from master) if (table_exists($pdo,'saree_name_data')) { try { $st = $pdo->prepare("SELECT id, saree_name FROM saree_name_data WHERE company_id = :cid AND COALESCE(is_active,1)=1 ORDER BY saree_name"); $st->execute([':cid'=>$company_id]); $master = $st->fetchAll(PDO::FETCH_ASSOC) ?: []; foreach($master as $m){ $id = (int)$m['id']; $name = (string)$m['saree_name']; $saree_names[] = ['id'=>$id, 'name'=>$name]; $map_by_id[$id] = $name; } } catch(Throwable $e){ /* ignore */ } } /* gather distinct names from saree_in and saree_out */ $other_names = []; try { if (table_exists($pdo,'saree_in')) { $st = $pdo->prepare("SELECT DISTINCT name FROM saree_in WHERE company_id = :cid AND COALESCE(name,'') != ''"); $st->execute([':cid'=>$company_id]); foreach($st->fetchAll(PDO::FETCH_ASSOC) as $r){ $n = trim((string)$r['name']); if ($n !== '') $other_names[$n] = true; } } if (table_exists($pdo,'saree_out')) { $st = $pdo->prepare("SELECT DISTINCT name FROM saree_out WHERE company_id = :cid AND COALESCE(name,'') != ''"); $st->execute([':cid'=>$company_id]); foreach($st->fetchAll(PDO::FETCH_ASSOC) as $r){ $n = trim((string)$r['name']); if ($n !== '') $other_names[$n] = true; } } } catch(Throwable $e){} /* append other_names which are NOT already present in master */ foreach(array_keys($other_names) as $nm){ $found = false; foreach($saree_names as $sr){ if ($sr['name'] === $nm) { $found = true; break; } } if (!$found) $saree_names[] = ['id'=>null, 'name'=>$nm]; } /* ---------- Build stock map (name -> current stock) ---------- */ $stock_by_name = []; // name => int try { if ( (table_exists($pdo,'saree_in') || table_exists($pdo,'saree_out')) ) { $sql = " SELECT name, SUM(in_total) AS total_in, SUM(out_total) AS total_out FROM ( SELECT name, total_saree AS in_total, 0 AS out_total FROM saree_in WHERE company_id = :cid UNION ALL SELECT name, 0 AS in_total, total_saree AS out_total FROM saree_out WHERE company_id = :cid ) t GROUP BY name "; $st = $pdo->prepare($sql); $st->execute([':cid'=>$company_id]); foreach($st->fetchAll(PDO::FETCH_ASSOC) as $r){ $nm = (string)$r['name']; $in = (int)$r['total_in']; $out = (int)$r['total_out']; $stock_by_name[$nm] = $in - $out; } } } catch(Throwable $e){ // ignore } /* build final stock map keyed by the same keys JS will use (id as string OR raw name) */ $stock_map = []; foreach($saree_names as $s){ if ($s['id'] !== null) { $k = (string)$s['id']; $n = $s['name']; $stock_map[$k] = isset($stock_by_name[$n]) ? (int)$stock_by_name[$n] : 0; } else { $k = $s['name']; $stock_map[$k] = isset($stock_by_name[$k]) ? (int)$stock_by_name[$k] : 0; } } /* ---------- POST: Save with server-side stock guard ---------- */ $msg=''; $err=''; $saved_ok=false; $fv=[]; if ($_SERVER['REQUEST_METHOD'] === 'POST' && pv('act') === 'save') { $entry_date = pv('entry_date', date('Y-m-d')); $saree_name_id = pv('saree_name_id',''); // numeric id OR raw name $selected_name_text = ''; $modeling = (int)(pv('modeling','') ?: 0); $saree = (int)(pv('saree','') ?: 0); $second = (int)(pv('second','') ?: 0); $remark = pv('remark',''); if ($entry_date === '') $err = 'Date is required'; if ($saree_name_id === '' ) $err = $err ?: 'Please choose a Name from list'; if (!$err) { if (ctype_digit((string)$saree_name_id)) { $iid = (int)$saree_name_id; if (isset($map_by_id[$iid])) { $selected_name_text = $map_by_id[$iid]; } else { $err = 'Selected name ID not found in master list.'; } } else { $selected_name_text = trim((string)$saree_name_id); } } $total = $modeling + $saree + $second; /* server-side compute current stock for selected name (fresh) to be safe */ $current_stock = 0; if (!$err) { try { $st = $pdo->prepare(" SELECT COALESCE(SUM(in_total),0) - COALESCE(SUM(out_total),0) AS stock FROM ( SELECT total_saree AS in_total, 0 AS out_total FROM saree_in WHERE company_id = :cid AND name = :nm UNION ALL SELECT 0 AS in_total, total_saree AS out_total FROM saree_out WHERE company_id = :cid AND name = :nm ) t "); $st->execute([':cid'=>$company_id, ':nm'=>$selected_name_text]); $row = $st->fetch(PDO::FETCH_ASSOC); $current_stock = $row ? (int)$row['stock'] : 0; } catch(Throwable $e){ $current_stock = 0; } if ($total > $current_stock) { $err = "Cannot save: requested total ($total) exceeds current stock ($current_stock)."; } } if (!$err) { try { $cols = ['company_id','date','name','modeling','saree','second','total_saree','remark']; $vals = [':cid',':dt',':name',':m',':s',':sec',':t',':r']; $p = [ ':cid'=>$company_id, ':dt'=>$entry_date, ':name'=>$selected_name_text, ':m'=>$modeling, ':s'=>$saree, ':sec'=>$second, ':t'=>$total, ':r'=>$remark ]; if (col_exists($pdo,'saree_out','created_by')) { $cols[]='created_by'; $vals[]=':uid'; $p[':uid']=$user_id; } if (col_exists($pdo,'saree_out','created_at')) { $cols[]='created_at'; $vals[]='NOW()'; } $sql="INSERT INTO saree_out(`".implode('`,`',$cols)."`) VALUES(".implode(',',$vals).")"; $pdo->prepare($sql)->execute($p); $msg="Saved successfully."; $_POST=[]; $_POST['entry_date']=$entry_date; // update stock_map in memory to reflect new state (so page shows new value) $key = ctype_digit((string)$saree_name_id) ? (string)$saree_name_id : $saree_name_id; $stock_map[$key] = ($stock_map[$key] ?? 0) - $total; } catch(Throwable $e){ $err=$e->getMessage(); } } } /* ---------- Sticky ---------- */ $fv['entry_date']=pv('entry_date',date('Y-m-d')); $fv['modeling']=pv('modeling',''); $fv['saree']=pv('saree',''); $fv['second']=pv('second',''); $fv['remark']=pv('remark',''); $fv['name_text_after_save']=''; $SHOW=(gv('show','0')==='1'); $recent_rows=[]; if($SHOW){ try{ $st=$pdo->prepare("SELECT id,date,name,modeling,saree,second,(COALESCE(modeling,0)+COALESCE(saree,0)+COALESCE(second,0)) AS total_all,remark FROM saree_out WHERE company_id=:cid ORDER BY id DESC LIMIT 200"); $st->execute([':cid'=>$company_id]); $recent_rows=$st->fetchAll(PDO::FETCH_ASSOC); }catch(Throwable $e){} } /* JSON for client */ $saree_json = json_encode($saree_names, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT); $stock_json = json_encode($stock_map, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT); ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Saree Out</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body{font-family:system-ui;margin:0;background:#f6fff9;color:#222} .wrap{max-width:1000px;margin:32px auto;padding:0 16px} .card{background:#fff;border:1px solid #e5e7eb;border-radius:16px;padding:20px;margin:18px 0;box-shadow:0 14px 34px rgba(0,0,0,.1)} .row{display:grid;grid-template-columns:1fr 1fr;gap:16px} label{display:block;margin:10px 0 6px} input{padding:12px;border:1px solid #ccc;border-radius:10px;width:100%} .btn{background:#2f9e44;color:#fff;padding:12px 16px;border:0;border-radius:10px;cursor:pointer} .btn.sky{background:#a7d8de;color:#06353a} table{width:100%;border-collapse:separate;border-spacing:0 8px} th{text-align:left;color:#374151} td{background:#fff;border:1px solid #e5e7eb;padding:10px;border-radius:10px} .combo{position:relative} .dropdown{position:absolute;left:0;right:0;top:100%;background:#fff;border:1px solid #ccc;border-radius:10px;box-shadow:0 5px 15px rgba(0,0,0,.1);display:none;z-index:50;max-height:220px;overflow:auto} .combo.open .dropdown{display:block} .select-item{padding:8px 10px;cursor:pointer} .select-item:hover{background:#eef9f0} .search-input{padding:10px;border:0;outline:none;width:100%;box-sizing:border-box} .stock-box{margin-top:8px;padding:8px 10px;border-radius:8px;background:#f8fafb;border:1px solid #e6f0ea;display:inline-block} .error-msg{color:#9b1111;margin-top:8px} </style> </head> <body> <?php if (is_file(__DIR__.'/partials/header.php')) include __DIR__.'/partials/header.php'; ?> <div class="wrap"> <div class="card" style="display:flex;justify-content:space-between;align-items:center"> <h1 style="margin:0;color:#2f9e44">Saree Out</h1> <?php if(!$SHOW): ?><a class="btn sky" href="?show=1">Show Entries</a><?php else: ?><a class="btn sky" href="?">Hide Entries</a><?php endif; ?> </div> <?php if($msg): ?><div class="card" style="background:#e6fcf5;border-color:#c3fae8;color:#087f5b"><?=h($msg)?></div><?php endif;?> <?php if($err): ?><div class="card" style="background:#fff5f5;border-color:#ffc9c9;color:#c92a2a"><?=h($err)?></div><?php endif;?> <form method="post" class="card" id="sareeForm" autocomplete="off"> <input type="hidden" name="act" value="save"> <div> <label>Date</label> <input type="date" name="entry_date" id="entry_date" value="<?=h($fv['entry_date'])?>"> </div> <div class="row"> <div> <label>Name</label> <div class="combo" id="name_combo"> <input type="text" id="name_search" class="search-input" placeholder="Type to search name..." autocomplete="off"> <!-- hidden will carry either numeric id (if master) OR raw name string --> <input type="hidden" name="saree_name_id" id="saree_name_id" value=""> <div class="dropdown" id="name_dropdown"></div> </div> <div id="stock_display" class="stock-box" style="display:none">Current stock: <strong id="stock_value">0</strong></div> <div id="client_error" class="error-msg" style="display:none"></div> </div> <div> <label>Modeling (pcs)</label> <input type="number" name="modeling" id="modeling" value="<?=h($fv['modeling'])?>"> </div> </div> <div class="row"> <div><label>Saree (count)</label><input type="number" name="saree" id="saree" value="<?=h($fv['saree'])?>"></div> <div><label>Second (count)</label><input type="number" name="second" id="second" value="<?=h($fv['second'])?>"></div> </div> <div><label>Total (auto)</label><input type="number" id="total_saree" readonly></div> <div><label>Remark</label><input type="text" name="remark" id="remark" value="<?=h($fv['remark'])?>"></div> <div class="row"> <div style="display:flex;align-items:end;gap:10px; margin-top:20px"> <button class="btn" id="saveBtn">Save</button> <a class="btn sky" href="saree_out_list.php">Back</a> <div style="margin-top:8px; display:inline-block;"> <a class="btn" href="saree_name_add.php">Add Saree Name</a> </div> </div> </div> </form> <?php if($SHOW): ?> <div class="card"> <h3>Recent Entries</h3> <?php if($recent_rows): ?> <table> <thead><tr><th>Date</th><th>Name</th><th>Modeling</th><th>Saree (fresh)</th><th>Second</th><th>Total</th><th>Remark</th></tr></thead> <tbody> <?php foreach($recent_rows as $r): ?> <tr> <td><?=h($r['date'])?></td> <td><?=h($r['name'])?></td> <td><?=h($r['modeling'])?></td> <td><?=h($r['saree'])?></td> <td><?=h($r['second'])?></td> <td><?=h($r['total_all'])?></td> <td><?=h($r['remark'])?></td> </tr> <?php endforeach;?> </tbody> </table> <?php else:?><div>No entries yet.</div><?php endif;?> </div> <?php endif;?> </div> <script> (function(){ const list = <?= $saree_json ?>; // array of {id: int|null, name: string} const stockMap = <?= $stock_json ?>; // key => int (key = id as string or raw name) const combo = document.getElementById('name_combo'); const search = document.getElementById('name_search'); const dropdown = document.getElementById('name_dropdown'); const hidden = document.getElementById('saree_name_id'); const stockDisplay = document.getElementById('stock_display'); const stockValue = document.getElementById('stock_value'); const clientError = document.getElementById('client_error'); function renderList(filter){ dropdown.innerHTML = ''; let shown = 0; const q = (filter||'').toLowerCase().trim(); for (let i=0;i<list.length;i++){ const item = list[i]; if (q && item.name.toLowerCase().indexOf(q) === -1) continue; const el = document.createElement('div'); el.className = 'select-item'; el.dataset.name = item.name; el.dataset.value = item.id ? String(item.id) : item.name; el.innerText = item.name + (item.id ? ' (master)' : ''); el.addEventListener('click', function(){ search.value = this.dataset.name; hidden.value = this.dataset.value; updateStockDisplay(); closeDropdown(); }); dropdown.appendChild(el); shown++; } if (shown === 0){ const el = document.createElement('div'); el.className = 'select-item'; el.dataset.name = filter || ''; el.dataset.value = filter || ''; el.innerText = 'Use: "' + (filter||'') + '"'; el.addEventListener('click', function(){ search.value = this.dataset.name; hidden.value = this.dataset.value; updateStockDisplay(); closeDropdown(); }); dropdown.appendChild(el); } openDropdown(); } function openDropdown(){ combo.classList.add('open'); } function closeDropdown(){ combo.classList.remove('open'); } search.addEventListener('input', function(){ renderList(this.value); }); search.addEventListener('focus', function(){ renderList(this.value); }); document.addEventListener('click', function(e){ if (!combo.contains(e.target)) closeDropdown(); }); if (list.length===1){ search.value = list[0].name; hidden.value = list[0].id ? String(list[0].id) : list[0].name; updateStockDisplay(); } // total calc + client-side stock guard const modelEl = document.getElementById('modeling'); const sareeEl = document.getElementById('saree'); const secondEl = document.getElementById('second'); const totalEl = document.getElementById('total_saree'); function calcTotal(){ const m = parseInt(modelEl.value||0,10) || 0; const s = parseInt(sareeEl.value||0,10) || 0; const sec = parseInt(secondEl.value||0,10) || 0; const tot = m + s + sec; totalEl.value = tot; validateAgainstStock(); } [modelEl,sareeEl,secondEl].forEach(x=>x.addEventListener('input',calcTotal)); calcTotal(); function getSelectedKey(){ return hidden.value ? String(hidden.value) : ''; } function getStockForSelected(){ const k = getSelectedKey(); return (typeof stockMap[k] !== 'undefined') ? parseInt(stockMap[k],10) : 0; } function updateStockDisplay(){ const st = getStockForSelected(); stockValue.innerText = st; stockDisplay.style.display = 'inline-block'; clientError.style.display = 'none'; validateAgainstStock(); } function validateAgainstStock(){ const tot = parseInt(totalEl.value||0,10) || 0; const st = getStockForSelected(); if (tot > st) { clientError.style.display = 'block'; clientError.innerText = "Total ("+tot+") exceeds current stock ("+st+"). You cannot save more than available stock."; return false; } else { clientError.style.display = 'none'; clientError.innerText = ''; return true; } } // prevent Enter from submitting — move focus to next input document.getElementById('sareeForm').addEventListener('keydown', function(e){ if (e.key === 'Enter') { const tag = e.target.tagName.toLowerCase(); // allow enter in textarea (not present here) or when used with modifiers if (tag === 'textarea' || e.ctrlKey || e.shiftKey || e.metaKey) return; e.preventDefault(); // gather focusable inputs in form const focusables = Array.from(this.querySelectorAll('input:not([type=hidden]), button, textarea')).filter(el => !el.disabled && el.offsetParent !== null); const idx = focusables.indexOf(e.target); if (idx > -1 && idx < focusables.length-1) { focusables[idx+1].focus(); } else { // if last field, do nothing (user can press Save) } } }); // form submit: final client-side guard document.getElementById('sareeForm').addEventListener('submit', function(e){ if (!validateAgainstStock()) { e.preventDefault(); alert('Cannot save: total exceeds current stock. Fix values before saving.'); return false; } return true; }); })(); </script> <?php if (is_file(__DIR__.'/partials/footer.php')) include __DIR__.'/partials/footer.php'; ?> </body> </html>