73 lines
2.3 KiB
TypeScript
73 lines
2.3 KiB
TypeScript
|
|
import { supabase } from '@/lib/supabase';
|
|
import { Transaction } from '@/components/TransactionCard';
|
|
import { isSyncEnabled } from '../syncSettings';
|
|
|
|
/**
|
|
* Download transaction data from Supabase to local storage
|
|
* 서버에서 로컬 스토리지로 데이터 다운로드 (병합 방식)
|
|
*/
|
|
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);
|
|
|
|
if (error) {
|
|
console.error('트랜잭션 다운로드 실패:', error);
|
|
throw error;
|
|
}
|
|
|
|
if (!data || data.length === 0) {
|
|
console.log('서버에 저장된 트랜잭션 없음');
|
|
return; // 서버에 데이터가 없으면 로컬 데이터 유지
|
|
}
|
|
|
|
console.log(`서버에서 ${data.length}개의 트랜잭션 다운로드`);
|
|
|
|
// 서버 데이터를 로컬 형식으로 변환
|
|
const serverTransactions = data.map(t => ({
|
|
id: t.transaction_id || t.id,
|
|
title: t.title,
|
|
amount: t.amount,
|
|
date: t.date,
|
|
category: t.category,
|
|
type: t.type
|
|
}));
|
|
|
|
// 기존 로컬 데이터 불러오기
|
|
const localDataStr = localStorage.getItem('transactions');
|
|
const localTransactions = localDataStr ? JSON.parse(localDataStr) : [];
|
|
|
|
// 로컬 데이터와 서버 데이터 병합 (ID 기준)
|
|
const transactionMap = new Map();
|
|
|
|
// 로컬 데이터를 맵에 추가
|
|
localTransactions.forEach((tx: Transaction) => {
|
|
transactionMap.set(tx.id, tx);
|
|
});
|
|
|
|
// 서버 데이터로 맵 업데이트 (서버 데이터 우선)
|
|
serverTransactions.forEach(tx => {
|
|
transactionMap.set(tx.id, tx);
|
|
});
|
|
|
|
// 최종 병합된 데이터 생성
|
|
const mergedTransactions = Array.from(transactionMap.values());
|
|
|
|
// 로컬 스토리지에 저장
|
|
localStorage.setItem('transactions', JSON.stringify(mergedTransactions));
|
|
console.log(`총 ${mergedTransactions.length}개의 트랜잭션 병합 완료`);
|
|
|
|
// 이벤트 발생시켜 UI 업데이트
|
|
window.dispatchEvent(new Event('transactionUpdated'));
|
|
} catch (error) {
|
|
console.error('트랜잭션 다운로드 중 오류:', error);
|
|
throw error;
|
|
}
|
|
};
|