feat(installation): implement installation list with pagination and search

refactor(installation): move form schema and configuration to separate files
fix(installation): update page title and content display
This commit is contained in:
Khafid Prayoga
2025-09-03 17:00:49 +07:00
parent 646c7b6d73
commit 4c0312e487
8 changed files with 537 additions and 163 deletions
+37
View File
@@ -0,0 +1,37 @@
import * as z from 'zod'
export const installationConf = {
msg: {
placeholder: '---pilih encounter class (fhir7)',
},
items: [
{ value: '1', label: 'Ambulatory', code: 'AMB' },
{ value: '2', label: 'Inpatient', code: 'IMP' },
{ value: '3', label: 'Emergency', code: 'EMER' },
{ value: '4', label: 'Observation', code: 'OBSENC' },
{ value: '5', label: 'Pre-admission', code: 'PRENC' },
{ value: '6', label: 'Short Stay', code: 'SS' },
{ value: '7', label: 'Virtual', code: 'VR' },
{ value: '8', label: 'Home Health', code: 'HH' },
],
}
export const schemaConf = z.object({
name: z
.string({
required_error: 'Nama instalasi harus diisi',
})
.min(3, 'Nama instalasi minimal 3 karakter'),
code: z
.string({
required_error: 'Kode instalasi harus diisi',
})
.min(3, 'Kode instalasi minimal 3 karakter'),
encounterClassCode: z
.string({
required_error: 'Kelompok encounter class harus dipilih',
})
.min(1, 'Kelompok encounter class harus dipilih'),
})
@@ -1,71 +0,0 @@
<script setup lang="ts">
import * as z from 'zod'
import Action from '~/components/pub/custom-ui/nav-footer/ba-su.vue'
const { errors, setFromZodError, clearErrors } = useFormErrors()
const data = ref({
code: '',
name: '',
encounterClassCode: '',
})
const installation = {
msg: {
placeholder: '---pilih encounter class (fhir7)',
},
items: [
{ value: '1', label: 'Ambulatory', code: 'AMB' },
{ value: '2', label: 'Inpatient', code: 'IMP' },
{ value: '3', label: 'Emergency', code: 'EMER' },
{ value: '4', label: 'Observation', code: 'OBSENC' },
{ value: '5', label: 'Pre-admission', code: 'PRENC' },
{ value: '6', label: 'Short Stay', code: 'SS' },
{ value: '7', label: 'Virtual', code: 'VR' },
{ value: '8', label: 'Home Health', code: 'HH' },
],
}
const schema = z.object({
name: z.string().min(1, 'Nama instalasi harus diisi'),
code: z.string().min(1, 'Kode instalasi harus diisi'),
encounterClassCode: z.string().min(1, 'Kelompok encounter class harus dipilih'),
})
function onClick(type: string) {
if (type === 'cancel') {
navigateTo('/org-src/instalasion')
} else if (type === 'draft') {
// do something
} else if (type === 'submit') {
// Clear previous errors
clearErrors()
const requestData = schema.safeParse(data.value)
if (!requestData.success) {
// Set errors menggunakan composable
setFromZodError(requestData.error)
// Optional: tampilkan toast notification untuk error general
console.warn('Form validation failed:', requestData.error)
return
}
console.log('Form data valid:', requestData.data)
// do something with valid data
}
}
</script>
<template>
<div class="mb-5 border-b border-b-slate-300 pb-3 text-lg xl:text-xl">
<Icon name="i-lucide-user" class="me-2" />
<span class="font-semibold">Tambah</span> Instalasi
</div>
<div>
<AppInstallationEntryForm v-model="data" :errors="errors" :encounter-class-code="installation" />
</div>
<div class="my-2 flex justify-end py-2">
<Action @click="onClick" />
</div>
</template>
+275 -25
View File
@@ -1,51 +1,301 @@
<script setup lang="ts">
// #region Props & Emits
const props = defineProps<{
title: string
}>()
const emit = defineEmits<{
(e: 'update', value: string): void
}>()
// #endregion
import type { DataTableLoader } from '~/components/pub/base/data-table/type'
import type { HeaderPrep } from '~/components/pub/custom-ui/data/types'
import type { PaginationMeta } from '~/components/pub/custom-ui/pagination/pagination.type'
import { refDebounced, useUrlSearchParams } from '@vueuse/core'
import AppInstallationEntryForm from '~/components/app/installation/entry-form.vue'
import Dialog from '~/components/pub/base/modal/dialog.vue'
import RecordConfirmation from '~/components/pub/custom-ui/confirmation/record-confirmation.vue'
import { ActionEvents } from '~/components/pub/custom-ui/data/types'
import Header from '~/components/pub/custom-ui/nav-header/header.vue'
import { installationConf, schemaConf } from './entry'
import { defaultQuery, querySchema } from './schema.query'
// #region State & Computed
// =============================
const count = ref(0)
const double = computed(() => count.value * 2)
const data = ref([])
const isLoading = reactive<DataTableLoader>({
isTableLoading: false,
})
// Dialog state
const isFormEntryDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)
// URL state management
const queryParams = useUrlSearchParams('history', {
initialValue: defaultQuery,
removeFalsyValues: true,
})
const params = computed(() => {
const result = querySchema.safeParse(queryParams)
return result.data || defaultQuery
})
// Pagination state - computed from URL params
const paginationMeta = reactive<PaginationMeta>({
recordCount: 0,
page: params.value.page,
pageSize: params.value.pageSize,
totalPage: 0,
hasNext: false,
hasPrev: false,
})
// Table action rowId provider
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
// Search model with debounce
const searchInput = ref(params.value.q || '')
const debouncedSearch = refDebounced(searchInput, 500) // 500ms debounce
const headerPrep: HeaderPrep = {
title: 'Instalasi',
icon: 'i-lucide-box',
refSearchNav: {
placeholder: 'Cari (min. 3 karakter)...',
minLength: 3,
debounceMs: 500,
showValidationFeedback: true,
onInput: (_val: string) => {
// Handle search input - this will be triggered by the header component
},
onClick: () => {
// Handle search button click if needed
},
onClear: () => {
// Handle search clear
},
},
addNav: {
label: 'Tambah Instalasi',
icon: 'i-lucide-send',
onClick: () => {
isFormEntryDialogOpen.value = true
},
},
}
provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)
// #endregion
// #region Lifecycle Hooks
onMounted(() => {
// init code
fetchData()
getInstallationList()
})
// #endregion
// #region Functions
async function fetchData() {
console.log('fetched')
async function getInstallationList() {
isLoading.isTableLoading = true
try {
// Use current params from URL state
const currentParams = params.value
// Prepare query parameters for pagination and search
const urlParams = new URLSearchParams({
'page-number': currentParams.page.toString(),
'page-size': currentParams.pageSize.toString(),
})
if (currentParams.q) {
urlParams.append('search', currentParams.q)
}
const resp = await xfetch(`/api/v1/patient?${urlParams.toString()}`)
if (resp.success) {
const responseBody = resp.body as Record<string, any>
data.value = responseBody.data || []
const pager = responseBody.meta
// Update pagination meta from response
// Fallback if meta is not provided by API
paginationMeta.recordCount = pager.record_totalCount
paginationMeta.page = currentParams.page
paginationMeta.pageSize = currentParams.pageSize
paginationMeta.totalPage = Math.ceil(pager.record_totalCount / paginationMeta.pageSize)
paginationMeta.hasNext = paginationMeta.page < paginationMeta.totalPage
paginationMeta.hasPrev = paginationMeta.page > 1
}
} catch (error) {
console.error('Error fetching Installation list:', error)
data.value = []
paginationMeta.recordCount = 0
paginationMeta.totalPage = 0
paginationMeta.hasNext = false
paginationMeta.hasPrev = false
} finally {
isLoading.isTableLoading = false
}
}
// Handle pagination page change
function handlePageChange(page: number) {
// Update URL params - this will trigger watcher
queryParams.page = page
}
async function handleDeleteRow(record: any) {
try {
// TODO : hit backend request untuk delete
console.log('Deleting record:', record)
// Simulate API call
// const response = await xfetch(`/api/v1/Installation/${record.id}`, {
// method: 'DELETE'
// })
// Refresh data setelah berhasil delete
await getInstallationList()
// TODO: Show success message
console.log('Record deleted successfully')
} catch (error) {
console.error('Error deleting record:', error)
// TODO: Show error message
} finally {
// Reset record state
recId.value = 0
recAction.value = ''
recItem.value = null
}
}
// #endregion region
// #region Utilities & event handlers
function increment() {
count.value++
// #region Form event handlers
function onCancelForm(resetForm: () => void) {
isFormEntryDialogOpen.value = false
setTimeout(() => {
resetForm()
}, 500)
}
async function onSubmitForm(values: any, resetForm: () => void) {
let isSuccess = false
try {
// TODO: Implement form submission logic
console.log('Form submitted:', values)
// Simulate API call
// const response = await xfetch('/api/v1/Installation', {
// method: 'POST',
// body: JSON.stringify(values)
// })
// If successful, mark as success and close dialog
isFormEntryDialogOpen.value = false
isSuccess = true
// Refresh data after successful submission
await getInstallationList()
// TODO: Show success message
console.log('Installation created successfully')
} catch (error: unknown) {
console.warn('Error submitting form:', error)
isSuccess = false
// Don't close dialog or reset form on error
// TODO: Show error message to user
} finally {
if (isSuccess) {
setTimeout(() => {
resetForm()
}, 500)
}
}
}
// #endregion
// #region Watchers
watch(count, (newVal, oldVal) => {
console.log('count changed:', oldVal, '->', newVal)
// Watch for URL param changes and trigger refetch
watch(params, (newParams) => {
// Sync search input with URL params (for back/forward navigation)
if (newParams.q !== searchInput.value) {
searchInput.value = newParams.q || ''
}
getInstallationList()
}, { deep: true })
// Handle search from header component
function handleSearch(searchValue: string) {
// Update URL params - this will trigger watcher and refetch data
queryParams.q = searchValue
queryParams.page = 1 // Reset to first page when searching
}
// Watch debounced search and update URL params (keeping for backward compatibility)
watch(debouncedSearch, (newValue: any) => {
// Only search if 3+ characters or empty (to clear search)
if (newValue.length === 0 || newValue.length >= 3) {
queryParams.q = newValue
queryParams.page = 1 // Reset to first page when searching
}
})
// Watch for row actions
watch(recId, () => {
switch (recAction.value) {
case ActionEvents.showEdit:
// TODO: Handle edit action
// isFormEntryDialogOpen.value = true
break
case ActionEvents.showConfirmDelete:
// Trigger confirmation modal open
isRecordConfirmationOpen.value = true
break
}
})
// Handle confirmation result
function handleConfirmDelete(record: any, action: string) {
console.log('Confirmed action:', action, 'for record:', record)
handleDeleteRow(record)
}
function handleCancelConfirmation() {
// Reset record state when cancelled
recId.value = 0
recAction.value = ''
recItem.value = null
}
// #endregion
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double: {{ double }}</p>
<button @click="increment">+1</button>
<div class="rounded-md border p-4">
<Header v-model="searchInput" :prep="headerPrep" @search="handleSearch" />
<AppInstallationList :data="data" :pagination-meta="paginationMeta" @page-change="handlePageChange" />
<Dialog v-model:open="isFormEntryDialogOpen" title="Tambah Instalasi" size="lg" prevent-outside>
<AppInstallationEntryForm
:installation="installationConf" :schema="schemaConf"
:initial-values="{ name: '', code: '', encounterClassCode: '' }" @submit="onSubmitForm"
@cancel="onCancelForm"
/>
</Dialog>
<!-- Record Confirmation Modal -->
<RecordConfirmation
v-model:open="isRecordConfirmationOpen" action="delete" :record="recItem"
@confirm="handleConfirmDelete" @cancel="handleCancelConfirmation"
>
<template #default="{ record }">
<div class="text-sm">
<p><strong>ID:</strong> {{ record?.id }}</p>
<p v-if="record?.firstName"><strong>Nama:</strong> {{ record.firstName }}</p>
<p v-if="record?.code"><strong>Kode:</strong> {{ record.cellphone }}</p>
</div>
</template>
</RecordConfirmation>
</div>
</template>
@@ -0,0 +1,15 @@
import * as z from 'zod'
export const querySchema = z.object({
q: z.union([z.literal(''), z.string().min(3)]).optional().catch(''),
page: z.coerce.number().int().min(1).default(1).catch(1),
pageSize: z.coerce.number().int().min(5).max(20).default(10).catch(10),
})
export const defaultQuery = {
q: '',
page: 1,
pageSize: 10,
}
export type QueryParams = z.infer<typeof querySchema>