92 lines
3.0 KiB
TypeScript
92 lines
3.0 KiB
TypeScript
|
|
import { supabase } from '@/archive/lib/supabase';
|
|
import { Transaction } from '@/components/TransactionCard';
|
|
import { isSyncEnabled } from './syncSettings';
|
|
import { formatDateForDisplay } from './transaction/dateUtils';
|
|
|
|
/**
|
|
* 서버에서 트랜잭션 데이터 다운로드
|
|
*/
|
|
export const downloadTransactions = async (userId: string): Promise<void> => {
|
|
if (!isSyncEnabled()) return;
|
|
|
|
try {
|
|
console.log('서버에서 트랜잭션 다운로드 시작');
|
|
|
|
// 서버에서 모든 트랜잭션 가져오기
|
|
const { data, error } = await supabase
|
|
.from('transactions')
|
|
.select('*')
|
|
.eq('user_id', userId)
|
|
.order('date', { ascending: false });
|
|
|
|
if (error) {
|
|
console.error('트랜잭션 다운로드 실패:', error);
|
|
throw error;
|
|
}
|
|
|
|
if (data && data.length > 0) {
|
|
// 기존 로컬 트랜잭션 로드
|
|
let localTransactions: Transaction[] = [];
|
|
try {
|
|
const storedTransactions = localStorage.getItem('transactions');
|
|
if (storedTransactions) {
|
|
localTransactions = JSON.parse(storedTransactions);
|
|
}
|
|
} catch (e) {
|
|
console.error('로컬 트랜잭션 파싱 오류:', e);
|
|
}
|
|
|
|
// 서버 트랜잭션을 로컬 형식으로 변환
|
|
const serverTransactions: Transaction[] = data.map(t => ({
|
|
id: t.transaction_id || t.id,
|
|
title: t.title,
|
|
amount: t.amount,
|
|
// 날짜 포맷팅
|
|
date: formatDateForDisplay(t.date),
|
|
category: t.category,
|
|
type: t.type,
|
|
notes: t.notes
|
|
}));
|
|
|
|
console.log(`서버에서 ${serverTransactions.length}개의 트랜잭션 다운로드됨`);
|
|
|
|
// 로컬 데이터와 서버 데이터 병합 (중복 ID 제거)
|
|
const mergedTransactions: Transaction[] = [];
|
|
const processedIds = new Set<string>();
|
|
|
|
// 서버 데이터 우선 처리
|
|
serverTransactions.forEach(transaction => {
|
|
if (!processedIds.has(transaction.id)) {
|
|
mergedTransactions.push(transaction);
|
|
processedIds.add(transaction.id);
|
|
}
|
|
});
|
|
|
|
// 서버에 없는 로컬 트랜잭션 추가
|
|
localTransactions.forEach(transaction => {
|
|
if (!processedIds.has(transaction.id)) {
|
|
mergedTransactions.push(transaction);
|
|
processedIds.add(transaction.id);
|
|
}
|
|
});
|
|
|
|
// 병합된 트랜잭션 저장
|
|
localStorage.setItem('transactions', JSON.stringify(mergedTransactions));
|
|
localStorage.setItem('transactions_backup', JSON.stringify(mergedTransactions));
|
|
|
|
console.log(`${mergedTransactions.length}개의 트랜잭션 병합 완료`);
|
|
|
|
// UI 업데이트를 위한 이벤트 발생
|
|
window.dispatchEvent(new Event('transactionUpdated'));
|
|
} else {
|
|
console.log('서버에 저장된 트랜잭션이 없습니다.');
|
|
}
|
|
|
|
console.log('트랜잭션 데이터 다운로드 완료');
|
|
} catch (error) {
|
|
console.error('트랜잭션 다운로드 오류:', error);
|
|
throw error;
|
|
}
|
|
};
|