diff --git a/app/Http/Controllers/Barobill/EaccountController.php b/app/Http/Controllers/Barobill/EaccountController.php index e41612aa..7075fc72 100644 --- a/app/Http/Controllers/Barobill/EaccountController.php +++ b/app/Http/Controllers/Barobill/EaccountController.php @@ -1277,23 +1277,36 @@ public function destroyManual(int $id): JsonResponse * 로그는 날짜 내림차순(DESC) 정렬 상태로 전달됨 */ /** - * 조회기간 직전의 마지막 잔액 조회 (DB 저장 데이터 기준) + * 조회기간 직전의 마지막 잔액 조회 + * API 데이터는 잔액이 정확하므로 그대로 사용, + * 수동입력은 잔액이 0일 수 있으므로 입출금 누적으로 계산 */ private function findBaseBalance(int $tenantId, string $startDate, ?string $bankAccountNum = null): ?float { - $query = BankTransaction::where('tenant_id', $tenantId) + // 조회기간 이전의 모든 거래를 시간순(ASC)으로 조회 + $prevTransactions = BankTransaction::where('tenant_id', $tenantId) ->where('trans_date', '<', $startDate) - ->where('balance', '!=', 0); + ->when($bankAccountNum, fn($q) => $q->where('bank_account_num', $bankAccountNum)) + ->orderBy('trans_date', 'asc') + ->orderBy('trans_time', 'asc') + ->get(); - if ($bankAccountNum) { - $query->where('bank_account_num', $bankAccountNum); + if ($prevTransactions->isEmpty()) return null; + + // 시간순으로 순회하며 잔액 추적 + $balance = null; + foreach ($prevTransactions as $tx) { + if (!$tx->is_manual && (float) $tx->balance != 0) { + // API 데이터: 바로빌이 제공한 정확한 잔액 사용 + $balance = (float) $tx->balance; + } else { + // 수동입력 또는 잔액 0인 건: 이전 잔액에서 입출금 계산 + $prev = $balance ?? 0; + $balance = $prev + (float) $tx->deposit - (float) $tx->withdraw; + } } - $lastTx = $query->orderBy('trans_date', 'desc') - ->orderBy('trans_time', 'desc') - ->first(); - - return $lastTx ? (float) $lastTx->balance : null; + return $balance; } private function recalcManualBalances(array $logs, ?float $baseBalance = null): array