Files
sb-front/src/views/account/CategoryView.vue
T

322 lines
8.8 KiB
Vue
Raw Normal View History

<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import Sortable from 'sortablejs'
import { accountApi } from '@/api/accountApi'
import IconBtn from '@/components/ui/IconBtn.vue'
const router = useRouter()
const categories = ref([])
const rows = ref([]) // 현재 탭(activeType)의 분류 — 드래그 정렬 대상
const loading = ref(false)
const error = ref(null)
const activeType = ref('EXPENSE') // EXPENSE / INCOME
const newName = ref('')
const newParent = ref('') // 추가 시 대분류('' = 대분류로 추가)
// categories/activeType 변경 시 현재 탭 목록 동기화 (백엔드가 sort_order 순 정렬)
function syncRows() {
rows.value = categories.value.filter((c) => c.type === activeType.value)
}
watch([categories, activeType], syncRows, { immediate: true })
// 현재 탭의 대분류(parent 없는 것) 목록 — 부모 선택 옵션용
const majors = computed(() => rows.value.filter((c) => c.parentId == null))
// 부모(대분류) 선택 옵션: 자기 자신 제외
function parentOptions(c) {
return majors.value.filter((m) => m.id !== c.id)
}
async function load() {
loading.value = true
error.value = null
try {
categories.value = await accountApi.categories()
} catch (e) {
error.value = e.response?.data?.message || '불러오지 못했습니다.'
} finally {
loading.value = false
}
}
// ===== 드래그앤드랍 정렬 (SortableJS, 터치 지원) =====
const listEl = ref(null)
let sortable = null
function initSortable() {
if (sortable) {
sortable.destroy()
sortable = null
}
if (!listEl.value) return
sortable = Sortable.create(listEl.value, {
handle: '.drag-handle',
animation: 150,
onEnd: (evt) => {
if (evt.oldIndex === evt.newIndex) return
const arr = rows.value
const moved = arr.splice(evt.oldIndex, 1)[0]
arr.splice(evt.newIndex, 0, moved)
persistOrder(arr.map((r) => r.id))
},
})
}
async function persistOrder(ids) {
try {
await accountApi.reorderCategories(activeType.value, ids)
await load()
} catch (e) {
alert(e.response?.data?.message || '순서 저장에 실패했습니다.')
await load()
}
}
async function addCategory() {
const name = newName.value.trim()
if (!name) return
try {
await accountApi.createCategory({ type: activeType.value, name, parentId: newParent.value || null })
newName.value = ''
await load()
} catch (e) {
alert(e.response?.data?.message || '추가에 실패했습니다.')
}
}
async function saveCategory(c) {
const name = (c.name || '').trim()
if (!name) return
try {
// parentId 는 항상 현재값을 함께 전송(미전송 시 대분류로 풀림)
await accountApi.updateCategory(c.id, { type: c.type, name, parentId: c.parentId || null })
await load()
} catch (e) {
alert(e.response?.data?.message || '수정에 실패했습니다.')
}
}
async function removeCategory(c) {
if (!confirm(`'${c.name}' 분류를 삭제할까요? (기존 내역의 분류명은 그대로 유지됩니다)`)) return
try {
await accountApi.removeCategory(c.id)
await load()
} catch (e) {
alert(e.response?.data?.message || '삭제에 실패했습니다.')
}
}
async function importExisting() {
if (!confirm('기존 내역에서 사용한 분류들을 목록으로 가져올까요?')) return
try {
categories.value = await accountApi.importCategories()
} catch (e) {
alert(e.response?.data?.message || '불러오기에 실패했습니다.')
}
}
onMounted(async () => {
await load()
await nextTick()
initSortable()
})
onBeforeUnmount(() => sortable?.destroy())
</script>
<template>
<section class="cat">
<header class="head">
<h1>분류 관리</h1>
<div class="head-actions">
<button type="button" class="text-btn" @click="importExisting">기존 분류 불러오기</button>
<IconBtn icon="back" title="가계부로" @click="router.push('/account')" />
</div>
</header>
<p class="hint">내역·예산에서 선택할 분류를 관리합니다. <b>대분류 아래 소분류</b> 묶을 있고(2단계), 예산·통계는 소분류 기준입니다. 이름을 바꾸면 기존 내역·예산에도 반영됩니다.</p>
<div class="tabs">
<button type="button" :class="{ active: activeType === 'EXPENSE' }" @click="activeType = 'EXPENSE'">지출 분류</button>
<button type="button" :class="{ active: activeType === 'INCOME' }" @click="activeType = 'INCOME'">수입 분류</button>
</div>
<form class="new-cat" @submit.prevent="addCategory">
<select v-model="newParent" class="parent-sel" title="대분류 선택">
<option value="">대분류로 추가</option>
<option v-for="m in majors" :key="m.id" :value="m.id">{{ m.name }} 소분류</option>
</select>
<div class="nc-line">
<input v-model="newName" type="text" :placeholder="activeType === 'EXPENSE' ? '예: 식비, 교통' : '예: 급여, 용돈'" />
<IconBtn icon="plus" title="추가" variant="primary" type="submit" size="sm" />
</div>
</form>
<p class="hint sm"> 손잡이를 끌어 순서 변경. 행의 대분류를 바꾸면 소분류로 묶입니다.</p>
<p v-if="error" class="msg error">{{ error }}</p>
<p v-if="loading" class="msg">불러오는 중...</p>
<ul v-show="!loading && rows.length" ref="listEl" class="cat-list">
<li v-for="c in rows" :key="c.id" :data-id="c.id" class="cat-row" :class="{ child: c.parentId != null }">
<div class="cat-main">
<span class="drag-handle" title="드래그하여 순서 변경"></span>
<span v-if="c.parentId != null" class="sub-mark" title="소분류"></span>
<input v-model="c.name" class="cat-name" @keyup.enter="saveCategory(c)" />
<IconBtn icon="check" title="저장" size="sm" @click="saveCategory(c)" />
<IconBtn icon="trash" title="삭제" variant="danger" size="sm" @click="removeCategory(c)" />
</div>
<label class="cat-parent">
<span class="pl">대분류</span>
<select v-model="c.parentId" class="parent-sel" title="대분류" @change="saveCategory(c)">
<option :value="null">(없음 · 대분류)</option>
<option v-for="m in parentOptions(c)" :key="m.id" :value="m.id">{{ m.name }}</option>
</select>
</label>
</li>
</ul>
<p v-if="!loading && !rows.length" class="msg">
등록된 {{ activeType === 'EXPENSE' ? '지출' : '수입' }} 분류가 없습니다.
</p>
</section>
</template>
<style scoped>
.cat {
max-width: 560px;
margin: 0 auto;
}
.head {
display: flex;
align-items: center;
justify-content: space-between;
}
.head-actions {
display: flex;
gap: 0.5rem;
}
h1 {
font-size: 1.5rem;
}
.hint {
font-size: 0.85rem;
opacity: 0.7;
margin: 0.5rem 0 1rem;
}
input {
padding: 0.5rem 0.7rem;
border: 1px solid var(--color-border);
border-radius: 4px;
background: var(--color-background-soft);
color: var(--color-text);
}
button {
padding: 0.45rem 0.85rem;
border: 1px solid var(--color-border);
border-radius: 4px;
background: var(--color-background-soft);
color: var(--color-text);
cursor: pointer;
}
button.danger {
border-color: #c0392b;
color: #c0392b;
}
.tabs {
display: flex;
gap: 0.25rem;
border-bottom: 1px solid var(--color-border);
margin-bottom: 1rem;
}
.tabs button {
border: 0;
border-bottom: 2px solid transparent;
border-radius: 0;
background: transparent;
padding: 0.6rem 1rem;
}
.tabs button.active {
border-bottom-color: hsla(160, 100%, 37%, 1);
color: hsla(160, 100%, 37%, 1);
font-weight: 600;
}
.new-cat {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-bottom: 1rem;
}
.nc-line {
display: flex;
gap: 0.5rem;
}
.nc-line input {
flex: 1;
min-width: 0;
}
.cat-list {
list-style: none;
padding-left: 0;
margin: 0;
}
.cat-row {
display: flex;
flex-direction: column;
gap: 0.35rem;
padding: 0.5rem 0;
border-bottom: 1px solid var(--color-border);
background: var(--color-background);
}
.cat-main {
display: flex;
gap: 0.4rem;
align-items: center;
}
.cat-parent {
display: flex;
align-items: center;
gap: 0.4rem;
padding-left: 1.4rem;
font-size: 0.8rem;
opacity: 0.85;
}
.cat-parent .pl {
flex: 0 0 auto;
opacity: 0.6;
}
.cat-parent .parent-sel {
flex: 1;
min-width: 0;
}
.drag-handle {
cursor: grab;
user-select: none;
opacity: 0.5;
font-size: 1.1rem;
padding: 0 0.2rem;
touch-action: none;
}
.drag-handle:active {
cursor: grabbing;
}
.cat-name {
flex: 1;
min-width: 0;
}
.cat-row.child {
padding-left: 1.2rem;
}
.cat-row.child .cat-name {
background: var(--color-background-soft);
}
.sub-mark {
opacity: 0.45;
}
.hint.sm {
font-size: 0.78rem;
margin: 0 0 0.75rem;
}
.msg {
margin: 0.75rem 0;
}
.msg.error {
color: #c0392b;
}
</style>