=== METHOD: resolveStableRouterId === public function resolveStableRouterId(string $sessionName, ?RouterosAPI $api = null): string { if ($api && $api->connected) { try { $rb = $api->comm('/system/routerboard/print'); $serial = $rb[0]['serial-number'] ?? ''; if (!empty($serial) && $serial !== 'N/A') { return 'RB-' . $serial; } $lic = $api->comm('/system/license/print'); $swId = $lic[0]['software-id'] ?? ''; if (!empty($swId) && $swId !== 'N/A') { return 'SW-' . $swId; } } catch (Throwable $e) { // Ignore API read error, fallback to deterministic hash } } $sessionRow = $GLOBALS['data'][$sessionName] ?? null; if ($sessionRow && isset($sessionRow[1], $sessionRow[2])) { $iphost = explode('!', $sessionRow[1])[1] ?? ''; $userhost = explode('@|@', $sessionRow[2])[1] ?? ''; if ($iphost !== '') { return 'ROUTER-' . substr(md5($iphost . ':' . $userhost), 0, 12); } } return 'ROUTER-' . strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $sessionName)); } === METHOD: getCustomerByRouterAndPppoe === public function getCustomerByRouterAndPppoe(string $routerId, ?string $routerSession, string $username): ?array { $username = trim($username); if ($username === '') { return null; } $hasRouterId = $this->hasColumn('billing_customers', 'router_id'); $hasRouterSession = $this->hasColumn('billing_customers', 'router_session'); $hasPppoeUsername = $this->hasColumn('billing_customers', 'pppoe_username'); $hasGeniePppoe = $this->hasColumn('billing_customers', 'genieacs_pppoe_username'); $where = []; $params = []; if ($hasRouterId && !empty($routerId) && $routerId !== 'default') { if ($hasRouterSession && !empty($routerSession)) { // Primary boundary is router_id; session fallback only for legacy unmigrated rows where router_id is 'default' $where[] = "(bc.router_id = :router_id OR (bc.router_id = 'default' AND bc.router_session = :router_session))"; $params[':router_id'] = $routerId; $params[':router_session'] = $routerSession; } else { $where[] = "bc.router_id = :router_id"; $params[':router_id'] = $routerId; } } elseif ($hasRouterSession && !empty($routerSession)) { $where[] = "bc.router_session = :router_session"; $params[':router_session'] = $routerSession; } if ($hasPppoeUsername && $hasGeniePppoe) { $where[] = "(bc.pppoe_username = :uname OR bc.genieacs_pppoe_username = :uname_g)"; $params[':uname'] = $username; $params[':uname_g'] = $username; } elseif ($hasPppoeUsername) { $where[] = "bc.pppoe_username = :uname"; $params[':uname'] = $username; } elseif ($hasGeniePppoe) { $where[] = "bc.genieacs_pppoe_username = :uname"; $params[':uname'] = $username; } else { $where[] = "bc.service_number = :uname"; $params[':uname'] = $username; } $sql = "SELECT bc.*, bp.profile_name, bp.price_monthly, bp.price_monthly AS price FROM billing_customers bc LEFT JOIN billing_profiles bp ON bc.profile_id = bp.id"; if (!empty($where)) { $sql .= " WHERE " . implode(" AND ", $where); } $sql .= " LIMIT 1"; $stmt = $this->db->prepare($sql); $stmt->execute($params); $customer = $stmt->fetch(PDO::FETCH_ASSOC); return $customer ?: null; } === METHOD: getInvoiceSummary === public function getInvoiceSummary(string $period, ?string $routerId = null, ?string $routerSession = null): array { $hasRouterId = $this->hasColumn('billing_invoices', 'router_id'); $hasRouterSession = $this->hasColumn('billing_invoices', 'router_session'); $hasPaidAmount = $this->hasColumn('billing_invoices', 'paid_amount'); $hasOutstandingAmount = $this->hasColumn('billing_invoices', 'outstanding_amount'); $sql = "SELECT COUNT(*) AS total_count, COALESCE(SUM(CASE WHEN bi.status = 'paid' THEN 1 ELSE 0 END), 0) AS paid_count, COALESCE(SUM(CASE WHEN bi.status = 'partially_paid' THEN 1 ELSE 0 END), 0) AS partially_paid_count, COALESCE(SUM(CASE WHEN bi.status = 'unpaid' THEN 1 ELSE 0 END), 0) AS unpaid_count, COALESCE(SUM(CASE WHEN bi.status = 'overdue' THEN 1 ELSE 0 END), 0) AS overdue_count, COALESCE(SUM(bi.amount), 0) AS total_invoiced_amount"; if ($hasPaidAmount) { $sql .= ", COALESCE(SUM(bi.paid_amount), 0) AS total_paid_amount"; } else { $sql .= ", COALESCE(SUM(CASE WHEN bi.status = 'paid' THEN bi.amount ELSE 0 END), 0) AS total_paid_amount"; } if ($hasOutstandingAmount) { $sql .= ", COALESCE(SUM(bi.outstanding_amount), 0) AS total_outstanding_amount"; } else { $sql .= ", COALESCE(SUM(CASE WHEN bi.status != 'paid' THEN bi.amount ELSE 0 END), 0) AS total_outstanding_amount"; } $sql .= " FROM billing_invoices bi WHERE bi.period = :period"; $params = [':period' => $period]; if ($routerId !== null && $routerId !== '' && $routerId !== 'all') { if ($hasRouterId) { if ($hasRouterSession && $routerSession !== null && $routerSession !== '') { $sql .= " AND (bi.router_id = :router_id OR (bi.router_id = 'default' AND bi.router_session = :router_session))"; $params[':router_id'] = $routerId; $params[':router_session'] = $routerSession; } else { $sql .= " AND bi.router_id = :router_id"; $params[':router_id'] = $routerId; } } elseif ($hasRouterSession && $routerSession !== null) { $sql .= " AND bi.router_session = :router_session"; $params[':router_session'] = $routerSession; } } $stmt = $this->db->prepare($sql); $stmt->execute($params); $row = $stmt->fetch(PDO::FETCH_ASSOC); return [ 'period' => $period, 'total_count' => (int)($row['total_count'] ?? 0), 'paid_count' => (int)($row['paid_count'] ?? 0), 'partially_paid_count' => (int)($row['partially_paid_count'] ?? 0), 'unpaid_count' => (int)($row['unpaid_count'] ?? 0), 'overdue_count' => (int)($row['overdue_count'] ?? 0), 'total_invoiced_amount' => (float)($row['total_invoiced_amount'] ?? 0.0), 'total_paid_amount' => (float)($row['total_paid_amount'] ?? 0.0), 'total_outstanding_amount' => (float)($row['total_outstanding_amount'] ?? 0.0), ]; } === METHOD: getFinancialSummary === public function getFinancialSummary(?string $startDate = null, ?string $endDate = null, ?string $routerId = null, ?string $routerSession = null): array { $hasRouterId = $this->hasColumn('billing_payments', 'router_id'); $hasRouterSession = $this->hasColumn('billing_payments', 'router_session'); $hasVoid = $this->hasColumn('billing_payments', 'is_voided'); // 1. Cash Revenue metrics from billing_payments $sql = "SELECT COUNT(*) AS total_transactions, COALESCE(SUM(amount), 0) AS period_cash_revenue, COALESCE(SUM(CASE WHEN DATE(payment_date) = CURDATE() THEN amount ELSE 0 END), 0) AS today_cash_revenue, COALESCE(SUM(CASE WHEN payment_date >= DATE_FORMAT(NOW(), '%Y-%m-01 00:00:00') THEN amount ELSE 0 END), 0) AS month_cash_revenue FROM billing_payments WHERE 1=1"; if ($hasVoid) { $sql .= " AND is_voided = 0"; } $params = []; if (!empty($startDate)) { $sql .= " AND DATE(payment_date) >= :start_date"; $params[':start_date'] = $startDate; } if (!empty($endDate)) { $sql .= " AND DATE(payment_date) <= :end_date"; $params[':end_date'] = $endDate; } if ($routerId !== null && $routerId !== '' && $routerId !== 'all') { if ($hasRouterId) { if ($hasRouterSession && $routerSession !== null && $routerSession !== '') { $sql .= " AND (router_id = :router_id OR (router_id = 'default' AND router_session = :router_session))"; $params[':router_id'] = $routerId; $params[':router_session'] = $routerSession; } else { $sql .= " AND router_id = :router_id"; $params[':router_id'] = $routerId; } } } $stmt = $this->db->prepare($sql); $stmt->execute($params); $cashTotals = $stmt->fetch(PDO::FETCH_ASSOC) ?: []; // 2. Revenue breakdown by Payment Method $methodSql = "SELECT method, COUNT(*) AS count, COALESCE(SUM(amount), 0) AS total_amount FROM billing_payments WHERE 1=1"; if ($hasVoid) $methodSql .= " AND is_voided = 0"; $methodParams = []; if (!empty($startDate)) { $methodSql .= " AND DATE(payment_date) >= :start_date"; $methodParams[':start_date'] = $startDate; } if (!empty($endDate)) { $methodSql .= " AND DATE(payment_date) <= :end_date"; $methodParams[':end_date'] = $endDate; } if ($routerId !== null && $routerId !== '' && $routerId !== 'all' && $hasRouterId) { $methodSql .= " AND router_id = :router_id"; $methodParams[':router_id'] = $routerId; } $methodSql .= " GROUP BY method ORDER BY total_amount DESC"; $mStmt = $this->db->prepare($methodSql); $mStmt->execute($methodParams); $byMethod = $mStmt->fetchAll(PDO::FETCH_ASSOC); // 3. Receivables & Outstanding from billing_invoices $invSql = "SELECT COALESCE(SUM(amount), 0) AS total_invoiced, COALESCE(SUM(paid_amount), 0) AS total_paid_invoices, COALESCE(SUM(outstanding_amount), 0) AS total_outstanding, COALESCE(SUM(CASE WHEN due_date < CURDATE() AND status != 'paid' AND status != 'cancelled' THEN outstanding_amount ELSE 0 END), 0) AS total_overdue FROM billing_invoices WHERE status != 'cancelled'"; $invParams = []; if ($routerId !== null && $routerId !== '' && $routerId !== 'all' && $this->hasColumn('billing_invoices', 'router_id')) { $invSql .= " AND router_id = :router_id"; $invParams[':router_id'] = $routerId; } $invStmt = $this->db->prepare($invSql); $invStmt->execute($invParams); $invTotals = $invStmt->fetch(PDO::FETCH_ASSOC) ?: []; return [ 'today_cash_revenue' => (float)($cashTotals['today_cash_revenue'] ?? 0.0), 'month_cash_revenue' => (float)($cashTotals['month_cash_revenue'] ?? 0.0), 'period_cash_revenue' => (float)($cashTotals['period_cash_revenue'] ?? 0.0), 'total_transactions' => (int)($cashTotals['total_transactions'] ?? 0), 'total_invoiced_accrual' => (float)($invTotals['total_invoiced'] ?? 0.0), 'total_outstanding_receivable' => (float)($invTotals['total_outstanding'] ?? 0.0), 'total_overdue_receivable' => (float)($invTotals['total_overdue'] ?? 0.0), 'revenue_by_method' => $byMethod ]; } === METHOD: recordInvoicePayment === public function recordInvoicePayment(int $invoiceId, float $amount, array $meta = []): array { if ($amount <= 0.0) { return [ 'success' => false, 'message' => 'Nominal pembayaran harus lebih besar dari 0.' ]; } $amount = round($amount, 2); $startedTransaction = false; if (!$this->db->inTransaction()) { $this->db->beginTransaction(); $startedTransaction = true; } try { // Row lock on invoice to prevent concurrent overpayments $stmt = $this->db->prepare("SELECT * FROM billing_invoices WHERE id = :id FOR UPDATE"); $stmt->execute([':id' => $invoiceId]); $invoice = $stmt->fetch(PDO::FETCH_ASSOC); if (!$invoice) { if ($startedTransaction) $this->db->rollBack(); return ['success' => false, 'message' => "Invoice #{$invoiceId} tidak ditemukan."]; } if ($invoice['status'] === 'cancelled') { if ($startedTransaction) $this->db->rollBack(); return ['success' => false, 'message' => "Invoice #{$invoiceId} telah dibatalkan, pembayaran ditolak."]; } $currentPaid = (float)($invoice['paid_amount'] ?? 0.0); $totalAmount = (float)$invoice['amount']; $currentOutstanding = max(0.0, round($totalAmount - $currentPaid, 2)); if ($currentOutstanding <= 0.0 || $invoice['status'] === 'paid') { if ($startedTransaction) $this->db->rollBack(); return ['success' => false, 'message' => "Invoice #{$invoiceId} sudah lunas sebelumnya."]; } // Overpayment check if ($amount > $currentOutstanding) { if ($startedTransaction) $this->db->rollBack(); return [ 'success' => false, 'message' => "Nominal pembayaran (Rp " . number_format($amount, 0, ',', '.') . ") melebihi sisa tagihan (Rp " . number_format($currentOutstanding, 0, ',', '.') . ")." ]; } // Reference check for idempotency & duplicate prevention $refNum = !empty($meta['reference_number']) ? trim((string)$meta['reference_number']) : null; if ($refNum !== null && $refNum !== '') { $dupStmt = $this->db->prepare("SELECT id FROM billing_payments WHERE reference_number = :ref AND is_voided = 0 LIMIT 1"); $dupStmt->execute([':ref' => $refNum]); $existingPayId = $dupStmt->fetchColumn(); if ($existingPayId) { if ($startedTransaction) $this->db->rollBack(); return [ 'success' => false, 'message' => "Pembayaran dengan nomor referensi '{$refNum}' sudah tercatat sebelumnya (#{$existingPayId}).", 'payment_id' => (int)$existingPayId ]; } } $customerId = (int)$invoice['customer_id']; $routerId = !empty($invoice['router_id']) ? (string)$invoice['router_id'] : (!empty($meta['router_id']) ? (string)$meta['router_id'] : 'default'); $routerSession = !empty($invoice['router_session']) ? (string)$invoice['router_session'] : (!empty($meta['router_session']) ? (string)$meta['router_session'] : 'default'); $paymentDate = !empty($meta['payment_date']) ? (string)$meta['payment_date'] : date('Y-m-d H:i:s'); $method = !empty($meta['method']) ? (string)$meta['method'] : (!empty($meta['payment_channel']) ? (string)$meta['payment_channel'] : 'cash'); $notes = !empty($meta['notes']) ? (string)$meta['notes'] : null; $createdBy = !empty($meta['created_by']) ? (int)$meta['created_by'] : null; // Insert into billing_payments $hasCustomerId = $this->hasColumn('billing_payments', 'customer_id'); $hasRouterId = $this->hasColumn('billing_payments', 'router_id'); $hasRouterSession = $this->hasColumn('billing_payments', 'router_session'); $hasPaymentRef = $this->hasColumn('billing_payments', 'reference_number'); $pCols = ['invoice_id', 'amount', 'payment_date', 'method', 'notes', 'created_by']; $pPlaceholders = [':invoice_id', ':amount', ':payment_date', ':method', ':notes', ':created_by']; $pParams = [ ':invoice_id' => $invoiceId, ':amount' => $amount, ':payment_date' => $paymentDate, ':method' => $method, ':notes' => $notes, ':created_by' => $createdBy ]; if ($hasCustomerId) { $pCols[] = 'customer_id'; $pPlaceholders[] = ':customer_id'; $pParams[':customer_id'] = $customerId; } if ($hasRouterId) { $pCols[] = 'router_id'; $pPlaceholders[] = ':router_id'; $pParams[':router_id'] = $routerId; } if ($hasRouterSession) { $pCols[] = 'router_session'; $pPlaceholders[] = ':router_session'; $pParams[':router_session'] = $routerSession; } if ($hasPaymentRef) { $pCols[] = 'reference_number'; $pPlaceholders[] = ':reference_number'; $pParams[':reference_number'] = $refNum; } $insertSql = "INSERT INTO billing_payments (" . implode(', ', $pCols) . ") VALUES (" . implode(', ', $pPlaceholders) . ")"; $pStmt = $this->db->prepare($insertSql); $pStmt->execute($pParams); $paymentId = (int)$this->db->lastInsertId(); // Calculate new balances $newPaid = round($currentPaid + $amount, 2); $newOutstanding = max(0.0, round($totalAmount - $newPaid, 2)); if ($newOutstanding <= 0.0) { $newStatus = 'paid'; $paidAt = $paymentDate; } else { $newStatus = 'partially_paid'; $paidAt = $invoice['paid_at'] ?? null; } // Update billing_invoices $invSets = [ "paid_amount = :paid_amount", "outstanding_amount = :outstanding_amount", "status = :status", "payment_channel = :channel" ]; $invParams = [ ':id' => $invoiceId, ':paid_amount' => $newPaid, ':outstanding_amount' => $newOutstanding, ':status' => $newStatus, ':channel' => $method, ]; if ($newStatus === 'paid') { $invSets[] = "paid_at = :paid_at"; $invParams[':paid_at'] = $paidAt; } $updateSql = "UPDATE billing_invoices SET " . implode(', ', $invSets) . " WHERE id = :id"; $upStmt = $this->db->prepare($updateSql); $upStmt->execute($invParams); // Sprint 09: Update customer subscription lifecycle according to rolling 30-day policy $subscriptionUpdate = null; if ($newStatus === 'paid') { $subscriptionUpdate = $this->processPaymentSubscriptionUpdate($customerId, $invoiceId, $amount, $paymentDate); } // Audit logging $this->logEvent($customerId, $invoiceId, 'payment_recorded', [ 'payment_id' => $paymentId, 'amount' => $amount, 'new_paid' => $newPaid, 'new_outstanding' => $newOutstanding, 'new_status' => $newStatus, 'method' => $method, 'reference' => $refNum, 'router_id' => $routerId, 'subscription_update' => $subscriptionUpdate ]); if ($startedTransaction) { $this->db->commit(); } return [ 'success' => true, 'payment_id' => $paymentId, 'invoice_id' => $invoiceId, 'customer_id' => $customerId, 'amount_paid' => $amount, 'total_paid' => $newPaid, 'outstanding_amount' => $newOutstanding, 'status' => $newStatus, 'reference_number' => $refNum, 'subscription' => $subscriptionUpdate, 'message' => $newStatus === 'paid' ? "Pembayaran berhasil. Tagihan #{$invoiceId} LUNAS." : "Pembayaran sebagian sebesar Rp " . number_format($amount, 0, ',', '.') . " diterima. Sisa tagihan: Rp " . number_format($newOutstanding, 0, ',', '.') . "." ]; } catch (Throwable $e) { if ($startedTransaction && $this->db->inTransaction()) { $this->db->rollBack(); } throw $e; } }