Refactor transaction sync module
Refactors the transaction sync module for better organization.
This commit is contained in:
98
src/utils/sync/transaction/uploadTransaction.ts
Normal file
98
src/utils/sync/transaction/uploadTransaction.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
|
||||
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<void> => {
|
||||
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);
|
||||
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) {
|
||||
// 날짜 형식 정규화
|
||||
const normalizedDate = normalizeDate(t.date);
|
||||
|
||||
const transactionData = {
|
||||
user_id: userId,
|
||||
title: t.title,
|
||||
amount: t.amount,
|
||||
date: normalizedDate, // 정규화된 날짜 사용
|
||||
category: t.category,
|
||||
type: t.type,
|
||||
transaction_id: t.id
|
||||
};
|
||||
|
||||
if (existingIds.has(t.id)) {
|
||||
updateTransactions.push(transactionData);
|
||||
} else {
|
||||
newTransactions.push(transactionData);
|
||||
}
|
||||
}
|
||||
|
||||
// 새 트랜잭션 삽입 (있는 경우)
|
||||
if (newTransactions.length > 0) {
|
||||
console.log(`${newTransactions.length}개의 새 트랜잭션 업로드`);
|
||||
const { error: insertError } = await supabase
|
||||
.from('transactions')
|
||||
.insert(newTransactions);
|
||||
|
||||
if (insertError) {
|
||||
console.error('새 트랜잭션 업로드 실패:', insertError);
|
||||
throw insertError;
|
||||
}
|
||||
}
|
||||
|
||||
// 기존 트랜잭션 업데이트 (있는 경우)
|
||||
if (updateTransactions.length > 0) {
|
||||
console.log(`${updateTransactions.length}개의 기존 트랜잭션 업데이트`);
|
||||
for (const transaction of updateTransactions) {
|
||||
const { error: updateError } = await supabase
|
||||
.from('transactions')
|
||||
.update(transaction)
|
||||
.eq('transaction_id', transaction.transaction_id)
|
||||
.eq('user_id', userId);
|
||||
|
||||
if (updateError) {
|
||||
console.error('트랜잭션 업데이트 실패:', updateError);
|
||||
// 실패해도 계속 진행
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('트랜잭션 업로드 완료');
|
||||
} catch (error) {
|
||||
console.error('트랜잭션 업로드 실패:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user