feat: [journal] 일반전표입력에 카드사용내역 분개 기능 추가

- JournalEntryController에 cardTransactions/storeFromCard/cardJournals/deleteCardJournal 메서드 추가
- 카드거래 분개 라우트 4개 추가 (card-transactions, store-from-card, card-journals, delete-card-journal)
- JournalEntryList에 카드거래 탭/필터/통계 통합
- CardJournalEntryModal 컴포넌트 추가 (공제/불공제에 따른 기본 분개 라인 자동 생성)
- source_type=ecard_transaction 호환 (기존 ecard 페이지 분개와 동일 키)
This commit is contained in:
김보곤
2026-02-26 20:52:44 +09:00
parent e86b7869b9
commit d2c3ce678a
3 changed files with 846 additions and 18 deletions

View File

@@ -5,6 +5,8 @@
use App\Http\Controllers\Controller;
use App\Models\Barobill\AccountCode;
use App\Models\Barobill\BankTransaction;
use App\Models\Barobill\CardTransaction;
use App\Models\Barobill\CardTransactionHide;
use App\Models\Finance\JournalEntry;
use App\Models\Finance\JournalEntryLine;
use App\Models\Finance\TradingPartner;
@@ -861,4 +863,322 @@ public function accountCodeDestroy(int $id): JsonResponse
'message' => '계정과목이 삭제되었습니다.',
]);
}
// ================================================================
// 카드거래 기반 분개 API
// ================================================================
/**
* 카드거래 목록 조회 (DB 직접 조회 + 분개상태 병합)
*/
public function cardTransactions(Request $request): JsonResponse
{
try {
$tenantId = session('selected_tenant_id', 1);
$startDate = $request->input('startDate', date('Ymd'));
$endDate = $request->input('endDate', date('Ymd'));
$cardNum = $request->input('cardNum', '');
$query = CardTransaction::where('tenant_id', $tenantId)
->whereBetween('use_date', [$startDate, $endDate]);
if (! empty($cardNum)) {
$query->where('card_num', $cardNum);
}
$transactions = $query->orderBy('use_date', 'desc')
->orderBy('use_time', 'desc')
->get();
// 숨김 처리된 거래 제외
$hiddenKeys = CardTransactionHide::getHiddenKeys($tenantId, $startDate, $endDate);
$hiddenKeysMap = $hiddenKeys->flip();
$transactions = $transactions->filter(function ($tx) use ($hiddenKeysMap) {
return ! $hiddenKeysMap->has($tx->unique_key);
});
// 로그 데이터 변환
$logs = [];
foreach ($transactions as $tx) {
$supplyAmount = $tx->modified_supply_amount !== null
? (int) $tx->modified_supply_amount
: (int) $tx->approval_amount - (int) $tx->tax;
$taxAmount = $tx->modified_tax !== null
? (int) $tx->modified_tax
: (int) $tx->tax;
$logs[] = [
'uniqueKey' => $tx->unique_key,
'useDate' => $tx->use_date,
'useTime' => $tx->use_time,
'cardNum' => $tx->card_num,
'cardCompanyName' => $tx->card_company_name,
'approvalNum' => $tx->approval_num,
'approvalType' => $tx->approval_type,
'approvalAmount' => (int) $tx->approval_amount,
'supplyAmount' => $supplyAmount,
'taxAmount' => $taxAmount,
'merchantName' => $tx->merchant_name,
'merchantBizNum' => $tx->merchant_biz_num,
'deductionType' => $tx->deduction_type,
'accountCode' => $tx->account_code,
'accountName' => $tx->account_name,
'memo' => $tx->memo,
'description' => $tx->description,
];
}
// 각 거래의 uniqueKey 수집
$uniqueKeys = array_column($logs, 'uniqueKey');
// 분개 완료된 source_key 조회
$journaledKeys = JournalEntry::getJournaledSourceKeys($tenantId, 'ecard_transaction', $uniqueKeys);
$journaledKeysMap = array_flip($journaledKeys);
// 분개된 전표 ID 조회
$journalMap = [];
if (! empty($journaledKeys)) {
$journals = JournalEntry::where('tenant_id', $tenantId)
->where('source_type', 'ecard_transaction')
->whereIn('source_key', $journaledKeys)
->select('id', 'source_key', 'entry_no')
->get();
foreach ($journals as $j) {
$journalMap[$j->source_key] = ['id' => $j->id, 'entry_no' => $j->entry_no];
}
}
// 각 거래에 분개 상태 추가
foreach ($logs as &$log) {
$key = $log['uniqueKey'] ?? '';
$log['hasJournal'] = isset($journaledKeysMap[$key]);
$log['journalId'] = $journalMap[$key]['id'] ?? null;
$log['journalEntryNo'] = $journalMap[$key]['entry_no'] ?? null;
}
unset($log);
// 통계
$totalCount = count($logs);
$totalAmount = array_sum(array_column($logs, 'approvalAmount'));
$deductibleSum = 0;
$nonDeductibleSum = 0;
foreach ($logs as $log) {
if ($log['deductionType'] === 'non_deductible') {
$nonDeductibleSum += $log['approvalAmount'];
} else {
$deductibleSum += $log['approvalAmount'];
}
}
$journaledCount = count($journaledKeys);
// 카드 목록 (드롭다운용)
$cards = CardTransaction::where('tenant_id', $tenantId)
->select('card_num', 'card_company_name')
->distinct()
->get()
->toArray();
return response()->json([
'success' => true,
'data' => [
'logs' => $logs,
'cards' => $cards,
'summary' => [
'totalCount' => $totalCount,
'totalAmount' => $totalAmount,
'deductibleSum' => $deductibleSum,
'nonDeductibleSum' => $nonDeductibleSum,
],
'journalStats' => [
'journaledCount' => $journaledCount,
'unjournaledCount' => $totalCount - $journaledCount,
],
],
]);
} catch (\Throwable $e) {
Log::error('카드거래 목록 조회 오류: '.$e->getMessage());
return response()->json([
'success' => false,
'message' => '카드거래 목록 조회 실패: '.$e->getMessage(),
], 500);
}
}
/**
* 카드거래 기반 전표 생성
*/
public function storeFromCard(Request $request): JsonResponse
{
$request->validate([
'source_key' => 'required|string|max:255',
'entry_date' => 'required|date',
'description' => 'nullable|string|max:500',
'lines' => 'required|array|min:2',
'lines.*.dc_type' => 'required|in:debit,credit',
'lines.*.account_code' => 'required|string|max:10',
'lines.*.account_name' => 'required|string|max:100',
'lines.*.trading_partner_id' => 'nullable|integer',
'lines.*.trading_partner_name' => 'nullable|string|max:100',
'lines.*.debit_amount' => 'required|integer|min:0',
'lines.*.credit_amount' => 'required|integer|min:0',
'lines.*.description' => 'nullable|string|max:300',
]);
$tenantId = session('selected_tenant_id', 1);
$lines = $request->lines;
$totalDebit = collect($lines)->sum('debit_amount');
$totalCredit = collect($lines)->sum('credit_amount');
if ($totalDebit !== $totalCredit || $totalDebit === 0) {
return response()->json([
'success' => false,
'message' => '차변합계와 대변합계가 일치해야 하며 0보다 커야 합니다.',
], 422);
}
// 중복 분개 체크
$existing = JournalEntry::getJournalBySourceKey($tenantId, 'ecard_transaction', $request->source_key);
if ($existing) {
return response()->json([
'success' => false,
'message' => '이미 분개가 완료된 거래입니다. (전표번호: '.$existing->entry_no.')',
], 422);
}
$maxRetries = 3;
$lastError = null;
for ($attempt = 0; $attempt < $maxRetries; $attempt++) {
try {
$entry = DB::transaction(function () use ($tenantId, $request, $lines, $totalDebit, $totalCredit) {
$entryNo = JournalEntry::generateEntryNo($tenantId, $request->entry_date);
$entry = JournalEntry::create([
'tenant_id' => $tenantId,
'entry_no' => $entryNo,
'entry_date' => $request->entry_date,
'description' => $request->description,
'total_debit' => $totalDebit,
'total_credit' => $totalCredit,
'status' => 'draft',
'source_type' => 'ecard_transaction',
'source_key' => $request->source_key,
'created_by_name' => auth()->user()?->name ?? '시스템',
]);
foreach ($lines as $i => $line) {
JournalEntryLine::create([
'tenant_id' => $tenantId,
'journal_entry_id' => $entry->id,
'line_no' => $i + 1,
'dc_type' => $line['dc_type'],
'account_code' => $line['account_code'],
'account_name' => $line['account_name'],
'trading_partner_id' => $line['trading_partner_id'] ?? null,
'trading_partner_name' => $line['trading_partner_name'] ?? null,
'debit_amount' => $line['debit_amount'],
'credit_amount' => $line['credit_amount'],
'description' => $line['description'] ?? null,
]);
}
return $entry;
});
return response()->json([
'success' => true,
'message' => '분개가 저장되었습니다.',
'data' => ['id' => $entry->id, 'entry_no' => $entry->entry_no],
]);
} catch (\Illuminate\Database\QueryException $e) {
$lastError = $e;
if ($e->errorInfo[1] === 1062) {
continue;
}
break;
} catch (\Throwable $e) {
$lastError = $e;
break;
}
}
Log::error('카드거래 분개 저장 오류: '.$lastError->getMessage());
return response()->json([
'success' => false,
'message' => '분개 저장 실패: '.$lastError->getMessage(),
], 500);
}
/**
* 특정 카드거래의 기존 분개 조회
*/
public function cardJournals(Request $request): JsonResponse
{
$tenantId = session('selected_tenant_id', 1);
$sourceKey = $request->get('source_key');
if (! $sourceKey) {
return response()->json(['success' => false, 'message' => 'source_key가 필요합니다.'], 422);
}
$entry = JournalEntry::forTenant($tenantId)
->where('source_type', 'ecard_transaction')
->where('source_key', $sourceKey)
->with('lines')
->first();
if (! $entry) {
return response()->json(['success' => true, 'data' => null]);
}
return response()->json([
'success' => true,
'data' => [
'id' => $entry->id,
'entry_no' => $entry->entry_no,
'entry_date' => $entry->entry_date->format('Y-m-d'),
'description' => $entry->description,
'total_debit' => $entry->total_debit,
'total_credit' => $entry->total_credit,
'status' => $entry->status,
'lines' => $entry->lines->map(function ($line) {
return [
'id' => $line->id,
'line_no' => $line->line_no,
'dc_type' => $line->dc_type,
'account_code' => $line->account_code,
'account_name' => $line->account_name,
'trading_partner_id' => $line->trading_partner_id,
'trading_partner_name' => $line->trading_partner_name,
'debit_amount' => $line->debit_amount,
'credit_amount' => $line->credit_amount,
'description' => $line->description,
];
}),
],
]);
}
/**
* 카드거래 분개 삭제 (soft delete)
*/
public function deleteCardJournal(int $id): JsonResponse
{
$tenantId = session('selected_tenant_id', 1);
$entry = JournalEntry::forTenant($tenantId)
->where('source_type', 'ecard_transaction')
->findOrFail($id);
$entry->delete();
return response()->json([
'success' => true,
'message' => '분개가 삭제되었습니다.',
]);
}
}