import { isSyncEnabled, setSyncEnabled, getLastSyncTime, setLastSyncTime, initSyncSettings } from './sync/syncSettings'; import { uploadTransactions, downloadTransactions, deleteTransactionFromServer } from './sync/transactionSync'; import { uploadBudgets, downloadBudgets } from './sync/budget'; import { clearCloudData } from './sync/clearCloudData'; // Export all utility functions to maintain the same public API export { isSyncEnabled, setSyncEnabled, uploadTransactions, downloadTransactions, deleteTransactionFromServer, uploadBudgets, downloadBudgets, getLastSyncTime, setLastSyncTime, initSyncSettings, clearCloudData }; /** * Synchronize all data with Supabase */ export const syncAllData = async (userId: string): Promise => { if (!userId || !isSyncEnabled()) return; try { console.log('데이터 동기화 시작...'); // 기존 동기화 순서: 서버에서 먼저 다운로드 후, 로컬 데이터 업로드 // 이 순서를 유지하여 서버에 저장된 데이터를 먼저 가져온 후, 로컬 변경사항을 반영 // 1. 서버에서 데이터 다운로드 (기존 데이터 불러오기) await downloadTransactions(userId); await downloadBudgets(userId); // 약간의 딜레이를 추가하여 다운로드된 데이터가 처리될 시간을 줌 await new Promise(resolve => setTimeout(resolve, 500)); // 2. 로컬 데이터를 서버에 업로드 (변경사항 반영) await uploadTransactions(userId); await uploadBudgets(userId); // 동기화 시간 업데이트 setLastSyncTime(); console.log('데이터 동기화 완료!'); } catch (error) { console.error('동기화 중 오류 발생:', error); throw error; // 오류를 상위 호출자에게 전달하여 적절히 처리하도록 함 } }; // trySyncAllData의 반환 타입 명시적 정의 // 동기화 결과를 위한 인터페이스 정의 export interface SyncResult { success: boolean; partial?: boolean; downloadSuccess?: boolean; uploadSuccess?: boolean; error?: any; } // 안전하게 동기화 시도하는 함수 개선 export const trySyncAllData = async (userId: string): Promise => { if (!userId || !isSyncEnabled()) return { success: true }; let downloadSuccess = false; let uploadSuccess = false; try { console.log('안전한 데이터 동기화 시도...'); try { // 1단계: 서버에서 데이터 다운로드 await downloadTransactions(userId); await downloadBudgets(userId); console.log('서버 데이터 다운로드 성공'); downloadSuccess = true; // 다운로드 단계가 성공적으로 완료되면 부분 동기화 마킹 setLastSyncTime('부분-다운로드'); } catch (downloadError) { console.error('다운로드 동기화 오류:', downloadError); // 다운로드 실패해도 업로드는 시도 - 부분 동기화 } // 다운로드 후 약간의 지연을 추가하여 로컬 상태가 업데이트될 시간을 줌 await new Promise(resolve => setTimeout(resolve, 500)); try { // 2단계: 로컬 데이터를 서버에 업로드 await uploadTransactions(userId); await uploadBudgets(userId); console.log('로컬 데이터 업로드 성공'); uploadSuccess = true; // 업로드까지 성공적으로 완료되면 동기화 시간 업데이트 setLastSyncTime(); } catch (uploadError) { console.error('업로드 동기화 오류:', uploadError); // 업로드 실패해도 다운로드는 성공했을 수 있으므로 부분 성공으로 간주 } // 하나라도 성공했으면 부분 성공으로 간주 const result: SyncResult = { success: downloadSuccess || uploadSuccess, partial: (downloadSuccess && !uploadSuccess) || (!downloadSuccess && uploadSuccess), downloadSuccess, uploadSuccess }; console.log('동기화 결과:', result); return result; } catch (error) { console.error('전체 동기화 시도 중 오류:', error); return { success: false, error, downloadSuccess, uploadSuccess }; } };