Refactor syncSettings.ts

Refactor syncSettings.ts to improve modularity.
This commit is contained in:
gpt-engineer-app[bot]
2025-03-15 12:13:19 +00:00
parent 2493f958de
commit 6991f5d27f
5 changed files with 160 additions and 134 deletions

52
src/utils/sync/config.ts Normal file
View File

@@ -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);
}
};

71
src/utils/sync/data.ts Normal file
View File

@@ -0,0 +1,71 @@
import { supabase } from '@/lib/supabase';
import { setLastSyncTime } from './time';
/**
* 모든 데이터 동기화 기능
*/
export const syncAllData = async (userId: string): Promise<void> => {
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;
}
};

View File

@@ -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<void> => {
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
};

24
src/utils/sync/time.ts Normal file
View File

@@ -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);
}
};

View File

@@ -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';