feat(division): fix schemas

This commit is contained in:
riefive
2025-09-30 11:37:44 +07:00
parent 18eaef2e37
commit 9e4133b976
10 changed files with 456 additions and 130 deletions
@@ -0,0 +1,144 @@
<script setup lang="ts">
import type { TreeItem } from '~/components/pub/base/select-tree/type'
import type { FormErrors } from '~/types/error'
import { toTypedSchema } from '@vee-validate/zod'
import TreeSelect from '~/components/pub/base/select-tree/tree-select.vue'
import Combobox from '~/components/pub/custom-ui/form/combobox.vue'
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'
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>
+81 -122
View File
@@ -1,144 +1,103 @@
<script setup lang="ts">
import type { TreeItem } from '~/components/pub/base/select-tree/type'
import type { FormErrors } from '~/types/error'
// Components
import Block from '~/components/pub/custom-ui/doc-entry/block.vue'
import Cell from '~/components/pub/custom-ui/doc-entry/cell.vue'
import Field from '~/components/pub/custom-ui/doc-entry/field.vue'
import Label from '~/components/pub/custom-ui/doc-entry/label.vue'
// Types
import type { DivisionFormData } from '~/schemas/division.schema.ts'
// Helpers
import type z from 'zod'
import { toTypedSchema } from '@vee-validate/zod'
import TreeSelect from '~/components/pub/base/select-tree/tree-select.vue'
import Combobox from '~/components/pub/custom-ui/form/combobox.vue'
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 { useForm } from 'vee-validate'
interface DivisionFormData {
name: string
code: string
parentId: string
interface Props {
schema: z.ZodSchema<any>
uoms: any[]
values: any
isLoading?: boolean
isReadonly?: boolean
}
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 props = defineProps<Props>()
const isLoading = props.isLoading !== undefined ? props.isLoading : false
const isReadonly = props.isReadonly !== undefined ? props.isReadonly : false
const emit = defineEmits<{
'submit': [values: DivisionFormData, resetForm: () => void]
'cancel': [resetForm: () => void]
submit: [values: DivisionFormData, resetForm: () => void]
cancel: [resetForm: () => void]
}>()
const formSchema = toTypedSchema(props.schema)
const { defineField, errors, meta } = useForm({
validationSchema: toTypedSchema(props.schema),
initialValues: {
code: '',
name: '',
division_id: '',
} as Partial<DivisionFormData>,
})
const [code, codeAttrs] = defineField('code')
const [name, nameAttrs] = defineField('name')
const [division, divisionAttrs] = defineField('uom_code')
// Fill fields from props.values if provided
if (props.values) {
if (props.values.code !== undefined) code.value = props.values.code
if (props.values.name !== undefined) name.value = props.values.name
if (props.values.division_id !== undefined) division.value = props.values.division_id
}
const resetForm = () => {
code.value = ''
name.value = ''
division.value = ''
}
// Form submission handler
function onSubmitForm(values: any, { resetForm }: { resetForm: () => void }) {
function onSubmitForm(values: any) {
const formData: DivisionFormData = {
name: values.name || '',
code: values.code || '',
parentId: values.parentId || '',
name: name.value || '',
code: code.value || '',
division_id: division.value || '',
}
emit('submit', formData, resetForm)
}
// Form cancel handler
function onCancelForm({ resetForm }: { resetForm: () => void }) {
function onCancelForm() {
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>
<form id="form-tools" @submit.prevent>
<Block labelSize="thin" class="!mb-2.5 !pt-0 xl:!mb-3" :colCount="1">
<Cell>
<Label height="compact">Kode</Label>
<Field :errMessage="errors.code">
<Input id="code" v-model="code" v-bind="codeAttrs" :disabled="isLoading || isReadonly" />
</Field>
</Cell>
<Cell>
<Label height="compact">Nama</Label>
<Field :errMessage="errors.name">
<Input id="name" v-model="name" v-bind="nameAttrs" :disabled="isLoading || isReadonly" />
</Field>
</Cell>
</Block>
<div class="my-2 flex justify-end gap-2 py-2">
<Button type="button" variant="secondary" class="w-[120px]" @click="onCancelForm"> Kembali </Button>
<Button
v-if="!isReadonly"
type="button"
class="w-[120px]"
:disabled="isLoading || !meta.valid"
@click="onSubmitForm"
>
Simpan
</Button>
</div>
</form>
</template>
+1 -1
View File
@@ -6,7 +6,7 @@ import Field from '~/components/pub/custom-ui/doc-entry/field.vue'
import Label from '~/components/pub/custom-ui/doc-entry/label.vue'
// Types
import type { MaterialFormData } from '~/schemas/material.schema'
import type { MaterialFormData } from '~/schemas/material.schema.ts'
// Helpers
import type z from 'zod'
@@ -8,7 +8,7 @@ import Label from '~/components/pub/custom-ui/doc-entry/label.vue'
import Button from '~/components/pub/ui/button/Button.vue'
// Types
import { type BaseFormData } from '~/schemas/base.schema'
import type { BaseFormData } from '~/schemas/base.schema.ts'
// Helpers
import type z from 'zod'
@@ -8,7 +8,7 @@ import Label from '~/components/pub/custom-ui/doc-entry/label.vue'
import Button from '~/components/pub/ui/button/Button.vue'
// Types
import { type BaseFormData } from '~/schemas/base.schema'
import type { BaseFormData } from '~/schemas/base.schema.ts'
// Helpers
import type z from 'zod'
+6 -3
View File
@@ -1,13 +1,16 @@
<script setup lang="ts">
import type z from 'zod'
import { useForm } from 'vee-validate'
import { toTypedSchema } from '@vee-validate/zod'
// Components
import Block from '~/components/pub/custom-ui/doc-entry/block.vue'
import Cell from '~/components/pub/custom-ui/doc-entry/cell.vue'
import Field from '~/components/pub/custom-ui/doc-entry/field.vue'
import Label from '~/components/pub/custom-ui/doc-entry/label.vue'
import Button from '~/components/pub/ui/button/Button.vue'
// Helpers
import type z from 'zod'
import { useForm } from 'vee-validate'
import { toTypedSchema } from '@vee-validate/zod'
interface Props {
schema?: z.ZodSchema<any>
values?: any
+1 -1
View File
@@ -6,7 +6,7 @@ import Field from '~/components/pub/custom-ui/doc-entry/field.vue'
import Label from '~/components/pub/custom-ui/doc-entry/label.vue'
// Types
import type { DeviceFormData } from '~/schemas/device.schema'
import type { DeviceFormData } from '~/schemas/device.schema.ts'
// Helpers
import type z from 'zod'
+1 -1
View File
@@ -8,7 +8,7 @@ import Label from '~/components/pub/custom-ui/doc-entry/label.vue'
import Button from '~/components/pub/ui/button/Button.vue'
// Types
import type { UomFormData } from '~/schemas/uom.schema'
import type { UomFormData } from '~/schemas/uom.schema.ts'
// Helpers
import type z from 'zod'
@@ -0,0 +1,208 @@
<script setup lang="ts">
import type { HeaderPrep } from '~/components/pub/custom-ui/data/types'
import AppDivisionEntryForm from '~/components/app/divison/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 { 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>
+12
View File
@@ -0,0 +1,12 @@
import { z } from 'zod'
import type { Division, DivisionPosition } from '~/models/division'
const DivisionSchema = z.object({
code: z.string({ required_error: 'Kode harus diisi' }).min(1, 'Kode minimum 1 karakter'),
name: z.string({ required_error: 'Nama harus diisi' }).min(1, 'Nama minimum 1 karakter'),
})
type DivisionFormData = z.infer<typeof DivisionSchema> & (Division | DivisionPosition)
export { DivisionSchema }
export type { DivisionFormData }