cents/apps/web/src/views/EntryDetailView.vue

890 lines
24 KiB
Vue

<script setup lang="ts">
import type { EntryType, LedgerEntry } from "@cents/domain";
import {
ArrowLeft,
BookOpen,
CalendarDays,
Check,
ChevronRight,
CircleUserRound,
CloudOff,
NotebookText,
Trash2,
WalletCards,
X,
} from "@lucide/vue";
import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
categories,
entryTypes,
findCategory,
findCategoryPath,
type Category,
} from "../data/categories";
import { useEntryStore } from "../stores/entries";
import { useLedgerStore } from "../stores/ledgers";
type CategorySheetMode = "parent" | "child";
const route = useRoute();
const router = useRouter();
const store = useEntryStore();
const ledgerStore = useLedgerStore();
const entry = ref<LedgerEntry | null>(null);
const loading = ref(true);
const saving = ref(false);
const savedToast = ref(false);
const errorMessage = ref("");
const categorySheetMode = ref<CategorySheetMode | null>(null);
const ledgerPickerOpen = ref(false);
const dateInput = ref<HTMLInputElement | null>(null);
const amount = ref("");
const ledgerIds = ref<string[]>([]);
const parentCategoryId = ref("");
const childCategoryId = ref("");
const note = ref("");
const occurredAt = ref("");
const entryType = computed<EntryType>(() => entry.value?.type ?? "expense");
const typeOption = computed(() => entryTypes.find((type) => type.id === entryType.value)!);
const parentCategories = computed(() => categories[entryType.value]);
const selectedParent = computed(() =>
parentCategories.value.find((category) => category.id === parentCategoryId.value),
);
const childCategories = computed(() => selectedParent.value?.children ?? []);
const selectedChild = computed(() =>
childCategories.value.find((category) => category.id === childCategoryId.value),
);
const selectedCategory = computed(() => selectedChild.value ?? selectedParent.value);
const ledgerOptions = computed(() =>
ledgerStore.ledgers.map((ledger) => ({ id: ledger.id, label: ledger.name })),
);
const dateLabel = computed(() => {
if (!occurredAt.value) return "请选择时间";
const date = new Date(occurredAt.value);
return new Intl.DateTimeFormat("zh-CN", {
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
hour12: false,
}).format(date);
});
const timeInvalid = computed(() => {
if (!occurredAt.value) return true;
return Number.isNaN(new Date(occurredAt.value).getTime());
});
const ledgerLabel = computed(() =>
ledgerIds.value.length === 1
? ledgerOptions.value.find((ledger) => ledger.id === ledgerIds.value[0])?.label ?? "未知账本"
: `${ledgerIds.value.length} 个账本`,
);
const createdAtLabel = computed(() => {
if (!entry.value) return "";
return new Intl.DateTimeFormat("zh-CN", {
year: "numeric",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
hour12: false,
}).format(new Date(entry.value.createdAt));
});
onMounted(async () => {
await Promise.all([store.loadEntries(), ledgerStore.loadLedgers()]);
const found = store.entries.find((item) => item.id === String(route.params.id));
if (found) hydrate(found);
loading.value = false;
});
function hydrate(value: LedgerEntry) {
entry.value = value;
amount.value = (value.amount / 100).toFixed(2);
ledgerIds.value = [...new Set([...value.ledgerIds, ledgerStore.personalLedger?.id].filter((id): id is string => Boolean(id)))];
note.value = value.note;
occurredAt.value = toLocalDateTime(new Date(value.occurredAt));
const path = findCategoryPath(value.type, value.categoryId);
parentCategoryId.value = path[0]?.id ?? "";
childCategoryId.value = path[1]?.id ?? "";
}
function toLocalDateTime(date: Date) {
const pad = (value: number) => String(value).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
function openDatePicker() {
const input = dateInput.value;
if (!input) return;
if (typeof input.showPicker === "function") input.showPicker();
else input.click();
}
function chooseParent(category: Category) {
const parentChanged = parentCategoryId.value !== category.id;
parentCategoryId.value = category.id;
if (parentChanged) childCategoryId.value = "";
categorySheetMode.value = null;
}
function chooseChild(category: Category) {
childCategoryId.value = category.id;
categorySheetMode.value = null;
}
function toggleLedger(ledgerId: string) {
if (ledgerId === ledgerStore.personalLedger?.id) return;
if (ledgerIds.value.includes(ledgerId)) {
if (ledgerIds.value.length > 1) ledgerIds.value = ledgerIds.value.filter((id) => id !== ledgerId);
return;
}
ledgerIds.value = [...ledgerIds.value, ledgerId];
}
async function saveEntry() {
if (!entry.value || saving.value) return;
const numericAmount = Number(amount.value.replaceAll(",", ""));
if (!Number.isFinite(numericAmount) || numericAmount <= 0) {
errorMessage.value = "请输入有效金额";
return;
}
if (!parentCategoryId.value) {
errorMessage.value = "请选择大类";
return;
}
const occurredDate = new Date(occurredAt.value);
if (timeInvalid.value) {
errorMessage.value = "请选择时间";
return;
}
saving.value = true;
errorMessage.value = "";
const cents = Math.round(numericAmount * 100);
const exchangeRate = Number(entry.value.exchangeRate) || 1;
const updated = await store.updateEntry({
...entry.value,
amount: cents,
baseAmount: Math.round(cents * exchangeRate),
ledgerIds: ledgerIds.value,
categoryId: childCategoryId.value || parentCategoryId.value,
note: note.value.trim(),
occurredAt: occurredDate.toISOString(),
});
hydrate(updated);
saving.value = false;
savedToast.value = true;
window.setTimeout(() => (savedToast.value = false), 1600);
}
async function deleteEntry() {
if (!entry.value || !window.confirm("确定删除这笔条目吗?")) return;
await store.deleteEntry(entry.value.id);
await router.replace("/");
}
</script>
<template>
<main class="app-shell entry-detail-shell">
<header class="entry-detail-appbar">
<button class="entry-detail-icon-button" type="button" aria-label="返回流水" title="返回" @click="router.push('/')">
<ArrowLeft :size="22" />
</button>
<strong>条目明细</strong>
<span aria-hidden="true"></span>
</header>
<div v-if="loading" class="entry-detail-state">正在载入...</div>
<div v-else-if="!entry" class="entry-detail-state">
<strong>条目不存在</strong>
<button type="button" @click="router.replace('/')">返回流水</button>
</div>
<form v-else class="entry-detail-form" @submit.prevent="saveEntry">
<div class="entry-detail-scroll">
<section class="entry-detail-amount" :class="entryType">
<div
class="entry-detail-category-mark"
:style="{
color: selectedCategory?.color ?? typeOption.color,
background: selectedCategory?.tint ?? typeOption.tint,
}"
>
<component :is="selectedCategory?.icon ?? typeOption.icon" :size="27" />
</div>
<span class="entry-type-label">{{ typeOption.label }}</span>
<label class="entry-amount-input">
<span>¥</span>
<input v-model="amount" inputmode="decimal" aria-label="金额" />
</label>
</section>
<section class="entry-edit-fields" aria-label="编辑条目">
<button class="entry-edit-row" type="button" @click="categorySheetMode = 'parent'">
<span class="entry-field-icon category"><WalletCards :size="19" /></span>
<span class="entry-field-copy"><small>大类</small><strong>{{ selectedParent?.label ?? "请选择" }}</strong></span>
<ChevronRight :size="19" />
</button>
<button
class="entry-edit-row"
type="button"
:disabled="!childCategories.length"
@click="categorySheetMode = 'child'"
>
<span class="entry-field-icon subcategory">
<component :is="selectedParent?.icon ?? WalletCards" :size="19" />
</span>
<span class="entry-field-copy">
<small>小类</small>
<strong>{{ childCategories.length ? selectedChild?.label ?? "未选择" : "无小类" }}</strong>
</span>
<ChevronRight v-if="childCategories.length" :size="19" />
</button>
<button class="entry-edit-row" :class="{ invalid: timeInvalid }" type="button" @click="openDatePicker">
<span class="entry-field-icon date"><CalendarDays :size="19" /></span>
<span class="entry-field-copy"><small>时间</small><strong>{{ dateLabel }}</strong></span>
<ChevronRight :size="19" />
</button>
<input
ref="dateInput"
v-model="occurredAt"
class="entry-native-date-input"
type="datetime-local"
aria-label="时间"
:aria-invalid="timeInvalid"
tabindex="-1"
/>
<button class="entry-edit-row" type="button" @click="ledgerPickerOpen = true">
<span class="entry-field-icon ledger"><BookOpen :size="19" /></span>
<span class="entry-field-copy"><small>账本</small><strong>{{ ledgerLabel }}</strong></span>
<ChevronRight :size="18" />
</button>
<div class="entry-edit-row readonly-row">
<span class="entry-field-icon member"><CircleUserRound :size="19" /></span>
<span class="entry-field-copy"><small>记录人</small><strong>{{ ledgerStore.memberName(entry.createdBy) }}</strong></span>
</div>
<label class="entry-note-row">
<span class="entry-field-icon note"><NotebookText :size="19" /></span>
<span class="entry-field-copy">
<small>备注</small>
<textarea v-model="note" maxlength="120" rows="3" placeholder="补充说明(可选)"></textarea>
</span>
</label>
</section>
<p class="entry-created-at">
<span v-if="store.isEntryPending(entry.id)" class="entry-sync-pending" role="img" aria-label="未同步云端" title="未同步云端"><CloudOff :size="13" /></span>
由{{ ledgerStore.memberName(entry.createdBy) }}创建 · {{ createdAtLabel }}
</p>
<p v-if="errorMessage" class="entry-save-error" role="alert">{{ errorMessage }}</p>
</div>
<div class="entry-detail-actions">
<button class="entry-delete-button" type="button" aria-label="删除条目" title="删除条目" @click="deleteEntry">
<Trash2 :size="20" />
</button>
<button class="entry-save-button" type="submit" :disabled="saving">
<Check :size="19" />{{ saving ? "保存中" : "保存修改" }}
</button>
</div>
</form>
<Transition name="sheet">
<div v-if="categorySheetMode" class="entry-category-layer">
<button class="entry-category-scrim" type="button" aria-label="关闭类别选择" @click="categorySheetMode = null"></button>
<section class="entry-category-sheet" :aria-label="categorySheetMode === 'parent' ? '选择大类' : '选择小类'">
<div class="entry-sheet-handle"></div>
<header>
<strong>{{ categorySheetMode === "parent" ? "选择大类" : "选择小类" }}</strong>
<button type="button" aria-label="关闭" title="关闭" @click="categorySheetMode = null"><X :size="20" /></button>
</header>
<div v-if="categorySheetMode === 'parent'" class="entry-category-grid">
<button
v-for="category in parentCategories"
:key="category.id"
type="button"
:class="{ active: parentCategoryId === category.id }"
:style="{ '--category-color': category.color, '--category-tint': category.tint }"
@click="chooseParent(category)"
>
<span><component :is="category.icon" :size="23" /></span>
<small>{{ category.label }}</small>
<Check v-if="parentCategoryId === category.id" :size="15" />
</button>
</div>
<div v-else class="entry-subcategory-grid">
<button
v-for="category in childCategories"
:key="category.id"
type="button"
:class="{ active: childCategoryId === category.id }"
:style="{ '--category-color': category.color, '--category-tint': category.tint }"
@click="chooseChild(category)"
>
<span><component :is="category.icon" :size="22" /></span>
<strong>{{ category.label }}</strong>
<Check v-if="childCategoryId === category.id" :size="16" />
</button>
</div>
</section>
</div>
</Transition>
<div v-if="ledgerPickerOpen" class="quick-ledger-picker-layer">
<button class="quick-ledger-picker-scrim" type="button" aria-label="关闭账本选择" @click="ledgerPickerOpen = false"></button>
<section class="quick-ledger-picker" aria-label="选择关联账本">
<div class="quick-ledger-picker-handle"></div>
<header><div><strong>选择账本</strong><span>至少选择一个账本</span></div><button type="button" aria-label="关闭" @click="ledgerPickerOpen = false"><X :size="19" /></button></header>
<div class="quick-ledger-options">
<button v-for="ledger in ledgerStore.ledgers" :key="ledger.id" type="button" :class="{ selected: ledgerIds.includes(ledger.id), automatic: ledger.isPersonal }" :disabled="ledger.isPersonal" @click="toggleLedger(ledger.id)">
<span :style="{ background: ledger.color }"><BookOpen :size="17" /></span>
<strong>{{ ledger.name }}<small v-if="ledger.isPersonal">自动记入</small></strong>
<Check v-if="ledgerIds.includes(ledger.id)" :size="19" />
</button>
</div>
<button class="quick-ledger-picker-done" type="button" @click="ledgerPickerOpen = false"><Check :size="18" />完成</button>
</section>
</div>
<Transition name="toast">
<div v-if="savedToast" class="entry-detail-toast" role="status"><Check :size="17" />修改已保存</div>
</Transition>
</main>
</template>
<style scoped>
.entry-detail-shell {
color: #1d2926;
background: #f5f8f7;
}
.entry-detail-appbar {
position: relative;
z-index: 3;
height: calc(58px + env(safe-area-inset-top));
display: grid;
grid-template-columns: 44px 1fr 44px;
align-items: end;
gap: 8px;
border-bottom: 1px solid #dce8e4;
padding: env(safe-area-inset-top) 12px 7px;
background: rgba(255, 255, 255, 0.97);
backdrop-filter: blur(14px);
}
.entry-detail-appbar > strong {
align-self: center;
text-align: center;
font-size: 17px;
}
.entry-detail-icon-button {
width: 42px;
height: 42px;
display: grid;
place-items: center;
border: 0;
border-radius: 8px;
background: transparent;
color: #31504a;
}
.entry-detail-form {
height: calc(100% - 58px - env(safe-area-inset-top));
}
.entry-detail-scroll {
height: 100%;
overflow-y: auto;
padding-bottom: calc(92px + env(safe-area-inset-bottom));
}
.entry-detail-amount {
min-height: 184px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
border-bottom: 1px solid #dce7e4;
padding: 22px 18px;
background: #ffffff;
}
.entry-detail-category-mark {
width: 52px;
height: 52px;
display: grid;
place-items: center;
border-radius: 12px;
}
.entry-type-label {
margin-top: 7px;
color: #73817d;
font-size: 13px;
font-weight: 650;
}
.entry-amount-input {
width: min(100%, 270px);
height: 52px;
display: flex;
align-items: center;
justify-content: center;
gap: 7px;
color: #d84c36;
}
.income .entry-amount-input {
color: #0d8b67;
}
.entry-amount-input > span {
font-size: 23px;
font-weight: 700;
}
.entry-amount-input input {
width: 200px;
border: 0;
padding: 0;
outline: 0;
background: transparent;
color: inherit;
font-size: 36px;
font-weight: 760;
font-variant-numeric: tabular-nums;
text-align: center;
}
.entry-edit-fields {
margin-top: 12px;
border-top: 1px solid #dce7e4;
border-bottom: 1px solid #dce7e4;
padding: 0 16px;
background: #ffffff;
}
.entry-edit-row,
.entry-note-row {
width: 100%;
min-height: 64px;
display: grid;
grid-template-columns: 34px minmax(0, 1fr) auto;
align-items: center;
gap: 10px;
border: 0;
border-bottom: 1px solid #e3ece9;
padding: 8px 0;
background: transparent;
color: #27342f;
text-align: left;
}
.entry-edit-row:disabled {
cursor: default;
opacity: 0.62;
}
.entry-edit-row.invalid {
border-bottom-color: transparent;
border-radius: 8px;
padding-right: 8px;
padding-left: 8px;
background: #fff3f0;
color: #c83f2d;
box-shadow: inset 0 0 0 1px #ef9a8c;
}
.entry-edit-row.invalid .entry-field-icon.date {
background: #ffe2dc;
color: #d44531;
}
.entry-edit-row.invalid .entry-field-copy small,
.entry-edit-row.invalid .entry-field-copy strong {
color: #c83f2d;
}
.entry-field-icon {
width: 32px;
height: 32px;
display: grid;
place-items: center;
border-radius: 8px;
}
.entry-field-icon.category { background: #fff0e8; color: #e85e2b; }
.entry-field-icon.subcategory { background: #fff7dd; color: #a56e05; }
.entry-field-icon.date { background: #fff7dd; color: #9b6d0f; }
.entry-field-icon.ledger { background: #e9f7f3; color: #087f72; }
.entry-field-icon.member { background: #edf4ff; color: #3478e5; }
.entry-field-icon.note { background: #f3efff; color: #7559d9; }
.entry-field-copy {
min-width: 0;
display: grid;
gap: 2px;
}
.entry-field-copy small {
color: #7b8884;
font-size: 11px;
}
.entry-field-copy strong {
min-width: 0;
overflow: hidden;
font-size: 14px;
text-overflow: ellipsis;
white-space: nowrap;
}
.entry-select-row {
position: relative;
grid-template-columns: 34px minmax(0, 1fr) 18px;
}
.entry-select-row select {
position: absolute;
inset: 0;
width: 100%;
opacity: 0;
cursor: pointer;
}
.readonly-row {
grid-template-columns: 34px minmax(0, 1fr);
}
.entry-note-row {
align-items: start;
border-bottom: 0;
padding-top: 12px;
}
.entry-note-row .entry-field-icon {
margin-top: 3px;
}
.entry-note-row textarea {
width: 100%;
min-height: 64px;
border: 0;
padding: 0;
outline: 0;
resize: none;
background: transparent;
color: #27342f;
font-size: 14px;
line-height: 1.45;
}
.entry-native-date-input {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
pointer-events: none;
}
.entry-created-at {
margin: 18px 16px 8px;
color: #8b9693;
text-align: center;
font-size: 12px;
}
.entry-sync-pending {
display: inline-flex;
align-items: center;
margin-right: 4px;
color: #b35a24;
vertical-align: -2px;
}
.entry-save-error {
margin: 8px 16px;
color: #c94635;
text-align: center;
font-size: 13px;
}
.entry-detail-actions {
position: absolute;
right: 0;
bottom: 0;
left: 0;
z-index: 4;
display: grid;
grid-template-columns: 48px 1fr;
gap: 10px;
border-top: 1px solid #d8e5e1;
padding: 10px 16px calc(10px + env(safe-area-inset-bottom));
background: rgba(255, 255, 255, 0.97);
backdrop-filter: blur(14px);
}
.entry-detail-actions button {
height: 46px;
border-radius: 8px;
}
.entry-delete-button {
display: grid;
place-items: center;
border: 1px solid #f1c8c2;
background: #fff7f5;
color: #c94635;
}
.entry-save-button {
display: flex;
align-items: center;
justify-content: center;
gap: 7px;
border: 0;
background: #087f72;
color: #ffffff;
font-weight: 720;
}
.entry-save-button:disabled {
opacity: 0.65;
}
.entry-category-layer {
position: absolute;
inset: 0;
z-index: 10;
}
.entry-category-scrim {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
border: 0;
background: rgba(18, 35, 32, 0.42);
backdrop-filter: blur(3px);
}
.entry-category-sheet {
position: absolute;
right: 0;
bottom: 0;
left: 0;
max-height: 68%;
overflow-y: auto;
border-radius: 14px 14px 0 0;
padding: 0 16px calc(22px + env(safe-area-inset-bottom));
background: #ffffff;
box-shadow: 0 -16px 36px rgba(22, 45, 40, 0.22);
}
.entry-sheet-handle {
width: 38px;
height: 4px;
margin: 8px auto 3px;
border-radius: 2px;
background: #b9cac5;
}
.entry-category-sheet header {
height: 50px;
display: flex;
align-items: center;
justify-content: space-between;
}
.entry-category-sheet header > strong {
font-size: 16px;
}
.entry-category-sheet header button {
width: 38px;
height: 38px;
display: grid;
place-items: center;
border: 0;
border-radius: 8px;
background: #f0f5f3;
color: #536762;
}
.entry-category-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 16px 8px;
}
.entry-category-grid button {
position: relative;
min-width: 0;
display: grid;
place-items: center;
gap: 5px;
border: 0;
padding: 0;
background: transparent;
color: #53615e;
}
.entry-category-grid button > span {
width: 50px;
height: 50px;
display: grid;
place-items: center;
border: 2px solid transparent;
border-radius: 50%;
background: var(--category-tint);
color: var(--category-color);
}
.entry-category-grid button.active > span {
border-color: var(--category-color);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--category-color) 13%, white);
}
.entry-category-grid button > svg {
position: absolute;
top: 0;
right: max(0px, calc(50% - 30px));
border-radius: 50%;
padding: 2px;
background: var(--category-color);
color: #ffffff;
}
.entry-category-grid small {
overflow: hidden;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.entry-subcategory-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.entry-subcategory-grid button {
min-width: 0;
height: 58px;
display: grid;
grid-template-columns: 32px minmax(0, 1fr) 18px;
align-items: center;
gap: 8px;
border: 1px solid color-mix(in srgb, var(--category-color) 24%, #d8e4e1);
border-radius: 8px;
padding: 0 10px;
background: var(--category-tint);
color: var(--category-color);
text-align: left;
}
.entry-subcategory-grid button.active {
border-color: var(--category-color);
}
.entry-subcategory-grid button > span {
width: 32px;
height: 32px;
display: grid;
place-items: center;
border-radius: 50%;
background: rgba(255, 255, 255, 0.72);
}
.entry-subcategory-grid strong {
overflow: hidden;
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
.entry-detail-toast {
position: absolute;
right: 50%;
bottom: 82px;
z-index: 20;
min-height: 40px;
display: flex;
align-items: center;
gap: 7px;
transform: translateX(50%);
border-radius: 8px;
padding: 0 14px;
background: #173c35;
color: #ffffff;
box-shadow: 0 10px 24px rgba(21, 50, 44, 0.2);
font-size: 13px;
white-space: nowrap;
}
.entry-detail-state {
height: calc(100% - 58px);
display: grid;
place-items: center;
align-content: center;
gap: 10px;
color: #71807c;
}
.entry-detail-state button {
height: 40px;
border: 0;
border-radius: 8px;
padding: 0 14px;
background: #087f72;
color: #ffffff;
}
.sheet-enter-active,
.sheet-leave-active {
transition: opacity 180ms ease;
}
.sheet-enter-active .entry-category-sheet,
.sheet-leave-active .entry-category-sheet {
transition: transform 220ms ease;
}
.sheet-enter-from,
.sheet-leave-to {
opacity: 0;
}
.sheet-enter-from .entry-category-sheet,
.sheet-leave-to .entry-category-sheet {
transform: translateY(100%);
}
@media (max-width: 360px) {
.entry-edit-fields {
padding-right: 12px;
padding-left: 12px;
}
.entry-category-grid {
column-gap: 4px;
}
.entry-subcategory-grid {
grid-template-columns: 1fr;
}
}
</style>