« Back to History
production_karigar_performance.php
|
20260723_000646.php
Initial Domain Snapshot
Copy Code
<?php // ============================================================ // File: /erp/production_karigar_performance.php // Purpose: Karigar Performance Report - machine+quality headers + machine-column AVG row + black header text // ============================================================ error_reporting(E_ALL); ini_set('display_errors', 1); require_once __DIR__ . '/modules/auth/page_acl.php'; $ctx = page_require_access('production_performance'); $u = $ctx['user'] ?? null; $pdo = $ctx['pdo'] ?? null; $company_id = (int)($ctx['company_id'] ?? 0); if (!$pdo) { if (file_exists(__DIR__ . '/core/db.php')) require_once __DIR__ . '/core/db.php'; $pdo = $GLOBALS['pdo'] ?? null; } if (!function_exists('h')) { function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); } } // ---- Filters ---- $filter_type = $_GET['filter'] ?? 'this_month'; $from_date = $_GET['from'] ?? null; $to_date = $_GET['to'] ?? null; $month = $_GET['month'] ?? null; $tz = new DateTimeZone('+05:30'); $today = new DateTime('now', $tz); switch ($filter_type) { case 'select_month': $month = $month ?: $today->format('Y-m'); $from_date = (new DateTime($month . '-01', $tz))->format('Y-m-d'); $to_date = (new DateTime($from_date, $tz))->modify('last day of this month')->format('Y-m-d'); break; case 'period': if (!$from_date || !$to_date) { $to_date = $today->format('Y-m-d'); $from_date = (new DateTime($to_date, $tz))->modify('-6 days')->format('Y-m-d'); } break; default: $from_date = (new DateTime($today->format('Y-m-01'), $tz))->format('Y-m-d'); $to_date = (new DateTime($from_date, $tz))->modify('last day of this month')->format('Y-m-d'); break; } // ---- Fetch production_entry rows for period ---- $sql = "SELECT id, entry_date, lines_json, machine_id AS entry_machine_id, quality_id AS entry_quality_id FROM production_entry WHERE company_id = :cid AND entry_date BETWEEN :from_date AND :to_date ORDER BY entry_date ASC, id ASC"; $stmt = $pdo->prepare($sql); $stmt->execute([ ':cid' => $company_id, ':from_date' => $from_date, ':to_date' => $to_date ]); $rawRows = $stmt->fetchAll(PDO::FETCH_ASSOC); // ---- Fetch qualities map (id -> name) ---- $qualities = []; try { $qst = $pdo->prepare("SELECT id, quality_name FROM qualities WHERE company_id = :cid"); $qst->execute([':cid' => $company_id]); while ($qr = $qst->fetch(PDO::FETCH_ASSOC)) { $qualities[(int)$qr['id']] = $qr['quality_name']; } } catch (Exception $e) { // ignore if table missing } // ----------------- Robust build loop ----------------- $dates_map = []; $karigar_ids = []; $data_list = []; // data_list[date][kid] = array of entries (preserve order) $labels_collected = []; // labels_collected[kid] = ordered unique labels function make_label_from_item($it, $qualities_map, $entry_machine_id = null, $entry_quality_id = null) { $possibleMachineKeys = ['machine_no','machine','machine_id','mc','machine_no_text','mc_no','mc_no_text','machineno','mc_no']; $machine_label = null; foreach ($possibleMachineKeys as $k) { if (array_key_exists($k, $it) && $it[$k] !== '' && $it[$k] !== null) { $machine_label = (string)$it[$k]; break; } } $possibleQualityKeys = ['quality_id','quality','quality_code','q_id','quality_name','qname','qualityId']; $qname = null; foreach ($possibleQualityKeys as $k) { if (array_key_exists($k, $it) && $it[$k] !== '' && $it[$k] !== null) { $qid = $it[$k]; if (is_numeric($qid) && isset($qualities_map[(int)$qid])) { $qname = $qualities_map[(int)$qid]; } else { $qname = (string)$qid; } break; } } // fallback to entry-level if (($machine_label === null || $machine_label === '') && !empty($entry_machine_id)) { $machine_label = (string)$entry_machine_id; } if (($qname === null || $qname === '') && !empty($entry_quality_id)) { if (is_numeric($entry_quality_id) && isset($qualities_map[(int)$entry_quality_id])) { $qname = $qualities_map[(int)$entry_quality_id]; } else { $qname = (string)$entry_quality_id; } } if ($machine_label !== null && $machine_label !== '' && $qname !== null && $qname !== '') { return trim($machine_label) . "\n(" . trim($qname) . ")"; } elseif ($machine_label !== null && $machine_label !== '') { return trim($machine_label); } elseif ($qname !== null && $qname !== '') { return trim($qname); } else { return ''; } } foreach ($rawRows as $r) { $d = $r['entry_date']; $dates_map[$d] = $d; $entry_machine_id = $r['entry_machine_id'] ?? null; $entry_quality_id = $r['entry_quality_id'] ?? null; $json = $r['lines_json'] ?? '[]'; $arr = json_decode($json, true); if (!is_array($arr)) continue; foreach ($arr as $it) { $kid = (int)($it['karigar_id'] ?? 0); if ($kid <= 0) continue; if (array_key_exists('meter', $it)) $meter = (float)$it['meter']; elseif (array_key_exists('meters', $it)) $meter = (float)$it['meters']; else $meter = 0.0; $label = make_label_from_item($it, $qualities, $entry_machine_id, $entry_quality_id); $karigar_ids[$kid] = $kid; if (!isset($data_list[$d][$kid])) $data_list[$d][$kid] = []; $data_list[$d][$kid][] = ['meter' => $meter, 'label' => $label]; if ($label !== '') { if (!isset($labels_collected[$kid])) $labels_collected[$kid] = []; if (!in_array($label, $labels_collected[$kid], true)) { $labels_collected[$kid][] = $label; } } } } // ---- Get karigar names ---- $karigar_map = []; if (!empty($karigar_ids)) { $placeholders = implode(',', array_fill(0, count($karigar_ids), '?')); $sqlk = "SELECT id, karigar_name FROM loom_karigar_master WHERE id IN ($placeholders) AND company_id = ?"; $stmtk = $pdo->prepare($sqlk); $params = array_values($karigar_ids); $params[] = $company_id; $stmtk->execute($params); while ($rk = $stmtk->fetch(PDO::FETCH_ASSOC)) { $karigar_map[(int)$rk['id']] = $rk['karigar_name']; } } foreach ($karigar_ids as $kid) { if (!isset($karigar_map[$kid])) $karigar_map[$kid] = 'K-'.$kid; } uasort($karigar_map, function($a,$b){ return strcmp($a,$b); }); $karigars = $karigar_map; $dates = array_values($dates_map); sort($dates, SORT_STRING); // ---- Build header labels mapping: up to 4 labels per karigar (from collected labels) ---- $header_labels = []; foreach ($karigars as $kid => $kname) { $labels = $labels_collected[$kid] ?? []; $header_labels[$kid] = array_slice($labels, 0, 4); for ($i = count($header_labels[$kid]); $i < 4; $i++) $header_labels[$kid][$i] = ''; } // ---- Compute machine-column averages for each karigar column (col 0..3) across dates ---- $machine_avg = []; // machine_avg[kid][col] = avg or '' foreach ($karigars as $kid => $kname) { for ($col = 0; $col < 4; $col++) { $vals = []; foreach ($dates as $d) { if (isset($data_list[$d][$kid][$col])) { $v = $data_list[$d][$kid][$col]['meter']; if ($v !== null && $v !== '') $vals[] = $v; } } if (count($vals) > 0) { $avg = array_sum($vals) / count($vals); $machine_avg[$kid][$col] = (fmod($avg,1) == 0) ? (int)$avg : rtrim(rtrim(number_format($avg,2,'.',''),'0'),'.'); } else { $machine_avg[$kid][$col] = ''; } } } // ---- CSV export (flat) ---- if (isset($_GET['export']) && $_GET['export'] === 'csv') { header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=karigar_perf_machines_' . $from_date . '_' . $to_date . '.csv'); $out = fopen('php://output', 'w'); $head = ['Date']; foreach ($karigars as $kid => $kname) { $head[] = $kname . ' - c1'; $head[] = $kname . ' - c2'; $head[] = $kname . ' - c3'; $head[] = $kname . ' - c4'; $head[] = $kname . ' - AVG'; } fputcsv($out, $head); foreach ($dates as $d) { $row = [$d]; foreach ($karigars as $kid => $kname) { $arr = $data_list[$d][$kid] ?? []; for ($i=0;$i<4;$i++){ $val = $arr[$i]['meter'] ?? ''; if ($val === '') $row[] = ''; else $row[] = (fmod($val,1)==0)? (int)$val : rtrim(rtrim(number_format($val,2,'.',''),'0'),'.'); } if (!empty($arr)) { $s = array_sum(array_column($arr,'meter')); $avg = $s / count($arr); $row[] = (fmod($avg,1)==0)? (int)$avg : rtrim(rtrim(number_format($avg,2,'.',''),'0'),'.'); } else $row[] = ''; } fputcsv($out, $row); } fclose($out); exit; } // ---- Render page ---- require_once __DIR__ . '/partials/header.php'; ?> <div style="padding:6px;background:#fff;border-radius:6px;box-shadow:0 0 6px rgba(0,0,0,0.05);font-family:Arial,Helvetica,sans-serif;"> <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;"> <div> <h3 style="margin:0 0 4px 0;font-size:15px;">Karigar Performance (Machine + Quality headers)</h3> <div style="font-size:12px;color:#333;">Period: <strong><?= h($from_date) ?></strong> → <strong><?= h($to_date) ?></strong></div> </div> <div style="display:flex;gap:8px;align-items:center;"> <form method="get" style="display:inline-flex;gap:6px;align-items:center;"> <select name="filter" onchange="this.form.submit()" style="padding:4px;font-size:13px;"> <option value="this_month" <?= $filter_type==='this_month'?'selected':'' ?>>This month</option> <option value="select_month" <?= $filter_type==='select_month'?'selected':'' ?>>Select month</option> <option value="period" <?= $filter_type==='period'?'selected':'' ?>>Custom period</option> </select> <input type="month" name="month" value="<?= h($month) ?>" style="padding:4px;"> <input type="date" name="from" value="<?= h($from_date) ?>" style="padding:4px;"> <input type="date" name="to" value="<?= h($to_date) ?>" style="padding:4px;"> <button type="submit" style="padding:6px 10px;">Apply</button> </form> <a href="?<?= http_build_query(array_merge($_GET, ['export'=>'csv'])) ?>" style="padding:6px 10px;background:#eee;border-radius:4px;text-decoration:none;color:#111;">Export CSV</a> </div> </div> <?php // chunk karigars into blocks (per block shows N karigars horizontally) $perBlock = 4; $kidKeys = array_keys($karigars); $blocks = array_chunk($kidKeys, $perBlock, true); foreach ($blocks as $blockIndex => $blockKids) : ?> <div style="margin-bottom:10px;overflow:auto;border:1px solid #e6e6e6;padding:6px;"> <table style="border-collapse:collapse;width:100%;font-size:11px;"> <thead> <tr> <th style="border:1px solid #bbb;padding:4px;background:#dfe6ee;width:70px;">Date</th> <?php foreach ($blockKids as $kid): ?> <!-- karigar header: black bg, white text --> <th style="border:1px solid #bbb;padding:4px;background:#000;color:#fff;text-align:center;" colspan="5"><?= h($karigars[$kid]) ?></th> <?php endforeach; ?> </tr> <tr> <th style="border:1px solid #ccc;padding:3px;background:#f5f7fa;"></th> <?php foreach ($blockKids as $kid): $labels = $header_labels[$kid] ?? ['', '', '', '']; for ($col=0;$col<4;$col++): $lab = $labels[$col] ?? ''; ?> <th style="border:1px solid #ccc;padding:2px 4px;background:#fbfdff;font-size:10px;width:28px;white-space:pre-line;line-height:1.0;"><?= h($lab) ?></th> <?php endfor; ?> <th style="border:1px solid #ccc;padding:2px 4px;background:#fbfdff;font-size:10px;width:30px;">AVG</th> <?php endforeach; ?> </tr> <!-- NEW: machine-column AVG row (black background, white text) --> <tr> <th style="border:1px solid #333;padding:3px;background:#000;color:#fff;"></th> <?php foreach ($blockKids as $kid): for ($col=0;$col<4;$col++): $mavg = $machine_avg[$kid][$col] ?? ''; ?> <th style="border:1px solid #333;padding:3px;background:#000;color:#fff;font-size:11px;width:28px;text-align:center;"><?= h($mavg) ?></th> <?php endfor; ?> <th style="border:1px solid #333;padding:3px;background:#000;color:#fff;font-size:11px;width:30px;text-align:center;"></th> <?php endforeach; ?> </tr> </thead> <tbody> <?php if (empty($dates)): ?> <tr><td colspan="<?= 1 + count($blockKids)*5 ?>" style="padding:8px;text-align:center;">No data for selected period.</td></tr> <?php else: ?> <?php foreach ($dates as $d): ?> <tr> <td style="border:1px solid #ddd;padding:4px;"><?= h($d) ?></td> <?php foreach ($blockKids as $kid): $arr = $data_list[$d][$kid] ?? []; for ($i=0;$i<4;$i++){ if (!isset($arr[$i])) { echo '<td style="border:1px solid #eee;padding:3px;width:28px;"></td>'; } else { $val = $arr[$i]['meter']; $valStr = (fmod($val,1)==0) ? (int)$val : rtrim(rtrim(number_format($val,2,'.',''),'0'),'.'); echo '<td style="border:1px solid #eee;padding:3px;width:28px;text-align:center;">' . h($valStr) . '</td>'; } } if (!empty($arr)) { $avg = array_sum(array_column($arr,'meter')) / count($arr); $avgStr = (fmod($avg,1)==0) ? (int)$avg : rtrim(rtrim(number_format($avg,2,'.',''),'0'),'.'); echo '<td style="border:1px solid #eee;padding:3px;width:30px;text-align:center;font-weight:700;">' . h($avgStr) . '</td>'; } else { echo '<td style="border:1px solid #eee;padding:3px;width:30px;"></td>'; } endforeach; ?> </tr> <?php endforeach; ?> <?php endif; ?> </tbody> </table> </div> <?php endforeach; ?> </div> <?php require_once __DIR__ . '/partials/footer.php'; ?>