fix: adjustment division app + flow

This commit is contained in:
riefive
2025-10-06 12:42:08 +07:00
parent 8601d4a4fd
commit ba61d05257
5 changed files with 1 additions and 664 deletions
@@ -1,145 +0,0 @@
<script setup lang="ts">
import type { TreeItem } from '~/components/pub/my-ui/select-tree/type'
import type { FormErrors } from '~/types/error'
import { toTypedSchema } from '@vee-validate/zod'
import TreeSelect from '~/components/pub/my-ui/select-tree/tree-select.vue'
import Combobox from '~/components/pub/my-ui/form/combobox.vue'
import FieldGroup from '~/components/pub/my-ui/form/field-group.vue'
import Field from '~/components/pub/my-ui/form/field.vue'
import Label from '~/components/pub/my-ui/form/label.vue'
import { Form } from '~/components/pub/ui/form'
interface DivisionFormData {
name: string
code: string
parentId: string
}
const props = defineProps<{
division: {
msg: {
placeholder: string
search: string
empty: string
}
items: {
value: string
label: string
}[]
}
divisionTree?: {
msg: {
placeholder: string
search: string
empty: string
}
data: TreeItem[]
onFetchChildren: (parentId: string) => Promise<void>
}
schema: any
initialValues?: Partial<DivisionFormData>
errors?: FormErrors
}>()
const emit = defineEmits<{
'submit': [values: DivisionFormData, resetForm: () => void]
'cancel': [resetForm: () => void]
}>()
const formSchema = toTypedSchema(props.schema)
// Form submission handler
function onSubmitForm(values: any, { resetForm }: { resetForm: () => void }) {
const formData: DivisionFormData = {
name: values.name || '',
code: values.code || '',
parentId: values.parentId || '',
}
emit('submit', formData, resetForm)
}
// Form cancel handler
function onCancelForm({ resetForm }: { resetForm: () => void }) {
emit('cancel', resetForm)
}
</script>
<template>
<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">
<FormField v-slot="{ componentField }" name="name">
<FormItem>
<FormControl>
<Input
id="name" type="text" placeholder="Masukkan nama divisi" autocomplete="off"
v-bind="componentField"
/>
</FormControl>
<FormMessage />
</FormItem>
</FormField>
</Field>
</FieldGroup>
<FieldGroup>
<Label label-for="code">Kode</Label>
<Field id="code" :errors="errors">
<FormField v-slot="{ componentField }" name="code">
<FormItem>
<FormControl>
<Input id="code" type="text" placeholder="Masukkan kode divisi" autocomplete="off" v-bind="componentField" />
</FormControl>
<FormMessage />
</FormItem>
</FormField>
</Field>
</FieldGroup>
<FieldGroup>
<Label label-for="parentId">Divisi Induk</Label>
<Field id="parentId" :errors="errors">
<FormField v-slot="{ componentField }" name="parentId">
<FormItem>
<FormControl>
<!-- Gunakan TreeSelect jika divisionTree tersedia, fallback ke Combobox -->
<TreeSelect
v-if="props.divisionTree"
id="parentId"
:model-value="componentField.modelValue"
:data="props.divisionTree.data"
:on-fetch-children="props.divisionTree.onFetchChildren"
@update:model-value="componentField.onChange"
/>
<Combobox
v-else
id="parentId" v-bind="componentField" :items="props.division.items"
:placeholder="props.division.msg.placeholder" :search-placeholder="props.division.msg.search"
:empty-message="props.division.msg.empty"
/>
</FormControl>
<FormMessage />
</FormItem>
</FormField>
</Field>
</FieldGroup>
</div>
</div>
<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>
+1 -1
View File
@@ -4,7 +4,7 @@ import Block from '~/components/pub/my-ui/doc-entry/block.vue'
import Cell from '~/components/pub/my-ui/doc-entry/cell.vue'
import Field from '~/components/pub/my-ui/doc-entry/field.vue'
import Label from '~/components/pub/my-ui/doc-entry/label.vue'
import TreeSelect from '~/components/pub/base/select-tree/tree-select.vue'
import TreeSelect from '~/components/pub/my-ui/select-tree/tree-select.vue'
// Types
import type { DivisionFormData } from '~/schemas/division.schema.ts'
-165
View File
@@ -1,165 +0,0 @@
<script setup lang="ts">
import TreeSelect from '~/components/pub/my-ui/select-tree/tree-select.vue'
/**
* DEMO COMPONENT - Tree Select dengan Lazy Loading
*
* Komponen ini adalah contoh penggunaan TreeSelect dengan data teknologi.
* Untuk penggunaan dalam aplikasi nyata, lihat komponen content/division/entry.vue
* yang menggunakan tree select untuk data divisi rumah sakit.
*/
// Tipe data untuk konsistensi
interface TreeItem {
value: string
label: string
hasChildren: boolean
children?: TreeItem[]
}
// State untuk data pohon demo - data teknologi sebagai contoh
const treeData = ref<TreeItem[]>([
{ value: 'frontend', label: 'Frontend Development', hasChildren: true },
{ value: 'backend', label: 'Backend Development', hasChildren: true },
{ value: 'mobile', label: 'Mobile Development', hasChildren: true },
{ value: 'devops', label: 'DevOps & Infrastructure', hasChildren: false },
])
// State untuk menampung nilai yang dipilih
const selectedValue = ref<string>()
// --- DEMO LOGIC: SIMULASI API DAN MANIPULASI DATA ---
// Helper: Fungsi rekursif untuk mencari dan menyisipkan data anak ke dalam state
function findAndInsertChildren(nodes: TreeItem[], parentId: string, newChildren: TreeItem[]): boolean {
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i]
if (node && node.value === parentId) {
// Gunakan Vue.set equivalent untuk memastikan reactivity
node.children = [...newChildren]
console.log(`[findAndInsertChildren] Updated children for ${parentId}:`, node.children)
return true
}
if (node && node.children && findAndInsertChildren(node.children, parentId, newChildren)) {
return true
}
}
return false
}
// Fungsi demo untuk simulasi fetch data dari API
async function handleFetchChildren(parentId: string): Promise<void> {
console.log(`[DEMO] Mengambil data anak untuk parent: ${parentId}`)
// Simulasi delay API call
await new Promise(resolve => setTimeout(resolve, 600))
let childrenData: TreeItem[] = []
// Sample data berdasarkan parent ID
switch (parentId) {
case 'frontend':
childrenData = [
{ value: 'vue', label: 'Vue.js', hasChildren: true },
{ value: 'react', label: 'React.js', hasChildren: true },
{ value: 'angular', label: 'Angular', hasChildren: false },
{ value: 'svelte', label: 'Svelte', hasChildren: false },
]
break
case 'backend':
childrenData = [
{ value: 'nodejs', label: 'Node.js', hasChildren: true },
{ value: 'python', label: 'Python', hasChildren: true },
{ value: 'golang', label: 'Go', hasChildren: false },
{ value: 'rust', label: 'Rust', hasChildren: false },
]
break
case 'mobile':
childrenData = [
{ value: 'flutter', label: 'Flutter', hasChildren: false },
{ value: 'react-native', label: 'React Native', hasChildren: false },
{ value: 'ionic', label: 'Ionic', hasChildren: false },
]
break
case 'vue':
childrenData = [
{ value: 'nuxt', label: 'Nuxt.js', hasChildren: false },
{ value: 'quasar', label: 'Quasar', hasChildren: false },
]
break
case 'react':
childrenData = [
{ value: 'nextjs', label: 'Next.js', hasChildren: false },
{ value: 'gatsby', label: 'Gatsby', hasChildren: false },
]
break
case 'nodejs':
childrenData = [
{ value: 'express', label: 'Express.js', hasChildren: false },
{ value: 'nestjs', label: 'NestJS', hasChildren: false },
{ value: 'fastify', label: 'Fastify', hasChildren: false },
]
break
case 'python':
childrenData = [
{ value: 'django', label: 'Django', hasChildren: false },
{ value: 'fastapi', label: 'FastAPI', hasChildren: false },
{ value: 'flask', label: 'Flask', hasChildren: false },
]
break
}
// Insert data ke dalam tree state
const success = findAndInsertChildren(treeData.value, parentId, childrenData)
console.log(`[DEMO] Insert children result:`, success)
// Force trigger reactivity
triggerRef(treeData)
console.log(`[DEMO] Current tree data:`, JSON.stringify(treeData.value, null, 2))
}
</script>
<template>
<div class="p-10 max-w-2xl mx-auto">
<div class="mb-6">
<h1 class="mb-2 text-3xl font-bold text-slate-800">Demo: Tree Select dengan Lazy Loading</h1>
<p class="text-slate-600">
Contoh penggunaan komponen TreeSelect dengan data teknologi.
Pilih item untuk melihat sub-kategori yang dimuat secara lazy.
</p>
</div>
<div class="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
<h3 class="font-semibold text-blue-800 mb-2">💡 Catatan untuk Developer:</h3>
<p class="text-sm text-blue-700">
Untuk implementasi nyata dengan data divisi rumah sakit,
lihat komponen <code class="px-1 bg-blue-100 rounded">content/division/entry.vue</code>
</p>
</div>
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-slate-700 mb-2">
Pilih Teknologi:
</label>
<TreeSelect
v-model="selectedValue"
:data="treeData"
:on-fetch-children="handleFetchChildren"
/>
</div>
<div class="p-4 bg-slate-50 rounded-lg">
<p class="text-sm text-slate-600 mb-1">Value yang terpilih:</p>
<span class="px-3 py-1 font-mono text-sm bg-white border rounded-md">
{{ selectedValue || 'Belum ada yang dipilih' }}
</span>
</div>
</div>
<div class="mt-8 text-xs text-slate-500">
<p>🔄 Data dimuat secara lazy saat node parent dibuka</p>
<p> Simulasi delay 600ms untuk menampilkan loading state</p>
</div>
</div>
</template>
-145
View File
@@ -1,145 +0,0 @@
import type { TreeItem } from '~/components/pub/my-ui/select-tree/type'
import * as z from 'zod'
export const divisionConf = {
msg: {
placeholder: '---pilih divisi utama',
search: 'kode, nama divisi',
empty: 'divisi tidak ditemukan',
},
items: [
{ value: '1', label: 'Medical' },
{ value: '2', label: 'Nursing' },
{ value: '3', label: 'Admin' },
{ value: '4', label: 'Support' },
{ value: '5', label: 'Education' },
{ value: '6', label: 'Pharmacy' },
{ value: '7', label: 'Radiology' },
{ value: '8', label: 'Laboratory' },
{ value: '9', label: 'Finance' },
{ value: '10', label: 'Human Resources' },
{ value: '11', label: 'IT Services' },
{ value: '12', label: 'Maintenance' },
{ value: '13', label: 'Catering' },
{ value: '14', label: 'Security' },
{ value: '15', label: 'Emergency' },
{ value: '16', label: 'Surgery' },
{ value: '17', label: 'Outpatient' },
{ value: '18', label: 'Inpatient' },
{ value: '19', label: 'Rehabilitation' },
{ value: '20', label: 'Research' },
],
}
export const schema = z.object({
name: z
.string({
required_error: 'Nama wajib diisi',
})
.min(1, 'Nama divisi wajib diisi'),
code: z
.string({
required_error: 'Kode wajib diisi',
})
.min(1, 'Kode divisi wajib diisi'),
parentId: z.string().optional(),
})
// State untuk tree data divisi - dimulai dengan data level atas
const divisionTreeData = ref<TreeItem[]>([
{ value: '1', label: 'Medical', hasChildren: true },
{ value: '2', label: 'Nursing', hasChildren: true },
{ value: '3', label: 'Admin', hasChildren: false },
{ value: '4', label: 'Support', hasChildren: true },
{ value: '5', label: 'Education', hasChildren: false },
{ value: '6', label: 'Pharmacy', hasChildren: true },
{ value: '7', label: 'Radiology', hasChildren: false },
{ value: '8', label: 'Laboratory', hasChildren: true },
])
// Helper function untuk mencari dan menyisipkan data anak ke dalam tree
function findAndInsertChildren(nodes: TreeItem[], parentId: string, newChildren: TreeItem[]): boolean {
for (const node of nodes) {
if (node.value === parentId) {
node.children = newChildren
return true
}
if (node.children && findAndInsertChildren(node.children as TreeItem[], parentId, newChildren)) {
return true
}
}
return false
}
// Fungsi untuk fetch data anak divisi (lazy loading)
async function handleFetchDivisionChildren(parentId: string): Promise<void> {
console.log(`Mengambil data sub-divisi untuk parent: ${parentId}`)
// Simulasi delay API call
await new Promise((resolve) => setTimeout(resolve, 800))
let childrenData: TreeItem[] = []
// Sample data berdasarkan parent ID
switch (parentId) {
case '1': // Medical
childrenData = [
{ value: '1-1', label: 'Cardiology', hasChildren: true },
{ value: '1-2', label: 'Neurology', hasChildren: false },
{ value: '1-3', label: 'Oncology', hasChildren: false },
]
break
case '2': // Nursing
childrenData = [
{ value: '2-1', label: 'ICU Nursing', hasChildren: false },
{ value: '2-2', label: 'ER Nursing', hasChildren: false },
{ value: '2-3', label: 'Ward Nursing', hasChildren: true },
]
break
case '4': // Support
childrenData = [
{ value: '4-1', label: 'IT Support', hasChildren: false },
{ value: '4-2', label: 'Maintenance', hasChildren: false },
]
break
case '6': // Pharmacy
childrenData = [
{ value: '6-1', label: 'Inpatient Pharmacy', hasChildren: false },
{ value: '6-2', label: 'Outpatient Pharmacy', hasChildren: false },
]
break
case '8': // Laboratory
childrenData = [
{ value: '8-1', label: 'Clinical Lab', hasChildren: false },
{ value: '8-2', label: 'Pathology Lab', hasChildren: false },
]
break
case '1-1': // Cardiology sub-divisions
childrenData = [
{ value: '1-1-1', label: 'Cardiac Surgery', hasChildren: false },
{ value: '1-1-2', label: 'Cardiac Cathlab', hasChildren: false },
]
break
case '2-3': // Ward Nursing sub-divisions
childrenData = [
{ value: '2-3-1', label: 'Pediatric Ward', hasChildren: false },
{ value: '2-3-2', label: 'Surgical Ward', hasChildren: false },
]
break
}
// Insert data ke dalam tree state
findAndInsertChildren(divisionTreeData.value, parentId, childrenData)
}
export const divisionTreeConfig = computed(() => ({
msg: {
placeholder: '--- Pilih divisi induk',
search: 'Cari divisi...',
empty: 'Divisi tidak ditemukan',
},
data: divisionTreeData.value,
onFetchChildren: handleFetchDivisionChildren,
}))
@@ -1,208 +0,0 @@
<script setup lang="ts">
import type { HeaderPrep } from '~/components/pub/my-ui/data/types'
import AppDivisionEntryForm from '~/components/app/division/entry-form.vue'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'
import { ActionEvents } from '~/components/pub/my-ui/data/types'
import Header from '~/components/pub/my-ui/nav-header/header.vue'
import { usePaginatedList } from '~/composables/usePaginatedList'
import { divisionConf, divisionTreeConfig, schema } from './entry'
// #region State & Computed
// Dialog state
const isFormEntryDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)
// Table action rowId provider
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
async function fetchDivisionData(_params: any) {
const endpoint = '/api/v1/_dev/division/list'
return await xfetch(endpoint)
}
// Menggunakan composable untuk pagination
const {
data,
isLoading,
paginationMeta,
searchInput,
handlePageChange,
handleSearch,
fetchData: getDivisionList,
} = usePaginatedList({
fetchFn: fetchDivisionData,
entityName: 'division',
})
const headerPrep: HeaderPrep = {
title: 'Divisi',
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 Divisi',
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 Functions
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/division/${record.id}`, {
// method: 'DELETE'
// })
// Refresh data setelah berhasil delete
await getDivisionList()
// 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 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/division', {
// 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 getDivisionList()
// TODO: Show success message
console.log('Division 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 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>
<Header v-model="searchInput" :prep="headerPrep" @search="handleSearch" />
<AppDivisonList :data="data" :pagination-meta="paginationMeta" @page-change="handlePageChange" />
<Dialog v-model:open="isFormEntryDialogOpen" title="Tambah Divisi" size="lg" prevent-outside>
<AppDivisionEntryFormPrev
:division="divisionConf" :division-tree="divisionTreeConfig" :schema="schema"
:initial-values="{ name: '', code: '', parentId: '' }" @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>
</template>
<style scoped>
/* component style */
</style>