Merge pull request #89 from dikstub-rssa/fe-integrasi-device-material-65

Feat: Integrasi Device + Material
This commit is contained in:
Munawwirul Jamal
2025-09-25 16:54:18 +07:00
committed by GitHub
28 changed files with 1152 additions and 429 deletions
+67 -91
View File
@@ -3,30 +3,36 @@
import type z from 'zod'
import type { MaterialFormData } from '~/schemas/material'
// helpers
import { toTypedSchema } from '@vee-validate/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'
interface Props {
schema: z.ZodSchema<any>
uoms: any[]
items: any[]
values: any
isLoading?: boolean
isReadonly?: boolean
}
const isLoading = ref(false)
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: MaterialFormData, resetForm: () => void]
cancel: [resetForm: () => void]
}>()
const { handleSubmit, defineField, errors } = useForm({
const { defineField, errors, meta } = useForm({
validationSchema: toTypedSchema(props.schema),
initialValues: {
code: '',
name: '',
uom_code: '',
item_id: '',
stock: 0,
} as Partial<MaterialFormData>,
})
@@ -34,113 +40,83 @@ const { handleSubmit, defineField, errors } = useForm({
const [code, codeAttrs] = defineField('code')
const [name, nameAttrs] = defineField('name')
const [uom, uomAttrs] = defineField('uom_code')
const [item, itemAttrs] = defineField('item_id')
const [stock, stockAttrs] = defineField('stock')
// 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.uom_code !== undefined) uom.value = props.values.uom_code
if (props.values.stock !== undefined) stock.value = props.values.stock
}
const resetForm = () => {
code.value = ''
name.value = ''
uom.value = ''
item.value = ''
stock.value = 0
}
// Form submission handler
function onSubmitForm(values: any) {
function onSubmitForm() {
const formData: MaterialFormData = {
name: values.name || '',
code: values.code || '',
uom_code: values.uom_code || '',
item_id: values.item_id || '',
stock: values.stock || 0,
name: name.value || '',
code: code.value || '',
uom_code: uom.value || '',
stock: stock.value || 0,
}
emit('submit', formData, resetForm)
}
// Form cancel handler
function onCancelForm() {
emit('cancel', resetForm)
}
</script>
<template>
<form class="grid gap-2" @submit="handleSubmit(onSubmitForm)">
<div class="grid gap-2">
<label for="code">Kode</label>
<Input
id="code"
v-model="code"
v-bind="codeAttrs"
:disabled="isLoading"
:class="{ 'border-red-500': errors.code }"
/>
<span v-if="errors.code" class="text-sm text-red-500">
{{ errors.code }}
</span>
</div>
<div class="grid gap-2">
<label for="name">Nama</label>
<Input
id="name"
v-model="name"
v-bind="nameAttrs"
:disabled="isLoading"
:class="{ 'border-red-500': errors.name }"
/>
<span v-if="errors.name" class="text-sm text-red-500">
{{ errors.name }}
</span>
</div>
<div class="grid gap-2">
<label for="uom">Satuan</label>
<Select
id="uom"
v-model="uom"
icon-name="i-lucide-chevron-down"
placeholder="Pilih satuan"
v-bind="uomAttrs"
:items="uoms"
:disabled="isLoading"
:class="{ 'border-red-500': errors.uom_code }"
/>
<span v-if="errors.uom_code" class="text-sm text-red-500">
{{ errors.uom_code }}
</span>
</div>
<div class="grid gap-2">
<label for="item">Item</label>
<Select
id="item"
v-model="item"
icon-name="i-lucide-chevron-down"
placeholder="Pilih item"
v-bind="itemAttrs"
:items="items"
:disabled="isLoading"
:class="{ 'border-red-500': errors.item_id }"
/>
<span v-if="errors.item_id" class="text-sm text-red-500">
{{ errors.item_id }}
</span>
</div>
<div class="grid gap-2">
<label for="stock">Stok</label>
<Input
id="stock"
v-model="stock"
type="number"
v-bind="stockAttrs"
:disabled="isLoading"
:class="{ 'border-red-500': errors.stock }"
/>
<span v-if="errors.stock" class="text-sm text-red-500">
{{ errors.stock }}
</span>
</div>
<form id="form-equipment">
<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" />
</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>
<Cell>
<Label height="compact">Satuan</Label>
<Field :errMessage="errors.uom_code">
<Select
id="uom"
v-model="uom"
icon-name="i-lucide-chevron-down"
placeholder="Pilih satuan"
v-bind="uomAttrs"
:items="uoms"
:disabled="isLoading || isReadonly"
/>
</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" />
</Field>
</Cell>
</Block>
<div class="my-2 flex justify-end gap-2 py-2">
<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" />
<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>
+6 -14
View File
@@ -1,21 +1,17 @@
import type {
Col,
KeyLabel,
RecComponent,
RecStrFuncComponent,
Th,
} from '~/components/pub/custom-ui/data/types'
import type { Col, KeyLabel, RecComponent, RecStrFuncComponent, 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-dud.vue'))
export const cols: Col[] = [{ width: 100 }, { width: 250 }, { width: 100 }, { width: 100 }, { width: 100 }, { width: 50 }]
export const cols: Col[] = [{ width: 100 }, { width: 250 }, { width: 100 }, { width: 100 }, { width: 50 }]
export const header: Th[][] = [[{ label: 'Kode' }, { label: 'Nama' }, { label: 'Stok' }, { label: 'Item' }, { label: 'Satuan' }]]
export const header: Th[][] = [
[{ label: 'Kode' }, { label: 'Nama' }, { label: 'Stok' }, { label: 'Satuan' }, { label: '' }],
]
export const keys = ['code', 'name', 'stock', 'item_id', 'uom_code', 'action']
export const keys = ['code', 'name', 'stock', 'uom_code', 'action']
export const delKeyNames: KeyLabel[] = [
{ key: 'code', label: 'Kode' },
@@ -27,10 +23,6 @@ export const funcParsed: Record<string, (row: any, ...args: any[]) => any> = {
const recX = rec as SmallDetailDto
return `${recX.name}`.trim()
},
item_id: (rec: unknown): unknown => {
const recX = rec as SmallDetailDto
return recX.item_id
},
uom_code: (rec: unknown): unknown => {
const recX = rec as SmallDetailDto
return recX.uom_code
+58 -71
View File
@@ -5,21 +5,29 @@ import { useForm } from 'vee-validate'
// types
import type z from 'zod'
import type { DeviceFormData } from '~/schemas/device'
// 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'
interface Props {
schema: z.ZodSchema<any>
uoms: any[]
items: any[]
values: any
isLoading?: boolean
isReadonly?: boolean
}
const isLoading = ref(false)
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: DeviceFormData, resetForm: () => void]
cancel: [resetForm: () => void]
}>()
const { handleSubmit, defineField, errors } = useForm({
const { defineField, errors, meta } = useForm({
validationSchema: toTypedSchema(props.schema),
initialValues: {
code: '',
@@ -32,22 +40,26 @@ const { handleSubmit, defineField, errors } = useForm({
const [code, codeAttrs] = defineField('code')
const [name, nameAttrs] = defineField('name')
const [uom, uomAttrs] = defineField('uom_code')
const [item, itemAttrs] = defineField('item_id')
// 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.uom_code !== undefined) uom.value = props.values.uom_code
}
const resetForm = () => {
code.value = ''
name.value = ''
uom.value = ''
item.value = ''
}
// Form submission handler
function onSubmitForm(values: any) {
const formData: DeviceFormData = {
name: values.name || '',
code: values.code || '',
uom_code: values.uom_code || '',
item_id: values.item_id || '',
name: name.value || '',
code: code.value || '',
uom_code: uom.value || '',
}
emit('submit', formData, resetForm)
}
@@ -59,69 +71,44 @@ function onCancelForm() {
</script>
<template>
<form class="grid gap-2" @submit="handleSubmit(onSubmitForm)">
<div class="grid gap-2">
<label for="code">Kode</label>
<Input
id="code"
v-model="code"
v-bind="codeAttrs"
:disabled="isLoading"
:class="{ 'border-red-500': errors.code }"
/>
<span v-if="errors.code" class="text-sm text-red-500">
{{ errors.code }}
</span>
</div>
<div class="grid gap-2">
<label for="name">Nama</label>
<Input
id="name"
v-model="name"
v-bind="nameAttrs"
:disabled="isLoading"
:class="{ 'border-red-500': errors.name }"
/>
<span v-if="errors.name" class="text-sm text-red-500">
{{ errors.name }}
</span>
</div>
<div class="grid gap-2">
<label for="uom">Satuan</label>
<Select
id="uom"
icon-name="i-lucide-chevron-down"
placeholder="Pilih satuan"
v-model="uom"
v-bind="uomAttrs"
:items="uoms"
:disabled="isLoading"
:class="{ 'border-red-500': errors.uom_code }"
/>
<span v-if="errors.uom_code" class="text-sm text-red-500">
{{ errors.uom_code }}
</span>
</div>
<div class="grid gap-2">
<label for="item">Item</label>
<Select
id="item"
icon-name="i-lucide-chevron-down"
placeholder="Pilih item"
v-model="item"
v-bind="itemAttrs"
:items="items"
:disabled="isLoading"
:class="{ 'border-red-500': errors.item_id }"
/>
<span v-if="errors.item_id" class="text-sm text-red-500">
{{ errors.item_id }}
</span>
</div>
<form id="form-tools">
<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>
<Cell>
<Label height="compact">Satuan</Label>
<Field :errMessage="errors.uom_code">
<Select
id="uom"
icon-name="i-lucide-chevron-down"
placeholder="Pilih satuan"
v-model="uom"
v-bind="uomAttrs"
:items="uoms"
:disabled="isLoading || isReadonly"
/>
</Field>
</Cell>
</Block>
<div class="my-2 flex justify-end gap-2 py-2">
<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" />
<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>
+3 -7
View File
@@ -12,11 +12,11 @@ type SmallDetailDto = any
const action = defineAsyncComponent(() => import('~/components/pub/custom-ui/data/dropdown-action-dud.vue'))
export const cols: Col[] = [{ width: 100 }, { width: 250 }, { width: 100 }, { width: 100 }, { width: 50 }]
export const cols: Col[] = [{ width: 100 }, { width: 250 }, { width: 100 }, { width: 50 }]
export const header: Th[][] = [[{ label: 'Kode' }, { label: 'Nama' }, { label: 'Item' }, { label: 'Satuan' }]]
export const header: Th[][] = [[{ label: 'Kode' }, { label: 'Nama' }, { label: 'Satuan' }, { label: '' }]]
export const keys = ['code', 'name', 'item_id', 'uom_code', 'action']
export const keys = ['code', 'name', 'uom_code', 'action']
export const delKeyNames: KeyLabel[] = [
{ key: 'code', label: 'Kode' },
@@ -28,10 +28,6 @@ export const funcParsed: Record<string, (row: any, ...args: any[]) => any> = {
const recX = rec as SmallDetailDto
return `${recX.name}`.trim()
},
item_id: (rec: unknown): unknown => {
const recX = rec as SmallDetailDto
return recX.item_id
},
uom_code: (rec: unknown): unknown => {
const recX = rec as SmallDetailDto
return recX.uom_code
+2 -2
View File
@@ -2,8 +2,8 @@
import { z } from 'zod'
const loginSchema = z.object({
name: z.string().min(6, 'Please enter a valid username'),
password: z.string().min(6, 'Password must be at least 6 characters'),
name: z.string().min(3, 'Please enter a valid username'),
password: z.string().min(3, 'Password must be at least 3 characters'),
})
const { login } = useUserStore()
+93 -111
View File
@@ -7,30 +7,51 @@ 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)
// helpers
import { toast } from '~/components/pub/ui/toast'
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' },
]
// Types
import type { Uom } from '~/models/uom'
// Fungsi untuk fetch data equipment
async function fetchEquipmentData(params: any) {
const endpoint = transform('/api/v1/equipment', params)
return await xfetch(endpoint)
// Handlers
import {
recId,
recAction,
recItem,
isReadonly,
isProcessing,
isFormEntryDialogOpen,
isRecordConfirmationOpen,
handleActionSave,
handleActionEdit,
handleActionRemove,
handleCancelForm,
} from '~/handlers/material.handler'
// Services
import { getSourceMaterials, getSourceMaterialDetail } from '~/services/material.service'
import { getSourceUoms } from '~/services/uom.service'
const uoms = ref<{ value: string; label: string }[]>([])
const title = ref('')
const getEquipmentDetail = async (id: number | string) => {
const result = await getSourceMaterialDetail(id)
if (result.success) {
const currentMaterial = result.body?.data || {}
recItem.value = currentMaterial
isFormEntryDialogOpen.value = true
}
}
const getUomList = async () => {
const result = await getSourceUoms()
if (result.success) {
const currentUoms = result.body?.data || []
uoms.value = currentUoms.map((uom: Uom) => ({ value: uom.code || uom.erp_id, label: uom.name }))
}
}
// Menggunakan composable untuk pagination
const {
data,
isLoading,
@@ -40,7 +61,10 @@ const {
handleSearch,
fetchData: getEquipmentList,
} = usePaginatedList({
fetchFn: fetchEquipmentData,
fetchFn: async ({ page }) => {
const result = await getSourceMaterials({ search: searchInput.value, page })
return { success: result.success || false, body: result.body || {} }
},
entityName: 'equipment',
})
@@ -66,7 +90,10 @@ const headerPrep: HeaderPrep = {
label: 'Tambah Perlengkapan',
icon: 'i-lucide-plus',
onClick: () => {
recItem.value = null
recId.value = 0
isFormEntryDialogOpen.value = true
isReadonly.value = false
},
},
}
@@ -76,116 +103,71 @@ provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)
// Watch for row actions
watch(recId, () => {
// Watch for row actions when recId or recAction changes
watch([recId, recAction], () => {
switch (recAction.value) {
case ActionEvents.showDetail:
getEquipmentDetail(recId.value)
title.value = 'Detail Perlengkapan'
isReadonly.value = true
break
case ActionEvents.showEdit:
// TODO: Handle edit action
// isFormEntryDialogOpen.value = true
getEquipmentDetail(recId.value)
title.value = 'Edit Perlengkapan'
isReadonly.value = false
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
}
onMounted(async () => {
await getUomList()
await getEquipmentList()
})
</script>
<template>
<div class="rounded-md border p-4">
<div class="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
v-model:open="isFormEntryDialogOpen"
:title="!!recItem ? title : 'Tambah Perlengkapan'"
size="lg"
prevent-outside
>
<AppEquipmentEntryForm
:schema="MaterialSchema"
:values="recItem"
:uoms="uoms"
:is-loading="isProcessing"
:is-readonly="isReadonly"
@submit="
(values: MaterialFormData, resetForm: any) => {
if (recId > 0) {
handleActionEdit(recId, values, getEquipmentList, resetForm, toast)
return
}
handleActionSave(values, getEquipmentList, resetForm, toast)
}
"
@cancel="handleCancelForm"
/>
</Dialog>
<!-- Record Confirmation Modal -->
<RecordConfirmation v-model:open="isRecordConfirmationOpen" action="delete" :record="recItem"
@confirm="handleConfirmDelete" @cancel="handleCancelConfirmation">
<RecordConfirmation
v-model:open="isRecordConfirmationOpen"
action="delete"
:record="recItem"
@confirm="() => handleActionRemove(recId, getEquipmentList, toast)"
@cancel=""
>
<template #default="{ record }">
<div class="text-sm">
<p><strong>ID:</strong> {{ record?.id }}</p>
+90 -110
View File
@@ -4,32 +4,53 @@ 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 AppToolsEntryForm from '~/components/app/tools/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)
// helpers
import { toast } from '~/components/pub/ui/toast'
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' },
]
// Types
import type { Uom } from '~/models/uom'
async function fetchDeviceData(params: any) {
const endpoint = transform('/api/v1/device', params)
return await xfetch(endpoint)
// Handlers
import {
recId,
recAction,
recItem,
isReadonly,
isProcessing,
isFormEntryDialogOpen,
isRecordConfirmationOpen,
handleActionSave,
handleActionEdit,
handleActionRemove,
handleCancelForm,
} from '~/handlers/device.handler'
// Services
import { getSourceDevices, getSourceDeviceDetail } from '~/services/device.service'
import { getSourceUoms } from '~/services/uom.service'
const uoms = ref<{ value: string; label: string }[]>([])
const title = ref('')
const getToolsDetail = async (id: number | string) => {
const result = await getSourceDeviceDetail(id)
if (result.success) {
const currentDevice = result.body?.data || {}
recItem.value = currentDevice
}
}
const getUomList = async () => {
const result = await getSourceUoms()
if (result.success) {
const currentUoms = result.body?.data || []
uoms.value = currentUoms.map((uom: Uom) => ({ value: uom.code || uom.erp_id, label: uom.name }))
}
}
// Menggunakan composable untuk pagination
const {
data,
isLoading,
@@ -37,9 +58,12 @@ const {
searchInput,
handlePageChange,
handleSearch,
fetchData: getDeviceList,
fetchData: getToolsList,
} = usePaginatedList({
fetchFn: fetchDeviceData,
fetchFn: async ({ page }) => {
const result = await getSourceDevices({ search: searchInput.value, page })
return { success: result.success || false, body: result.body || {} }
},
entityName: 'device',
})
@@ -65,7 +89,10 @@ const headerPrep: HeaderPrep = {
label: 'Tambah Peralatan',
icon: 'i-lucide-plus',
onClick: () => {
recItem.value = null
recId.value = 0
isFormEntryDialogOpen.value = true
isReadonly.value = false
},
},
}
@@ -76,109 +103,62 @@ provide('rec_item', recItem)
provide('table_data_loader', isLoading)
// Watch for row actions
watch(recId, () => {
watch([recId, recAction], () => {
switch (recAction.value) {
case ActionEvents.showDetail:
getToolsDetail(recId.value)
title.value = 'Detail Peralatan'
isReadonly.value = true
isFormEntryDialogOpen.value = true
break
case ActionEvents.showEdit:
// TODO: Handle edit action
// isFormEntryDialogOpen.value = true
getToolsDetail(recId.value)
title.value = 'Edit Peralatan'
isReadonly.value = false
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/device/${record.id}`, {
// method: 'DELETE'
// })
// Refresh data setelah berhasil delete
await getDeviceList()
// 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 getDeviceList()
// TODO: Show success message
console.log('Device 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
}
onMounted(async () => {
await getUomList()
await getToolsList()
})
</script>
<template>
<div class="rounded-md border p-4">
<div class="p-4">
<Header v-model="searchInput" :prep="headerPrep" @search="handleSearch" />
<div class="rounded-md border p-4">
<AppToolsList :data="data" :pagination-meta="paginationMeta" @page-change="handlePageChange" />
</div>
<Dialog v-model:open="isFormEntryDialogOpen" title="Tambah Peralatan" size="lg" prevent-outside>
<AppToolsEntryForm :schema="DeviceSchema" :uoms="uoms" :items="items" @back="onCancelForm" @submit="onSubmitForm" />
<Dialog
v-model:open="isFormEntryDialogOpen"
:title="!!recItem ? title : 'Tambah Peralatan'"
size="lg"
prevent-outside
>
<AppToolsEntryForm
:schema="DeviceSchema"
:values="recItem"
:uoms="uoms"
:is-loading="isProcessing"
:is-readonly="isReadonly"
@submit="
(values: DeviceFormData, resetForm: any) => {
if (recId > 0) {
handleActionEdit(recId, values, getToolsList, resetForm, toast)
return
}
handleActionSave(values, getToolsList, resetForm, toast)
}
"
@cancel="handleCancelForm"
/>
</Dialog>
<!-- Record Confirmation Modal -->
@@ -186,8 +166,8 @@ const handleCancelConfirmation = () => {
v-model:open="isRecordConfirmationOpen"
action="delete"
:record="recItem"
@confirm="handleConfirmDelete"
@cancel="handleCancelConfirmation"
@confirm="() => handleActionRemove(recId, getToolsList, toast)"
@cancel=""
>
<template #default="{ record }">
<div class="text-sm">
@@ -9,6 +9,6 @@ const props = defineProps({
<template>
<div :class="`${props.defaultClass} ${props.class}`">
<slot />
<div v-if="props.errMessage" class="text-red-500">{{ props.errMessage }}</div>
<div v-if="props.errMessage" class="mt-1 text-xs font-medium text-red-500">{{ props.errMessage }}</div>
</div>
</template>
+42
View File
@@ -0,0 +1,42 @@
// Reusable async handler for CRUD actions with toast and state management
export type ToastFn = (params: { title: string; description: string; variant: 'default' | 'destructive' }) => void
export interface HandleAsyncActionOptions<T extends any[], R> {
action: (...args: T) => Promise<R & { success: boolean }>
args?: T
toast: ToastFn
successMessage: string
errorMessage: string
onSuccess?: (result: R) => void
onError?: (error: unknown) => void
onFinally?: (isSuccess: boolean) => void
}
export async function handleAsyncAction<T extends any[], R>({
action,
args = [] as unknown as T,
toast,
successMessage,
errorMessage,
onSuccess,
onError,
onFinally,
}: HandleAsyncActionOptions<T, R>) {
let isSuccess = false
try {
const result = await action(...args)
if (result.success) {
toast({ title: 'Berhasil', description: successMessage, variant: 'default' })
isSuccess = true
if (onSuccess) onSuccess(result)
} else {
toast({ title: 'Gagal', description: errorMessage, variant: 'destructive' })
if (onError) onError(result)
}
} catch (error) {
toast({ title: 'Gagal', description: errorMessage, variant: 'destructive' })
if (onError) onError(error)
} finally {
if (onFinally) onFinally(isSuccess)
}
}
+101
View File
@@ -0,0 +1,101 @@
import { ref } from 'vue'
// Handlers
import { type ToastFn, handleAsyncAction } from '~/handlers/_handler'
// Services
import { postSourceDevice, patchSourceDevice, removeSourceDevice } from '~/services/device.service'
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
const isReadonly = ref(false)
const isProcessing = ref(false)
const isFormEntryDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)
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: postSourceDevice,
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: patchSourceDevice,
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: removeSourceDevice,
args: [id],
toast,
successMessage: 'Data berhasil dihapus',
errorMessage: 'Gagal menghapus data',
onSuccess: () => {
if (refresh) refresh();
},
onFinally: () => {
onResetState();
isProcessing.value = false;
},
});
}
export function handleCancelForm(reset: () => void) {
isFormEntryDialogOpen.value = false
setTimeout(() => {
reset()
}, 500)
}
export { recId, recAction, recItem, isReadonly, isProcessing, isFormEntryDialogOpen, isRecordConfirmationOpen }
+92
View File
@@ -0,0 +1,92 @@
import { ref } from 'vue'
// Handlers
import { type ToastFn, handleAsyncAction } from '~/handlers/_handler'
// Services
import { postSourceMaterial, patchSourceMaterial, removeSourceMaterial } from '~/services/material.service'
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
const isReadonly = ref(false)
const isProcessing = ref(false)
const isFormEntryDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)
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: postSourceMaterial,
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: patchSourceMaterial,
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: removeSourceMaterial,
args: [id],
toast,
successMessage: 'Data berhasil dihapus',
errorMessage: 'Gagal menghapus data',
onSuccess: () => {
if (refresh) refresh()
},
onFinally: () => {
onResetState()
isProcessing.value = false
},
})
}
export function handleCancelForm(reset: () => void) {
isFormEntryDialogOpen.value = false
setTimeout(() => {
reset()
}, 500)
}
export { recId, recAction, recItem, isReadonly, isProcessing, isFormEntryDialogOpen, isRecordConfirmationOpen }
+101
View File
@@ -0,0 +1,101 @@
import { ref } from 'vue'
// Handlers
import { type ToastFn, handleAsyncAction } from '~/handlers/_handler'
// Services
import { postMedicineGroup, patchMedicineGroup, removeMedicineGroup } from '~/services/medicine-group.service'
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
const isReadonly = ref(false)
const isProcessing = ref(false)
const isFormEntryDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)
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: postMedicineGroup,
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: patchMedicineGroup,
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: removeMedicineGroup,
args: [id],
toast,
successMessage: 'Data berhasil dihapus',
errorMessage: 'Gagal menghapus data',
onSuccess: () => {
if (refresh) refresh();
},
onFinally: () => {
onResetState();
isProcessing.value = false;
},
});
}
export function handleCancelForm(reset: () => void) {
isFormEntryDialogOpen.value = false
setTimeout(() => {
reset()
}, 500)
}
export { recId, recAction, recItem, isReadonly, isProcessing, isFormEntryDialogOpen, isRecordConfirmationOpen }
+101
View File
@@ -0,0 +1,101 @@
import { ref } from 'vue'
// Handlers
import { type ToastFn, handleAsyncAction } from '~/handlers/_handler'
// Services
import { postMedicineMethod, patchMedicineMethod, removeMedicineMethod } from '~/services/medicine-method.service'
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
const isReadonly = ref(false)
const isProcessing = ref(false)
const isFormEntryDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)
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: postMedicineMethod,
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: patchMedicineMethod,
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: removeMedicineMethod,
args: [id],
toast,
successMessage: 'Data berhasil dihapus',
errorMessage: 'Gagal menghapus data',
onSuccess: () => {
if (refresh) refresh();
},
onFinally: () => {
onResetState();
isProcessing.value = false;
},
});
}
export function handleCancelForm(reset: () => void) {
isFormEntryDialogOpen.value = false
setTimeout(() => {
reset()
}, 500)
}
export { recId, recAction, recItem, isReadonly, isProcessing, isFormEntryDialogOpen, isRecordConfirmationOpen }
+15
View File
@@ -0,0 +1,15 @@
// Default item meta model for entities
export interface ItemMeta {
id: number;
createdAt: string | null;
deletedAt: string | null;
updatedAt: string | null;
}
// Pagination meta model for API responses
export interface PaginationMeta {
page_number: string;
page_size: string;
record_totalCount: string;
source: string;
}
+5
View File
@@ -0,0 +1,5 @@
export interface Device {
code: string
name: string
uom_code: string
}
+6
View File
@@ -0,0 +1,6 @@
export interface Material {
code: string
name: string
uom_code: string
stock: number
}
+5
View File
@@ -0,0 +1,5 @@
export interface Uom {
code: string
name: string
erp_id: string
}
+5 -5
View File
@@ -1,13 +1,13 @@
import { z } from 'zod'
import type { Device } from '~/models/device'
const schema = z.object({
const DeviceSchema = 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'),
uom_code: z.string({ required_error: 'Kode unit harus diisi' }).min(1, 'Kode unit harus diisi'),
item_id: z.string({ required_error: 'Tipe harus diisi' }).min(1, 'Tipe harus diisi'),
})
type formData = z.infer<typeof schema>
type DeviceFormData = z.infer<typeof DeviceSchema> & Device
export { schema as DeviceSchema }
export type { formData as DeviceFormData }
export { DeviceSchema }
export type { DeviceFormData }
+5 -5
View File
@@ -1,14 +1,14 @@
import { z } from 'zod'
import type { Material } from '~/models/material'
const schema = z.object({
const MaterialSchema = 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'),
uom_code: z.string({ required_error: 'Kode unit harus diisi' }).min(1, 'Kode unit harus diisi'),
item_id: z.string({ required_error: 'Tipe harus diisi' }).min(1, 'Tipe harus diisi'),
stock: z.preprocess((val) => Number(val), z.number({ invalid_type_error: 'Stok harus berupa angka' }).min(1, 'Stok harus lebih besar dari 0')),
})
type formData = z.infer<typeof schema>
type MaterialFormData = z.infer<typeof MaterialSchema> & Material
export { schema as MaterialSchema }
export type { formData as MaterialFormData }
export { MaterialSchema }
export type { MaterialFormData }
+79
View File
@@ -0,0 +1,79 @@
import { xfetch } from '~/composables/useXfetch'
const mainUrl = '/api/v1/device'
export async function getSourceDevices(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 source devices:', error)
throw new Error('Failed to fetch source devices')
}
}
export async function getSourceDeviceDetail(id: string | number) {
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 device detail:', error)
throw new Error('Failed to fetch device detail')
}
}
export async function postSourceDevice(data: any) {
try {
const resp = await xfetch(mainUrl, 'POST', data)
const result: any = {}
result.success = resp.success
result.body = (resp.body as Record<string, any>) || {}
return result
} catch (error) {
console.error('Error creating device:', error)
throw new Error('Failed to create device')
}
}
export async function patchSourceDevice(id: string | number, data: any) {
try {
const resp = await xfetch(`${mainUrl}/${id}`, 'PATCH', data)
const result: any = {}
result.success = resp.success
result.body = (resp.body as Record<string, any>) || {}
return result
} catch (error) {
console.error('Error updating device:', error)
throw new Error('Failed to update device')
}
}
export async function removeSourceDevice(id: string | number) {
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 device:', error)
throw new Error('Failed to delete device')
}
}
+79
View File
@@ -0,0 +1,79 @@
import { xfetch } from '~/composables/useXfetch'
const mainUrl = '/api/v1/material'
export async function getSourceMaterials(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 source materials:', error)
throw new Error('Failed to fetch source materials')
}
}
export async function getSourceMaterialDetail(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 source material detail:', error)
throw new Error('Failed to get source material detail')
}
}
export async function postSourceMaterial(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 source material:', error)
throw new Error('Failed to post source material')
}
}
export async function patchSourceMaterial(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 putting source material:', error)
throw new Error('Failed to put source material')
}
}
export async function removeSourceMaterial(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 record:', error)
throw new Error('Failed to delete source material')
}
}
+79
View File
@@ -0,0 +1,79 @@
import { xfetch } from '~/composables/useXfetch'
const mainUrl = '/api/v1/medicine-group'
export async function getMedicineGroups(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(mainUrl, 'GET')
const result: any = {}
result.success = resp.success
result.body = (resp.body as Record<string, any>) || {}
return result
} catch (error) {
console.error('Error fetching source materials:', error)
throw new Error('Failed to fetch source materials')
}
}
export async function getMedicineGroupDetail(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 source material detail:', error)
throw new Error('Failed to get source material detail')
}
}
export async function postMedicineGroup(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 source material:', error)
throw new Error('Failed to post source material')
}
}
export async function patchMedicineGroup(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 putting source material:', error)
throw new Error('Failed to put source material')
}
}
export async function removeMedicineGroup(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 record:', error)
throw new Error('Failed to delete source material')
}
}
+79 -1
View File
@@ -1,9 +1,87 @@
import { xfetch } from '~/composables/useXfetch'
export async function getMedicineMethods() {
const mainUrl = '/api/v1/medicine-method'
export async function getMedicineMethodsPrev() {
const resp = await xfetch('/api/v1/medicine-method')
if (resp.success) {
return (resp.body as Record<string, any>).data
}
throw new Error('Failed to fetch medicine methods')
}
export async function getMedicineMethods(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(mainUrl, 'GET')
const result: any = {}
result.success = resp.success
result.body = (resp.body as Record<string, any>) || {}
return result
} catch (error) {
console.error('Error fetching source materials:', error)
throw new Error('Failed to fetch source materials')
}
}
export async function getMedicineMethodDetail(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 source material detail:', error)
throw new Error('Failed to get source material detail')
}
}
export async function postMedicineMethod(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 source material:', error)
throw new Error('Failed to post source material')
}
}
export async function patchMedicineMethod(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 putting source material:', error)
throw new Error('Failed to put source material')
}
}
export async function removeMedicineMethod(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 record:', error)
throw new Error('Failed to delete source material')
}
}
+25
View File
@@ -0,0 +1,25 @@
import { xfetch } from '~/composables/useXfetch'
export async function getSourceUoms(params: any = null) {
try {
let url = '/api/v1/uom'
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 source uoms:', error)
throw new Error('Failed to fetch source uoms')
}
}
+5 -1
View File
@@ -1,10 +1,14 @@
import process from 'node:process'
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
devtools: { enabled: true },
runtimeConfig: {
API_ORIGIN: process.env.API_ORIGIN || 'https://main-api.dev-hopis.sabbi.id',
API_ORIGIN: process.env.NUXT_API_ORIGIN || 'https://main-api.dev-hopis.sabbi.id',
public: {
API_ORIGIN: process.env.NUXT_API_ORIGIN || 'https://main-api.dev-hopis.sabbi.id',
}
},
ssr: false,
+3 -3
View File
@@ -5285,7 +5285,7 @@ packages:
chokidar: 4.0.3
confbox: 0.2.2
defu: 6.1.4
dotenv: 17.2.1
dotenv: 17.2.2
exsolve: 1.0.7
giget: 2.0.0
jiti: 2.5.1
@@ -6440,8 +6440,8 @@ packages:
engines: {node: '>=12'}
dev: true
/dotenv@17.2.1:
resolution: {integrity: sha512-kQhDYKZecqnM0fCnzI5eIv5L4cAe/iRI+HqMbO/hbRdTAeXDG+M9FjipUxNfbARuEg4iHIbhnhs78BCHNbSxEQ==}
/dotenv@17.2.2:
resolution: {integrity: sha512-Sf2LSQP+bOlhKWWyhFsn0UsfdK/kCWRv1iuA2gXAwt3dyNabr6QSj00I2V10pidqz69soatm9ZwZvpQMTIOd5Q==}
engines: {node: '>=12'}
/dunder-proto@1.0.1:
+4 -4
View File
@@ -1,15 +1,15 @@
import process from 'node:process'
import { defineEventHandler, getCookie, getRequestHeaders, getRequestURL, readBody } from 'h3'
const API_ORIGIN = process.env.API_ORIGIN as string
export default defineEventHandler(async (event) => {
const { method } = event.node.req
const headers = getRequestHeaders(event)
const url = getRequestURL(event)
const config = useRuntimeConfig()
const apiOrigin = config.public.API_ORIGIN
const pathname = url.pathname.replace(/^\/api/, '')
const targetUrl = API_ORIGIN + pathname + (url.search || '')
const targetUrl = apiOrigin + pathname + (url.search || '')
const verificationId = headers['verification-id'] as string | undefined
let bearer = ''
+1 -3
View File
@@ -1,4 +1,3 @@
import { useRuntimeConfig } from '#imports'
import { getRequestURL, readBody, setCookie } from 'h3'
export default defineEventHandler(async (event) => {
@@ -6,8 +5,7 @@ export default defineEventHandler(async (event) => {
const url = getRequestURL(event)
const config = useRuntimeConfig()
const apiOrigin = config.API_ORIGIN
const apiOrigin = config.public.API_ORIGIN
const externalUrl = apiOrigin + url.pathname.replace(/^\/api/, '') + url.search
const resp = await fetch(externalUrl, {