From 6991f5d27f1a564998a29d25c1dbac251b709e4c Mon Sep 17 00:00:00 2001 From: "gpt-engineer-app[bot]" <159125892+gpt-engineer-app[bot]@users.noreply.github.com> Date: Sat, 15 Mar 2025 12:13:19 +0000 Subject: [PATCH] Refactor syncSettings.ts Refactor syncSettings.ts to improve modularity. --- src/utils/sync/config.ts | 52 ++++++++++++ src/utils/sync/data.ts | 71 ++++++++++++++++ src/utils/sync/syncSettings.ts | 145 +++------------------------------ src/utils/sync/time.ts | 24 ++++++ src/utils/syncUtils.ts | 2 +- 5 files changed, 160 insertions(+), 134 deletions(-) create mode 100644 src/utils/sync/config.ts create mode 100644 src/utils/sync/data.ts create mode 100644 src/utils/sync/time.ts diff --git a/src/utils/sync/config.ts b/src/utils/sync/config.ts new file mode 100644 index 0000000..fe7a28a --- /dev/null +++ b/src/utils/sync/config.ts @@ -0,0 +1,52 @@ + +import { supabase } from '@/lib/supabase'; + +/** + * 동기화 기능이 활성화되어 있는지 확인 + */ +export const isSyncEnabled = (): boolean => { + try { + return localStorage.getItem('syncEnabled') === 'true'; + } catch (error) { + console.error('동기화 설정 확인 중 오류:', error); + return false; + } +}; + +/** + * 동기화 설정 업데이트 + */ +export const setSyncEnabled = (enabled: boolean): void => { + try { + localStorage.setItem('syncEnabled', enabled.toString()); + } catch (error) { + console.error('동기화 설정 업데이트 중 오류:', error); + } +}; + +/** + * 동기화 설정 초기화 + */ +export const initSyncSettings = (): void => { + try { + if (localStorage.getItem('syncEnabled') === null) { + localStorage.setItem('syncEnabled', 'false'); + } + + // Supabase 연결 테스트 + (async () => { + try { + const { data, error } = await supabase.auth.getUser(); + if (error) { + console.warn('Supabase 연결 테스트 실패:', error.message); + } else { + console.log('Supabase 연결 테스트 성공:', data.user ? '사용자 로그인됨' : '사용자 로그인 필요'); + } + } catch (testError) { + console.error('Supabase 연결 테스트 중 예외 발생:', testError); + } + })(); + } catch (error) { + console.error('동기화 설정 초기화 중 오류:', error); + } +}; diff --git a/src/utils/sync/data.ts b/src/utils/sync/data.ts new file mode 100644 index 0000000..b574b63 --- /dev/null +++ b/src/utils/sync/data.ts @@ -0,0 +1,71 @@ + +import { supabase } from '@/lib/supabase'; +import { setLastSyncTime } from './time'; + +/** + * 모든 데이터 동기화 기능 + */ +export const syncAllData = async (userId: string): Promise => { + if (!userId) { + throw new Error('사용자 ID가 필요합니다'); + } + + try { + // 로컬 트랜잭션 데이터 가져오기 + const transactionsJSON = localStorage.getItem('transactions'); + const transactions = transactionsJSON ? JSON.parse(transactionsJSON) : []; + + // 예산 데이터 가져오기 + const budgetDataJSON = localStorage.getItem('budgetData'); + const budgetData = budgetDataJSON ? JSON.parse(budgetDataJSON) : {}; + + // 카테고리 예산 가져오기 + const categoryBudgetsJSON = localStorage.getItem('categoryBudgets'); + const categoryBudgets = categoryBudgetsJSON ? JSON.parse(categoryBudgetsJSON) : {}; + + // 트랜잭션 데이터 동기화 + for (const transaction of transactions) { + // 이미 동기화된 데이터인지 확인 (transaction_id로 확인) + const { data: existingData } = await supabase + .from('transactions') + .select('*') + .eq('transaction_id', transaction.id) + .eq('user_id', userId); + + // 존재하지 않는 경우에만 삽입 + if (!existingData || existingData.length === 0) { + await supabase.from('transactions').insert({ + user_id: userId, + title: transaction.title, + amount: transaction.amount, + date: transaction.date, + category: transaction.category, + type: transaction.type, + transaction_id: transaction.id + }); + } + } + + // 예산 데이터 동기화 + await supabase.from('budget_data').upsert({ + user_id: userId, + data: budgetData, + updated_at: new Date().toISOString() + }); + + // 카테고리 예산 동기화 + await supabase.from('category_budgets').upsert({ + user_id: userId, + data: categoryBudgets, + updated_at: new Date().toISOString() + }); + + // 마지막 동기화 시간 업데이트 + setLastSyncTime(); + + console.log('모든 데이터가 성공적으로 동기화되었습니다'); + } catch (error) { + console.error('데이터 동기화 중 오류 발생:', error); + throw error; + } +}; diff --git a/src/utils/sync/syncSettings.ts b/src/utils/sync/syncSettings.ts index 541988c..e976459 100644 --- a/src/utils/sync/syncSettings.ts +++ b/src/utils/sync/syncSettings.ts @@ -1,136 +1,15 @@ -// Core synchronization settings utilities -import { supabase } from '@/lib/supabase'; +// 동기화 관련 모든 기능을 한 곳에서 내보내는 인덱스 파일 +import { isSyncEnabled, setSyncEnabled, initSyncSettings } from './config'; +import { getLastSyncTime, setLastSyncTime } from './time'; +import { syncAllData } from './data'; -/** - * Check if synchronization is enabled in local storage - */ -export const isSyncEnabled = (): boolean => { - try { - return localStorage.getItem('syncEnabled') === 'true'; - } catch (error) { - console.error('동기화 설정 확인 중 오류:', error); - return false; - } -}; - -/** - * Update synchronization settings in local storage - */ -export const setSyncEnabled = (enabled: boolean): void => { - try { - localStorage.setItem('syncEnabled', enabled.toString()); - } catch (error) { - console.error('동기화 설정 업데이트 중 오류:', error); - } -}; - -// 최종 동기화 시간 관리 -export const getLastSyncTime = (): string | null => { - try { - return localStorage.getItem('lastSyncTime'); - } catch (error) { - console.error('마지막 동기화 시간 확인 중 오류:', error); - return null; - } -}; - -export const setLastSyncTime = (): void => { - try { - const now = new Date().toISOString(); - localStorage.setItem('lastSyncTime', now); - } catch (error) { - console.error('마지막 동기화 시간 업데이트 중 오류:', error); - } -}; - -// 모든 데이터 동기화 함수 -export const syncAllData = async (userId: string): Promise => { - if (!userId) { - throw new Error('사용자 ID가 필요합니다'); - } - - try { - // 로컬 트랜잭션 데이터 가져오기 - const transactionsJSON = localStorage.getItem('transactions'); - const transactions = transactionsJSON ? JSON.parse(transactionsJSON) : []; - - // 예산 데이터 가져오기 - const budgetDataJSON = localStorage.getItem('budgetData'); - const budgetData = budgetDataJSON ? JSON.parse(budgetDataJSON) : {}; - - // 카테고리 예산 가져오기 - const categoryBudgetsJSON = localStorage.getItem('categoryBudgets'); - const categoryBudgets = categoryBudgetsJSON ? JSON.parse(categoryBudgetsJSON) : {}; - - // 트랜잭션 데이터 동기화 - for (const transaction of transactions) { - // 이미 동기화된 데이터인지 확인 (transaction_id로 확인) - const { data: existingData } = await supabase - .from('transactions') - .select('*') - .eq('transaction_id', transaction.id) - .eq('user_id', userId); - - // 존재하지 않는 경우에만 삽입 - if (!existingData || existingData.length === 0) { - await supabase.from('transactions').insert({ - user_id: userId, - title: transaction.title, - amount: transaction.amount, - date: transaction.date, - category: transaction.category, - type: transaction.type, - transaction_id: transaction.id - }); - } - } - - // 예산 데이터 동기화 - await supabase.from('budget_data').upsert({ - user_id: userId, - data: budgetData, - updated_at: new Date().toISOString() - }); - - // 카테고리 예산 동기화 - await supabase.from('category_budgets').upsert({ - user_id: userId, - data: categoryBudgets, - updated_at: new Date().toISOString() - }); - - // 마지막 동기화 시간 업데이트 - setLastSyncTime(); - - console.log('모든 데이터가 성공적으로 동기화되었습니다'); - } catch (error) { - console.error('데이터 동기화 중 오류 발생:', error); - throw error; - } -}; - -// 초기화 함수 추가 -export const initSyncSettings = (): void => { - try { - if (localStorage.getItem('syncEnabled') === null) { - localStorage.setItem('syncEnabled', 'false'); - } - - // Supabase 연결 테스트 - (async () => { - try { - const { data, error } = await supabase.auth.getUser(); - if (error) { - console.warn('Supabase 연결 테스트 실패:', error.message); - } else { - console.log('Supabase 연결 테스트 성공:', data.user ? '사용자 로그인됨' : '사용자 로그인 필요'); - } - } catch (testError) { - console.error('Supabase 연결 테스트 중 예외 발생:', testError); - } - })(); - } catch (error) { - console.error('동기화 설정 초기화 중 오류:', error); - } +// 단일 진입점에서 모든 기능 내보내기 +export { + isSyncEnabled, + setSyncEnabled, + getLastSyncTime, + setLastSyncTime, + syncAllData, + initSyncSettings }; diff --git a/src/utils/sync/time.ts b/src/utils/sync/time.ts new file mode 100644 index 0000000..96e9ba8 --- /dev/null +++ b/src/utils/sync/time.ts @@ -0,0 +1,24 @@ + +/** + * 마지막 동기화 시간 가져오기 + */ +export const getLastSyncTime = (): string | null => { + try { + return localStorage.getItem('lastSyncTime'); + } catch (error) { + console.error('마지막 동기화 시간 확인 중 오류:', error); + return null; + } +}; + +/** + * 마지막 동기화 시간 설정 + */ +export const setLastSyncTime = (): void => { + try { + const now = new Date().toISOString(); + localStorage.setItem('lastSyncTime', now); + } catch (error) { + console.error('마지막 동기화 시간 업데이트 중 오류:', error); + } +}; diff --git a/src/utils/syncUtils.ts b/src/utils/syncUtils.ts index 05f80db..862bd48 100644 --- a/src/utils/syncUtils.ts +++ b/src/utils/syncUtils.ts @@ -1,5 +1,5 @@ -import { isSyncEnabled, setSyncEnabled, getLastSyncTime, setLastSyncTime, initSyncSettings } from './sync/syncSettings'; +import { isSyncEnabled, setSyncEnabled, getLastSyncTime, setLastSyncTime, syncAllData, initSyncSettings } from './sync/syncSettings'; import { uploadTransactions, downloadTransactions } from './sync/transactionSync'; import { uploadBudgets, downloadBudgets } from './sync/budgetSync';