- utils/backup.js: 가계부 전체(내역·계좌·분류·고정지출·예산·태그·자주내역)를 이름 기준 참조로 .xlsx 다중 시트 생성. xlsx 동적 import(별도 청크) - 웹/PC=다운로드, 앱(네이티브)=Filesystem 저장 + Share - SettingsView: '데이터 백업' 카드(엑셀로 내보내기 동작 / 가져오기 버튼=준비중) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
+26
-5
@@ -94,15 +94,36 @@ const TAGS = [
|
||||
{ id: 403, name: '경조사' },
|
||||
]
|
||||
|
||||
// 요약은 내역에서 계산해 일관성 보장
|
||||
const SUMMARY = (() => {
|
||||
// 해당 연·월 내역만 (월 이동 반영)
|
||||
function inMonth(e, year, month) {
|
||||
if (!year || !month) return true
|
||||
return e.entryDate.startsWith(`${year}-${String(month).padStart(2, '0')}`)
|
||||
}
|
||||
// 검색·필터 적용
|
||||
function filterEntries(p = {}) {
|
||||
let rows = ENTRIES.filter((e) => inMonth(e, p.year, p.month))
|
||||
if (p.type) rows = rows.filter((e) => e.type === p.type)
|
||||
if (p.category) rows = rows.filter((e) => e.category === p.category)
|
||||
if (p.walletId) rows = rows.filter((e) => String(e.walletId) === String(p.walletId))
|
||||
if (p.keyword) {
|
||||
const k = String(p.keyword).trim()
|
||||
rows = rows.filter((e) => (e.memo || '').includes(k) || (e.category || '').includes(k))
|
||||
}
|
||||
if (p.tagId) {
|
||||
const t = TAGS.find((x) => String(x.id) === String(p.tagId))
|
||||
if (t) rows = rows.filter((e) => (e.tags || []).includes(t.name))
|
||||
}
|
||||
return rows
|
||||
}
|
||||
function summaryOf(p = {}) {
|
||||
let income = 0, expense = 0
|
||||
for (const e of ENTRIES) {
|
||||
if (!inMonth(e, p.year, p.month)) continue
|
||||
if (e.type === 'INCOME') income += e.amount
|
||||
else if (e.type === 'EXPENSE') expense += e.amount
|
||||
}
|
||||
return { totalIncome: income, totalExpense: expense, balance: income - expense }
|
||||
})()
|
||||
}
|
||||
const NETWORTH = { totalAssets: 15860000, totalLiabilities: 340000, netWorth: 15520000 }
|
||||
|
||||
function ok(data) {
|
||||
@@ -115,8 +136,8 @@ function block() {
|
||||
|
||||
// 읽기 응답 / 쓰기 차단
|
||||
export const demoApi = {
|
||||
list: () => ok(ENTRIES),
|
||||
summary: () => ok(SUMMARY),
|
||||
list: (params) => ok(filterEntries(params)),
|
||||
summary: (params) => ok(summaryOf(params)),
|
||||
wallets: () => ok(WALLETS),
|
||||
netWorth: () => ok(NETWORTH),
|
||||
categories: () => ok(CATEGORIES),
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// 데이터 백업 — 가계부 전체 데이터를 엑셀(.xlsx)로 내보내기.
|
||||
// 참조는 이름 기준(계좌명·분류명·태그명)으로 저장해 추후 '가져오기(복구)' 시 재매핑이 단순하도록 한다.
|
||||
import { Capacitor } from '@capacitor/core'
|
||||
import { accountApi } from '@/api/accountApi'
|
||||
|
||||
async function safe(promise) {
|
||||
try {
|
||||
return await promise
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function fileName() {
|
||||
const d = new Date()
|
||||
const p = (n) => String(n).padStart(2, '0')
|
||||
return `돈돼지가계부_백업_${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}.xlsx`
|
||||
}
|
||||
|
||||
// 워크북을 플랫폼에 맞게 저장: 웹/PC=다운로드, 앱(네이티브)=파일 저장 후 공유
|
||||
async function saveWorkbook(XLSX, wb, name) {
|
||||
if (Capacitor.isNativePlatform()) {
|
||||
const base64 = XLSX.write(wb, { type: 'base64', bookType: 'xlsx' })
|
||||
const { Filesystem, Directory } = await import('@capacitor/filesystem')
|
||||
const { Share } = await import('@capacitor/share')
|
||||
const res = await Filesystem.writeFile({ path: name, data: base64, directory: Directory.Cache })
|
||||
try {
|
||||
await Share.share({ title: name, text: '가계부 백업 파일', url: res.uri })
|
||||
} catch {
|
||||
/* 공유 취소 — 파일은 캐시에 저장됨 */
|
||||
}
|
||||
} else {
|
||||
XLSX.writeFile(wb, name)
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportBackup() {
|
||||
const XLSX = await import('xlsx')
|
||||
|
||||
const [entries, wallets, categories, recurrings, budgets, tags, quick] = await Promise.all([
|
||||
safe(accountApi.list({})),
|
||||
safe(accountApi.wallets()),
|
||||
safe(accountApi.categories()),
|
||||
safe(accountApi.recurrings()),
|
||||
safe(accountApi.budgets()),
|
||||
safe(accountApi.tags()),
|
||||
safe(accountApi.quickEntries()),
|
||||
])
|
||||
|
||||
const catNameById = {}
|
||||
categories.forEach((c) => (catNameById[c.id] = c.name))
|
||||
|
||||
const wb = XLSX.utils.book_new()
|
||||
const add = (name, rows) => XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(rows), name)
|
||||
|
||||
add('내역', entries.map((e) => ({
|
||||
날짜: e.entryDate, 구분: e.type, 분류: e.category, 금액: e.amount, 메모: e.memo,
|
||||
계좌: e.walletName, 입금계좌: e.toWalletName, 할부개월: e.installmentMonths,
|
||||
태그: (e.tags || []).join(','),
|
||||
})))
|
||||
add('계좌', wallets.map((w) => ({
|
||||
종류: w.type, 이름: w.name, '은행/카드사': w.issuer, 계좌번호: w.accountNumber,
|
||||
카드유형: w.cardType, 개시잔액: w.openingBalance, 개시일: w.openingDate, '평가액(수동)': w.currentValue,
|
||||
})))
|
||||
add('분류', categories.map((c) => ({
|
||||
구분: c.type, 이름: c.name, 대분류: c.parentId ? catNameById[c.parentId] || '' : '',
|
||||
})))
|
||||
add('고정지출', recurrings.map((r) => ({
|
||||
제목: r.title, 구분: r.type, 금액: r.amount, 분류: r.category, 메모: r.memo,
|
||||
계좌: r.walletName, 입금계좌: r.toWalletName, 주기: r.frequency,
|
||||
일: r.dayOfMonth, 요일: r.dayOfWeek, 월: r.monthOfYear,
|
||||
시작일: r.startDate, 종료일: r.endDate, 활성: r.active,
|
||||
})))
|
||||
add('예산', budgets.map((b) => ({
|
||||
분류: b.category, 고정: b.fixed, 기준단위: b.baseUnit, 기준금액: b.baseAmount,
|
||||
일: b.daily, 주: b.weekly, 월: b.monthly, 년: b.yearly,
|
||||
})))
|
||||
add('태그', tags.map((t) => ({ 이름: t.name })))
|
||||
add('자주쓰는내역', quick.map((q) => ({
|
||||
라벨: q.label, 구분: q.type, 분류: q.category, 금액: q.amount, 메모: q.memo, 계좌: q.walletName,
|
||||
})))
|
||||
|
||||
await saveWorkbook(XLSX, wb, fileName())
|
||||
}
|
||||
@@ -700,10 +700,15 @@ onMounted(load)
|
||||
}
|
||||
.cta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
justify-content: center;
|
||||
margin-top: 1.4rem;
|
||||
}
|
||||
.cta .btn {
|
||||
width: 100%;
|
||||
max-width: 260px;
|
||||
}
|
||||
.btn {
|
||||
padding: 0.6rem 1.4rem;
|
||||
border: 1px solid var(--color-border);
|
||||
|
||||
@@ -4,9 +4,26 @@ import { RouterLink } from 'vue-router'
|
||||
import { Preferences } from '@capacitor/preferences'
|
||||
import { useDialog } from '@/composables/dialog'
|
||||
import { useUiStore } from '@/stores/ui'
|
||||
import { exportBackup } from '@/utils/backup'
|
||||
|
||||
const dialog = useDialog()
|
||||
const ui = useUiStore()
|
||||
|
||||
const exporting = ref(false)
|
||||
async function doExport() {
|
||||
if (exporting.value) return
|
||||
exporting.value = true
|
||||
try {
|
||||
await exportBackup()
|
||||
} catch (e) {
|
||||
window.alert(e?.message || '내보내기에 실패했습니다.')
|
||||
} finally {
|
||||
exporting.value = false
|
||||
}
|
||||
}
|
||||
function importBackup() {
|
||||
dialog.alert('가져오기(복구)는 준비 중입니다. 곧 제공됩니다.')
|
||||
}
|
||||
const THEMES = [
|
||||
{ value: 'system', label: '시스템' },
|
||||
{ value: 'light', label: '라이트' },
|
||||
@@ -92,6 +109,24 @@ async function clearAppData() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 데이터 백업 -->
|
||||
<section class="card">
|
||||
<button type="button" class="row row-btn" :disabled="exporting" @click="doExport">
|
||||
<div class="row-main">
|
||||
<span class="row-label">엑셀로 내보내기</span>
|
||||
<span class="row-sub">가계부 전체 데이터를 .xlsx 파일로 저장</span>
|
||||
</div>
|
||||
<span class="row-value">{{ exporting ? '내보내는 중…' : '내보내기' }}</span>
|
||||
</button>
|
||||
<button type="button" class="row row-btn" @click="importBackup">
|
||||
<div class="row-main">
|
||||
<span class="row-label">엑셀에서 가져오기</span>
|
||||
<span class="row-sub">백업 파일로 데이터 복구</span>
|
||||
</div>
|
||||
<span class="row-value">가져오기</span>
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<RouterLink to="/settings/account" class="row row-link">
|
||||
<div class="row-main">
|
||||
|
||||
Reference in New Issue
Block a user