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
+90 -24
View File
@@ -1,14 +1,19 @@
<script setup lang="ts">
import type { FormErrors } from '~/types/error'
import Block from '~/components/pub/custom-ui/form/block.vue'
import { toTypedSchema } from '@vee-validate/zod'
import FieldGroup from '~/components/pub/custom-ui/form/field-group.vue'
import Field from '~/components/pub/custom-ui/form/field.vue'
import Label from '~/components/pub/custom-ui/form/label.vue'
import Select from '~/components/pub/custom-ui/form/select.vue'
interface InstallationFormData {
name: string
code: string
encounterClassCode: string
}
const props = defineProps<{
modelValue: any
encounterClassCode: {
installation: {
msg: {
placeholder: string
}
@@ -18,41 +23,102 @@ const props = defineProps<{
code: string
}[]
}
schema: any
initialValues?: Partial<InstallationFormData>
errors?: FormErrors
}>()
const emit = defineEmits(['update:modelValue', 'event'])
const data = computed({
get: () => props.modelValue,
set: (val) => emit('update:modelValue', val),
})
const emit = defineEmits<{
'submit': [values: InstallationFormData, resetForm: () => void]
'cancel': [resetForm: () => void]
}>()
const formSchema = toTypedSchema(props.schema)
// Form submission handler
function onSubmitForm(values: any, { resetForm }: { resetForm: () => void }) {
const formData: InstallationFormData = {
name: values.name || '',
code: values.code || '',
encounterClassCode: values.encounterClassCode || '',
}
emit('submit', formData, resetForm)
}
// Form cancel handler
function onCancelForm({ resetForm }: { resetForm: () => void }) {
emit('cancel', resetForm)
}
</script>
<template>
<form id="entry-form">
<div class="mb-5 border-b border-b-slate-300 pb-3 text-lg xl:text-xl">
<div class="flex flex-col justify-between">
<Block>
<FieldGroup :column="2">
<Label>Nama</Label>
<Form
v-slot="{ handleSubmit, resetForm }" as="" keep-values :validation-schema="formSchema"
:initial-values="initialValues"
>
<form id="entry-form" @submit="handleSubmit($event, (values) => onSubmitForm(values, { resetForm }))">
<div class="mb-5 border-b border-b-slate-300 pb-3 text-lg xl:text-xl">
<div class="flex flex-col justify-between">
<FieldGroup>
<Label label-for="name">Nama</Label>
<Field id="name" :errors="errors">
<Input v-model="data.name" />
<FormField v-slot="{ componentField }" name="name">
<FormItem>
<FormControl>
<Input
id="name" type="text" placeholder="Masukkan nama instalasi" autocomplete="off"
v-bind="componentField"
/>
</FormControl>
<FormMessage />
</FormItem>
</FormField>
</Field>
</FieldGroup>
<FieldGroup :column="2">
<Label>Kode</Label>
<FieldGroup>
<Label label-for="code">Kode</Label>
<Field id="code" :errors="errors">
<Input v-model="data.code" />
<FormField v-slot="{ componentField }" name="code">
<FormItem>
<FormControl>
<Input id="code" type="text" placeholder="Masukkan kode instalasi" autocomplete="off" v-bind="componentField" />
</FormControl>
<FormMessage />
</FormItem>
</FormField>
</Field>
</FieldGroup>
<FieldGroup :column="2">
<Label height="compact">Encounter Code</Label>
<FieldGroup>
<Label label-for="parentId">Encounter Class</Label>
<Field id="encounterClassCode" :errors="errors">
<Select v-model="data.encounterClassCode" :items="props.encounterClassCode.items" />
<FormField v-slot="{ componentField }" name="encounterClassCode">
<FormItem>
<FormControl>
<Select
v-bind="componentField"
:items="installation.items"
:placeholder="installation.msg.placeholder"
/>
</FormControl>
<FormMessage />
</FormItem>
</FormField>
</Field>
</FieldGroup>
</Block>
</div>
</div>
</div>
</form>
<div class="flex justify-end gap-2 mt-4">
<Button type="button" variant="outline" @click="onCancelForm({ resetForm })">
Batal
</Button>
<Button type="submit">
Simpan
</Button>
</div>
</form>
</Form>
</template>
@@ -0,0 +1,68 @@
import type {
Col,
KeyLabel,
RecComponent,
RecStrFuncComponent,
RecStrFuncUnknown,
Th,
} from '~/components/pub/custom-ui/data/types'
import { defineAsyncComponent } from 'vue'
type SmallDetailDto = any
const action = defineAsyncComponent(() => import('~/components/pub/custom-ui/data/dropdown-action-ud.vue'))
export const cols: Col[] = [{ width: 100 }, {}, {}, {}, { width: 50 }]
export const header: Th[][] = [
[{ label: 'Id' }, { label: 'Nama' }, { label: 'Kode' }, { label: 'Encounter Class' }, { label: '' }],
]
export const keys = ['id', 'name', 'cellphone', 'religion_code', 'action']
export const delKeyNames: KeyLabel[] = [
{ key: 'code', label: 'Kode' },
{ key: 'name', label: 'Nama' },
]
export const funcParsed: RecStrFuncUnknown = {
name: (rec: unknown): unknown => {
const recX = rec as SmallDetailDto
return `${recX.firstName} ${recX.lastName || ''}`.trim()
},
identity_number: (rec: unknown): unknown => {
const recX = rec as SmallDetailDto
if (recX.identity_number?.substring(0, 5) === 'BLANK') {
return '(TANPA NIK)'
}
return recX.identity_number
},
inPatient_itemPrice: (rec: unknown): unknown => {
const recX = rec as SmallDetailDto
return Number(recX.inPatient_itemPrice.price).toLocaleString('id-ID')
},
outPatient_itemPrice: (rec: unknown): unknown => {
const recX = rec as SmallDetailDto
return Number(recX.outPatient_itemPrice.price).toLocaleString('id-ID')
},
}
export const funcComponent: RecStrFuncComponent = {
action(rec, idx) {
const res: RecComponent = {
idx,
rec: rec as object,
component: action,
props: {
size: 'sm',
},
}
return res
},
}
export const funcHtml: RecStrFuncUnknown = {
patient_address(_rec) {
return '-'
},
}
+50 -41
View File
@@ -1,54 +1,63 @@
<script setup lang="ts">
// #region Props & Emits
const props = defineProps<{
title: string
}>()
import type { PaginationMeta } from '~/components/pub/custom-ui/pagination/pagination.type'
import { cols, funcComponent, funcHtml, funcParsed, header, keys } from './list-cfg'
interface Props {
data: any[]
paginationMeta?: PaginationMeta
}
const props = defineProps<Props>()
const emit = defineEmits<{
(e: 'update', value: string): void
pageChange: [page: number]
}>()
// #endregion
// #region State & Computed
// =============================
const count = ref(0)
const double = computed(() => count.value * 2)
// #endregion
// #region Lifecycle Hooks
onMounted(() => {
// init code
fetchData()
})
// #endregion
// #region Functions
async function fetchData() {
console.log('fetched')
function handlePageChange(page: number) {
emit('pageChange', page)
}
// #endregion region
// #region Utilities & event handlers
function increment() {
count.value++
}
// #endregion
// #region Watchers
watch(count, (newVal, oldVal) => {
console.log('count changed:', oldVal, '->', newVal)
// Computed properties for formatted display
const formattedRecordCount = computed(() => {
if (!props.paginationMeta) return '0'
const count = props.paginationMeta.recordCount
if (count == null || count === undefined) return '0'
return Number(count).toLocaleString('id-ID')
})
const startRecord = computed(() => {
if (!props.paginationMeta) return 1
return ((props.paginationMeta.page - 1) * props.paginationMeta.pageSize) + 1
})
const endRecord = computed(() => {
if (!props.paginationMeta) return 0
return Math.min(props.paginationMeta.page * props.paginationMeta.pageSize, props.paginationMeta.recordCount)
})
// #endregion
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double: {{ double }}</p>
<button @click="increment">+1</button>
<div class="space-y-4">
<PubBaseDataTable
:rows="data" :cols="cols" :header="header" :keys="keys" :func-parsed="funcParsed"
:func-html="funcHtml" :func-component="funcComponent"
/>
<!-- Data info and pagination -->
<div v-if="paginationMeta" class="flex align-center justify-between">
<!-- Data info - always show -->
<div class="flex items-center justify-between px-2 mb-4">
<div class="flex-1 text-sm text-muted-foreground">
Menampilkan {{ startRecord }}
hingga {{ endRecord }}
dari {{ formattedRecordCount }} data
</div>
</div>
<!-- Pagination controls - only show when multiple pages -->
<div v-if="paginationMeta.totalPage > 1">
<PubCustomUiPagination :pagination-meta="paginationMeta" :show-info="false" @page-change="handlePageChange" />
</div>
</div>
</div>
</template>
<style scoped>
/* component style */
</style>
+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>
@@ -6,7 +6,7 @@ import Error from '~/components/pub/base/error/error.vue'
definePageMeta({
// middleware: ['rbac'],
roles: ['doctor', 'nurse', 'admisi', 'pharmacy', 'billing', 'management'],
title: 'List Division',
title: 'List Installation',
contentFrame: 'cf-full-width',
})
@@ -34,7 +34,7 @@ const canRead = true
<template>
<div>
<div v-if="canRead">
route installation list
<FlowInstallationList />
</div>
<Error v-else :status-code="403" />
</div>