import { supabase } from '@/lib/supabase'; import { Transaction } from '@/components/TransactionCard'; import { isSyncEnabled } from '../syncSettings'; import { normalizeDate } from './dateUtils'; /** * Upload transaction data from local storage to Supabase * 로컬 데이터를 서버에 업로드 (새로운 또는 수정된 데이터만) */ export const uploadTransactions = async (userId: string): Promise => { if (!isSyncEnabled()) return; try { const localTransactions = localStorage.getItem('transactions'); if (!localTransactions) return; const transactions: Transaction[] = JSON.parse(localTransactions); console.log(`로컬 트랜잭션 ${transactions.length}개 동기화 시작`); if (transactions.length === 0) return; // 트랜잭션이 없으면 처리하지 않음 // 먼저 서버에서 현재 트랜잭션 목록 가져오기 const { data: existingData, error: fetchError } = await supabase .from('transactions') .select('transaction_id') .eq('user_id', userId); if (fetchError) { console.error('[동기화] 기존 트랜잭션 조회 실패:', fetchError); console.error('[동기화] 오류 상세:', JSON.stringify(fetchError, null, 2)); throw fetchError; } // 서버에 이미 있는 트랜잭션 ID 맵 생성 const existingIds = new Set(existingData?.map(t => t.transaction_id) || []); console.log(`서버에 이미 존재하는 트랜잭션: ${existingIds.size}개`); // 삽입할 새 트랜잭션과 업데이트할 기존 트랜잭션 분리 const newTransactions = []; const updateTransactions = []; for (const t of transactions) { try { // 날짜 형식 정규화 const normalizedDate = normalizeDate(t.date); const transactionData = { user_id: userId, title: t.title || '무제', amount: t.amount || 0, date: normalizedDate, // 정규화된 날짜 사용 category: t.category || '기타', type: t.type || 'expense', transaction_id: t.id, notes: t.notes || null }; if (existingIds.has(t.id)) { updateTransactions.push(transactionData); } else { newTransactions.push(transactionData); } } catch (err) { console.error(`[동기화] 트랜잭션 처리 중 오류 (ID: ${t.id}):`, err); // 개별 트랜잭션 오류는 기록하고 계속 진행 } } // 새 트랜잭션 삽입 (있는 경우) - 배치 처리 if (newTransactions.length > 0) { console.log(`${newTransactions.length}개의 새 트랜잭션 업로드`); // 대용량 데이터 처리를 위해 배치 처리 (최대 100개씩) const batchSize = 100; for (let i = 0; i < newTransactions.length; i += batchSize) { const batch = newTransactions.slice(i, i + batchSize); const { error: insertError } = await supabase .from('transactions') .insert(batch); if (insertError) { console.error(`[동기화] 새 트랜잭션 배치 업로드 실패 (${i}~${i + batch.length}):`, insertError); console.error('[동기화] 오류 상세:', JSON.stringify(insertError, null, 2)); // 배치 실패해도 다음 배치 계속 시도 } } } // 기존 트랜잭션 업데이트 (있는 경우) - 배치 처리 if (updateTransactions.length > 0) { console.log(`${updateTransactions.length}개의 기존 트랜잭션 업데이트`); // 대용량 데이터 처리를 위해 배치 처리 (최대 50개씩) // 업데이트는 개별 쿼리보다 효율적이지만 삽입보다는 복잡하므로 더 작은 배치 크기 사용 const batchSize = 50; for (let i = 0; i < updateTransactions.length; i += batchSize) { const batch = updateTransactions.slice(i, i + batchSize); // 배치 내 트랜잭션을 병렬로 업데이트 (Promise.all 사용) const updatePromises = batch.map(transaction => supabase .from('transactions') .update(transaction) .eq('transaction_id', transaction.transaction_id) .eq('user_id', userId) ); try { const results = await Promise.all(updatePromises); // 오류 확인 const errors = results.filter(result => result.error); if (errors.length > 0) { console.error(`[동기화] ${errors.length}개의 트랜잭션 업데이트 실패`); errors.forEach(err => { console.error('[동기화] 업데이트 오류:', err.error); }); } } catch (batchError) { console.error(`[동기화] 트랜잭션 배치 업데이트 실패 (${i}~${i + batch.length}):`, batchError); // 배치 실패해도 다음 배치 계속 시도 } } } console.log('[동기화] 트랜잭션 업로드 완료'); } catch (error) { console.error('[동기화] 트랜잭션 업로드 실패:', error); console.error('[동기화] 오류 상세:', JSON.stringify(error, null, 2)); throw error; } };