2025-09-13 03:03:08 +07:00

933 lines
32 KiB
TypeScript

'use client'
import React, { useState, useMemo } from 'react'
import {
Card,
CardContent,
Button,
Box,
Typography,
IconButton,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper,
CircularProgress,
Alert,
Popover,
Divider
} from '@mui/material'
import Grid from '@mui/material/Grid2'
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
import CustomTextField from '@/@core/components/mui/TextField'
import ImageUpload from '@/components/ImageUpload'
import { DropdownOption } from '@/types/apps/purchaseOrderTypes'
import { useVendorActive } from '@/services/queries/vendor'
import { useIngredients } from '@/services/queries/ingredients'
import { useUnits } from '@/services/queries/units'
import { useFilesMutation } from '@/services/mutations/files'
import { usePurchaseOrdersMutation } from '@/services/mutations/purchaseOrder'
import { PurchaseOrderFormData, PurchaseOrderFormItem, PurchaseOrderRequest } from '@/types/services/purchaseOrder'
import { IngredientItem } from '@/types/services/ingredient'
export type Unit = {
id: string
name: string
}
interface ValidationErrors {
vendor?: string
po_number?: string
transaction_date?: string
due_date?: string
items?: string
general?: string
}
interface PopoverState {
isOpen: boolean
anchorEl: HTMLElement | null
itemIndex: number | null
}
// Komponen PricePopover
const PricePopover: React.FC<{
anchorEl: HTMLElement | null
open: boolean
onClose: () => void
ingredientData: any
}> = ({ anchorEl, open, onClose, ingredientData }) => {
if (!ingredientData) return null
const lastPrice = ingredientData.originalData?.cost || 0
return (
<Popover
open={open}
anchorEl={anchorEl}
onClose={onClose}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left'
}}
transformOrigin={{
vertical: 'top',
horizontal: 'left'
}}
PaperProps={{
sx: {
minWidth: 300,
maxWidth: 350,
boxShadow: '0 8px 32px rgba(0,0,0,0.12)',
borderRadius: 2
}
}}
>
<Box sx={{ p: 2 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
<Typography variant='body2' color='text.secondary'>
Harga beli terakhir
</Typography>
<Typography variant='h6' color='primary' fontWeight={600}>
{new Intl.NumberFormat('id-ID').format(lastPrice)}
</Typography>
</Box>
<Divider sx={{ mb: 2 }} />
<Button
variant='text'
size='small'
sx={{
color: 'primary.main',
textTransform: 'none',
p: 0,
minWidth: 'auto'
}}
onClick={() => {
console.log('Navigate to purchase history')
onClose()
}}
>
Riwayat harga beli
</Button>
</Box>
</Popover>
)
}
const PurchaseAddForm: React.FC = () => {
const [imageUrl, setImageUrl] = useState<string>('')
const [errors, setErrors] = useState<ValidationErrors>({})
const [popoverState, setPopoverState] = useState<PopoverState>({
isOpen: false,
anchorEl: null,
itemIndex: null
})
const [formData, setFormData] = useState<PurchaseOrderFormData>({
vendor: null,
po_number: '',
transaction_date: '',
due_date: '',
reference: '',
status: 'sent',
showPesan: false,
showAttachment: false,
message: '',
items: [
{
id: 1,
ingredient: null,
description: '',
quantity: 1,
unit: null,
amount: 0,
total: 0
}
],
attachment_file_ids: []
})
// API Hooks
const { data: vendors, isLoading: isLoadingVendors } = useVendorActive()
const { data: ingredients, isLoading: isLoadingIngredients } = useIngredients()
const { data: units, isLoading: isLoadingUnits } = useUnits({
page: 1,
limit: 50
})
const { mutate, isPending } = useFilesMutation().uploadFile
const { createPurchaseOrder } = usePurchaseOrdersMutation()
// Transform vendors data to dropdown options
const vendorOptions: DropdownOption[] = useMemo(() => {
return (
vendors?.map(vendor => ({
label: vendor.name,
value: vendor.id
})) || []
)
}, [vendors])
// Transform ingredients data to autocomplete options format
const ingredientOptions = useMemo(() => {
if (!ingredients || isLoadingIngredients) {
return []
}
return ingredients?.data.map((ingredient: IngredientItem) => ({
label: ingredient.name,
value: ingredient.id,
id: ingredient.id,
originalData: ingredient
}))
}, [ingredients, isLoadingIngredients])
// Transform units data to dropdown options
const unitOptions = useMemo(() => {
if (!units || isLoadingUnits) {
return []
}
return (
units?.data?.map((unit: any) => ({
label: unit.name || unit.nama || unit.unit_name,
value: unit.id || unit.code || unit.value
})) || []
)
}, [units, isLoadingUnits])
// Handle price field click untuk menampilkan popover
const handlePriceFieldClick = (event: React.MouseEvent<HTMLElement>, itemIndex: number) => {
const item = formData.items[itemIndex]
if (item.ingredient) {
setPopoverState({
isOpen: true,
anchorEl: event.currentTarget,
itemIndex: itemIndex
})
}
}
// Close popover
const handleClosePopover = () => {
setPopoverState({
isOpen: false,
anchorEl: null,
itemIndex: null
})
}
// Fungsi validasi
const validateForm = (): boolean => {
const newErrors: ValidationErrors = {}
if (!formData.vendor || !formData.vendor.value) {
newErrors.vendor = 'Vendor wajib dipilih'
}
if (!formData.po_number.trim()) {
newErrors.po_number = 'Nomor PO wajib diisi'
}
if (!formData.transaction_date) {
newErrors.transaction_date = 'Tanggal transaksi wajib diisi'
}
if (!formData.due_date) {
newErrors.due_date = 'Tanggal jatuh tempo wajib diisi'
}
if (formData.transaction_date && formData.due_date) {
if (new Date(formData.due_date) < new Date(formData.transaction_date)) {
newErrors.due_date = 'Tanggal jatuh tempo tidak boleh sebelum tanggal transaksi'
}
}
const validItems = formData.items.filter(
item => item.ingredient && item.unit && item.quantity > 0 && item.amount > 0
)
if (validItems.length === 0) {
newErrors.items = 'Minimal harus ada 1 item yang valid dengan bahan, satuan, kuantitas dan harga yang terisi'
}
setErrors(newErrors)
return Object.keys(newErrors).length === 0
}
// Handler Functions
const handleInputChange = (field: keyof PurchaseOrderFormData, value: any): void => {
setFormData(prev => ({
...prev,
[field]: value
}))
if (errors[field as keyof ValidationErrors]) {
setErrors(prev => ({
...prev,
[field]: undefined
}))
}
}
const handleItemChange = (index: number, field: keyof PurchaseOrderFormItem, value: any): void => {
setFormData(prev => {
const newItems = [...prev.items]
newItems[index] = { ...newItems[index], [field]: value }
if (field === 'amount' || field === 'quantity') {
const item = newItems[index]
item.total = item.amount * item.quantity
}
return { ...prev, items: newItems }
})
if (errors.items) {
setErrors(prev => ({
...prev,
items: undefined
}))
}
}
const handleIngredientSelection = (index: number, selectedIngredient: any) => {
handleItemChange(index, 'ingredient', selectedIngredient)
if (selectedIngredient) {
const ingredientData: IngredientItem = selectedIngredient.originalData || selectedIngredient
if (ingredientData.unit_id || ingredientData.unit) {
let unitToFind = null
if (ingredientData.unit && typeof ingredientData.unit === 'object') {
unitToFind = ingredientData.unit
} else if (ingredientData.unit_id) {
unitToFind = unitOptions.find(option => option.value === ingredientData.unit_id)
}
if (unitToFind) {
const unitOption = {
label: (unitToFind as any).label || (unitToFind as any).name || (unitToFind as any).unit_name,
value: (unitToFind as any).value || ingredientData.unit_id
}
handleItemChange(index, 'unit', unitOption)
}
}
if (ingredientData.cost !== undefined && ingredientData.cost !== null) {
handleItemChange(index, 'amount', ingredientData.cost)
}
if (ingredientData.name) {
handleItemChange(index, 'description', ingredientData.name)
}
}
}
const addItem = (): void => {
const newItem: PurchaseOrderFormItem = {
id: Date.now(),
ingredient: null,
description: '',
quantity: 1,
unit: null,
amount: 0,
total: 0
}
setFormData(prev => ({
...prev,
items: [...prev.items, newItem]
}))
}
const removeItem = (index: number): void => {
setFormData(prev => ({
...prev,
items: prev.items.filter((_, i) => i !== index)
}))
}
const getSelectedVendorData = () => {
if (!formData.vendor?.value || !vendors) return null
const selectedVendor = vendors.find(vendor => vendor.id === (formData?.vendor?.value ?? ''))
return selectedVendor
}
const upsertAttachment = (attachments: string[], newId: string, index = 0) => {
if (attachments.length === 0) {
return [newId]
}
return attachments.map((id, i) => (i === index ? newId : id))
}
const handleUpload = async (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const formData = new FormData()
formData.append('file', file)
formData.append('file_type', 'image')
formData.append('description', 'Gambar Purchase Order')
mutate(formData, {
onSuccess: data => {
setFormData(prev => ({
...prev,
attachment_file_ids: upsertAttachment(prev.attachment_file_ids, data.id)
}))
setImageUrl(data.file_url)
resolve(data.id)
},
onError: error => {
reject(error)
}
})
})
}
const subtotal = formData.items.reduce((sum, item) => sum + (item.total || 0), 0)
const convertToApiRequest = (): PurchaseOrderRequest => {
return {
vendor_id: formData.vendor?.value || '',
po_number: formData.po_number,
transaction_date: formData.transaction_date,
due_date: formData.due_date,
reference: formData.reference || undefined,
status: formData.status,
message: formData.message || undefined,
items: formData.items
.filter(item => item.ingredient && item.unit)
.map(item => ({
ingredient_id: item.ingredient!.value,
description: item.description || undefined,
quantity: item.quantity,
unit_id: item.unit!.value,
amount: item.amount
})),
attachment_file_ids: formData.attachment_file_ids.length > 0 ? formData.attachment_file_ids : undefined
}
}
const handleSave = () => {
if (!validateForm()) {
setErrors(prev => ({
...prev,
general: 'Mohon lengkapi semua field yang wajib diisi'
}))
return
}
createPurchaseOrder.mutate(convertToApiRequest(), {
onSuccess: () => {
window.history.back()
},
onError: error => {
setErrors(prev => ({
...prev,
general: 'Terjadi kesalahan saat menyimpan data. Silakan coba lagi.'
}))
}
})
}
// Get current ingredient data for popover
const getCurrentIngredientData = () => {
if (popoverState.itemIndex !== null) {
return formData.items[popoverState.itemIndex]?.ingredient
}
return null
}
return (
<Card>
<CardContent>
{errors.general && (
<Alert severity='error' sx={{ mb: 3 }}>
{errors.general}
</Alert>
)}
<Grid container spacing={3}>
{/* BASIC INFO SECTION */}
<Grid size={{ xs: 12, sm: 6, md: 6 }}>
<CustomAutocomplete
fullWidth
options={vendorOptions}
value={formData.vendor}
onChange={(event, newValue) => {
handleInputChange('vendor', newValue)
if (newValue?.value) {
const selectedVendorData = vendors?.find(vendor => vendor.id === newValue.value)
console.log('Vendor terpilih:', selectedVendorData)
}
}}
loading={isLoadingVendors}
renderInput={params => (
<CustomTextField
{...params}
label='Vendor *'
placeholder={isLoadingVendors ? 'Memuat vendor...' : 'Pilih vendor'}
fullWidth
error={!!errors.vendor}
helperText={errors.vendor}
/>
)}
/>
{getSelectedVendorData() && (
<Box className='space-y-1 mt-3'>
<Box className='flex items-center space-x-2'>
<i className='tabler-user text-gray-500 w-3 h-3' />
<Typography className='text-gray-700 font-medium text-xs'>
{getSelectedVendorData()?.contact_person ?? ''}
</Typography>
</Box>
<Box className='flex items-start space-x-2'>
<i className='tabler-map text-gray-500 w-3 h-3' />
<Typography className='text-gray-700 font-medium text-xs'>
{getSelectedVendorData()?.address ?? '-'}
</Typography>
</Box>
<Box className='flex items-center space-x-2'>
<i className='tabler-phone text-gray-500 w-3 h-3' />
<Typography className='text-gray-700 font-medium text-xs'>
{getSelectedVendorData()?.phone_number ?? '-'}
</Typography>
</Box>
</Box>
)}
</Grid>
<Grid size={{ xs: 12, sm: 6, md: 6 }}>
<CustomTextField
fullWidth
label='Nomor PO *'
value={formData.po_number}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('po_number', e.target.value)}
error={!!errors.po_number}
helperText={errors.po_number}
/>
</Grid>
{/* Row 2 - Transaction Date, Due Date, Status */}
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
<CustomTextField
fullWidth
label='Tanggal Transaksi *'
type='date'
value={formData.transaction_date}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
handleInputChange('transaction_date', e.target.value)
}
InputLabelProps={{
shrink: true
}}
error={!!errors.transaction_date}
helperText={errors.transaction_date}
/>
</Grid>
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
<CustomTextField
fullWidth
label='Tanggal Jatuh Tempo *'
type='date'
value={formData.due_date}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('due_date', e.target.value)}
InputLabelProps={{
shrink: true
}}
error={!!errors.due_date}
helperText={errors.due_date}
/>
</Grid>
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
<CustomTextField
fullWidth
label='Referensi'
placeholder='Referensi'
value={formData.reference}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('reference', e.target.value)}
/>
</Grid>
{/* ITEMS TABLE SECTION */}
<Grid size={{ xs: 12 }} sx={{ mt: 4 }}>
<Typography variant='h6' sx={{ mb: 2, fontWeight: 600 }}>
Item Purchase Order
</Typography>
{errors.items && (
<Alert severity='error' sx={{ mb: 2 }}>
{errors.items}
</Alert>
)}
<TableContainer component={Paper} variant='outlined'>
<Table>
<TableHead>
<TableRow sx={{ backgroundColor: 'grey.50' }}>
<TableCell sx={{ fontWeight: 'bold', minWidth: 180 }}>Bahan</TableCell>
<TableCell sx={{ fontWeight: 'bold', minWidth: 150 }}>Deskripsi</TableCell>
<TableCell sx={{ fontWeight: 'bold', width: 100 }}>Kuantitas</TableCell>
<TableCell sx={{ fontWeight: 'bold', width: 120 }}>Satuan</TableCell>
<TableCell sx={{ fontWeight: 'bold', width: 120 }}>Harga</TableCell>
<TableCell sx={{ fontWeight: 'bold', width: 100, textAlign: 'right' }}>Total</TableCell>
<TableCell sx={{ width: 50 }}></TableCell>
</TableRow>
</TableHead>
<TableBody>
{formData.items.map((item: PurchaseOrderFormItem, index: number) => (
<TableRow key={item.id}>
<TableCell>
<CustomAutocomplete
size='small'
options={ingredientOptions}
value={item.ingredient || null}
onChange={(event, newValue) => handleIngredientSelection(index, newValue)}
loading={isLoadingIngredients}
getOptionLabel={(option: any) => {
if (!option) return ''
return option.label || option.name || option.nama || ''
}}
isOptionEqualToValue={(option: any, value: any) => {
if (!option || !value) return false
const optionId = option.value || option.id
const valueId = value.value || value.id
return optionId === valueId
}}
renderInput={params => (
<CustomTextField
{...params}
placeholder={isLoadingIngredients ? 'Memuat bahan...' : 'Pilih Bahan'}
InputProps={{
...params.InputProps,
endAdornment: (
<>
{isLoadingIngredients ? <CircularProgress color='inherit' size={20} /> : null}
{params.InputProps.endAdornment}
</>
)
}}
/>
)}
disabled={isLoadingIngredients}
/>
</TableCell>
<TableCell>
<CustomTextField
fullWidth
size='small'
value={item.description}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
handleItemChange(index, 'description', e.target.value)
}
placeholder='Deskripsi'
/>
</TableCell>
<TableCell>
<CustomTextField
fullWidth
size='small'
type='number'
value={item.quantity}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
handleItemChange(index, 'quantity', parseInt(e.target.value) || 1)
}
inputProps={{ min: 1 }}
/>
</TableCell>
<TableCell>
<CustomAutocomplete
size='small'
options={unitOptions}
value={item.unit}
onChange={(event, newValue) => handleItemChange(index, 'unit', newValue)}
loading={isLoadingUnits}
getOptionLabel={(option: any) => {
if (!option) return ''
return option.label || option.name || option.nama || ''
}}
renderInput={params => (
<CustomTextField
{...params}
placeholder={isLoadingUnits ? 'Memuat satuan...' : 'Pilih satuan...'}
InputProps={{
...params.InputProps,
endAdornment: (
<>
{isLoadingUnits ? <CircularProgress color='inherit' size={20} /> : null}
{params.InputProps.endAdornment}
</>
)
}}
/>
)}
disabled={isLoadingUnits}
/>
</TableCell>
<TableCell>
<CustomTextField
fullWidth
size='small'
type='number'
value={item.amount === 0 ? '' : item.amount?.toString() || ''}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value
if (value === '') {
handleItemChange(index, 'amount', 0)
return
}
const numericValue = parseFloat(value)
handleItemChange(index, 'amount', isNaN(numericValue) ? 0 : numericValue)
}}
onClick={e => handlePriceFieldClick(e, index)}
inputProps={{ min: 0, step: 'any' }}
placeholder='0'
sx={{ cursor: item.ingredient ? 'pointer' : 'text' }}
/>
</TableCell>
<TableCell>
<CustomTextField
fullWidth
size='small'
value={item.total}
InputProps={{ readOnly: true }}
sx={{
'& .MuiInputBase-input': {
textAlign: 'right'
}
}}
/>
</TableCell>
<TableCell>
<IconButton
size='small'
color='error'
onClick={() => removeItem(index)}
disabled={formData.items.length === 1}
>
<i className='tabler-trash' />
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
{/* Add New Item Button */}
<Button
startIcon={<i className='tabler-plus' />}
onClick={addItem}
variant='outlined'
size='small'
sx={{ mt: 1 }}
disabled={isLoadingIngredients || isLoadingUnits}
>
Tambah Item
</Button>
</Grid>
{/* SUMMARY SECTION */}
<Grid size={12} sx={{ mt: 4 }}>
<Grid container spacing={3}>
{/* Left Side - Message and Attachment */}
<Grid size={{ xs: 12, md: 7 }}>
{/* Message Section */}
<Box sx={{ mb: 3 }}>
<Button
variant='text'
color='inherit'
onClick={() => handleInputChange('showPesan', !formData.showPesan)}
sx={{
textTransform: 'none',
fontSize: '14px',
fontWeight: 500,
padding: '12px 16px',
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-start',
width: '100%',
backgroundColor: '#f5f5f5',
border: '1px solid #e0e0e0',
borderRadius: '4px',
color: 'text.primary',
'&:hover': {
backgroundColor: '#eeeeee'
}
}}
>
<Box component='span' sx={{ mr: 1 }}>
{formData.showPesan ? (
<i className='tabler-chevron-down w-4 h-4' />
) : (
<i className='tabler-chevron-right w-4 h-4' />
)}
</Box>
Pesan
</Button>
{formData.showPesan && (
<Box sx={{ mt: 2 }}>
<CustomTextField
fullWidth
multiline
rows={3}
placeholder='Tambahkan pesan...'
value={formData.message || ''}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
handleInputChange('message', e.target.value)
}
/>
</Box>
)}
</Box>
{/* Attachment Section */}
<Box>
<Button
variant='text'
color='inherit'
onClick={() => handleInputChange('showAttachment', !formData.showAttachment)}
sx={{
textTransform: 'none',
fontSize: '14px',
fontWeight: 500,
padding: '12px 16px',
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-start',
width: '100%',
backgroundColor: '#f5f5f5',
border: '1px solid #e0e0e0',
borderRadius: '4px',
color: 'text.primary',
'&:hover': {
backgroundColor: '#eeeeee'
}
}}
>
<Box component='span' sx={{ mr: 1 }}>
{formData.showAttachment ? (
<i className='tabler-chevron-down w-4 h-4' />
) : (
<i className='tabler-chevron-right w-4 h-4' />
)}
</Box>
Lampiran
</Button>
{formData.showAttachment && (
<ImageUpload
onUpload={handleUpload}
maxFileSize={1 * 1024 * 1024}
showUrlOption={false}
currentImageUrl={imageUrl}
dragDropText='Letakkan gambar Anda di sini'
browseButtonText='Pilih Gambar'
/>
)}
</Box>
</Grid>
{/* Right Side - Totals */}
<Grid size={{ xs: 12, md: 5 }}>
<Box sx={{ backgroundColor: '#ffffff', p: 3, borderRadius: '8px' }}>
{/* Sub Total */}
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
py: 2,
borderBottom: '1px solid #e0e0e0',
'&:hover': {
backgroundColor: '#f8f8f8'
}
}}
>
<Typography variant='body1' color='text.secondary' sx={{ fontSize: '16px' }}>
Sub Total
</Typography>
<Typography variant='body1' fontWeight={600} sx={{ fontSize: '16px', textAlign: 'right' }}>
{new Intl.NumberFormat('id-ID', {
style: 'currency',
currency: 'IDR',
minimumFractionDigits: 0
}).format(subtotal)}
</Typography>
</Box>
{/* Total */}
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
py: 2,
borderBottom: '1px solid #e0e0e0',
'&:hover': {
backgroundColor: '#f8f8f8'
}
}}
>
<Typography variant='h6' fontWeight={600} sx={{ fontSize: '18px' }}>
Total
</Typography>
<Typography variant='h6' fontWeight={600} sx={{ fontSize: '18px', textAlign: 'right' }}>
{new Intl.NumberFormat('id-ID', {
style: 'currency',
currency: 'IDR',
minimumFractionDigits: 0
}).format(subtotal)}
</Typography>
</Box>
{/* Save Button */}
<Button
variant='contained'
color='primary'
fullWidth
onClick={handleSave}
disabled={createPurchaseOrder.isPending}
sx={{
textTransform: 'none',
fontWeight: 600,
py: 1.5,
mt: 3,
boxShadow: 'none',
'&:hover': {
boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
}
}}
>
{createPurchaseOrder.isPending ? (
<>
<CircularProgress size={16} sx={{ mr: 1 }} />
Menyimpan...
</>
) : (
'Simpan'
)}
</Button>
</Box>
</Grid>
</Grid>
</Grid>
</Grid>
{/* Price Popover */}
<PricePopover
anchorEl={popoverState.anchorEl}
open={popoverState.isOpen}
onClose={handleClosePopover}
ingredientData={getCurrentIngredientData()}
/>
</CardContent>
</Card>
)
}
export default PurchaseAddForm