refactor(equipment): add modal form to component list

This commit is contained in:
riefive
2025-09-08 13:09:55 +07:00
parent e2ba3c070c
commit 9cb8dd9caf
9 changed files with 285 additions and 144 deletions
@@ -5,20 +5,18 @@ import { useForm } from 'vee-validate'
// types
import type z from 'zod'
import type { MaterialFormData } from '~/schemas/material'
// components
import Label from '~/components/pub/custom-ui/form/label.vue'
interface Props {
isLoading: boolean
schema: z.ZodSchema<any>
uoms: any[]
items: any[]
}
const isLoading = ref(false)
const props = defineProps<Props>()
const emit = defineEmits<{
back: []
submit: [data: any]
submit: [values: MaterialFormData, resetForm: () => void]
cancel: [resetForm: () => void]
}>()
const { handleSubmit, defineField, errors } = useForm({
@@ -38,19 +36,36 @@ const [uom, uomAttrs] = defineField('uom_code')
const [item, itemAttrs] = defineField('item_id')
const [stock, stockAttrs] = defineField('stock')
const onSubmit = handleSubmit(async (values) => {
try {
emit('submit', values)
} catch (error) {
console.error('Submission failed:', error)
const resetForm = () => {
code.value = ''
name.value = ''
uom.value = ''
item.value = ''
stock.value = 0
}
// Form submission handler
function onSubmitForm(values: any) {
const formData: MaterialFormData = {
name: values.name || '',
code: values.code || '',
uom_code: values.uom_code || '',
item_id: values.item_id || '',
stock: values.stock || 0,
}
})
emit('submit', formData, resetForm)
}
// Form cancel handler
function onCancelForm() {
emit('cancel', resetForm)
}
</script>
<template>
<form class="grid gap-2" @submit="onSubmit">
<form class="grid gap-2" @submit="onSubmitForm">
<div class="grid gap-2">
<Label for="code">Kode</Label>
<label for="code">Kode</label>
<Input
id="code"
v-model="code"
@@ -63,7 +78,7 @@ const onSubmit = handleSubmit(async (values) => {
</span>
</div>
<div class="grid gap-2">
<Label for="name">Nama</Label>
<label for="name">Nama</label>
<Input
id="name"
v-model="name"
@@ -76,7 +91,7 @@ const onSubmit = handleSubmit(async (values) => {
</span>
</div>
<div class="grid gap-2">
<Label for="uom">Satuan</Label>
<label for="uom">Satuan</label>
<Select
id="uom"
icon-name="i-lucide-chevron-down"
@@ -92,7 +107,7 @@ const onSubmit = handleSubmit(async (values) => {
</span>
</div>
<div class="grid gap-2">
<Label for="item">Item</Label>
<label for="item">Item</label>
<Select
id="item"
icon-name="i-lucide-chevron-down"
@@ -108,7 +123,7 @@ const onSubmit = handleSubmit(async (values) => {
</span>
</div>
<div class="grid gap-2">
<Label for="stock">Stok</Label>
<label for="stock">Stok</label>
<Input
id="stock"
type="number"
@@ -122,7 +137,7 @@ const onSubmit = handleSubmit(async (values) => {
</span>
</div>
<div class="my-2 flex justify-end gap-2 py-2">
<Button variant="secondary" class="w-[120px]" @click="emit('back')"> Kembali </Button>
<Button variant="secondary" class="w-[120px]" @click="onCancelForm"> Kembali </Button>
<Button type="submit" class="w-[120px]">
<Loader2 v-if="isLoading" class="mr-2 h-4 w-4 animate-spin" />
Simpan
+38
View File
@@ -0,0 +1,38 @@
<script setup lang="ts">
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
}
defineProps<Props>()
const emit = defineEmits<{
pageChange: [page: number]
}>()
function handlePageChange(page: number) {
emit('pageChange', page)
}
</script>
<template>
<div class="space-y-4">
<PubBaseDataTable
:rows="data"
:cols="cols"
:header="header"
:keys="keys"
:func-parsed="funcParsed"
:func-html="funcHtml"
:func-component="funcComponent"
/>
<template v-if="paginationMeta">
<div v-if="paginationMeta.totalPage > 1">
<PubCustomUiPagination :pagination-meta="paginationMeta" @page-change="handlePageChange" />
</div>
</template>
</div>
</template>
-19
View File
@@ -1,19 +0,0 @@
<script setup lang="ts">
import { cols, funcComponent, funcHtml, funcParsed, header, keys } from './list-cfg'
defineProps<{
data: any[]
}>()
</script>
<template>
<PubBaseDataTable
:rows="data"
:cols="cols"
:header="header"
:keys="keys"
:func-parsed="funcParsed"
:func-html="funcHtml"
:func-component="funcComponent"
/>
</template>
+211
View File
@@ -0,0 +1,211 @@
<script setup lang="ts">
import { MaterialSchema, type MaterialFormData } from '~/schemas/material'
import { usePaginatedList } from '~/composables/usePaginatedList'
import { ActionEvents, type HeaderPrep } from '~/components/pub/custom-ui/data/types'
import Dialog from '~/components/pub/base/modal/dialog.vue'
import Header from '~/components/pub/custom-ui/nav-header/prep.vue'
import AppEquipmentEntryForm from '~/components/app/equipment/entry-form.vue'
import RecordConfirmation from '~/components/pub/custom-ui/confirmation/record-confirmation.vue'
const isFormEntryDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
const uoms = [
{ value: 'uom-1', label: 'Satuan 1' },
{ value: 'uom-2', label: 'Satuan 2' },
{ value: 'uom-3', label: 'Satuan 3' },
]
const items = [
{ value: 'item-1', label: 'Item 1' },
{ value: 'item-2', label: 'Item 2' },
{ value: 'item-3', label: 'Item 3' },
]
// Fungsi untuk fetch data division
async function fetchEquipmentData(params: any) {
// Prepare query parameters for pagination and search
const urlParams = new URLSearchParams({
'page-number': params.page.toString(),
'page-size': params.pageSize.toString(),
})
if (params.q) {
urlParams.append('search', params.q)
}
return await xfetch(`/api/v1/equipment?${urlParams.toString()}`)
}
// Menggunakan composable untuk pagination
const {
data,
isLoading,
paginationMeta,
searchInput,
handlePageChange,
handleSearch,
fetchData: getEquipmentList,
} = usePaginatedList({
fetchFn: fetchEquipmentData,
entityName: 'equipment',
})
const headerPrep: HeaderPrep = {
title: 'Perlengkapan (BMHP)',
icon: 'i-lucide-layout-dashboard',
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 Perlengkapan',
icon: 'i-lucide-plus',
onClick: () => {
isFormEntryDialogOpen.value = true
},
},
}
provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)
// 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
}
})
const handleDeleteRow = async (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 getEquipmentList()
// 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
}
}
const onCancelForm = (resetForm: () => void) => {
isFormEntryDialogOpen.value = false
setTimeout(() => {
resetForm()
}, 500)
}
const onSubmitForm = async (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 getEquipmentList()
// 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)
}
}
}
// Handle confirmation result
const handleConfirmDelete = (record: any, action: string) => {
console.log('Confirmed action:', action, 'for record:', record)
handleDeleteRow(record)
}
const handleCancelConfirmation = () => {
// Reset record state when cancelled
recId.value = 0
recAction.value = ''
recItem.value = null
}
</script>
<template>
<div class="rounded-md border p-4">
<Header v-model="searchInput" :prep="headerPrep" @search="handleSearch" />
<div class="rounded-md border p-4">
<AppEquipmentList :data="data" :pagination-meta="paginationMeta" @page-change="handlePageChange" />
</div>
<Dialog v-model:open="isFormEntryDialogOpen" title="Tambah Perlengkapan" size="lg" prevent-outside>
<AppEquipmentEntryForm :schema="MaterialSchema" :uoms="uoms" :items="items" @back="onCancelForm" @submit="onSubmitForm" />
</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?.name"><strong>Nama:</strong> {{ record.name }}</p>
<p v-if="record?.code"><strong>Kode:</strong> {{ record.code }}</p>
</div>
</template>
</RecordConfirmation>
</div>
</template>
-39
View File
@@ -1,39 +0,0 @@
<script setup lang="ts">
// types
import { MaterialSchema, type MaterialFormData } from '~/schemas/material'
const isLoading = ref(false)
const uoms = [
{ value: 'uom-1', label: 'Satuan 1' },
{ value: 'uom-2', label: 'Satuan 2' },
{ value: 'uom-3', label: 'Satuan 3' },
]
const items = [
{ value: 'item-1', label: 'Item 1' },
{ value: 'item-2', label: 'Item 2' },
{ value: 'item-3', label: 'Item 3' },
]
function onBack() {
navigateTo('/tools-equipment-src/equipment')
}
async function onSubmit(data: MaterialFormData) {
console.log(data)
}
</script>
<template>
<div class="mb-5 border-b border-b-slate-300 pb-3 text-lg xl:text-xl">
<Icon name="i-lucide-panel-bottom" class="me-2" />
<span class="font-semibold">Tambah</span> Perlengkapan (BMHP)
</div>
<AppMaterialEntryForm
:is-loading="isLoading"
:schema="MaterialSchema"
:uoms="uoms"
:items="items"
@back="onBack"
@submit="onSubmit"
/>
</template>
-65
View File
@@ -1,65 +0,0 @@
<script setup lang="ts">
import type { DataTableLoader } from '~/components/pub/base/data-table/type'
import type { HeaderPrep, RefSearchNav } from '~/components/pub/custom-ui/data/types'
import Header from '~/components/pub/custom-ui/nav-header/prep.vue'
const data = ref([])
const refSearchNav: RefSearchNav = {
onClick: () => {
// open filter modal
},
onInput: (_val: string) => {
// filter patient list
},
onClear: () => {
// clear url param
},
}
const isLoading = reactive<DataTableLoader>({
isTableLoading: false,
})
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
const headerPrep: HeaderPrep = {
title: 'Perlengkapan (BMHP)',
icon: 'i-lucide-panel-bottom',
addNav: {
label: 'Tambah',
onClick: () => navigateTo('/tools-equipment-src/equipment/add'),
},
}
async function getMaterialList() {
isLoading.dataListLoading = true
// const resp = await xfetch('/api/v1/material')
// if (resp.success) {
// data.value = (resp.body as Record<string, any>).data
// }
isLoading.dataListLoading = false
}
onMounted(() => {
getMaterialList()
})
provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)
</script>
<template>
<div class="rounded-md border p-4">
<Header :prep="{ ...headerPrep }" :ref-search-nav="refSearchNav" />
<div class="rounded-md border p-4">
<AppMaterialList v-if="!isLoading.dataListLoading" :data="data" />
</div>
</div>
</template>
@@ -35,7 +35,7 @@ const canCreate = hasCreateAccess(roleAccess)
<template>
<div v-if="canCreate">
<FlowMaterialEntry />
<ContentMaterialEntry />
</div>
<Error v-else :status-code="403" />
</template>
@@ -27,13 +27,13 @@ if (!hasAccess) {
}
// Define permission-based computed properties
const canRead = hasReadAccess(roleAccess)
const canRead = true // hasReadAccess(roleAccess)
</script>
<template>
<div>
<div v-if="canRead">
<FlowMaterialList />
<ContentEquipmentList />
</div>
<Error v-else :status-code="403" />
</div>