« Back to History
diwali_bonus.php
|
20260921_175631.php
Initial Domain Snapshot
Copy Code
<?php /* ============================================================================ File: /erp/diwali_bonus.php Purpose: Diwali Bonus Calculator — final with client-side print window - Eligibility: >=1 month (pro-rata) - Export inserts into monthly_salary_report (gross/net = bonus) - Print: opens a minimal new window containing only report HTML and auto-prints - Follows project bootstrap + CSRF + robust header/footer includes Updated: 2025-10-21 (client print) ============================================================================ */ header('X-Frame-Options: SAMEORIGIN'); error_reporting(E_ALL); ini_set('display_errors', 1); /* ---- Auth + DB ---- */ 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'; /* ---- Robust header include (if available) ---- */ $header_candidates = [ __DIR__ . '/partials/header.php', __DIR__ . '/erp/partials/header.php', __DIR__ . '/../erp/partials/header.php', __DIR__ . '/../../erp/partials/header.php' ]; foreach ($header_candidates as $hf) if (file_exists($hf)) { require_once $hf; break; } /* ---- CSRF ---- */ if (session_status() !== PHP_SESSION_ACTIVE) session_start(); if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16)); function csrf_field(){ echo '<input type="hidden" name="csrf" value="'.htmlspecialchars($_SESSION['csrf']).'">'; } function check_csrf(){ if (($_POST['csrf'] ?? '') !== ($_SESSION['csrf'] ?? '')) { http_response_code(403); exit('Bad CSRF'); }} /* ---- Helpers ---- */ function ymd($y,$m,$d=1){ return sprintf('%04d-%02d-%02d',$y,$m,$d); } function parse_ym($ym){ $p=preg_split('/[^0-9]+/',$ym); return count($p)>=2?['y'=>(int)$p[0],'m'=>(int)$p[1]]:null; } function days_in_month($y,$m){ return (int)date('t',strtotime(ymd($y,$m,1))); } /* ---- Ensure diwali_bonus_report table ---- */ $pdo->exec("CREATE TABLE IF NOT EXISTS diwali_bonus_report( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, company_id BIGINT, diwali_month DATE, employee_id BIGINT, employee_name VARCHAR(191), department_id BIGINT, department_name VARCHAR(100), designation_name VARCHAR(100), first_attendance_month DATE, months_of_service INT, per_month_bonus DECIMAL(12,2), bonus_amount DECIMAL(12,2), payment_type ENUM('BANK','CASH','UPI'), beneficiary_name VARCHAR(191), account_number VARCHAR(64), ifsc VARCHAR(20), paid_date DATE, created_by BIGINT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY uniq (company_id,diwali_month,employee_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); /* ---- Inputs ---- */ $diwali_ym = $_GET['diwali'] ?? $_POST['diwali'] ?? date('Y-m'); $per_month_bonus = (float)($_GET['per_month_bonus'] ?? $_POST['per_month_bonus'] ?? 100.00); $dept = (int)($_GET['dept'] ?? $_POST['dept'] ?? 0); $p = parse_ym($diwali_ym) ?: ['y'=>date('Y'),'m'=>date('n')]; $y=$p['y']; $m=$p['m']; $MONTH_KEY=ymd($y,$m,1); /* ---- Departments ---- */ $stDept=$pdo->prepare("SELECT id,name FROM company_departments WHERE company_id=? ORDER BY name"); $stDept->execute([$COMPANY_ID]); $departments=$stDept->fetchAll(PDO::FETCH_KEY_PAIR); /* ---- Employees ---- */ $sql="SELECT id,name,department_id,department_name,designation_name,payment_type,beneficiary_name,account_number,ifsc FROM company_employee_master WHERE company_id=? AND COALESCE(is_active,0)=1".($dept?" AND department_id=?":"")." ORDER BY department_id,name"; $st=$pdo->prepare($sql); $st->execute($dept?[$COMPANY_ID,$dept]:[$COMPANY_ID]); $emps=$st->fetchAll(PDO::FETCH_ASSOC); /* ---- First attendance stmt ---- */ $stFirst=$pdo->prepare("SELECT MIN(period_start) FROM manual_attendance_data WHERE company_id=? AND employee_id=?"); /* ---- Build rows ---- */ $rows=[]; $eligible_total=0; $bonus_total=0; foreach($emps as $e){ $stFirst->execute([$COMPANY_ID,$e['id']]); $first=$stFirst->fetchColumn(); $months=0; $capped=0; $eligible=false; if($first){ $fy=(int)date('Y',strtotime($first)); $fm=(int)date('n',strtotime($first)); $months=(($y-$fy)*12+$m-$fm)+1; if($months<0) $months=0; $capped=min($months,12); $eligible = ($capped >= 1); // eligibility rule: >=1 month } $bonus = round($per_month_bonus * $capped, 2); if($eligible){ $eligible_total++; $bonus_total += $bonus; } $rows[] = [ 'employee_id' => (int)$e['id'], 'employee_name' => $e['name'], 'department_id' => (int)($e['department_id'] ?? 0), 'department_name' => $e['department_name'] ?? ($departments[$e['department_id']] ?? ''), 'designation_name' => $e['designation_name'] ?? '', 'first_attendance' => $first ? date('Y-m-01', strtotime($first)) : null, 'months' => $months, 'months_capped' => $capped, 'per_month_bonus' => $per_month_bonus, 'bonus' => $bonus, 'payment_type' => $e['payment_type'] ?: 'BANK', 'beneficiary_name' => $e['beneficiary_name'] ?: $e['name'], 'account_number' => $e['account_number'] ?? '', 'ifsc' => $e['ifsc'] ?? '', 'eligible' => $eligible ]; } /* ---- SAVE handler (store in diwali_bonus_report) ---- */ if(($_POST['action'] ?? '') === 'save'){ check_csrf(); $ins = $pdo->prepare("INSERT INTO diwali_bonus_report (company_id,diwali_month,employee_id,employee_name,department_id,department_name,designation_name, first_attendance_month,months_of_service,per_month_bonus,bonus_amount,payment_type,beneficiary_name, account_number,ifsc,created_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE employee_name=VALUES(employee_name), bonus_amount=VALUES(bonus_amount)"); $pdo->beginTransaction(); foreach($rows as $r){ // saving all calculated rows by default; change if you want to restrict $ins->execute([ $COMPANY_ID, $MONTH_KEY, $r['employee_id'], $r['employee_name'], $r['department_id'], $r['department_name'], $r['designation_name'], $r['first_attendance'], (int)$r['months_capped'], $r['per_month_bonus'], $r['bonus'], $r['payment_type'], $r['beneficiary_name'], $r['account_number'], $r['ifsc'], $USER_ID ]); } $pdo->commit(); header("Location: diwali_bonus.php?diwali=" . urlencode($diwali_ym) . "&per_month_bonus=" . urlencode($per_month_bonus) . "&saved=1"); exit; } /* ---- EXPORT handler (bank) ---- Saves diwali_bonus_report then inserts rows into monthly_salary_report with gross/net = bonus_amount, then hands off to payment_export_monthly.php (same flow as monthly salary). */ if(($_POST['action'] ?? '') === 'export'){ check_csrf(); $paid_date = $_POST['paid_date'] ?? date('Y-m-d'); // save to diwali_bonus_report $insD = $pdo->prepare("INSERT INTO diwali_bonus_report (company_id,diwali_month,employee_id,employee_name,department_id,department_name,designation_name, first_attendance_month,months_of_service,per_month_bonus,bonus_amount,payment_type,beneficiary_name, account_number,ifsc,paid_date,created_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE bonus_amount=VALUES(bonus_amount), paid_date=VALUES(paid_date)"); $pdo->beginTransaction(); foreach($rows as $r){ $insD->execute([ $COMPANY_ID, $MONTH_KEY, $r['employee_id'], $r['employee_name'], $r['department_id'], $r['department_name'], $r['designation_name'], $r['first_attendance'], (int)$r['months_capped'], $r['per_month_bonus'], $r['bonus'], $r['payment_type'], $r['beneficiary_name'], $r['account_number'], $r['ifsc'], $paid_date, $USER_ID ]); } $pdo->commit(); // insert into monthly_salary_report (gross/net = bonus) $insMSR = $pdo->prepare(" INSERT INTO monthly_salary_report (company_id, month_key, employee_id, employee_name, department_id, department_name, payroll_period_name, salary_type_name, total_days_in_month, attendance_days, per_day, basic_salary, calc_basic_amount, extra_amount, deduction_amount, advance_deduct, advance_ids, gross_amount, net_pay, payment_type, beneficiary_name, account_number, ifsc, narration, created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE net_pay=VALUES(net_pay), gross_amount=VALUES(gross_amount), updated_at=NOW()"); $pdo->beginTransaction(); $days = days_in_month($y,$m); foreach($rows as $r){ $insMSR->execute([ $COMPANY_ID, $MONTH_KEY, $r['employee_id'], $r['employee_name'], $r['department_id'], $r['department_name'], 'Diwali Bonus', 'Diwali Bonus', $days, 0, 0, 0,0,0,0,0, json_encode([], JSON_UNESCAPED_UNICODE), $r['bonus'], $r['bonus'], $r['payment_type'], $r['beneficiary_name'], $r['account_number'], $r['ifsc'], 'Diwali Bonus - ' . date('M-Y', strtotime($MONTH_KEY)), $USER_ID ]); } $pdo->commit(); // handoff ?> <form id="handoff" method="post" action="payment_export_monthly.php"> <input type="hidden" name="source" value="monthly_salary_report"> <input type="hidden" name="company_id" value="<?php echo htmlspecialchars($COMPANY_ID); ?>"> <input type="hidden" name="month_key" value="<?php echo htmlspecialchars($MONTH_KEY); ?>"> <input type="hidden" name="dept" value="<?php echo htmlspecialchars($dept); ?>"> <?php csrf_field(); ?> </form> <script>document.getElementById('handoff').submit();</script> <?php exit; } /* ---- Server-side print_cash handler (kept as fallback) ---- */ if(($_POST['action'] ?? '') === 'print_cash'){ check_csrf(); $scope = $_POST['print_scope'] ?? 'eligible'; $paid_date = $_POST['paid_date'] ?? date('Y-m-d'); // build print_rows per scope & dept $print_rows = []; foreach($rows as $r){ if($dept && $r['department_id'] != $dept) continue; if($scope === 'eligible' && !$r['eligible']) continue; $print_rows[] = $r; } if(empty($print_rows) && $scope === 'eligible'){ foreach($rows as $r) if(!$dept || $r['department_id']==$dept) $print_rows[] = $r; $scope = 'all (fallback)'; } $stC = $pdo->prepare("SELECT name FROM companies WHERE id=?"); $stC->execute([$COMPANY_ID]); $cname = $stC->fetchColumn() ?: 'Company'; echo '<!doctype html><html><head><meta charset="utf-8"><title>'.htmlspecialchars($cname).' - Employee Hakraja (Diwali)</title>'; echo '<style>body{font-family:Arial,Helvetica,sans-serif;margin:12mm}h2{text-align:center}table{width:100%;border-collapse:collapse;font-size:13px}th,td{border:1px solid #999;padding:6px 8px}th{background:#eee}.center{text-align:center}.right{text-align:right}@media print{@page{margin:12mm}}</style>'; echo '</head><body>'; echo '<h2>'.htmlspecialchars($cname).' - Employee Hakraja (Diwali) '.htmlspecialchars($diwali_ym).'</h2>'; echo '<div><strong>Paid Date:</strong> '.htmlspecialchars($paid_date).' | <strong>Scope:</strong> '.htmlspecialchars(ucfirst($scope)).'</div>'; echo '<table><thead><tr><th>SL</th><th>Name</th><th>Designation</th><th>Department</th><th>Total Month</th><th>Total Hakraja Amount</th><th>Paid Date</th><th>Signature / Thumb</th></tr></thead><tbody>'; $i=1; $tot=0; foreach($print_rows as $r){ echo '<tr><td class="center">'.$i++.'</td><td>'.htmlspecialchars($r['employee_name']).'</td><td>'.htmlspecialchars($r['designation_name']).'</td><td>'.htmlspecialchars($r['department_name']).'</td><td class="center">'.(int)$r['months_capped'].'</td><td class="right">'.number_format($r['bonus'],2).'</td><td class="center">'.htmlspecialchars($paid_date).'</td><td></td></tr>'; $tot += $r['bonus']; } echo '<tr><td colspan="5" class="right"><strong>Total</strong></td><td class="right"><strong>'.number_format($tot,2).'</strong></td><td colspan="2"></td></tr>'; echo '</tbody></table>'; echo '<script>window.print();setTimeout(function(){ window.close(); },500);</script>'; echo '</body></html>'; exit; } /* ---- UI ---- */ ?> <!doctype html> <html> <head> <meta charset="utf-8"> <title>Employee Hakraja (Diwali) Calculator</title> <!-- Strong print CSS: hides site header/topbar during browser print (extra safety) --> <style> @media print { header,.header,.site-header,.main-header,.topbar,.top-nav,.navbar,.navbar-fixed-top, .erp-topbar,.erp-company-card,.appbar,.erp-report-controls,.no-print,.breadcrumb, .page-header,.toolbar,.header-wrapper,.user-box,.nav-wrapper,.masthead,.site-nav, .page-controls,.headerbar{ display:none !important; visibility:hidden !important; height:0 !important; margin:0 !important; padding:0 !important; overflow:hidden !important; } body>div:first-child, body>header, body>.header, body>.topbar { display:none !important; } #reportContent{ display:block !important; width:100% !important; margin:0 !important; padding:0 !important; } *[style*="position:fixed"], *[style*="position:sticky"]{ position: static !important; } @page { margin: 12mm; } body { margin:0; padding:0; } } </style> </head> <body> <!-- Page header area (visible on screen only) --> <div class="erp-company-card" role="banner" aria-label="Company details"> <div class="company-name"><?php $stc = $pdo->prepare("SELECT name FROM companies WHERE id=?"); $stc->execute([$COMPANY_ID]); echo htmlspecialchars($stc->fetchColumn() ?: 'Company'); ?></div> <div class="company-sub">Company ID: <?php echo $COMPANY_ID; ?></div> </div> <h2>Employee Hakraja (Diwali) Calculator</h2> <?php if(isset($_GET['saved'])): ?><div class="notice">Saved bonus for <?php echo htmlspecialchars($diwali_ym); ?></div><?php endif; ?> <!-- Controls (compact single line) --> <div class="erp-report-controls no-print" style="display:flex;align-items:center;flex-wrap:wrap;gap:8px;padding:8px;background:#f8fff8;border:1px solid #d8eed8;border-radius:8px;margin-bottom:10px;"> <form method="get" style="display:flex;gap:8px;align-items:center;margin:0;"> <label>Month <input type="month" name="diwali" value="<?php echo htmlspecialchars($diwali_ym); ?>" style="padding:4px"></label> <label>Per-month <input type="number" name="per_month_bonus" value="<?php echo htmlspecialchars($per_month_bonus); ?>" style="width:90px;padding:4px"></label> <label>Dept <select name="dept" style="padding:4px"> <option value="0">All</option> <?php foreach($departments as $id=>$nm) echo '<option value="'.(int)$id.'"'.($dept==$id?' selected':'').'>'.htmlspecialchars($nm).'</option>'; ?> </select> </label> <button type="submit">Show</button> </form> <form id="actions" method="post" style="display:flex;gap:6px;align-items:center;margin-left:10px;"> <?php csrf_field(); ?> <input type="hidden" name="diwali" value="<?php echo htmlspecialchars($diwali_ym); ?>"> <input type="hidden" name="per_month_bonus" value="<?php echo htmlspecialchars($per_month_bonus); ?>"> <input type="hidden" name="dept" value="<?php echo htmlspecialchars($dept); ?>"> <label>Paid <input type="date" name="paid_date" value="<?php echo date('Y-m-d'); ?>" style="padding:4px"></label> <select name="print_scope" style="padding:4px"> <option value="eligible">Eligible only (≥1 mo)</option> <option value="all">All employees</option> </select> <button name="action" value="save" type="submit">💾 Save</button> <button name="action" value="export" type="submit">🏦 Export</button> <!-- Client-side print button (opens minimal window with only report content) --> <button type="button" id="btnClientPrint" onclick="openReportPrintWindow()" style="padding:6px 10px;">🖨️ Print</button> </form> <div style="margin-left:auto;font-size:13px;"> Eligible ≥1 mo: <b><?php echo $eligible_total; ?></b> • Total Bonus: <b><?php echo number_format($bonus_total,2); ?></b> </div> </div> <!-- Report content --> <div id="reportContent"> <table style="width:100%;border-collapse:collapse;font-size:13px"> <thead> <tr style="background:#f6f6f6"> <th style="border:1px solid #ddd;padding:6px">#</th> <th style="border:1px solid #ddd;padding:6px">Name</th> <th style="border:1px solid #ddd;padding:6px">Designation</th> <th style="border:1px solid #ddd;padding:6px">Department</th> <th style="border:1px solid #ddd;padding:6px">First Attendance</th> <th style="border:1px solid #ddd;padding:6px">Months</th> <th style="border:1px solid #ddd;padding:6px">Capped</th> <th style="border:1px solid #ddd;padding:6px">Per-Month</th> <th style="border:1px solid #ddd;padding:6px">Bonus</th> </tr> </thead> <tbody> <?php $i=1; foreach($rows as $r): if($dept && $r['department_id'] != $dept) continue; ?> <tr> <td style="border:1px solid #f1f1f1;padding:6px;text-align:center"><?php echo $i++; ?></td> <td style="border:1px solid #f1f1f1;padding:6px"><?php echo htmlspecialchars($r['employee_name']); ?></td> <td style="border:1px solid #f1f1f1;padding:6px"><?php echo htmlspecialchars($r['designation_name']); ?></td> <td style="border:1px solid #f1f1f1;padding:6px"><?php echo htmlspecialchars($r['department_name']); ?></td> <td style="border:1px solid #f1f1f1;padding:6px"><?php echo $r['first_attendance'] ? htmlspecialchars(date('M Y', strtotime($r['first_attendance']))) : '—'; ?></td> <td style="border:1px solid #f1f1f1;padding:6px;text-align:center"><?php echo (int)$r['months']; ?></td> <td style="border:1px solid #f1f1f1;padding:6px;text-align:center"><?php echo (int)$r['months_capped']; ?></td> <td style="border:1px solid #f1f1f1;padding:6px;text-align:right"><?php echo number_format($r['per_month_bonus'],2); ?></td> <td style="border:1px solid #f1f1f1;padding:6px;text-align:right"><?php echo number_format($r['bonus'],2); ?></td> </tr> <?php endforeach; ?> </tbody> </table> </div> <!-- Client-side print: open minimal window with only #reportContent and print --> <script> function escapeHtml(s){ return String(s||'').replace(/[&<>"']/g, function(ch){ return ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[ch]); }); } function openReportPrintWindow(){ var content = document.getElementById('reportContent'); if(!content){ alert('Report content not found'); return; } // optional meta var companyName = (document.querySelector('.company-name') || {}).textContent || ''; var title = (companyName.trim()?companyName.trim() + ' - Employee Hakraja (Diwali)' : 'Employee Hakraja (Diwali)'); var paidInput = document.querySelector('input[name="paid_date"]'); var paidDate = paidInput ? paidInput.value : ''; var printCSS = '<style>' + 'body{font-family:Arial,Helvetica,sans-serif;margin:12mm;color:#111;}' + '.print-title{ text-align:center; font-weight:700; font-size:16px; margin-bottom:6px; }' + '.print-sub{ text-align:center; font-size:12px; margin-bottom:10px; color:#333 }' + 'table{ width:100%; border-collapse:collapse; font-size:12px; }' + 'th,td{ border:1px solid #999; padding:6px 8px; vertical-align:middle; }' + 'th{ background:#f2f2f2; font-weight:700; }' + '.right{text-align:right} .center{text-align:center}' + '@media print{@page{margin:12mm} body{margin:0}}' + '</style>'; var html = '<!doctype html><html><head><meta charset="utf-8"><title>' + escapeHtml(title) + '</title>' + printCSS + '</head><body>'; html += '<div class="print-title">' + escapeHtml(title) + '</div>'; if(paidDate) html += '<div class="print-sub">Paid Date: ' + escapeHtml(paidDate) + '</div>'; html += '<div id="printArea">' + content.innerHTML + '</div>'; html += '</body></html>'; var win = window.open('', '_blank', 'width=1100,height=800,scrollbars=yes'); win.document.open(); win.document.write(html); win.document.close(); win.focus(); setTimeout(function(){ try{ win.print(); }catch(e){ console.error(e); } setTimeout(function(){ win.close(); }, 800); }, 500); } </script> <?php /* ---- Robust footer include ---- */ $footer_candidates = [ __DIR__ . '/partials/footer.php', __DIR__ . '/erp/partials/footer.php', __DIR__ . '/../erp/partials/footer.php', __DIR__ . '/../../erp/partials/footer.php' ]; foreach ($footer_candidates as $ff) if (file_exists($ff)) { require_once $ff; break; } ?> </body> </html>