« Back to History
taka_edit1.php
|
20260722_120325.php
Initial Domain Snapshot
Copy Code
<?php /* ============================================================================= File: loom_production_entry_manage.php Purpose: View + Edit + Update + Delete for loom_production_entry (company-scoped) Includes: - Machine No / Khata Name / Quality Name in grid - Karigar list from loom_karigar_master (khata-wise) - Qualities from quality_rates - Meter Total lock + lines sum must equal original total - Filters: • Machine ID (exact id) • Machine No/Code (text: machine_no / mc_no / machine_code / code; supports partial) • Date pickers + Khata + Quality + Search + Sort + Per-page - Actions: Edit dialog (visual lines), Delete (taka delete) Scope: Page-local only (no global/base changes) ============================================================================= */ error_reporting(E_ALL); ini_set('display_errors', 1); /* ====================================================================== SECTION 0: Auth + PDO bootstrap (scoped) ====================================================================== */ require __DIR__ . '/modules/auth/auth.php'; require_login(); $u = auth_user(); $company_id = (int)$u['company_id']; $user_id = (int)$u['id']; $pdo = $GLOBALS['pdo'] ?? null; if (!$pdo) { require __DIR__ . '/core/db.php'; } /* ====================================================================== SECTION 1: Helpers ====================================================================== */ function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); } function gv($k,$d=null){ return isset($_GET[$k])?trim((string)$_GET[$k]):$d; } function pv($k,$d=null){ return isset($_POST[$k])?trim((string)$_POST[$k]):$d; } $alerts = []; $errors = []; function _table_exists(PDO $pdo, $name){ try{ $st=$pdo->prepare("SHOW TABLES LIKE ?"); $st->execute([$name]); return (bool)$st->fetchColumn(); }catch(Throwable $e){ return false; } } function _col_exists(PDO $pdo,$tbl,$col){ try{ $st=$pdo->prepare("SHOW COLUMNS FROM `$tbl` LIKE ?"); $st->execute([$col]); return (bool)$st->fetch(); }catch(Throwable $e){ return false; } } function _fetch_map(PDO $pdo, $sql, $params=[]){ $map=[]; try{ $st=$pdo->prepare($sql); $st->execute($params); foreach($st as $r){ $map[(int)$r['id']] = (string)$r['name']; } }catch(Throwable $e){} return $map; } /* ====================================================================== SECTION 2: CSRF token ====================================================================== */ if (session_status() !== PHP_SESSION_ACTIVE) session_start(); if (empty($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(16)); } $CSRF = $_SESSION['csrf']; /* ====================================================================== SECTION 3: POST handlers (update + delete) ====================================================================== */ try { if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (pv('csrf') !== $CSRF) { throw new Exception('Invalid CSRF token'); } $action = pv('action',''); if ($action === 'delete') { $id = (int)pv('id',0); if ($id<=0) throw new Exception('Invalid record id for delete'); $st = $pdo->prepare("DELETE FROM loom_production_entry WHERE company_id=? AND id=? LIMIT 1"); $st->execute([$company_id, $id]); if ($st->rowCount()===1) { $alerts[] = "Taka #{$id} deleted."; } else { throw new Exception('Delete failed (not found)'); } } if ($action === 'update') { $id = (int)pv('id', 0); if ($id<=0) throw new Exception('Invalid record id'); $entry_date = pv('entry_date',''); if ($entry_date) { $ts = strtotime(str_replace('/','-',$entry_date)); if (!$ts) throw new Exception('Invalid entry_date'); $entry_date = date('Y-m-d',$ts); } $machine_id = (int)pv('machine_id', 0); $khata_id = (int)pv('khata_id', 0); $quality_id = (int)pv('quality_id', 0); $taka_no = (int)pv('taka_no', 0); $pbn = (int)pv('pbn', 0); $sbn = (int)pv('sbn', 0); $extra_mtr = (float)pv('extra_mtr', 0); $meter_total_post = (float)pv('meter_total', 0); $meter_total_orig = (float)pv('orig_meter_total', $meter_total_post); if (abs($meter_total_post - $meter_total_orig) > 0.0001) { throw new Exception('Meter Total is locked and cannot be changed.'); } $meter_total = $meter_total_orig; $weight = (float)pv('weight', 0); $remark = pv('remark',''); $lines_json = pv('lines_json',''); $sum_lines = 0.0; if ($lines_json !== '') { $arr = json_decode($lines_json, true); if (json_last_error() !== JSON_ERROR_NONE || !is_array($arr)) { throw new Exception('lines_json must be a valid JSON array'); } foreach ($arr as &$x) { if (isset($x['karigar_id'])) $x['karigar_id'] = (int)$x['karigar_id']; if (isset($x['meter'])) $x['meter'] = (float)$x['meter']; if (isset($x['date'])) { $ts = strtotime(str_replace('/','-',$x['date'])); if ($ts) $x['date'] = date('Y-m-d',$ts); } if (isset($x['quality_id'])) unset($x['quality_id']); $sum_lines += (float)($x['meter'] ?? 0); } unset($x); if (abs($sum_lines - $meter_total) > 0.01) { throw new Exception('Lines total must equal Meter Total.'); } $lines_json = json_encode($arr, JSON_UNESCAPED_UNICODE); } else { if (abs($meter_total) > 0.01) throw new Exception('Lines cannot be empty when Meter Total is non-zero.'); $lines_json = json_encode([], JSON_UNESCAPED_UNICODE); } $sql = "UPDATE loom_production_entry SET entry_date=?, machine_id=?, khata_id=?, quality_id=?, taka_no=?, pbn=?, sbn=?, extra_mtr=?, lines_json=?, meter_total=?, weight=?, remark=?, updated_at=NOW() WHERE company_id=? AND id=?"; $st = $pdo->prepare($sql); $ok = $st->execute([ $entry_date ?: null, $machine_id ?: null, $khata_id ?: null, $quality_id ?: null, $taka_no, $pbn, $sbn, $extra_mtr, $lines_json, $meter_total, $weight, $remark, $company_id, $id ]); if ($ok) $alerts[] = "Record #{$id} updated."; else throw new Exception('Update failed'); } } } catch(Throwable $e){ $errors[] = $e->getMessage(); $alerts[] = "ERROR: ".$e->getMessage(); } /* ====================================================================== SECTION 4: Filters + Pagination + SORT (Added: machine_no text filter that matches multiple columns in machines) ====================================================================== */ $page = max(1, (int)gv('page', 1)); $per_page = min(100, max(10, (int)gv('pp', 25))); $off = ($page - 1) * $per_page; $sort = gv('sort','date_desc'); $SORT_MAP = [ 'date_desc' => 'e.entry_date DESC, e.id DESC', 'date_asc' => 'e.entry_date ASC, e.id ASC', 'id_desc' => 'e.id DESC', 'id_asc' => 'e.id ASC', 'machine_asc' => 'e.machine_id ASC, e.entry_date DESC, e.id DESC', 'machine_desc' => 'e.machine_id DESC, e.entry_date DESC, e.id DESC', ]; $ORDER = $SORT_MAP[$sort] ?? $SORT_MAP['date_desc']; $where = ["e.company_id = :cid"]; $args = [':cid' => $company_id]; $needMachineJoin = false; if (($mid = gv('machine_id','')) !== '') { $where[] = "e.machine_id = :mid"; $args[':mid'] = (int)$mid; } if ($mno = gv('machine_no','')) { $needMachineJoin = true; $where[] = "(m.company_id=:cid AND (m.machine_no LIKE :mno OR m.mc_no LIKE :mno OR m.machine_code LIKE :mno OR m.code LIKE :mno) AND e.machine_id=m.id)"; $args[':mno'] = '%'.$mno.'%'; } if (($kid = gv('khata_id','')) !== '') { $where[]="e.khata_id=:kid"; $args[':kid']=(int)$kid; } if ($qid = (int)gv('quality_id',0)) { $where[]="e.quality_id=:qid"; $args[':qid']=$qid; } $W = implode(' AND ', $where); $total=0; $rows=[]; try{ $countSql="SELECT COUNT(*) FROM loom_production_entry e".($needMachineJoin&&_table_exists($pdo,'machines')?" JOIN machines m ON m.id=e.machine_id":"")." WHERE $W"; $stmt=$pdo->prepare($countSql); $stmt->execute($args); $total=(int)$stmt->fetchColumn(); $sql="SELECT e.* FROM loom_production_entry e".($needMachineJoin&&_table_exists($pdo,'machines')?" JOIN machines m ON m.id=e.machine_id":"")." WHERE $W ORDER BY $ORDER LIMIT :off,:pp"; $stmt=$pdo->prepare($sql); foreach($args as $k=>$v){ $stmt->bindValue($k,$v); } $stmt->bindValue(':off',$off,PDO::PARAM_INT); $stmt->bindValue(':pp',$per_page,PDO::PARAM_INT); $stmt->execute(); $rows=$stmt->fetchAll(PDO::FETCH_ASSOC); }catch(Throwable $e){ $errors[]=$e->getMessage(); } /* ====================================================================== SECTION 5: Lookup maps ====================================================================== */ $MACHINES=[]; if(_table_exists($pdo,'machines')){ $col=_col_exists($pdo,'machines','machine_no')?'machine_no':(_col_exists($pdo,'machines','mc_no')?'mc_no':(_col_exists($pdo,'machines','machine_code')?'machine_code':(_col_exists($pdo,'machines','code')?'code':null))); if($col){ $MACHINES=_fetch_map($pdo,"SELECT id,$col AS name FROM machines WHERE company_id=?",[$company_id]); } } $KHATAS=[]; foreach(['khata_master','loom_khata_master','khatas'] as $kt){ if(_table_exists($pdo,$kt)&&_col_exists($pdo,$kt,'id')&&_col_exists($pdo,$kt,'name')){ $KHATAS=_fetch_map($pdo,"SELECT id,name FROM `$kt` WHERE company_id=? ORDER BY name",[$company_id]); if($KHATAS) break; } } $QUALS=[]; if(_table_exists($pdo,'quality_rates')){ $QUALS=_fetch_map($pdo,"SELECT COALESCE(NULLIF(quality_id,0),id) AS id,quality_name AS name FROM quality_rates WHERE company_id=? ORDER BY quality_name",[$company_id]); } ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Loom Production — View & Edit</title> </head> <body> <h2>Machine Filter Added + Delete Works</h2> <form method="get"> Machine ID: <select name="machine_id"> <option value="">All</option> <?php foreach($MACHINES as $mid=>$mn): ?> <option value="<?php echo $mid; ?>" <?php if(gv('machine_id')==$mid) echo 'selected'; ?>><?php echo h($mn); ?></option> <?php endforeach; ?> </select> Machine No/Code: <input type="text" name="machine_no" value="<?php echo h(gv('machine_no','')); ?>"> <button type="submit">Filter</button> </form> <table border="1"> <tr><th>ID</th><th>Date</th><th>Machine</th><th>Khata</th><th>Quality</th><th>Taka</th><th>Action</th></tr> <?php foreach($rows as $r): ?> <tr> <td><?php echo $r['id']; ?></td> <td><?php echo $r['entry_date']; ?></td> <td><?php echo h($MACHINES[$r['machine_id']]??$r['machine_id']); ?></td> <td><?php echo h($KHATAS[$r['khata_id']]??$r['khata_id']); ?></td> <td><?php echo h($QUALS[$r['quality_id']]??$r['quality_id']); ?></td> <td><?php echo $r['taka_no']; ?></td> <td> <form method="post" onsubmit="return confirm('Delete?');"> <input type="hidden" name="csrf" value="<?php echo h($CSRF); ?>"> <input type="hidden" name="action" value="delete"> <input type="hidden" name="id" value="<?php echo $r['id']; ?>"> <button type="submit">Delete</button> </form> </td> </tr> <?php endforeach; ?> </table> </body> </html>