feat(material): modify handlers and service of material

This commit is contained in:
riefive
2025-09-19 15:23:09 +07:00
parent 29b54b072c
commit 70378a69e9
11 changed files with 244 additions and 142 deletions
@@ -45,19 +45,16 @@ const resetForm = () => {
stock.value = 0
}
// Form submission handler
function onSubmitForm(values: any) {
const formData: MaterialFormData = {
name: values.name || '',
code: values.code || '',
uom_code: values.uom_code || '',
item_id: values.item_id || '',
stock: values.stock || 0,
}
emit('submit', formData, resetForm)
}
// Form cancel handler
function onCancelForm() {
emit('cancel', resetForm)
}
@@ -107,22 +104,6 @@ function onCancelForm() {
{{ 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
+38 -97
View File
@@ -7,15 +7,21 @@ 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'
// Services
import { getSourceMaterials } from "~/services/source-material.service"
import { getSourceUoms } from "~/services/source-uom.service"
// Handlers
import {
recId,
recAction,
recItem,
isFormEntryDialogOpen,
isRecordConfirmationOpen,
handleActionSave,
handleActionRemove,
handleCancelForm,
} from '~/handlers/material.handler'
const isFormEntryDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
// Services
import { getSourceMaterials, getSourceMaterialDetail } from '~/services/material.service'
import { getSourceUoms } from '~/services/uom.service'
const uoms = [
{ value: 'uom-1', label: 'Satuan 1' },
@@ -28,7 +34,14 @@ const items = [
{ value: 'item-3', label: 'Item 3' },
]
// Menggunakan composable untuk pagination
const getEquipmentDetail = async (id: number | string) => {
const result = await getSourceMaterialDetail(id)
if (result.success) {
recItem.value = result.data
isFormEntryDialogOpen.value = true
}
}
const {
data,
isLoading,
@@ -38,7 +51,7 @@ const {
handleSearch,
fetchData: getEquipmentList,
} = usePaginatedList({
fetchFn: getSourceMaterials,
fetchFn: getSourceMaterials as any,
entityName: 'equipment',
})
@@ -78,96 +91,14 @@ provide('table_data_loader', isLoading)
watch(recId, () => {
switch (recAction.value) {
case ActionEvents.showEdit:
// TODO: Handle edit action
// isFormEntryDialogOpen.value = true
getEquipmentDetail(recId.value)
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 getSourceUoms()
})
@@ -181,13 +112,23 @@ onMounted(async () => {
</div>
<Dialog v-model:open="isFormEntryDialogOpen" title="Tambah Perlengkapan" size="lg" prevent-outside>
<AppEquipmentEntryForm :schema="MaterialSchema" :uoms="uoms" :items="items" @back="onCancelForm"
@submit="onSubmitForm" />
<AppEquipmentEntryForm
:schema="MaterialSchema"
:uoms="uoms"
:items="items"
@submit="(values: MaterialFormData, resetForm: any) => handleActionSave(values, getEquipmentList, resetForm)"
@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)"
@cancel=""
>
<template #default="{ record }">
<div class="text-sm">
<p><strong>ID:</strong> {{ record?.id }}</p>
+80
View File
@@ -0,0 +1,80 @@
import { ref } from 'vue'
// Services
import { postSourceMaterial, putSourceMaterial, removeSourceMaterial } from '~/services/material.service'
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
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) {
let isSuccess = false
try {
const result = await postSourceMaterial(values)
if (result.success) {
isFormEntryDialogOpen.value = false
isSuccess = true
if (refresh) refresh()
}
} catch (error) {
console.warn('Error saving form:', error)
isSuccess = false
} finally {
if (isSuccess) {
setTimeout(() => {
reset()
}, 500)
}
}
}
export async function handleActionEdit(id: number | string, values: any, refresh: () => void, reset: () => void) {
let isSuccess = false
try {
const result = await putSourceMaterial(id, values)
if (result.success) {
isFormEntryDialogOpen.value = false
isSuccess = true
if (refresh) refresh()
}
} catch (error) {
console.warn('Error editing form:', error)
isSuccess = false
} finally {
if (isSuccess) {
setTimeout(() => {
reset()
}, 500)
}
}
}
export async function handleActionRemove(id: number | string, refresh: () => void) {
try {
const result = await removeSourceMaterial(id)
if (result.success) {
if (refresh) refresh()
}
} catch (error) {
console.error('Error deleting record:', error)
} finally {
onResetState()
}
}
export function handleCancelForm(reset: () => void) {
isFormEntryDialogOpen.value = false
setTimeout(() => {
reset()
}, 500)
}
export { recId, recAction, recItem, isFormEntryDialogOpen, isRecordConfirmationOpen }
-6
View File
@@ -1,6 +0,0 @@
export interface EquipmentMaterial {
code: string;
name: string;
uom_code: string;
stock: number;
}
+6
View File
@@ -0,0 +1,6 @@
export interface Material {
code: string
name: string
uom_code: string
stock: number
}
+4
View File
@@ -0,0 +1,4 @@
export interface Uom {
code: string
name: string
}
+2 -2
View File
@@ -1,5 +1,5 @@
import { z } from 'zod'
import type { EquipmentMaterial } from '~/models/equipment-material'
import type { Material } from '~/models/material'
const MaterialSchema = z.object({
code: z.string({ required_error: 'Kode harus diisi' }).min(1, 'Kode minimum 1 karakter'),
@@ -8,7 +8,7 @@ const MaterialSchema = z.object({
stock: z.preprocess((val) => Number(val), z.number({ invalid_type_error: 'Stok harus berupa angka' }).min(1, 'Stok harus lebih besar dari 0')),
})
type MaterialFormData = z.infer<typeof MaterialSchema> & EquipmentMaterial
type MaterialFormData = z.infer<typeof MaterialSchema> & Material
export { MaterialSchema }
export type { MaterialFormData }
+87
View File
@@ -0,0 +1,87 @@
import { xfetch } from '~/composables/useXfetch'
export async function getSourceMaterials(params: any = null) {
try {
let url = '/api/v1/material';
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;
if (resp.success) {
result.data = (resp.body as Record<string, any>).data;
}
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(`/api/v1/material/${id}`, 'GET');
const result: any = {}
result.success = resp.success
if (resp.success) {
result.data = (resp.body as Record<string, any>).data
}
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('/api/v1/material', 'POST', record);
const result: any = {}
result.success = resp.success
if (resp.success) {
result.data = (resp.body as Record<string, any>).data
}
return result
} catch (error) {
console.error('Error posting source material:', error)
throw new Error('Failed to post source material')
}
}
export async function putSourceMaterial(id: number | string, record: any) {
try {
const resp = await xfetch(`/api/v1/material/${id}`, 'PUT', record);
const result: any = {}
result.success = resp.success
if (resp.success) {
result.data = (resp.body as Record<string, any>).data
}
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(`/api/v1/material/${id}`, 'DELETE')
const result: any = {}
result.success = resp.success
if (resp.success) {
result.data = (resp.body as Record<string, any>).data
}
return result
} catch (error) {
console.error('Error deleting record:', error)
throw new Error('Failed to delete source material')
}
}
-9
View File
@@ -1,9 +0,0 @@
import { xfetch } from '~/composables/useXfetch'
export async function getSourceMaterials() {
const resp = await xfetch('/api/v1/material')
if (resp.success) {
return (resp.body as Record<string, any>).data
}
throw new Error('Failed to fetch source materials')
}
-9
View File
@@ -1,9 +0,0 @@
import { xfetch } from '~/composables/useXfetch'
export async function getSourceUoms() {
const resp = await xfetch('/api/v1/uom')
if (resp.success) {
return (resp.body as Record<string, any>).data
}
throw new Error('Failed to fetch source uoms')
}
+27
View File
@@ -0,0 +1,27 @@
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
if (resp.success) {
result.data = (resp.body as Record<string, any>).data
}
return result
} catch (error) {
console.error('Error fetching source uoms:', error)
throw new Error('Failed to fetch source uoms')
}
}