feat(medicine): modify entry-form, create handler and service

This commit is contained in:
riefive
2025-09-29 09:57:57 +07:00
parent 97d36f1279
commit 11e63dde3e
9 changed files with 566 additions and 110 deletions
@@ -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 { MedicineBaseFormData } from '~/schemas/medicine.schema'
import { type BaseFormData } from '~/schemas/base.schema'
// Helpers
import type z from 'zod'
@@ -26,7 +26,7 @@ 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: MedicineBaseFormData, resetForm: () => void]
submit: [values: BaseFormData, resetForm: () => void]
cancel: [resetForm: () => void]
}>()
+149 -69
View File
@@ -1,80 +1,160 @@
<script setup lang="ts">
import Block from '~/components/pub/custom-ui/form/block.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 type z from 'zod'
import { useForm } from 'vee-validate'
import { toTypedSchema } from '@vee-validate/zod'
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'
const props = defineProps<{ modelValue: any }>()
const emit = defineEmits(['update:modelValue', 'event'])
interface Props {
schema?: z.ZodSchema<any>
values?: any
isLoading?: boolean
isReadonly?: boolean
medicineGroups?: { value: string, label: string }[]
medicineMethods?: { value: string, label: string }[]
uoms?: { value: string, label: string }[]
infras?: { value: number|null, label: string }[]
}
const data = computed({
get: () => props.modelValue,
set: (val) => emit('update:modelValue', val),
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: any, resetForm: () => void]
cancel: [resetForm: () => void]
}>()
const { defineField, errors, meta } = useForm({
validationSchema: props.schema ? toTypedSchema(props.schema) : undefined,
initialValues: {
code: '',
name: '',
medicineGroup_code: '',
medicineMethod_code: '',
uom_code: '',
infra_id: null,
stock: 0,
},
})
const items = [
{ value: '1', label: 'item 1' },
{ value: '2', label: 'item 2' },
{ value: '3', label: 'item 3' },
{ value: '4', label: 'item 4' },
]
const [code, codeAttrs] = defineField('code')
const [name, nameAttrs] = defineField('name')
const [medicineGroup_code, medicineGroupAttrs] = defineField('medicineGroup_code')
const [medicineMethod_code, medicineMethodAttrs] = defineField('medicineMethod_code')
const [uom_code, uomAttrs] = defineField('uom_code')
const [infra_id, infraAttrs] = defineField('infra_id')
const [stock, stockAttrs] = defineField('stock')
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.medicineGroup_code !== undefined) medicineGroup_code.value = props.values.medicineGroup_code
if (props.values.medicineMethod_code !== undefined) medicineMethod_code.value = props.values.medicineMethod_code
if (props.values.uom_code !== undefined) uom_code.value = props.values.uom_code
if (props.values.infra_id !== undefined) infra_id.value = props.values.infra_id
if (props.values.stock !== undefined) stock.value = props.values.stock
}
const resetForm = () => {
code.value = ''
name.value = ''
medicineGroup_code.value = ''
medicineMethod_code.value = ''
uom_code.value = ''
infra_id.value = null
stock.value = 0
}
function onSubmitForm() {
const formData = {
code: code.value || '',
name: name.value || '',
medicineGroup_code: medicineGroup_code.value || '',
medicineMethod_code: medicineMethod_code.value || '',
uom_code: uom_code.value || '',
infra_id: infra_id.value === '' ? null : infra_id.value,
stock: stock.value || 0,
}
emit('submit', formData, resetForm)
}
function onCancelForm() {
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>
<Field>
<Input type="text" name="identity_number" />
</Field>
</FieldGroup>
<FieldGroup :column="2">
<Label>Kode</Label>
<Field name="sip_number">
<Input type="text" name="sip_no" />
</Field>
</FieldGroup>
<FieldGroup :column="2">
<Label>Cara Pemberian</Label>
<Field name="phone">
<Select :items="items" />
</Field>
</FieldGroup>
<FieldGroup :column="2">
<Label>Bentuk Sediaan</Label>
<Field>
<Select :items="items" />
</Field>
</FieldGroup>
<FieldGroup :column="2">
<Label>Dosis</Label>
<Field>
<Input type="number" name="outPatient_rate" />
</Field>
</FieldGroup>
<FieldGroup :column="2">
<Label>Infra</Label>
<Field>
<Input />
</Field>
</FieldGroup>
<FieldGroup :column="2">
<Label>Stock</Label>
<Field>
<Input type="number" />
</Field>
</FieldGroup>
<FieldGroup :column="2">
<Label>Status</Label>
<Field>
<Input />
</Field>
</FieldGroup>
</Block>
</div>
<form id="form-medicine" @submit.prevent>
<Block labelSize="thin" class="!mb-2.5 !pt-0 xl:!mb-3" :colCount="1">
<Cell>
<Label height="">Kode</Label>
<Field :errMessage="errors.code">
<input id="code" v-model="code" v-bind="codeAttrs" :disabled="isLoading || isReadonly" class="input input-bordered w-full" />
</Field>
</Cell>
<Cell>
<Label height="compact">Nama</Label>
<Field :errMessage="errors.name">
<input id="name" v-model="name" v-bind="nameAttrs" :disabled="isLoading || isReadonly" class="input input-bordered w-full" />
</Field>
</Cell>
<Cell>
<Label height="compact">Kelompok Obat</Label>
<Field :errMessage="errors.medicineGroup_code">
<select id="medicineGroup_code" v-model="medicineGroup_code" v-bind="medicineGroupAttrs" :disabled="isLoading || isReadonly" class="input input-bordered w-full">
<option value="">Pilih kelompok obat</option>
<option v-for="item in props.medicineGroups || []" :key="item.value" :value="item.value">{{ item.label }}</option>
</select>
</Field>
</Cell>
<Cell>
<Label height="compact">Metode Pemberian</Label>
<Field :errMessage="errors.medicineMethod_code">
<select id="medicineMethod_code" v-model="medicineMethod_code" v-bind="medicineMethodAttrs" :disabled="isLoading || isReadonly" class="input input-bordered w-full">
<option value="">Pilih metode pemberian</option>
<option v-for="item in props.medicineMethods || []" :key="item.value" :value="item.value">{{ item.label }}</option>
</select>
</Field>
</Cell>
<Cell>
<Label height="compact">Satuan</Label>
<Field :errMessage="errors.uom_code">
<select id="uom_code" v-model="uom_code" v-bind="uomAttrs" :disabled="isLoading || isReadonly" class="input input-bordered w-full">
<option value="">Pilih satuan</option>
<option v-for="item in props.uoms || []" :key="item.value" :value="item.value">{{ item.label }}</option>
</select>
</Field>
</Cell>
<Cell>
<Label height="compact">Infra</Label>
<Field :errMessage="errors.infra_id">
<select id="infra_id" v-model="infra_id" v-bind="infraAttrs" :disabled="isLoading || isReadonly" class="input input-bordered w-full">
<option value="">Tidak ada</option>
<option v-for="item in props.infras || []" :key="String(item.value)" :value="item.value">{{ item.label }}</option>
</select>
</Field>
</Cell>
<Cell>
<Label height="compact">Stok</Label>
<Field :errMessage="errors.stock">
<input id="stock" v-model="stock" type="number" v-bind="stockAttrs" :disabled="isLoading || isReadonly" class="input input-bordered w-full" />
</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>
@@ -11,7 +11,7 @@ import { toast } from '~/components/pub/ui/toast'
// Types
import { ActionEvents, type HeaderPrep } from '~/components/pub/custom-ui/data/types'
import { MedicineBaseSchema, type MedicineBaseFormData } from '~/schemas/medicine.schema'
import { BaseSchema, type BaseFormData } from '~/schemas/base.schema'
// Handlers
import {
@@ -122,12 +122,12 @@ onMounted(async () => {
prevent-outside
>
<AppMedicineGroupEntryForm
:schema="MedicineBaseSchema"
:schema="BaseSchema"
:values="recItem"
:is-loading="isProcessing"
:is-readonly="isReadonly"
@submit="
(values: MedicineBaseFormData | Record<string, any>, resetForm: () => void) => {
(values: BaseFormData | Record<string, any>, resetForm: () => void) => {
if (recId > 0) {
handleActionEdit(recId, values, getMedicineGroupList, resetForm, toast)
return
@@ -11,7 +11,7 @@ import { toast } from '~/components/pub/ui/toast'
// Types
import { ActionEvents, type HeaderPrep } from '~/components/pub/custom-ui/data/types'
import { MedicineBaseSchema, type MedicineBaseFormData } from '~/schemas/medicine.schema'
import { BaseSchema, type BaseFormData } from '~/schemas/base.schema'
// Handlers
import {
@@ -122,12 +122,12 @@ onMounted(async () => {
prevent-outside
>
<AppMedicineMethodEntryForm
:schema="MedicineBaseSchema"
:schema="BaseSchema"
:values="recItem"
:is-loading="isProcessing"
:is-readonly="isReadonly"
@submit="
(values: MedicineBaseFormData | Record<string, any>, resetForm: () => void) => {
(values: BaseFormData | Record<string, any>, resetForm: () => void) => {
if (recId > 0) {
handleActionEdit(recId, values, getMedicineMethodList, resetForm, toast)
return
+214
View File
@@ -55,6 +55,220 @@ provide('rec_item', recItem)
provide('table_data_loader', isLoading)
</script>
<template>
<Header :prep="{ ...hreaderPrep }" :ref-search-nav="refSearchNav" />
<div class="my-4 flex flex-1 flex-col gap-4 md:gap-8">
<!-- Table/list component here -->
</div>
</template>
<script setup lang="ts">
import Dialog from '~/components/pub/base/modal/dialog.vue'
import Header from '~/components/pub/custom-ui/nav-header/prep.vue'
import AppMedicineEntryForm from '~/components/app/medicine/entry-form.vue'
import RecordConfirmation from '~/components/pub/custom-ui/confirmation/record-confirmation.vue'
import { usePaginatedList } from '~/composables/usePaginatedList'
import { toast } from '~/components/pub/ui/toast'
import { ActionEvents, type HeaderPrep } from '~/components/pub/custom-ui/data/types'
import {
recId,
recAction,
recItem,
isReadonly,
isProcessing,
isFormEntryDialogOpen,
isRecordConfirmationOpen,
handleActionSave,
handleActionEdit,
handleActionRemove,
handleCancelForm,
} from '~/handlers/medicine.handler'
import { getMedicines, getMedicineDetail } from '~/services/medicine.service'
import AppMedicineList from '~/components/app/medicine/list.vue'
const title = ref('')
const {
data,
isLoading,
paginationMeta,
searchInput,
handlePageChange,
handleSearch,
fetchData: getMedicineList,
} = usePaginatedList({
fetchFn: async ({ page, search }) => {
const result = await getMedicines({ search, page })
return { success: result.success || false, body: result.body || {} }
},
entityName: 'medicine',
})
const headerPrep: HeaderPrep = {
title: 'Obat',
icon: 'i-lucide-medicine-bottle',
refSearchNav: {
placeholder: 'Cari (min. 3 karakter)...',
minLength: 3,
debounceMs: 500,
showValidationFeedback: true,
onInput: (_val: string) => {},
onClick: () => {},
onClear: () => {},
},
addNav: {
label: 'Tambah',
icon: 'i-lucide-plus',
onClick: () => {
recItem.value = null
recId.value = 0
isFormEntryDialogOpen.value = true
isReadonly.value = false
},
},
}
provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)
watch([recId, recAction], () => {
switch (recAction.value) {
case ActionEvents.showDetail:
getMedicineDetail(recId.value).then(result => {
if (result.success) {
recItem.value = result.body?.data || {}
isFormEntryDialogOpen.value = true
}
})
title.value = 'Detail Obat'
isReadonly.value = true
break
case ActionEvents.showEdit:
getMedicineDetail(recId.value).then(result => {
if (result.success) {
recItem.value = result.body?.data || {}
isFormEntryDialogOpen.value = true
}
})
title.value = 'Edit Obat'
isReadonly.value = false
break
case ActionEvents.showConfirmDelete:
isRecordConfirmationOpen.value = true
break
}
})
onMounted(async () => {
await getMedicineList()
})
</script>
<template>
<div class="p-4">
<Header v-model="searchInput" :prep="headerPrep" @search="handleSearch" />
<div class="rounded-md border p-4">
<AppMedicineList :data="data" :pagination-meta="paginationMeta" @page-change="handlePageChange" />
</div>
<Dialog
v-model:open="isFormEntryDialogOpen"
:title="!!recItem ? title : 'Tambah Obat'"
size="lg"
prevent-outside
>
<AppMedicineEntryForm
:model-value="recItem"
:is-loading="isProcessing"
:is-readonly="isReadonly"
@submit="
(values, resetForm) => {
if (recId > 0) {
handleActionEdit(recId, values, getMedicineList, resetForm, toast)
return
}
handleActionSave(values, getMedicineList, resetForm, toast)
}
"
@cancel="handleCancelForm"
/>
</Dialog>
<!-- Record Confirmation Modal -->
<RecordConfirmation
v-model:open="isRecordConfirmationOpen"
action="delete"
:record="recItem"
@confirm="() => handleActionRemove(recId, getMedicineList, toast)"
@cancel=""
>
<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>
<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
},
}
// Loading state management
const isLoading = reactive<DataTableLoader>({
summary: false,
isTableLoading: false,
})
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
const hreaderPrep: HeaderPrep = {
title: 'Obat',
icon: 'i-lucide-medicine-bottle',
addNav: {
label: 'Tambah',
onClick: () => navigateTo('/tools-equipment-src/medicine/add'),
},
}
async function getPatientList() {
isLoading.isTableLoading = true
const resp = await xfetch('/api/v1/medicine')
if (resp.success) {
data.value = (resp.body as Record<string, any>).data
}
isLoading.isTableLoading = false
}
onMounted(() => {
getPatientList()
})
provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)
</script>
<template>
<Header :prep="{ ...hreaderPrep }" :ref-search-nav="refSearchNav" />
<div class="my-4 flex flex-1 flex-col gap-4 md:gap-8">
+94
View File
@@ -0,0 +1,94 @@
import { ref } from 'vue'
import { type ToastFn, handleAsyncAction } from '~/handlers/_handler'
import { postMedicine, patchMedicine, removeMedicine } from '~/services/medicine.service'
export const recId = ref<number>(0)
export const recAction = ref<string>('')
export const recItem = ref<any>(null)
export const isReadonly = ref(false)
export const isProcessing = ref(false)
export const isFormEntryDialogOpen = ref(false)
export const isRecordConfirmationOpen = ref(false)
export function onResetState() {
recId.value = 0
recAction.value = ''
recItem.value = null
}
export async function handleActionSave(
values: any,
refresh: () => void,
reset: () => void,
toast: ToastFn
) {
isProcessing.value = true;
await handleAsyncAction<[any], any>({
action: postMedicine,
args: [values],
toast,
successMessage: 'Data berhasil disimpan',
errorMessage: 'Gagal menyimpan data',
onSuccess: () => {
isFormEntryDialogOpen.value = false;
if (refresh) refresh();
},
onFinally: (isSuccess: boolean) => {
if (isSuccess) setTimeout(reset, 500);
isProcessing.value = false;
},
});
}
export async function handleActionEdit(
id: number | string,
values: any,
refresh: () => void,
reset: () => void,
toast: ToastFn
) {
isProcessing.value = true;
await handleAsyncAction<[number | string, any], any>({
action: patchMedicine,
args: [id, values],
toast,
successMessage: 'Data berhasil diubah',
errorMessage: 'Gagal mengubah data',
onSuccess: () => {
isFormEntryDialogOpen.value = false;
if (refresh) refresh();
},
onFinally: (isSuccess: boolean) => {
if (isSuccess) setTimeout(reset, 500);
isProcessing.value = false;
},
});
}
export async function handleActionRemove(
id: number | string,
refresh: () => void,
toast: ToastFn
) {
isProcessing.value = true;
await handleAsyncAction<[number | string], any>({
action: removeMedicine,
args: [id],
toast,
successMessage: 'Data berhasil dihapus',
errorMessage: 'Gagal menghapus data',
onSuccess: () => {
isRecordConfirmationOpen.value = false;
if (refresh) refresh();
},
onFinally: () => {
isProcessing.value = false;
},
});
}
export function handleCancelForm(reset: () => void) {
isFormEntryDialogOpen.value = false;
isReadonly.value = false;
setTimeout(reset, 300);
}
+13 -25
View File
@@ -4,30 +4,21 @@ export interface MedicineBase {
}
export interface Medicine {
id: string
name: string
code: string
name: string
medicineGroup_code: string
medicineMethod_code: string
uom_code: string
type: string
dose: string
infra_id: string
stock: string
status: string
infra_id?: string | null
stock: number
}
export interface CreateDto {
name: string
code: string
medicineGroup_code: string
medicineMethod_code: string
uom_code: string
type: string
dose: string
infra_id: string
stock: string
status: string
export interface CreateMedicineDto extends Medicine {
}
export interface UpdateMedicineDto extends CreateMedicineDto {
id: string | number
}
export interface GetListDto {
@@ -49,7 +40,7 @@ export interface GetDetailDto {
id?: string
}
export interface UpdateDto extends CreateDto {
export interface UpdateDto extends CreateMedicineDto {
id?: number
}
@@ -57,17 +48,14 @@ export interface DeleteDto {
id?: string
}
export function genMedicine(): CreateDto {
export function genMedicine(): CreateMedicineDto {
return {
name: 'name',
code: 'code',
medicineGroup_code: 'medicineGroup_code',
medicineMethod_code: 'medicineMethod_code',
uom_code: 'uom_code',
type: 'type',
dose: 'dose',
infra_id: 'infra_id',
stock: 'stock',
status: 'status',
infra_id: null,
stock: 0
}
}
+9 -8
View File
@@ -1,12 +1,13 @@
import { z } from 'zod'
import type { MedicineBase } from '~/models/medicine'
const MedicineBaseSchema = 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')
export const MedicineSchema = z.object({
code: z.string({ required_error: 'Kode harus diisi' }).min(1, 'Kode minimal 1 karakter'),
name: z.string({ required_error: 'Nama harus diisi' }).min(1, 'Nama minimal 1 karakter'),
medicineGroup_code: z.string({ required_error: 'Kelompok obat harus diisi' }).min(1, 'Kelompok obat harus diisi'),
medicineMethod_code: z.string({ required_error: 'Metode pemberian harus diisi' }).min(1, 'Metode pemberian harus diisi'),
uom_code: z.string({ required_error: 'Satuan harus diisi' }).min(1, 'Satuan harus diisi'),
infra_id: z.number().nullable().optional(),
stock: z.preprocess((val) => Number(val), z.number({ invalid_type_error: 'Stok harus berupa angka' }).min(1, 'Stok harus lebih besar dari 0')),
})
type MedicineBaseFormData = z.infer<typeof MedicineBaseSchema> & MedicineBase
export { MedicineBaseSchema }
export type { MedicineBaseFormData }
export type MedicineFormData = z.infer<typeof MedicineSchema>
+79
View File
@@ -0,0 +1,79 @@
import { xfetch } from '~/composables/useXfetch'
const mainUrl = '/api/v1/medicine'
export async function getMedicines(params: any = null) {
try {
let url = mainUrl
if (params && typeof params === 'object' && Object.keys(params).length > 0) {
const searchParams = new URLSearchParams()
for (const key in params) {
if (params[key] !== null && params[key] !== undefined && params[key] !== '') {
searchParams.append(key, params[key])
}
}
const queryString = searchParams.toString()
if (queryString) url += `?${queryString}`
}
const resp = await xfetch(url, 'GET')
const result: any = {}
result.success = resp.success
result.body = (resp.body as Record<string, any>) || {}
return result
} catch (error) {
console.error('Error fetching medicines:', error)
throw new Error('Failed to fetch medicines')
}
}
export async function getMedicineDetail(id: number | string) {
try {
const resp = await xfetch(`${mainUrl}/${id}`, 'GET')
const result: any = {}
result.success = resp.success
result.body = (resp.body as Record<string, any>) || {}
return result
} catch (error) {
console.error('Error fetching medicine detail:', error)
throw new Error('Failed to get medicine detail')
}
}
export async function postMedicine(record: any) {
try {
const resp = await xfetch(mainUrl, 'POST', record)
const result: any = {}
result.success = resp.success
result.body = (resp.body as Record<string, any>) || {}
return result
} catch (error) {
console.error('Error posting medicine:', error)
throw new Error('Failed to post medicine')
}
}
export async function patchMedicine(id: number | string, record: any) {
try {
const resp = await xfetch(`${mainUrl}/${id}`, 'PATCH', record)
const result: any = {}
result.success = resp.success
result.body = (resp.body as Record<string, any>) || {}
return result
} catch (error) {
console.error('Error patching medicine:', error)
throw new Error('Failed to patch medicine')
}
}
export async function removeMedicine(id: number | string) {
try {
const resp = await xfetch(`${mainUrl}/${id}`, 'DELETE')
const result: any = {}
result.success = resp.success
result.body = (resp.body as Record<string, any>) || {}
return result
} catch (error) {
console.error('Error deleting medicine:', error)
throw new Error('Failed to delete medicine')
}
}