refactor: replace common confirm dialogs with maintenance CRUD dialogs and streamline form handling in MasterDetailMntC.vue and SingleRecordMnt.vue

This commit is contained in:
skytek_xinliang
2026-03-26 16:01:20 +08:00
parent ec3fbace1a
commit 389ec56480
32 changed files with 2549 additions and 2763 deletions
+2 -388
View File
@@ -1,393 +1,7 @@
<template>
<div class="d-flex flex-column">
<v-card variant="flat">
<v-card-title class="d-flex flex-wrap align-center py-0 ga-2">
<span class="text-h6">可編輯表格維護示範</span>
<v-chip :color="hasAnyChange ? 'warning' : 'success'" variant="tonal">
{{ hasAnyChange ? '有未儲存變更' : '已同步' }}
</v-chip>
<v-chip color="info" variant="tonal">筆數 {{ filteredStudents.length }}</v-chip>
<v-spacer />
<v-btn flat :prepend-icon="mdiMagnify" @click="isSearchVisible = !isSearchVisible">條件搜尋</v-btn>
<v-switch v-model="isBulkEditEnabled" color="primary" hide-details label="啟用編輯" />
</v-card-title>
<v-divider />
<v-card-text class="pb-0 pt-2">
<!-- 搜尋條件 -->
<v-row v-if="isSearchVisible" class="mb-2" dense>
<v-col cols="12" md="3">
<div class="text-body-1 text-medium-emphasis pl-2">學號</div>
<v-text-field
v-model="search.studentId" clearable density="compact" hide-details
placeholder="例如:S2024001" variant="outlined" />
</v-col>
<v-col cols="12" md="3">
<div class="text-body-1 text-medium-emphasis pl-2">姓名</div>
<v-text-field
v-model="search.name" clearable density="compact" hide-details placeholder="例如:王小明"
variant="outlined" />
</v-col>
<v-col cols="12" md="3">
<div class="text-body-1 text-medium-emphasis pl-2">系所</div>
<v-select
v-model="search.department" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" clearable density="compact" hide-details
:items="departments" variant="outlined" />
</v-col>
</v-row>
<!-- 操作 -->
<v-row v-if="isBulkEditEnabled" align="center" class="mb-2 ga-1" dense>
<v-btn :disabled="!hasSelectedRows" :prepend-icon="mdiDelete" variant="outlined" @click="deleteSelectedRows">
批次刪除
</v-btn>
<v-spacer></v-spacer>
<v-btn
color="primary" :disabled="!hasAnyChange" :prepend-icon="mdiContentSave" variant="outlined"
@click="saveAllRows">
儲存變更
</v-btn>
<v-btn :disabled="!hasAnyChange" :prepend-icon="mdiRestore" variant="text" @click="resetAllRows">
取消變更
</v-btn>
</v-row>
<div ref="tableContainerRef">
<v-data-table
density="comfortable" fixed-header :headers="tableHeaders" :height="tableHeight"
item-value="id" :items="filteredStudents" :items-per-page="10" items-per-page-text="每頁筆數"
page-text=" {0}-{1} / {2} ">
<template #[`header.select`]>
<v-checkbox-btn
:disabled="!isBulkEditEnabled" :indeterminate="isPartiallyVisibleSelected"
:model-value="isAllVisibleSelected" @update:model-value="toggleSelectAll" />
</template>
<template #[`item.select`]="{ item }">
<v-checkbox-btn
:disabled="!isBulkEditEnabled" :model-value="selectedRowIds.includes(item.id)"
@update:model-value="(checked) => toggleSingleRowSelection(item.id, checked)" />
</template>
<template #[`item.studentId`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.studentId" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.name`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.name" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.department`]="{ item }">
<v-select
v-model="draftRows[item.id]!.department" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" density="compact" flat
hide-details :items="departments" :readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.grade`]="{ item }">
<v-select
v-model="draftRows[item.id]!.grade" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" density="compact" flat
hide-details item-title="title" item-value="value" :items="gradeOptions"
:readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.enrollYear`]="{ item }">
<v-select
v-model="draftRows[item.id]!.enrollYear" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" density="compact" flat
hide-details :items="enrollYears" :readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.credits`]="{ item }">
<v-text-field
v-model.number="draftRows[item.id]!.credits" density="compact" flat hide-details min="0"
:readonly="!isBulkEditEnabled" type="number" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.advisor`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.advisor" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.email`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.email" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.phone`]="{ item }">
<v-text-field
v-model="draftRows[item.id]!.phone" density="compact" flat
hide-details :readonly="!isBulkEditEnabled" :variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.status`]="{ item }">
<v-select
v-model="draftRows[item.id]!.status" :class="{ 'select-hide-arrow': !isBulkEditEnabled }" density="compact" flat
hide-details :items="statuses" :readonly="!isBulkEditEnabled"
:variant="isBulkEditEnabled ? 'outlined' : 'solo'" />
</template>
<template #[`item.actions`]="{ item }">
<div class="d-flex ga-1 justify-end">
<v-btn
color="error" :disabled="!isBulkEditEnabled" size="small" variant="text"
@click="deleteSingleRow(item.id)">
刪除
</v-btn>
</div>
</template>
</v-data-table>
</div>
</v-card-text>
</v-card>
</div>
<EditableStudentGrid />
</template>
<script setup lang="ts">
import { mdiContentSave, mdiDelete, mdiMagnify, mdiRestore } from '@mdi/js'
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { type StudentRecord, useStudentStore } from '@/stores/students'
type StudentPayload = Omit<StudentRecord, 'id'>
const studentStore = useStudentStore()
const students = computed(() => studentStore.students)
const departments = ['資訊工程', '企業管理', '應用外語', '視覺設計', '財務金融']
const gradeOptions = [
{ title: '大一', value: 1 },
{ title: '大二', value: 2 },
{ title: '大三', value: 3 },
{ title: '大四', value: 4 },
{ title: '研究所', value: 5 },
]
const enrollYears = [2024, 2023, 2022, 2021, 2020, 2019]
const statuses = ['在學', '休學', '畢業']
const tableHeaders = [
{ title: '', key: 'select', sortable: false, nowrap: true },
{ title: '學號', key: 'studentId', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '姓名', key: 'name', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '系所', key: 'department', sortable: true, minWidth: 140, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '年級', key: 'grade', sortable: true, minWidth: 140, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '入學年度', key: 'enrollYear', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '已修學分', key: 'credits', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '指導老師', key: 'advisor', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: 'Email', key: 'email', sortable: true, minWidth: 200, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '電話', key: 'phone', sortable: true, minWidth: 150, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '狀態', key: 'status', sortable: true, minWidth: 120, nowrap: true, cellProps: { class: 'px-1' } },
{ title: '操作', key: 'actions', sortable: false, width: 'auto', nowrap: true, cellProps: { class: 'bg-background' } },
] as const
const search = ref({
studentId: '',
name: '',
department: '',
})
const isBulkEditEnabled = ref(false)
const isSearchVisible = ref(false)
const tableContainerRef = ref<HTMLElement | null>(null)
const tableScrollParentRef = ref<HTMLElement | null>(null)
const tableResizeObserver = ref<ResizeObserver | null>(null)
const tableHeight = ref(300)
const draftRows = ref<Record<number, StudentPayload>>({})
const selectedRowIds = ref<number[]>([])
const TABLE_BOTTOM_GAP = 64
const TABLE_MIN_HEIGHT = 240
function toPayload (student: StudentRecord): StudentPayload {
return {
studentId: student.studentId,
name: student.name,
department: student.department,
grade: student.grade,
enrollYear: student.enrollYear,
credits: student.credits,
advisor: student.advisor,
email: student.email,
phone: student.phone,
status: student.status,
}
}
function rebuildDraftRows () {
draftRows.value = Object.fromEntries(students.value.map((item) => [item.id, toPayload(item)]))
}
const getSourceRow = (id: number) => students.value.find((item) => item.id === id) || null
function isRowDirty (id: number) {
const source = getSourceRow(id)
const draft = draftRows.value[id]
if (!source || !draft) return false
return (
source.studentId !== draft.studentId ||
source.name !== draft.name ||
source.department !== draft.department ||
source.grade !== draft.grade ||
source.enrollYear !== draft.enrollYear ||
source.credits !== draft.credits ||
source.advisor !== draft.advisor ||
source.email !== draft.email ||
source.phone !== draft.phone ||
source.status !== draft.status
)
}
const filteredStudents = computed(() => {
const keywordStudentId = search.value.studentId.trim().toLowerCase()
const keywordName = search.value.name.trim().toLowerCase()
const selectedDepartment = search.value.department
return students.value.filter((item) => {
if (studentStore.isMarkedAsDeleted(item.id)) return false
const matchesStudentId = keywordStudentId
? item.studentId.toLowerCase().includes(keywordStudentId)
: true
const matchesName = keywordName ? item.name.toLowerCase().includes(keywordName) : true
const matchesDepartment = selectedDepartment ? item.department === selectedDepartment : true
return matchesStudentId && matchesName && matchesDepartment
})
})
const visibleStudentIds = computed(() => filteredStudents.value.map((item) => item.id))
const isAllVisibleSelected = computed(() =>
visibleStudentIds.value.length > 0 && visibleStudentIds.value.every((id) => selectedRowIds.value.includes(id))
)
const isPartiallyVisibleSelected = computed(() =>
visibleStudentIds.value.some((id) => selectedRowIds.value.includes(id)) && !isAllVisibleSelected.value
)
function toggleSelectAll (checked: boolean | null) {
if (isPartiallyVisibleSelected.value) {
selectedRowIds.value = selectedRowIds.value.filter((id) => !visibleStudentIds.value.includes(id))
return
}
if (!checked) {
selectedRowIds.value = selectedRowIds.value.filter((id) => !visibleStudentIds.value.includes(id))
return
}
selectedRowIds.value = Array.from(new Set([...selectedRowIds.value, ...visibleStudentIds.value]))
}
function toggleSingleRowSelection (id: number, checked: boolean | null) {
if (checked) {
if (!selectedRowIds.value.includes(id)) {
selectedRowIds.value = [...selectedRowIds.value, id]
}
return
}
selectedRowIds.value = selectedRowIds.value.filter((selectedId) => selectedId !== id)
}
const hasAnyChange = computed(() =>
students.value.some((item) => isRowDirty(item.id)) || studentStore.deletedIds.size > 0
)
const hasSelectedRows = computed(() => selectedRowIds.value.length > 0)
function deleteSingleRow (id: number) {
selectedRowIds.value = selectedRowIds.value.filter((selectedId) => selectedId !== id)
studentStore.markAsDeleted(id)
rebuildDraftRows()
}
function deleteSelectedRows () {
if (selectedRowIds.value.length === 0) return
for (const id of selectedRowIds.value) {
studentStore.markAsDeleted(id)
}
selectedRowIds.value = []
rebuildDraftRows()
}
function saveAllRows () {
for (const item of students.value) {
const draft = draftRows.value[item.id]
if (!draft) continue
if (!isRowDirty(item.id)) continue
studentStore.updateStudent(item.id, draft)
}
studentStore.commitDeleted()
rebuildDraftRows()
}
function resetAllRows () {
studentStore.restoreDeleted()
selectedRowIds.value = []
rebuildDraftRows()
}
function recalculateTableHeight () {
const container = tableContainerRef.value
if (!container) return
const scrollParent = tableScrollParentRef.value || (container.closest('.overflow-auto') as HTMLElement | null)
tableScrollParentRef.value = scrollParent
const parentBottom = scrollParent
? scrollParent.getBoundingClientRect().bottom
: window.innerHeight
const top = container.getBoundingClientRect().top
const availableHeight = parentBottom - top - TABLE_BOTTOM_GAP
tableHeight.value = Math.max(TABLE_MIN_HEIGHT, Math.floor(availableHeight))
}
watch(students, () => {
const currentIds = new Set(students.value.map((item) => item.id))
selectedRowIds.value = selectedRowIds.value.filter((id) => currentIds.has(id))
})
watch(students, rebuildDraftRows, { immediate: true })
watch([isSearchVisible, isBulkEditEnabled], async () => {
await nextTick()
requestAnimationFrame(() => {
recalculateTableHeight()
})
})
onMounted(() => {
const container = tableContainerRef.value
if (container) {
tableScrollParentRef.value = container.closest('.overflow-auto') as HTMLElement | null
tableResizeObserver.value = new ResizeObserver(() => {
recalculateTableHeight()
})
tableResizeObserver.value.observe(container)
if (tableScrollParentRef.value) {
tableResizeObserver.value.observe(tableScrollParentRef.value)
}
}
requestAnimationFrame(() => {
recalculateTableHeight()
})
window.addEventListener('resize', recalculateTableHeight)
})
onBeforeUnmount(() => {
tableResizeObserver.value?.disconnect()
window.removeEventListener('resize', recalculateTableHeight)
})
import EditableStudentGrid from '@/components/maintenance/EditableStudentGrid.vue'
</script>
<style scoped>
:deep(.select-hide-arrow .v-field__append-inner) {
display: none;
}
:deep(.v-table__wrapper .v-field__input) {
padding-top: 0 !important;
padding-bottom: 0 !important;
min-height: 32px;
}
:deep(.v-data-table-footer) {
padding: 4px 0 0;
}
</style>
+115 -427
View File
@@ -123,54 +123,17 @@ v-for="error in errorSummary" :key="error.field" color="error" size="small" vari
<!-- 學生主檔表單檢視模式時會自動套用 readonly 樣式 -->
<v-form v-else :class="{ 'form-readonly': isFormReadonly }" @submit.prevent="requestSaveConfirmation">
<v-row dense>
<v-col cols="12" md="6">
<v-text-field
id="field-studentId" v-model="form.studentId" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.studentId" label="學號" placeholder="例如:S2024008"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('studentId')" />
</v-col>
<v-col cols="12" md="6">
<v-text-field
id="field-name" v-model="form.name" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.name"
label="姓名" placeholder="例如:陳怡君" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('name')" />
</v-col>
<v-col cols="12" md="6">
<v-select
id="field-department" v-model="form.department" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.department" :items="departments" label="系所"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('department')" />
</v-col>
<v-col cols="12" md="6">
<v-select
id="field-grade" v-model="form.grade" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.grade"
item-title="title" item-value="value" :items="gradeOptions" label="年級"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('grade')" />
</v-col>
<v-col cols="12" md="6">
<v-select
id="field-enrollYear" v-model="form.enrollYear" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.enrollYear" :items="enrollYears" label="入學年度"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('enrollYear')" />
</v-col>
<v-col cols="12" md="6">
<v-select
id="field-status" v-model="form.status" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.status"
:items="statuses" label="狀態" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('status')" />
</v-col>
<v-col cols="12">
<v-text-field
id="field-email" v-model="form.email" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.email" label="Email" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('email')" />
</v-col>
</v-row>
<maintenance-student-form-fields
:departments="departments"
:enroll-years="enrollYears"
:field-errors="fieldErrors"
:form="form"
:grade-options="gradeOptions"
:is-form-locked="isFormLocked"
:is-form-readonly="isFormReadonly"
:statuses="statuses"
@clear-field="clearFieldError"
/>
<v-divider />
@@ -217,44 +180,26 @@ v-if="!isViewMode" color="primary" :disabled="!isDirty || isLoading" :loading="i
</v-overlay>
</teleport>
<common-confirm-dialog
v-model="confirmCloseVisible" confirm-color="error" confirm-text="關閉不儲存" message="目前有尚未儲存的內容,確定要關閉嗎?"
title="未儲存變更" @confirm="confirmClose" />
<common-confirm-dialog
v-model="confirmSaveVisible" :confirm-loading="isSaving" confirm-text="確認儲存" max-width="520"
title="確認儲存變更" @confirm="confirmSave">
<div v-if="saveSummary.length > 0" class="d-flex flex-column ga-2">
<div v-for="item in saveSummary" :key="item.label" class="d-flex flex-column">
<div class="text-caption text-medium-emphasis">{{ item.label }}</div>
<div v-if="item.before !== null" class="text-body-2">
<span class="text-medium-emphasis"></span>
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.before) }">
{{ item.before }}
</span>
</div>
<div class="text-body-2">
<span class="text-medium-emphasis"></span>
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.after) }">
{{ item.after }}
</span>
</div>
</div>
</div>
<div v-else class="text-body-2">目前沒有可儲存的變更</div>
</common-confirm-dialog>
<common-confirm-dialog
v-model="confirmDeleteVisible" confirm-color="error" confirm-text="確定刪除"
:message="`確定要刪除 ${pendingDeleteLabel} 嗎?此操作無法復原。`" title="確認刪除" @confirm="confirmDelete" />
<common-confirm-dialog
v-model="confirmSwitchVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換為檢視模式將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmSwitch" />
<common-confirm-dialog
v-model="confirmNavigateVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換到其他資料將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmNavigate" />
<maintenance-crud-dialogs
:close-visible="confirmCloseVisible"
:delete-visible="confirmDeleteVisible"
:is-saving="isSaving"
:navigate-visible="confirmNavigateVisible"
:pending-delete-label="pendingDeleteLabel"
:save-summary="saveSummary"
:save-visible="confirmSaveVisible"
:switch-visible="confirmSwitchVisible"
@confirm-close="confirmClose"
@confirm-delete="confirmDelete"
@confirm-navigate="confirmNavigate"
@confirm-save="confirmSave"
@confirm-switch="confirmSwitch"
@update:close-visible="confirmCloseVisible = $event"
@update:delete-visible="confirmDeleteVisible = $event"
@update:navigate-visible="confirmNavigateVisible = $event"
@update:save-visible="confirmSaveVisible = $event"
@update:switch-visible="confirmSwitchVisible = $event"
/>
<!-- 成功提示 -->
<v-snackbar v-model="snackbarVisible" color="success" location="bottom right" :timeout="2200">
@@ -267,12 +212,15 @@ import { mdiBroom, mdiDelete, mdiEye, mdiMagnify, mdiPencil } from '@mdi/js'
import { computed, nextTick, ref } from 'vue'
import { useDisplay } from 'vuetify'
import CommonConfirmDialog from '@/components/maintenance/CommonConfirmDialog.vue'
import MaintenanceCrudDialogs from '@/components/maintenance/MaintenanceCrudDialogs.vue'
import MaintenanceStudentFormFields from '@/components/maintenance/MaintenanceStudentFormFields.vue'
import MasterDetailSemesterList from '@/components/maintenance/master-detail/MasterDetailSemesterList.vue'
import MasterDetailSemesterPanel from '@/components/maintenance/master-detail/MasterDetailSemesterPanel.vue'
import MntDialogCard from '@/components/maintenance/MntDialogCard.vue'
import MntPageCards from '@/components/maintenance/MntPageCards.vue'
import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue'
import { useMaintenanceCrudFlow } from '@/composables/maintenance/useMaintenanceCrudFlow'
import { useStudentMaintenanceForm } from '@/composables/maintenance/useStudentMaintenanceForm'
import { type SemesterRecord, useSemesterStore } from '@/stores/semesters'
import { type StudentRecord, useStudentStore } from '@/stores/students'
@@ -329,21 +277,11 @@ const editingId = ref<number | null>(null)
const dialogMode = ref<'create' | 'edit' | 'view'>('create')
const isLoading = ref(false)
const isSaving = ref(false)
// 各種確認彈窗
const confirmCloseVisible = ref(false)
const confirmSaveVisible = ref(false)
const confirmDeleteVisible = ref(false)
const confirmSwitchVisible = ref(false)
const confirmNavigateVisible = ref(false)
// UI 回饋
const snackbarVisible = ref(false)
const highlightedId = ref<number | null>(null)
// 防止快速切換導致的異步覆蓋
const loadSequence = ref(0)
// 暫存待處理的目標
const pendingDelete = ref<StudentRecord | null>(null)
const pendingSwitchTarget = ref<StudentRecord | null>(null)
const pendingNavigateTarget = ref<StudentRecord | null>(null)
// Master-Detail 擴充
const studentSemesters = ref<SemesterRecord[]>([])
@@ -433,32 +371,29 @@ function removeCourseFromDetail (index: number) {
}
// 表單資料與初始快照(用於 dirty 判斷)
const form = ref({
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
})
const initialForm = ref({ ...form.value })
// 欄位錯誤訊息(僅保存一則)
const fieldErrors = ref<Record<string, string[]>>({
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
const {
errorSummary,
fieldErrors,
form,
isDirty,
saveSummary,
clearAllErrors,
clearFieldError,
gradeLabel,
resetForm,
rowProps,
setForm,
statusColor,
syncInitialForm,
validateForm,
} = useStudentMaintenanceForm({
departments,
gradeOptions,
enrollYears,
statuses,
students,
editingId,
highlightedId,
})
// 表單欄位簡單排版(無分組)
@@ -473,60 +408,59 @@ const dialogSubtitle = computed(() => {
if (!editingId.value) return ''
return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}`
})
const isEditMode = computed(() => dialogMode.value === 'edit')
const isViewMode = computed(() => dialogMode.value === 'view')
// 是否有修改(用於啟用儲存與提示)
const isDirty = computed(
() => JSON.stringify(form.value) !== JSON.stringify(initialForm.value),
)
// 載入/儲存時鎖定、檢視模式 readonly
const isFormLocked = computed(() => isLoading.value || isSaving.value)
const {
closeDialog,
confirmClose,
confirmCloseVisible,
confirmDelete,
confirmDeleteVisible,
confirmNavigate,
confirmNavigateVisible,
confirmSaveVisible,
confirmSwitch,
confirmSwitchVisible,
currentEditingRecord,
handleDialogVisibility,
hasNextRecord,
hasPrevRecord,
isEditMode,
isViewMode,
openAdjacentRecord,
openEdgeRecord,
pendingDeleteLabel,
requestCloseDialog,
requestDeleteConfirmation,
requestDeleteCurrent,
switchToEditMode,
switchToViewMode,
} = useMaintenanceCrudFlow<StudentRecord>({
records: students,
editingId,
dialogMode,
dialogVisible,
isLoading,
isSaving,
isDirty,
clearAllErrors,
resetForm,
openEditDialog,
openViewDialog,
removeRecord: (id) => {
studentStore.removeStudent(id)
semesterStore.removeByStudentId(id)
},
describeRecord: (student) => `${student.studentId} ${student.name}`,
onCloseReset: () => {
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
isDetailEditing.value = false
detailForm.value = null
},
})
const isFormReadonly = computed(() => isViewMode.value)
// 目前筆數索引(用於導覽)
const currentRecordIndex = computed(() =>
students.value.findIndex((item) => item.id === editingId.value),
)
const currentEditingRecord = computed(
() => students.value.find((item) => item.id === editingId.value) || null,
)
const hasPrevRecord = computed(() => currentRecordIndex.value > 0)
const hasNextRecord = computed(
() => currentRecordIndex.value >= 0 && currentRecordIndex.value < students.value.length - 1,
)
const pendingDeleteLabel = computed(() => {
if (!pendingDelete.value) return '這筆資料'
return `${pendingDelete.value.studentId} ${pendingDelete.value.name}`
})
const saveSummary = computed(() => {
const labels: Record<string, string> = {
studentId: '學號',
name: '姓名',
department: '系所',
grade: '年級',
enrollYear: '入學年度',
credits: '已修學分',
advisor: '指導老師',
email: 'Email',
phone: '電話',
status: '狀態',
}
const before = initialForm.value
const after = form.value
const entries = Object.keys(labels).map((key) => {
const beforeValue = before[key as keyof typeof before]
const afterValue = after[key as keyof typeof after]
return {
key,
label: labels[key],
before: editingId.value ? formatSummaryValue(key, beforeValue) : null,
after: formatSummaryValue(key, afterValue),
}
})
if (!editingId.value) return entries
return entries.filter((entry) => entry.before !== entry.after)
})
// 重設查詢條件
function resetSearch () {
search.value = {
@@ -538,25 +472,6 @@ function resetSearch () {
}
}
// 重設表單與錯誤狀態
function resetForm () {
form.value = {
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
}
initialForm.value = { ...form.value }
isDetailEditing.value = false
clearAllErrors()
}
// 新增:開啟彈窗,使用預設值
function openAddDialog () {
loadSequence.value += 1
@@ -566,6 +481,7 @@ function openAddDialog () {
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
resetForm()
isDetailEditing.value = false
isLoading.value = false
dialogVisible.value = true
}
@@ -584,7 +500,7 @@ function openEditDialog (student: StudentRecord) {
clearAllErrors()
setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = {
setForm({
studentId: student.studentId,
name: student.name,
department: student.department,
@@ -595,8 +511,8 @@ function openEditDialog (student: StudentRecord) {
email: student.email,
phone: student.phone,
status: student.status,
}
initialForm.value = { ...form.value }
})
syncInitialForm()
isLoading.value = false
}, 350)
}
@@ -615,7 +531,7 @@ function openViewDialog (student: StudentRecord) {
clearAllErrors()
setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = {
setForm({
studentId: student.studentId,
name: student.name,
department: student.department,
@@ -626,89 +542,12 @@ function openViewDialog (student: StudentRecord) {
email: student.email,
phone: student.phone,
status: student.status,
}
initialForm.value = { ...form.value }
})
syncInitialForm()
isLoading.value = false
}, 350)
}
// 依方向切換上一筆/下一筆
function openAdjacentRecord (direction: 'prev' | 'next') {
if (!isViewMode.value && !isEditMode.value) return
const index = currentRecordIndex.value
if (index < 0) return
const targetIndex = direction === 'prev' ? index - 1 : index + 1
const target = students.value[targetIndex]
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 切換到第一筆/最後一筆
function openEdgeRecord (position: 'first' | 'last') {
if (!isViewMode.value && !isEditMode.value) return
if (students.value.length === 0) return
const target = position === 'first' ? students.value[0] : students.value.at(-1)
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 檢視 → 編輯(直接切換)
function switchToEditMode () {
if (!isViewMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
openEditDialog(current)
}
// 編輯 → 檢視(若 dirty 需確認)
function switchToViewMode () {
if (!isEditMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
if (isDirty.value) {
pendingSwitchTarget.value = current
confirmSwitchVisible.value = true
return
}
openViewDialog(current)
}
// 確認切換為檢視模式
function confirmSwitch () {
const target = pendingSwitchTarget.value
pendingSwitchTarget.value = null
confirmSwitchVisible.value = false
if (!target) return
openViewDialog(target)
}
// 確認切換到其他資料
function confirmNavigate () {
const target = pendingNavigateTarget.value
pendingNavigateTarget.value = null
confirmNavigateVisible.value = false
if (!target) return
openEditDialog(target)
}
// 先檢核再提示儲存確認
async function requestSaveConfirmation () {
if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return
@@ -761,7 +600,7 @@ async function saveStudent () {
highlightedId.value = createdId
}
initialForm.value = { ...form.value }
syncInitialForm()
dialogVisible.value = false
snackbarVisible.value = true
isSaving.value = false
@@ -770,163 +609,12 @@ async function saveStudent () {
}, 1600)
}
// 刪除:先提示確認
function requestDeleteConfirmation (student: StudentRecord) {
pendingDelete.value = student
confirmDeleteVisible.value = true
}
// 編輯模式刪除目前資料
function requestDeleteCurrent () {
const current = currentEditingRecord.value
if (!current) return
requestDeleteConfirmation(current)
}
// 確認刪除後,若正在編輯該筆則關閉彈窗
function confirmDelete () {
if (!pendingDelete.value) return
const deletedId = pendingDelete.value.id
studentStore.removeStudent(deletedId)
semesterStore.removeByStudentId(deletedId)
pendingDelete.value = null
confirmDeleteVisible.value = false
if (editingId.value === deletedId) {
closeDialog()
}
}
// 狀態顏色映射
function statusColor (status: string) {
if (status === '在學') return 'success'
if (status === '休學') return 'warning'
if (status === '畢業') return 'secondary'
return 'default'
}
// 年級顯示字串
function gradeLabel (grade: number) {
return gradeOptions.find((option) => option.value === grade)?.title ?? `年級 ${grade}`
}
// 列高亮(儲存後提示位置)
function rowProps (data: { item: StudentRecord }) {
return {
class: data.item.id === highlightedId.value ? 'is-highlighted' : '',
}
}
function clearAllErrors () {
fieldErrors.value = {
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
}
}
function clearFieldError (field: string) {
if (!fieldErrors.value[field]?.length) return
fieldErrors.value[field] = []
}
function validateForm () {
const errors: Array<{ field: string; message: string }> = []
const studentId = form.value.studentId.trim()
const name = form.value.name.trim()
const email = form.value.email.trim()
const credits = form.value.credits
if (!studentId) errors.push({ field: 'studentId', message: '請輸入學號' })
if (!name) errors.push({ field: 'name', message: '請輸入姓名' })
if (!form.value.department) errors.push({ field: 'department', message: '請選擇系所' })
if (!form.value.grade) errors.push({ field: 'grade', message: '請選擇年級' })
if (!form.value.enrollYear) errors.push({ field: 'enrollYear', message: '請選擇入學年度' })
if (credits === null || Number.isNaN(credits)) {
errors.push({ field: 'credits', message: '請輸入已修學分' })
} else if (credits < 0) {
errors.push({ field: 'credits', message: '已修學分不可小於 0' })
}
if (!form.value.status) errors.push({ field: 'status', message: '請選擇狀態' })
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push({ field: 'email', message: 'Email 格式不正確' })
}
const duplicate = students.value.find(
(item) => item.studentId === studentId && item.id !== editingId.value,
)
if (studentId && duplicate) {
errors.push({ field: 'studentId', message: '學號已存在,請確認是否重複' })
}
return errors
}
const errorSummary = computed(() => {
const entries = Object.entries(fieldErrors.value).flatMap(([field, messages]) =>
messages.map((message) => ({ field, message })),
)
return entries.slice(0, 3)
})
function scrollToField (field: string) {
const target = document.getElementById(`field-${field}`)
if (!target) return
target.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
function requestCloseDialog () {
if (isDirty.value && !isSaving.value) {
confirmCloseVisible.value = true
return
}
closeDialog()
}
function confirmClose () {
confirmCloseVisible.value = false
closeDialog()
}
function closeDialog () {
dialogVisible.value = false
isLoading.value = false
isSaving.value = false
confirmSaveVisible.value = false
confirmSwitchVisible.value = false
confirmNavigateVisible.value = false
dialogMode.value = 'create'
editingId.value = null
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
isDetailEditing.value = false
clearAllErrors()
resetForm()
}
function handleDialogVisibility (nextValue: boolean) {
if (nextValue) {
dialogVisible.value = true
return
}
requestCloseDialog()
}
const isPlaceholderValue = (value: string | null) => value === '—'
function formatSummaryValue (key: string, value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') return '—'
if (key === 'grade') return gradeLabel(Number(value))
return String(value)
}
function handleSemesterSelect (id: number) {
if (isMobile.value) {
selectedSemesterId.value = id
+113 -427
View File
@@ -113,54 +113,17 @@ v-else :class="[
{ 'form-readonly': isFormReadonly },
isMobile ? '' : 'd-flex flex-column h-100',
]" @submit.prevent="requestSaveConfirmation">
<v-row dense>
<v-col cols="12" md="3">
<v-text-field
id="field-studentId" v-model="form.studentId" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.studentId" label="學號" placeholder="例如:S2024008"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('studentId')" />
</v-col>
<v-col cols="12" md="3">
<v-text-field
id="field-name" v-model="form.name" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.name"
label="姓名" placeholder="例如:陳怡君" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('name')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-department" v-model="form.department" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.department" :items="departments" label="系所"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('department')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-grade" v-model="form.grade" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.grade"
item-title="title" item-value="value" :items="gradeOptions" label="年級"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('grade')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-enrollYear" v-model="form.enrollYear" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.enrollYear" :items="enrollYears" label="入學年度"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('enrollYear')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-status" v-model="form.status" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.status"
:items="statuses" label="狀態" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('status')" />
</v-col>
<v-col cols="12" md="3">
<v-text-field
id="field-email" v-model="form.email" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.email" label="Email" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('email')" />
</v-col>
</v-row>
<maintenance-student-form-fields
:departments="departments"
:enroll-years="enrollYears"
:field-errors="fieldErrors"
:form="form"
:grade-options="gradeOptions"
:is-form-locked="isFormLocked"
:is-form-readonly="isFormReadonly"
:statuses="statuses"
@clear-field="clearFieldError"
/>
<v-divider />
@@ -206,44 +169,26 @@ v-if="!isViewMode" color="primary" :disabled="!isDirty || isLoading" :loading="i
</v-overlay>
</teleport>
<common-confirm-dialog
v-model="confirmCloseVisible" confirm-color="error" confirm-text="關閉不儲存" message="目前有尚未儲存的內容,確定要關閉嗎?"
title="未儲存變更" @confirm="confirmClose" />
<common-confirm-dialog
v-model="confirmSaveVisible" :confirm-loading="isSaving" confirm-text="確認儲存" max-width="520"
title="確認儲存變更" @confirm="confirmSave">
<div v-if="saveSummary.length > 0" class="d-flex flex-column ga-2">
<div v-for="item in saveSummary" :key="item.label" class="d-flex flex-column">
<div class="text-caption text-medium-emphasis">{{ item.label }}</div>
<div v-if="item.before !== null" class="text-body-2">
<span class="text-medium-emphasis"></span>
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.before) }">
{{ item.before }}
</span>
</div>
<div class="text-body-2">
<span class="text-medium-emphasis"></span>
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.after) }">
{{ item.after }}
</span>
</div>
</div>
</div>
<div v-else class="text-body-2">目前沒有可儲存的變更</div>
</common-confirm-dialog>
<common-confirm-dialog
v-model="confirmDeleteVisible" confirm-color="error" confirm-text="確定刪除"
:message="`確定要刪除 ${pendingDeleteLabel} 嗎?此操作無法復原。`" title="確認刪除" @confirm="confirmDelete" />
<common-confirm-dialog
v-model="confirmSwitchVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換為檢視模式將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmSwitch" />
<common-confirm-dialog
v-model="confirmNavigateVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換到其他資料將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmNavigate" />
<maintenance-crud-dialogs
:close-visible="confirmCloseVisible"
:delete-visible="confirmDeleteVisible"
:is-saving="isSaving"
:navigate-visible="confirmNavigateVisible"
:pending-delete-label="pendingDeleteLabel"
:save-summary="saveSummary"
:save-visible="confirmSaveVisible"
:switch-visible="confirmSwitchVisible"
@confirm-close="confirmClose"
@confirm-delete="confirmDelete"
@confirm-navigate="confirmNavigate"
@confirm-save="confirmSave"
@confirm-switch="confirmSwitch"
@update:close-visible="confirmCloseVisible = $event"
@update:delete-visible="confirmDeleteVisible = $event"
@update:navigate-visible="confirmNavigateVisible = $event"
@update:save-visible="confirmSaveVisible = $event"
@update:switch-visible="confirmSwitchVisible = $event"
/>
<!-- 刪除課程確認 -->
<common-confirm-dialog
@@ -294,12 +239,15 @@ import { mdiBookPlus, mdiBroom, mdiDelete, mdiEye, mdiMagnify, mdiPencil } from
import { computed, nextTick, ref } from 'vue'
import { useDisplay } from 'vuetify'
import CommonConfirmDialog from '@/components/maintenance/CommonConfirmDialog.vue'
import MaintenanceCrudDialogs from '@/components/maintenance/MaintenanceCrudDialogs.vue'
import MaintenanceStudentFormFields from '@/components/maintenance/MaintenanceStudentFormFields.vue'
import MasterDetailBSemesterMobilePanel from '@/components/maintenance/master-detail-b/MasterDetailBSemesterMobilePanel.vue'
import MasterDetailBSemesterSection from '@/components/maintenance/master-detail-b/MasterDetailBSemesterSection.vue'
import MntDialogCard from '@/components/maintenance/MntDialogCard.vue'
import MntPageCards from '@/components/maintenance/MntPageCards.vue'
import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue'
import { useMaintenanceCrudFlow } from '@/composables/maintenance/useMaintenanceCrudFlow'
import { useStudentMaintenanceForm } from '@/composables/maintenance/useStudentMaintenanceForm'
import { type CourseRecord, type SemesterRecord, useSemesterStore } from '@/stores/semesters'
import { type StudentRecord, useStudentStore } from '@/stores/students'
@@ -356,21 +304,11 @@ const editingId = ref<number | null>(null)
const dialogMode = ref<'create' | 'edit' | 'view'>('create')
const isLoading = ref(false)
const isSaving = ref(false)
// 各種確認彈窗
const confirmCloseVisible = ref(false)
const confirmSaveVisible = ref(false)
const confirmDeleteVisible = ref(false)
const confirmSwitchVisible = ref(false)
const confirmNavigateVisible = ref(false)
// UI 回饋
const snackbarVisible = ref(false)
const highlightedId = ref<number | null>(null)
// 防止快速切換導致的異步覆蓋
const loadSequence = ref(0)
// 暫存待處理的目標
const pendingDelete = ref<StudentRecord | null>(null)
const pendingSwitchTarget = ref<StudentRecord | null>(null)
const pendingNavigateTarget = ref<StudentRecord | null>(null)
// Master-Detail 擴充
const studentSemesters = ref<SemesterRecord[]>([])
@@ -495,32 +433,29 @@ function handleUpdateCourse (semesterId: number, courseIndex: number, payload: P
}
// 表單資料與初始快照(用於 dirty 判斷)
const form = ref({
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
})
const initialForm = ref({ ...form.value })
// 欄位錯誤訊息(僅保存一則)
const fieldErrors = ref<Record<string, string[]>>({
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
const {
errorSummary,
fieldErrors,
form,
isDirty,
saveSummary,
clearAllErrors,
clearFieldError,
gradeLabel,
resetForm,
rowProps,
setForm,
statusColor,
syncInitialForm,
validateForm,
} = useStudentMaintenanceForm({
departments,
gradeOptions,
enrollYears,
statuses,
students,
editingId,
highlightedId,
})
// 表單欄位簡單排版(無分組)
@@ -535,60 +470,58 @@ const dialogSubtitle = computed(() => {
if (!editingId.value) return ''
return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}`
})
const isEditMode = computed(() => dialogMode.value === 'edit')
const isViewMode = computed(() => dialogMode.value === 'view')
// 是否有修改(用於啟用儲存與提示)
const isDirty = computed(
() => JSON.stringify(form.value) !== JSON.stringify(initialForm.value),
)
// 載入/儲存時鎖定、檢視模式 readonly
const isFormLocked = computed(() => isLoading.value || isSaving.value)
const {
closeDialog,
confirmClose,
confirmCloseVisible,
confirmDelete,
confirmDeleteVisible,
confirmNavigate,
confirmNavigateVisible,
confirmSaveVisible,
confirmSwitch,
confirmSwitchVisible,
currentEditingRecord,
handleDialogVisibility,
hasNextRecord,
hasPrevRecord,
isEditMode,
isViewMode,
openAdjacentRecord,
openEdgeRecord,
pendingDeleteLabel,
requestCloseDialog,
requestDeleteConfirmation,
requestDeleteCurrent,
switchToEditMode,
switchToViewMode,
} = useMaintenanceCrudFlow<StudentRecord>({
records: students,
editingId,
dialogMode,
dialogVisible,
isLoading,
isSaving,
isDirty,
clearAllErrors,
resetForm,
openEditDialog,
openViewDialog,
removeRecord: (id) => {
studentStore.removeStudent(id)
semesterStore.removeByStudentId(id)
},
describeRecord: (student) => `${student.studentId} ${student.name}`,
onCloseReset: () => {
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
studentSemesters.value = []
},
})
const isFormReadonly = computed(() => isViewMode.value)
// 目前筆數索引(用於導覽)
const currentRecordIndex = computed(() =>
students.value.findIndex((item) => item.id === editingId.value),
)
const currentEditingRecord = computed(
() => students.value.find((item) => item.id === editingId.value) || null,
)
const hasPrevRecord = computed(() => currentRecordIndex.value > 0)
const hasNextRecord = computed(
() => currentRecordIndex.value >= 0 && currentRecordIndex.value < students.value.length - 1,
)
const pendingDeleteLabel = computed(() => {
if (!pendingDelete.value) return '這筆資料'
return `${pendingDelete.value.studentId} ${pendingDelete.value.name}`
})
const saveSummary = computed(() => {
const labels: Record<string, string> = {
studentId: '學號',
name: '姓名',
department: '系所',
grade: '年級',
enrollYear: '入學年度',
credits: '已修學分',
advisor: '指導老師',
email: 'Email',
phone: '電話',
status: '狀態',
}
const before = initialForm.value
const after = form.value
const entries = Object.keys(labels).map((key) => {
const beforeValue = before[key as keyof typeof before]
const afterValue = after[key as keyof typeof after]
return {
key,
label: labels[key],
before: editingId.value ? formatSummaryValue(key, beforeValue) : null,
after: formatSummaryValue(key, afterValue),
}
})
if (!editingId.value) return entries
return entries.filter((entry) => entry.before !== entry.after)
})
// 重設查詢條件
function resetSearch () {
search.value = {
@@ -600,24 +533,6 @@ function resetSearch () {
}
}
// 重設表單與錯誤狀態
function resetForm () {
form.value = {
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
}
initialForm.value = { ...form.value }
clearAllErrors()
}
// 新增:開啟彈窗,使用預設值
function openAddDialog () {
loadSequence.value += 1
@@ -645,7 +560,7 @@ function openEditDialog (student: StudentRecord) {
clearAllErrors()
setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = {
setForm({
studentId: student.studentId,
name: student.name,
department: student.department,
@@ -656,8 +571,8 @@ function openEditDialog (student: StudentRecord) {
email: student.email,
phone: student.phone,
status: student.status,
}
initialForm.value = { ...form.value }
})
syncInitialForm()
isLoading.value = false
}, 350)
}
@@ -676,7 +591,7 @@ function openViewDialog (student: StudentRecord) {
clearAllErrors()
setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = {
setForm({
studentId: student.studentId,
name: student.name,
department: student.department,
@@ -687,89 +602,12 @@ function openViewDialog (student: StudentRecord) {
email: student.email,
phone: student.phone,
status: student.status,
}
initialForm.value = { ...form.value }
})
syncInitialForm()
isLoading.value = false
}, 350)
}
// 依方向切換上一筆/下一筆
function openAdjacentRecord (direction: 'prev' | 'next') {
if (!isViewMode.value && !isEditMode.value) return
const index = currentRecordIndex.value
if (index < 0) return
const targetIndex = direction === 'prev' ? index - 1 : index + 1
const target = students.value[targetIndex]
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 切換到第一筆/最後一筆
function openEdgeRecord (position: 'first' | 'last') {
if (!isViewMode.value && !isEditMode.value) return
if (students.value.length === 0) return
const target = position === 'first' ? students.value[0] : students.value.at(-1)
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 檢視 → 編輯(直接切換)
function switchToEditMode () {
if (!isViewMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
openEditDialog(current)
}
// 編輯 → 檢視(若 dirty 需確認)
function switchToViewMode () {
if (!isEditMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
if (isDirty.value) {
pendingSwitchTarget.value = current
confirmSwitchVisible.value = true
return
}
openViewDialog(current)
}
// 確認切換為檢視模式
function confirmSwitch () {
const target = pendingSwitchTarget.value
pendingSwitchTarget.value = null
confirmSwitchVisible.value = false
if (!target) return
openViewDialog(target)
}
// 確認切換到其他資料
function confirmNavigate () {
const target = pendingNavigateTarget.value
pendingNavigateTarget.value = null
confirmNavigateVisible.value = false
if (!target) return
openEditDialog(target)
}
// 先檢核再提示儲存確認
async function requestSaveConfirmation () {
if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return
@@ -822,7 +660,7 @@ async function saveStudent () {
highlightedId.value = createdId
}
initialForm.value = { ...form.value }
syncInitialForm()
dialogVisible.value = false
snackbarVisible.value = true
isSaving.value = false
@@ -831,163 +669,11 @@ async function saveStudent () {
}, 1600)
}
// 刪除:先提示確認
function requestDeleteConfirmation (student: StudentRecord) {
pendingDelete.value = student
confirmDeleteVisible.value = true
}
// 編輯模式刪除目前資料
function requestDeleteCurrent () {
const current = currentEditingRecord.value
if (!current) return
requestDeleteConfirmation(current)
}
// 確認刪除後,若正在編輯該筆則關閉彈窗
function confirmDelete () {
if (!pendingDelete.value) return
const deletedId = pendingDelete.value.id
studentStore.removeStudent(deletedId)
semesterStore.removeByStudentId(deletedId)
pendingDelete.value = null
confirmDeleteVisible.value = false
if (editingId.value === deletedId) {
closeDialog()
}
}
// 狀態顏色映射
function statusColor (status: string) {
if (status === '在學') return 'success'
if (status === '休學') return 'warning'
if (status === '畢業') return 'secondary'
return 'default'
}
// 年級顯示字串
function gradeLabel (grade: number) {
return gradeOptions.find((option) => option.value === grade)?.title ?? `年級 ${grade}`
}
// 列高亮(儲存後提示位置)
function rowProps (data: { item: StudentRecord }) {
return {
class: data.item.id === highlightedId.value ? 'is-highlighted' : '',
}
}
function clearAllErrors () {
fieldErrors.value = {
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
}
}
function clearFieldError (field: string) {
if (!fieldErrors.value[field]?.length) return
fieldErrors.value[field] = []
}
function validateForm () {
const errors: Array<{ field: string; message: string }> = []
const studentId = form.value.studentId.trim()
const name = form.value.name.trim()
const email = form.value.email.trim()
const credits = form.value.credits
if (!studentId) errors.push({ field: 'studentId', message: '請輸入學號' })
if (!name) errors.push({ field: 'name', message: '請輸入姓名' })
if (!form.value.department) errors.push({ field: 'department', message: '請選擇系所' })
if (!form.value.grade) errors.push({ field: 'grade', message: '請選擇年級' })
if (!form.value.enrollYear) errors.push({ field: 'enrollYear', message: '請選擇入學年度' })
if (credits === null || Number.isNaN(credits)) {
errors.push({ field: 'credits', message: '請輸入已修學分' })
} else if (credits < 0) {
errors.push({ field: 'credits', message: '已修學分不可小於 0' })
}
if (!form.value.status) errors.push({ field: 'status', message: '請選擇狀態' })
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push({ field: 'email', message: 'Email 格式不正確' })
}
const duplicate = students.value.find(
(item) => item.studentId === studentId && item.id !== editingId.value,
)
if (studentId && duplicate) {
errors.push({ field: 'studentId', message: '學號已存在,請確認是否重複' })
}
return errors
}
const errorSummary = computed(() => {
const entries = Object.entries(fieldErrors.value).flatMap(([field, messages]) =>
messages.map((message) => ({ field, message })),
)
return entries.slice(0, 3)
})
function scrollToField (field: string) {
const target = document.getElementById(`field-${field}`)
if (!target) return
target.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
function requestCloseDialog () {
if (isDirty.value && !isSaving.value) {
confirmCloseVisible.value = true
return
}
closeDialog()
}
function confirmClose () {
confirmCloseVisible.value = false
closeDialog()
}
function closeDialog () {
dialogVisible.value = false
isLoading.value = false
isSaving.value = false
confirmSaveVisible.value = false
confirmSwitchVisible.value = false
confirmNavigateVisible.value = false
dialogMode.value = 'create'
editingId.value = null
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
studentSemesters.value = []
clearAllErrors()
resetForm()
}
function handleDialogVisibility (nextValue: boolean) {
if (nextValue) {
dialogVisible.value = true
return
}
requestCloseDialog()
}
const isPlaceholderValue = (value: string | null) => value === '—'
function formatSummaryValue (key: string, value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') return '—'
if (key === 'grade') return gradeLabel(Number(value))
return String(value)
}
</script>
<style scoped>
+113 -427
View File
@@ -113,54 +113,17 @@ v-else :class="[
{ 'form-readonly': isFormReadonly },
isMobile ? '' : 'd-flex flex-column h-100',
]" @submit.prevent="requestSaveConfirmation">
<v-row dense>
<v-col cols="12" md="3">
<v-text-field
id="field-studentId" v-model="form.studentId" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.studentId" label="學號" placeholder="例如:S2024008"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('studentId')" />
</v-col>
<v-col cols="12" md="3">
<v-text-field
id="field-name" v-model="form.name" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.name"
label="姓名" placeholder="例如:陳怡君" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('name')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-department" v-model="form.department" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.department" :items="departments" label="系所"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('department')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-grade" v-model="form.grade" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.grade"
item-title="title" item-value="value" :items="gradeOptions" label="年級"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('grade')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-enrollYear" v-model="form.enrollYear" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.enrollYear" :items="enrollYears" label="入學年度"
:readonly="isFormReadonly" variant="outlined"
@update:model-value="clearFieldError('enrollYear')" />
</v-col>
<v-col cols="12" md="3">
<v-select
id="field-status" v-model="form.status" density="comfortable" :disabled="isFormLocked" :error-messages="fieldErrors.status"
:items="statuses" label="狀態" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('status')" />
</v-col>
<v-col cols="12" md="3">
<v-text-field
id="field-email" v-model="form.email" density="comfortable" :disabled="isFormLocked"
:error-messages="fieldErrors.email" label="Email" :readonly="isFormReadonly"
variant="outlined" @update:model-value="clearFieldError('email')" />
</v-col>
</v-row>
<maintenance-student-form-fields
:departments="departments"
:enroll-years="enrollYears"
:field-errors="fieldErrors"
:form="form"
:grade-options="gradeOptions"
:is-form-locked="isFormLocked"
:is-form-readonly="isFormReadonly"
:statuses="statuses"
@clear-field="clearFieldError"
/>
<v-divider />
<master-detail-c-course-section
@@ -205,44 +168,26 @@ v-if="!isViewMode" color="primary" :disabled="!isDirty || isLoading" :loading="i
</v-overlay>
</teleport>
<common-confirm-dialog
v-model="confirmCloseVisible" confirm-color="error" confirm-text="關閉不儲存" message="目前有尚未儲存的內容,確定要關閉嗎?"
title="未儲存變更" @confirm="confirmClose" />
<common-confirm-dialog
v-model="confirmSaveVisible" :confirm-loading="isSaving" confirm-text="確認儲存" max-width="520"
title="確認儲存變更" @confirm="confirmSave">
<div v-if="saveSummary.length > 0" class="d-flex flex-column ga-2">
<div v-for="item in saveSummary" :key="item.label" class="d-flex flex-column">
<div class="text-caption text-medium-emphasis">{{ item.label }}</div>
<div v-if="item.before !== null" class="text-body-2">
<span class="text-medium-emphasis"></span>
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.before) }">
{{ item.before }}
</span>
</div>
<div class="text-body-2">
<span class="text-medium-emphasis"></span>
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.after) }">
{{ item.after }}
</span>
</div>
</div>
</div>
<div v-else class="text-body-2">目前沒有可儲存的變更</div>
</common-confirm-dialog>
<common-confirm-dialog
v-model="confirmDeleteVisible" confirm-color="error" confirm-text="確定刪除"
:message="`確定要刪除 ${pendingDeleteLabel} 嗎?此操作無法復原。`" title="確認刪除" @confirm="confirmDelete" />
<common-confirm-dialog
v-model="confirmSwitchVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換為檢視模式將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmSwitch" />
<common-confirm-dialog
v-model="confirmNavigateVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換到其他資料將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmNavigate" />
<maintenance-crud-dialogs
:close-visible="confirmCloseVisible"
:delete-visible="confirmDeleteVisible"
:is-saving="isSaving"
:navigate-visible="confirmNavigateVisible"
:pending-delete-label="pendingDeleteLabel"
:save-summary="saveSummary"
:save-visible="confirmSaveVisible"
:switch-visible="confirmSwitchVisible"
@confirm-close="confirmClose"
@confirm-delete="confirmDelete"
@confirm-navigate="confirmNavigate"
@confirm-save="confirmSave"
@confirm-switch="confirmSwitch"
@update:close-visible="confirmCloseVisible = $event"
@update:delete-visible="confirmDeleteVisible = $event"
@update:navigate-visible="confirmNavigateVisible = $event"
@update:save-visible="confirmSaveVisible = $event"
@update:switch-visible="confirmSwitchVisible = $event"
/>
<!-- 成功提示 -->
<v-snackbar v-model="snackbarVisible" color="success" location="bottom right" :timeout="2200">
@@ -284,12 +229,15 @@ import { mdiBroom, mdiDelete, mdiEye, mdiMagnify, mdiPencil, mdiSchool } from '@
import { computed, nextTick, ref } from 'vue'
import { useDisplay } from 'vuetify'
import CommonConfirmDialog from '@/components/maintenance/CommonConfirmDialog.vue'
import MaintenanceCrudDialogs from '@/components/maintenance/MaintenanceCrudDialogs.vue'
import MaintenanceStudentFormFields from '@/components/maintenance/MaintenanceStudentFormFields.vue'
import MasterDetailCCourseMobilePanel from '@/components/maintenance/master-detail-c/MasterDetailCCourseMobilePanel.vue'
import MasterDetailCCourseSection from '@/components/maintenance/master-detail-c/MasterDetailCCourseSection.vue'
import MntDialogCard from '@/components/maintenance/MntDialogCard.vue'
import MntPageCards from '@/components/maintenance/MntPageCards.vue'
import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue'
import { useMaintenanceCrudFlow } from '@/composables/maintenance/useMaintenanceCrudFlow'
import { useStudentMaintenanceForm } from '@/composables/maintenance/useStudentMaintenanceForm'
import { type CourseRecord, type SemesterRecord, useSemesterStore } from '@/stores/semesters'
import { type StudentRecord, useStudentStore } from '@/stores/students'
@@ -346,21 +294,11 @@ const editingId = ref<number | null>(null)
const dialogMode = ref<'create' | 'edit' | 'view'>('create')
const isLoading = ref(false)
const isSaving = ref(false)
// 各種確認彈窗
const confirmCloseVisible = ref(false)
const confirmSaveVisible = ref(false)
const confirmDeleteVisible = ref(false)
const confirmSwitchVisible = ref(false)
const confirmNavigateVisible = ref(false)
// UI 回饋
const snackbarVisible = ref(false)
const highlightedId = ref<number | null>(null)
// 防止快速切換導致的異步覆蓋
const loadSequence = ref(0)
// 暫存待處理的目標
const pendingDelete = ref<StudentRecord | null>(null)
const pendingSwitchTarget = ref<StudentRecord | null>(null)
const pendingNavigateTarget = ref<StudentRecord | null>(null)
// Master-Detail 擴充
const studentSemesters = ref<SemesterRecord[]>([])
@@ -505,32 +443,29 @@ function removeCourseFromSemester (semesterId: number, courseIndex: number) {
}
// 表單資料與初始快照(用於 dirty 判斷)
const form = ref({
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
})
const initialForm = ref({ ...form.value })
// 欄位錯誤訊息(僅保存一則)
const fieldErrors = ref<Record<string, string[]>>({
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
const {
errorSummary,
fieldErrors,
form,
isDirty,
saveSummary,
clearAllErrors,
clearFieldError,
gradeLabel,
resetForm,
rowProps,
setForm,
statusColor,
syncInitialForm,
validateForm,
} = useStudentMaintenanceForm({
departments,
gradeOptions,
enrollYears,
statuses,
students,
editingId,
highlightedId,
})
// 表單欄位簡單排版(無分組)
@@ -545,60 +480,58 @@ const dialogSubtitle = computed(() => {
if (!editingId.value) return ''
return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}`
})
const isEditMode = computed(() => dialogMode.value === 'edit')
const isViewMode = computed(() => dialogMode.value === 'view')
// 是否有修改(用於啟用儲存與提示)
const isDirty = computed(
() => JSON.stringify(form.value) !== JSON.stringify(initialForm.value),
)
// 載入/儲存時鎖定、檢視模式 readonly
const isFormLocked = computed(() => isLoading.value || isSaving.value)
const {
closeDialog,
confirmClose,
confirmCloseVisible,
confirmDelete,
confirmDeleteVisible,
confirmNavigate,
confirmNavigateVisible,
confirmSaveVisible,
confirmSwitch,
confirmSwitchVisible,
currentEditingRecord,
handleDialogVisibility,
hasNextRecord,
hasPrevRecord,
isEditMode,
isViewMode,
openAdjacentRecord,
openEdgeRecord,
pendingDeleteLabel,
requestCloseDialog,
requestDeleteConfirmation,
requestDeleteCurrent,
switchToEditMode,
switchToViewMode,
} = useMaintenanceCrudFlow<StudentRecord>({
records: students,
editingId,
dialogMode,
dialogVisible,
isLoading,
isSaving,
isDirty,
clearAllErrors,
resetForm,
openEditDialog,
openViewDialog,
removeRecord: (id) => {
studentStore.removeStudent(id)
semesterStore.removeByStudentId(id)
},
describeRecord: (student) => `${student.studentId} ${student.name}`,
onCloseReset: () => {
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
studentSemesters.value = []
},
})
const isFormReadonly = computed(() => isViewMode.value)
// 目前筆數索引(用於導覽)
const currentRecordIndex = computed(() =>
students.value.findIndex((item) => item.id === editingId.value),
)
const currentEditingRecord = computed(
() => students.value.find((item) => item.id === editingId.value) || null,
)
const hasPrevRecord = computed(() => currentRecordIndex.value > 0)
const hasNextRecord = computed(
() => currentRecordIndex.value >= 0 && currentRecordIndex.value < students.value.length - 1,
)
const pendingDeleteLabel = computed(() => {
if (!pendingDelete.value) return '這筆資料'
return `${pendingDelete.value.studentId} ${pendingDelete.value.name}`
})
const saveSummary = computed(() => {
const labels: Record<string, string> = {
studentId: '學號',
name: '姓名',
department: '系所',
grade: '年級',
enrollYear: '入學年度',
credits: '已修學分',
advisor: '指導老師',
email: 'Email',
phone: '電話',
status: '狀態',
}
const before = initialForm.value
const after = form.value
const entries = Object.keys(labels).map((key) => {
const beforeValue = before[key as keyof typeof before]
const afterValue = after[key as keyof typeof after]
return {
key,
label: labels[key],
before: editingId.value ? formatSummaryValue(key, beforeValue) : null,
after: formatSummaryValue(key, afterValue),
}
})
if (!editingId.value) return entries
return entries.filter((entry) => entry.before !== entry.after)
})
// 重設查詢條件
function resetSearch () {
search.value = {
@@ -610,24 +543,6 @@ function resetSearch () {
}
}
// 重設表單與錯誤狀態
function resetForm () {
form.value = {
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
}
initialForm.value = { ...form.value }
clearAllErrors()
}
// 新增:開啟彈窗,使用預設值
function openAddDialog () {
loadSequence.value += 1
@@ -655,7 +570,7 @@ function openEditDialog (student: StudentRecord) {
clearAllErrors()
setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = {
setForm({
studentId: student.studentId,
name: student.name,
department: student.department,
@@ -666,8 +581,8 @@ function openEditDialog (student: StudentRecord) {
email: student.email,
phone: student.phone,
status: student.status,
}
initialForm.value = { ...form.value }
})
syncInitialForm()
isLoading.value = false
}, 350)
}
@@ -686,7 +601,7 @@ function openViewDialog (student: StudentRecord) {
clearAllErrors()
setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = {
setForm({
studentId: student.studentId,
name: student.name,
department: student.department,
@@ -697,89 +612,12 @@ function openViewDialog (student: StudentRecord) {
email: student.email,
phone: student.phone,
status: student.status,
}
initialForm.value = { ...form.value }
})
syncInitialForm()
isLoading.value = false
}, 350)
}
// 依方向切換上一筆/下一筆
function openAdjacentRecord (direction: 'prev' | 'next') {
if (!isViewMode.value && !isEditMode.value) return
const index = currentRecordIndex.value
if (index < 0) return
const targetIndex = direction === 'prev' ? index - 1 : index + 1
const target = students.value[targetIndex]
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 切換到第一筆/最後一筆
function openEdgeRecord (position: 'first' | 'last') {
if (!isViewMode.value && !isEditMode.value) return
if (students.value.length === 0) return
const target = position === 'first' ? students.value[0] : students.value.at(-1)
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 檢視 → 編輯(直接切換)
function switchToEditMode () {
if (!isViewMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
openEditDialog(current)
}
// 編輯 → 檢視(若 dirty 需確認)
function switchToViewMode () {
if (!isEditMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
if (isDirty.value) {
pendingSwitchTarget.value = current
confirmSwitchVisible.value = true
return
}
openViewDialog(current)
}
// 確認切換為檢視模式
function confirmSwitch () {
const target = pendingSwitchTarget.value
pendingSwitchTarget.value = null
confirmSwitchVisible.value = false
if (!target) return
openViewDialog(target)
}
// 確認切換到其他資料
function confirmNavigate () {
const target = pendingNavigateTarget.value
pendingNavigateTarget.value = null
confirmNavigateVisible.value = false
if (!target) return
openEditDialog(target)
}
// 先檢核再提示儲存確認
async function requestSaveConfirmation () {
if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return
@@ -832,7 +670,7 @@ async function saveStudent () {
highlightedId.value = createdId
}
initialForm.value = { ...form.value }
syncInitialForm()
dialogVisible.value = false
snackbarVisible.value = true
isSaving.value = false
@@ -841,163 +679,11 @@ async function saveStudent () {
}, 1600)
}
// 刪除:先提示確認
function requestDeleteConfirmation (student: StudentRecord) {
pendingDelete.value = student
confirmDeleteVisible.value = true
}
// 編輯模式刪除目前資料
function requestDeleteCurrent () {
const current = currentEditingRecord.value
if (!current) return
requestDeleteConfirmation(current)
}
// 確認刪除後,若正在編輯該筆則關閉彈窗
function confirmDelete () {
if (!pendingDelete.value) return
const deletedId = pendingDelete.value.id
studentStore.removeStudent(deletedId)
semesterStore.removeByStudentId(deletedId)
pendingDelete.value = null
confirmDeleteVisible.value = false
if (editingId.value === deletedId) {
closeDialog()
}
}
// 狀態顏色映射
function statusColor (status: string) {
if (status === '在學') return 'success'
if (status === '休學') return 'warning'
if (status === '畢業') return 'secondary'
return 'default'
}
// 年級顯示字串
function gradeLabel (grade: number) {
return gradeOptions.find((option) => option.value === grade)?.title ?? `年級 ${grade}`
}
// 列高亮(儲存後提示位置)
function rowProps (data: { item: StudentRecord }) {
return {
class: data.item.id === highlightedId.value ? 'is-highlighted' : '',
}
}
function clearAllErrors () {
fieldErrors.value = {
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
}
}
function clearFieldError (field: string) {
if (!fieldErrors.value[field]?.length) return
fieldErrors.value[field] = []
}
function validateForm () {
const errors: Array<{ field: string; message: string }> = []
const studentId = form.value.studentId.trim()
const name = form.value.name.trim()
const email = form.value.email.trim()
const credits = form.value.credits
if (!studentId) errors.push({ field: 'studentId', message: '請輸入學號' })
if (!name) errors.push({ field: 'name', message: '請輸入姓名' })
if (!form.value.department) errors.push({ field: 'department', message: '請選擇系所' })
if (!form.value.grade) errors.push({ field: 'grade', message: '請選擇年級' })
if (!form.value.enrollYear) errors.push({ field: 'enrollYear', message: '請選擇入學年度' })
if (credits === null || Number.isNaN(credits)) {
errors.push({ field: 'credits', message: '請輸入已修學分' })
} else if (credits < 0) {
errors.push({ field: 'credits', message: '已修學分不可小於 0' })
}
if (!form.value.status) errors.push({ field: 'status', message: '請選擇狀態' })
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push({ field: 'email', message: 'Email 格式不正確' })
}
const duplicate = students.value.find(
(item) => item.studentId === studentId && item.id !== editingId.value,
)
if (studentId && duplicate) {
errors.push({ field: 'studentId', message: '學號已存在,請確認是否重複' })
}
return errors
}
const errorSummary = computed(() => {
const entries = Object.entries(fieldErrors.value).flatMap(([field, messages]) =>
messages.map((message) => ({ field, message })),
)
return entries.slice(0, 3)
})
function scrollToField (field: string) {
const target = document.getElementById(`field-${field}`)
if (!target) return
target.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
function requestCloseDialog () {
if (isDirty.value && !isSaving.value) {
confirmCloseVisible.value = true
return
}
closeDialog()
}
function confirmClose () {
confirmCloseVisible.value = false
closeDialog()
}
function closeDialog () {
dialogVisible.value = false
isLoading.value = false
isSaving.value = false
confirmSaveVisible.value = false
confirmSwitchVisible.value = false
confirmNavigateVisible.value = false
dialogMode.value = 'create'
editingId.value = null
selectedSemesterId.value = null
activeMobilePanel.value = 'master'
studentSemesters.value = []
clearAllErrors()
resetForm()
}
function handleDialogVisibility (nextValue: boolean) {
if (nextValue) {
dialogVisible.value = true
return
}
requestCloseDialog()
}
const isPlaceholderValue = (value: string | null) => value === '—'
function formatSummaryValue (key: string, value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') return '—'
if (key === 'grade') return gradeLabel(Number(value))
return String(value)
}
</script>
<style scoped>
+95 -372
View File
@@ -192,44 +192,26 @@ v-if="!isViewMode" color="primary" :disabled="!isDirty || isLoading" :loading="i
<common-confirm-dialog
v-model="confirmCloseVisible" confirm-color="error" confirm-text="關閉不儲存" message="目前有尚未儲存的內容,確定要關閉嗎?"
title="未儲存變更" @confirm="confirmClose" />
<common-confirm-dialog
v-model="confirmSaveVisible" :confirm-loading="isSaving" confirm-text="確認儲存" max-width="520"
title="確認儲存變更" @confirm="confirmSave">
<div v-if="saveSummary.length > 0" class="d-flex flex-column ga-2">
<div v-for="item in saveSummary" :key="item.label" class="d-flex flex-column">
<div class="text-caption text-medium-emphasis">{{ item.label }}</div>
<div v-if="item.before !== null" class="text-body-2">
<span class="text-medium-emphasis"></span>
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.before) }">
{{ item.before }}
</span>
</div>
<div class="text-body-2">
<span class="text-medium-emphasis"></span>
<span :class="{ 'text-medium-emphasis': isPlaceholderValue(item.after) }">
{{ item.after }}
</span>
</div>
</div>
</div>
<div v-else class="text-body-2">目前沒有可儲存的變更</div>
</common-confirm-dialog>
<common-confirm-dialog
v-model="confirmDeleteVisible" confirm-color="error" confirm-text="確定刪除"
:message="`確定要刪除 ${pendingDeleteLabel} 嗎?此操作無法復原。`" title="確認刪除" @confirm="confirmDelete" />
<common-confirm-dialog
v-model="confirmSwitchVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換為檢視模式將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmSwitch" />
<common-confirm-dialog
v-model="confirmNavigateVisible" confirm-text="確定切換" max-width="480"
message="目前有尚未儲存的內容,切換到其他資料將會捨棄變更,確定要切換嗎?" title="未儲存變更" @confirm="confirmNavigate" />
<maintenance-crud-dialogs
:close-visible="confirmCloseVisible"
:delete-visible="confirmDeleteVisible"
:is-saving="isSaving"
:navigate-visible="confirmNavigateVisible"
:pending-delete-label="pendingDeleteLabel"
:save-summary="saveSummary"
:save-visible="confirmSaveVisible"
:switch-visible="confirmSwitchVisible"
@confirm-close="confirmClose"
@confirm-delete="confirmDelete"
@confirm-navigate="confirmNavigate"
@confirm-save="confirmSave"
@confirm-switch="confirmSwitch"
@update:close-visible="confirmCloseVisible = $event"
@update:delete-visible="confirmDeleteVisible = $event"
@update:navigate-visible="confirmNavigateVisible = $event"
@update:save-visible="confirmSaveVisible = $event"
@update:switch-visible="confirmSwitchVisible = $event"
/>
<!-- 成功提示 -->
<v-snackbar v-model="snackbarVisible" color="success" location="bottom right" :timeout="2200">
@@ -241,7 +223,9 @@ v-model="confirmNavigateVisible" confirm-text="確定切換" max-width="480"
import { mdiBroom, mdiDelete, mdiEye, mdiMagnify, mdiPencil } from '@mdi/js'
import { computed, nextTick, ref } from 'vue'
import { useDisplay } from 'vuetify'
import CommonConfirmDialog from '@/components/maintenance/CommonConfirmDialog.vue'
import MaintenanceCrudDialogs from '@/components/maintenance/MaintenanceCrudDialogs.vue'
import { useMaintenanceCrudFlow } from '@/composables/maintenance/useMaintenanceCrudFlow'
import { useStudentMaintenanceForm } from '@/composables/maintenance/useStudentMaintenanceForm'
import MntDialogCard from '@/components/maintenance/MntDialogCard.vue'
import MntPageCards from '@/components/maintenance/MntPageCards.vue'
import MntRecordNavToolbar from '@/components/maintenance/MntRecordNavToolbar.vue'
@@ -298,47 +282,34 @@ const editingId = ref<number | null>(null)
const dialogMode = ref<'create' | 'edit' | 'view'>('create')
const isLoading = ref(false)
const isSaving = ref(false)
// 各種確認彈窗
const confirmCloseVisible = ref(false)
const confirmSaveVisible = ref(false)
const confirmDeleteVisible = ref(false)
const confirmSwitchVisible = ref(false)
const confirmNavigateVisible = ref(false)
// UI 回饋
const snackbarVisible = ref(false)
const highlightedId = ref<number | null>(null)
// 防止快速切換導致的異步覆蓋
const loadSequence = ref(0)
// 暫存待處理的目標
const pendingDelete = ref<StudentRecord | null>(null)
const pendingSwitchTarget = ref<StudentRecord | null>(null)
const pendingNavigateTarget = ref<StudentRecord | null>(null)
// 表單資料與初始快照(用於 dirty 判斷)
const form = ref({
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
})
const initialForm = ref({ ...form.value })
// 欄位錯誤訊息(僅保存一則)
const fieldErrors = ref<Record<string, string[]>>({
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
const {
errorSummary,
fieldErrors,
form,
isDirty,
saveSummary,
clearAllErrors,
clearFieldError,
gradeLabel,
resetForm,
rowProps,
setForm,
statusColor,
syncInitialForm,
validateForm,
} = useStudentMaintenanceForm({
departments,
gradeOptions,
enrollYears,
statuses,
students,
editingId,
highlightedId,
})
// 表單欄位簡單排版(無分組)
@@ -353,59 +324,52 @@ const dialogSubtitle = computed(() => {
if (!editingId.value) return ''
return `${form.value.studentId || '未填學號'}${form.value.name || '未填姓名'}`
})
const isEditMode = computed(() => dialogMode.value === 'edit')
const isViewMode = computed(() => dialogMode.value === 'view')
// 是否有修改(用於啟用儲存與提示)
const isDirty = computed(
() => JSON.stringify(form.value) !== JSON.stringify(initialForm.value),
)
// 載入/儲存時鎖定、檢視模式 readonly
const isFormLocked = computed(() => isLoading.value || isSaving.value)
const {
closeDialog,
confirmClose,
confirmCloseVisible,
confirmDelete,
confirmDeleteVisible,
confirmNavigate,
confirmNavigateVisible,
confirmSaveVisible,
confirmSwitch,
confirmSwitchVisible,
currentEditingRecord,
handleDialogVisibility,
hasNextRecord,
hasPrevRecord,
isEditMode,
isViewMode,
openAdjacentRecord,
openEdgeRecord,
pendingDeleteLabel,
requestCloseDialog,
requestDeleteConfirmation,
requestDeleteCurrent,
switchToEditMode,
switchToViewMode,
} = useMaintenanceCrudFlow<StudentRecord>({
records: students,
editingId,
dialogMode,
dialogVisible,
isLoading,
isSaving,
isDirty,
clearAllErrors,
resetForm,
openEditDialog,
openViewDialog,
removeRecord: (id) => {
studentStore.removeStudent(id)
},
describeRecord: (student) => `${student.studentId} ${student.name}`,
})
const isFormReadonly = computed(() => isViewMode.value)
// 目前筆數索引(用於導覽)
const currentRecordIndex = computed(() =>
students.value.findIndex((item) => item.id === editingId.value),
)
const currentEditingRecord = computed(
() => students.value.find((item) => item.id === editingId.value) || null,
)
const hasPrevRecord = computed(() => currentRecordIndex.value > 0)
const hasNextRecord = computed(
() => currentRecordIndex.value >= 0 && currentRecordIndex.value < students.value.length - 1,
)
const pendingDeleteLabel = computed(() => {
if (!pendingDelete.value) return '這筆資料'
return `${pendingDelete.value.studentId} ${pendingDelete.value.name}`
})
const saveSummary = computed(() => {
const labels: Record<string, string> = {
studentId: '學號',
name: '姓名',
department: '系所',
grade: '年級',
enrollYear: '入學年度',
credits: '已修學分',
advisor: '指導老師',
email: 'Email',
phone: '電話',
status: '狀態',
}
const before = initialForm.value
const after = form.value
const entries = Object.keys(labels).map((key) => {
const beforeValue = before[key as keyof typeof before]
const afterValue = after[key as keyof typeof after]
return {
key,
label: labels[key],
before: editingId.value ? formatSummaryValue(key, beforeValue) : null,
after: formatSummaryValue(key, afterValue),
}
})
if (!editingId.value) return entries
return entries.filter((entry) => entry.before !== entry.after)
})
// 重設查詢條件
function resetSearch () {
@@ -418,24 +382,6 @@ function resetSearch () {
}
}
// 重設表單與錯誤狀態
function resetForm () {
form.value = {
studentId: '',
name: '',
department: departments[0] ?? '',
grade: gradeOptions[0]?.value ?? 1,
enrollYear: enrollYears[0] ?? 2024,
credits: 0,
advisor: '',
email: '',
phone: '',
status: statuses[0] ?? '',
}
initialForm.value = { ...form.value }
clearAllErrors()
}
// 新增:開啟彈窗,使用預設值
function openAddDialog () {
loadSequence.value += 1
@@ -457,7 +403,7 @@ function openEditDialog (student: StudentRecord) {
clearAllErrors()
setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = {
setForm({
studentId: student.studentId,
name: student.name,
department: student.department,
@@ -468,8 +414,8 @@ function openEditDialog (student: StudentRecord) {
email: student.email,
phone: student.phone,
status: student.status,
}
initialForm.value = { ...form.value }
})
syncInitialForm()
isLoading.value = false
}, 350)
}
@@ -485,7 +431,7 @@ function openViewDialog (student: StudentRecord) {
clearAllErrors()
setTimeout(() => {
if (sequence !== loadSequence.value || !dialogVisible.value) return
form.value = {
setForm({
studentId: student.studentId,
name: student.name,
department: student.department,
@@ -496,89 +442,12 @@ function openViewDialog (student: StudentRecord) {
email: student.email,
phone: student.phone,
status: student.status,
}
initialForm.value = { ...form.value }
})
syncInitialForm()
isLoading.value = false
}, 350)
}
// 依方向切換上一筆/下一筆
function openAdjacentRecord (direction: 'prev' | 'next') {
if (!isViewMode.value && !isEditMode.value) return
const index = currentRecordIndex.value
if (index < 0) return
const targetIndex = direction === 'prev' ? index - 1 : index + 1
const target = students.value[targetIndex]
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 切換到第一筆/最後一筆
function openEdgeRecord (position: 'first' | 'last') {
if (!isViewMode.value && !isEditMode.value) return
if (students.value.length === 0) return
const target = position === 'first' ? students.value[0] : students.value.at(-1)
if (!target) return
if (isEditMode.value) {
if (isDirty.value) {
pendingNavigateTarget.value = target
confirmNavigateVisible.value = true
return
}
openEditDialog(target)
return
}
openViewDialog(target)
}
// 檢視 → 編輯(直接切換)
function switchToEditMode () {
if (!isViewMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
openEditDialog(current)
}
// 編輯 → 檢視(若 dirty 需確認)
function switchToViewMode () {
if (!isEditMode.value) return
const current = students.value.find((item) => item.id === editingId.value)
if (!current) return
if (isDirty.value) {
pendingSwitchTarget.value = current
confirmSwitchVisible.value = true
return
}
openViewDialog(current)
}
// 確認切換為檢視模式
function confirmSwitch () {
const target = pendingSwitchTarget.value
pendingSwitchTarget.value = null
confirmSwitchVisible.value = false
if (!target) return
openViewDialog(target)
}
// 確認切換到其他資料
function confirmNavigate () {
const target = pendingNavigateTarget.value
pendingNavigateTarget.value = null
confirmNavigateVisible.value = false
if (!target) return
openEditDialog(target)
}
// 先檢核再提示儲存確認
async function requestSaveConfirmation () {
if (isSaving.value || isLoading.value || !isDirty.value || isViewMode.value) return
@@ -630,7 +499,7 @@ async function saveStudent () {
highlightedId.value = createdId
}
initialForm.value = { ...form.value }
syncInitialForm()
dialogVisible.value = false
snackbarVisible.value = true
isSaving.value = false
@@ -639,158 +508,12 @@ async function saveStudent () {
}, 1600)
}
// 刪除:先提示確認
function requestDeleteConfirmation (student: StudentRecord) {
pendingDelete.value = student
confirmDeleteVisible.value = true
}
// 編輯模式刪除目前資料
function requestDeleteCurrent () {
const current = currentEditingRecord.value
if (!current) return
requestDeleteConfirmation(current)
}
// 確認刪除後,若正在編輯該筆則關閉彈窗
function confirmDelete () {
if (!pendingDelete.value) return
const deletedId = pendingDelete.value.id
studentStore.removeStudent(deletedId)
pendingDelete.value = null
confirmDeleteVisible.value = false
if (editingId.value === deletedId) {
closeDialog()
}
}
// 狀態顏色映射
function statusColor (status: string) {
if (status === '在學') return 'success'
if (status === '休學') return 'warning'
if (status === '畢業') return 'secondary'
return 'default'
}
// 年級顯示字串
function gradeLabel (grade: number) {
return gradeOptions.find((option) => option.value === grade)?.title ?? `年級 ${grade}`
}
// 列高亮(儲存後提示位置)
function rowProps (data: { item: StudentRecord }) {
return {
class: data.item.id === highlightedId.value ? 'is-highlighted' : '',
}
}
function clearAllErrors () {
fieldErrors.value = {
studentId: [],
name: [],
department: [],
grade: [],
enrollYear: [],
credits: [],
advisor: [],
email: [],
phone: [],
status: [],
}
}
function clearFieldError (field: string) {
if (!fieldErrors.value[field]?.length) return
fieldErrors.value[field] = []
}
function validateForm () {
const errors: Array<{ field: string; message: string }> = []
const studentId = form.value.studentId.trim()
const name = form.value.name.trim()
const email = form.value.email.trim()
const credits = form.value.credits
if (!studentId) errors.push({ field: 'studentId', message: '請輸入學號' })
if (!name) errors.push({ field: 'name', message: '請輸入姓名' })
if (!form.value.department) errors.push({ field: 'department', message: '請選擇系所' })
if (!form.value.grade) errors.push({ field: 'grade', message: '請選擇年級' })
if (!form.value.enrollYear) errors.push({ field: 'enrollYear', message: '請選擇入學年度' })
if (credits === null || Number.isNaN(credits)) {
errors.push({ field: 'credits', message: '請輸入已修學分' })
} else if (credits < 0) {
errors.push({ field: 'credits', message: '已修學分不可小於 0' })
}
if (!form.value.status) errors.push({ field: 'status', message: '請選擇狀態' })
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push({ field: 'email', message: 'Email 格式不正確' })
}
const duplicate = students.value.find(
(item) => item.studentId === studentId && item.id !== editingId.value,
)
if (studentId && duplicate) {
errors.push({ field: 'studentId', message: '學號已存在,請確認是否重複' })
}
return errors
}
const errorSummary = computed(() => {
const entries = Object.entries(fieldErrors.value).flatMap(([field, messages]) =>
messages.map((message) => ({ field, message })),
)
return entries.slice(0, 3)
})
function scrollToField (field: string) {
const target = document.getElementById(`field-${field}`)
if (!target) return
target.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
function requestCloseDialog () {
if (isDirty.value && !isSaving.value) {
confirmCloseVisible.value = true
return
}
closeDialog()
}
function confirmClose () {
confirmCloseVisible.value = false
closeDialog()
}
function closeDialog () {
dialogVisible.value = false
isLoading.value = false
isSaving.value = false
confirmSaveVisible.value = false
confirmSwitchVisible.value = false
confirmNavigateVisible.value = false
dialogMode.value = 'create'
editingId.value = null
clearAllErrors()
resetForm()
}
function handleDialogVisibility (nextValue: boolean) {
if (nextValue) {
dialogVisible.value = true
return
}
requestCloseDialog()
}
const isPlaceholderValue = (value: string | null) => value === '—'
function formatSummaryValue (key: string, value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') return '—'
if (key === 'grade') return gradeLabel(Number(value))
return String(value)
}
</script>
<style scoped>