Compare commits

...

5 Commits

Author SHA1 Message Date
efrilm
fab31f1540 Add Waste at Product Recipe 2025-09-13 04:08:49 +07:00
efrilm
aa2946e627 menu 2025-09-13 03:52:11 +07:00
efrilm
2d3274d3bf Purchase Detail 2025-09-13 03:50:57 +07:00
efrilm
e1084277e0 status color 2025-09-13 03:05:45 +07:00
efrilm
222beb5043 Purchase create 2025-09-13 03:03:08 +07:00
12 changed files with 488 additions and 367 deletions

View File

@ -0,0 +1,18 @@
import PurchaseDetailContent from '@/views/apps/purchase/purchase-detail/PurchaseDetailContent'
import PurchaseDetailHeader from '@/views/apps/purchase/purchase-detail/PurchaseDetailHeader'
import Grid from '@mui/material/Grid2'
const PurchaseOrderDetailPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<PurchaseDetailHeader title='Detail Pesanan Pembelian' />
</Grid>
<Grid size={{ xs: 12 }}>
<PurchaseDetailContent />
</Grid>
</Grid>
)
}
export default PurchaseOrderDetailPage

View File

@ -91,27 +91,27 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
<MenuItem href={`/${locale}/dashboards/daily-report`}>{dictionary['navigation'].dailyReport}</MenuItem>
</SubMenu>
<MenuSection label={dictionary['navigation'].appsPages}>
<SubMenu label={dictionary['navigation'].sales} icon={<i className='tabler-receipt-2' />}>
{/* <SubMenu label={dictionary['navigation'].sales} icon={<i className='tabler-receipt-2' />}>
<MenuItem href={`/${locale}/apps/sales/overview`}>{dictionary['navigation'].overview}</MenuItem>
<MenuItem href={`/${locale}/apps/sales/sales-bills`}>{dictionary['navigation'].invoices}</MenuItem>
<MenuItem href={`/${locale}/apps/sales/sales-deliveries`}>{dictionary['navigation'].deliveries}</MenuItem>
<MenuItem href={`/${locale}/apps/sales/sales-orders`}>{dictionary['navigation'].sales_orders}</MenuItem>
<MenuItem href={`/${locale}/apps/sales/sales-quotes`}>{dictionary['navigation'].quotes}</MenuItem>
</SubMenu>
</SubMenu> */}
<SubMenu label={dictionary['navigation'].purchase_text} icon={<i className='tabler-shopping-cart' />}>
<MenuItem href={`/${locale}/apps/purchase/overview`}>{dictionary['navigation'].overview}</MenuItem>
<MenuItem href={`/${locale}/apps/purchase/purchase-bills`}>
{/* <MenuItem href={`/${locale}/apps/purchase/purchase-bills`}>
{dictionary['navigation'].purchase_bills}
</MenuItem>
<MenuItem href={`/${locale}/apps/purchase/purchase-deliveries`}>
{dictionary['navigation'].purchase_delivery}
</MenuItem>
</MenuItem> */}
<MenuItem href={`/${locale}/apps/purchase/purchase-orders`}>
{dictionary['navigation'].purchase_orders}
</MenuItem>
<MenuItem href={`/${locale}/apps/purchase/purchase-quotes`}>
{/* <MenuItem href={`/${locale}/apps/purchase/purchase-quotes`}>
{dictionary['navigation'].purchase_quotes}
</MenuItem>
</MenuItem> */}
</SubMenu>
<MenuItem
href={`/${locale}/apps/expense`}

View File

@ -1,4 +1,4 @@
import { PurchaseOrders } from '@/types/services/purchaseOrder'
import { PurchaseOrder, PurchaseOrders } from '@/types/services/purchaseOrder'
import { useQuery } from '@tanstack/react-query'
import { api } from '../api'
@ -39,3 +39,13 @@ export function usePurchaseOrders(params: PurchaseOrderQueryParams = {}) {
}
})
}
export function usePurchaseOrderById(id: string) {
return useQuery<PurchaseOrder>({
queryKey: ['purchase-orders', id],
queryFn: async () => {
const res = await api.get(`/purchase-orders/${id}`)
return res.data.data
}
})
}

View File

@ -10,46 +10,6 @@ export type PurchaseOrderType = {
total: number
}
export interface IngredientItem {
id: number
ingredient: { label: string; value: string } | null
deskripsi: string
kuantitas: number
satuan: { label: string; value: string } | null
harga: number
total: number
}
export interface PurchaseOrderFormData {
vendor: { label: string; value: string } | null
nomor: string
tglTransaksi: string
tglJatuhTempo: string
referensi: string
termin: { label: string; value: string } | null
hargaTermasukPajak: boolean
showShippingInfo: boolean
tanggalPengiriman: string
ekspedisi: { label: string; value: string } | null
noResi: string
showPesan: boolean
showAttachment: boolean
showTambahDiskon: boolean
showBiayaPengiriman: boolean
showBiayaTransaksi: boolean
showUangMuka: boolean
pesan: string
ingredientItems: IngredientItem[]
transactionCosts?: TransactionCost[]
subtotal?: number
discountType?: 'percentage' | 'fixed'
downPaymentType?: 'percentage' | 'fixed'
discountValue?: string
shippingCost?: string
transactionCost?: string
downPayment?: string
}
export interface TransactionCost {
id: string
type: string

View File

@ -42,6 +42,7 @@ export interface ProductRecipe {
variant_id: string | null
ingredient_id: string
quantity: number
waste: number
created_at: string
updated_at: string
product: Product
@ -54,6 +55,7 @@ export interface ProductRecipeRequest {
ingredient_id: string
quantity: number
outlet_id: string | null
waste: number
}
export interface IngredientUnit {

View File

@ -1,3 +1,4 @@
import { IngredientItem } from './ingredient'
import { Vendor } from './vendor'
export interface PurchaseOrderRequest {
@ -93,3 +94,27 @@ export interface PurchaseOrderFile {
created_at: string
updated_at: string
}
export interface PurchaseOrderFormData {
vendor: { label: string; value: string } | null
po_number: string
transaction_date: string
due_date: string
reference: string
status: 'draft' | 'sent' | 'approved' | 'received' | 'cancelled'
showPesan: boolean
showAttachment: boolean
message: string
items: PurchaseOrderFormItem[]
attachment_file_ids: string[]
}
export interface PurchaseOrderFormItem {
id: number // for UI tracking
ingredient: { label: string; value: string; originalData?: IngredientItem } | null
description: string
quantity: number
unit: { label: string; value: string } | null
amount: number
total: number // calculated field for UI
}

View File

@ -11,8 +11,6 @@ import Typography from '@mui/material/Typography'
// Third-party Imports
import PerfectScrollbar from 'react-perfect-scrollbar'
// Type Imports
// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import { Autocomplete } from '@mui/material'
@ -25,6 +23,7 @@ import { useOutlets } from '../../../../../services/queries/outlets'
import { Product } from '../../../../../types/services/product'
import { ProductRecipeRequest } from '../../../../../types/services/productRecipe'
import { resetProductVariant } from '../../../../../redux-store/slices/productRecipe'
import { IngredientItem } from '@/types/services/ingredient'
type Props = {
open: boolean
@ -38,7 +37,8 @@ const initialData = {
product_id: '',
variant_id: '',
ingredient_id: '',
quantity: 0
quantity: 0,
waste: 0
}
const AddRecipeDrawer = (props: Props) => {
@ -55,23 +55,45 @@ const AddRecipeDrawer = (props: Props) => {
const [ingredientDebouncedInput] = useDebounce(ingredientInput, 500)
const [formData, setFormData] = useState<ProductRecipeRequest>(initialData)
// Add state untuk menyimpan selected ingredient
const [selectedIngredient, setSelectedIngredient] = useState<IngredientItem | null>(null)
const { data: outlets, isLoading: outletsLoading } = useOutlets({
search: outletDebouncedInput
})
// Modifikasi query ingredients dengan enabled condition
const { data: ingredients, isLoading: ingredientsLoading } = useIngredients({
search: ingredientDebouncedInput
})
const outletOptions = useMemo(() => outlets?.outlets || [], [outlets])
const ingredientOptions = useMemo(() => ingredients?.data || [], [ingredients])
// Perbaiki ingredient options untuk include selected ingredient
const ingredientOptions = useMemo(() => {
const options = ingredients?.data || []
// Jika ada selected ingredient dan tidak ada di current options, tambahkan
if (selectedIngredient && !options.find(opt => opt.id === selectedIngredient.id)) {
return [selectedIngredient, ...options]
}
return options
}, [ingredients, selectedIngredient])
const { createProductRecipe, updateProductRecipe } = useProductRecipesMutation()
useEffect(() => {
if (currentProductRecipe.id) {
setFormData(currentProductRecipe)
// Set selected ingredient dari current product recipe
const currentIngredient = ingredients?.data?.find(ing => ing.id === currentProductRecipe.ingredient_id)
if (currentIngredient) {
setSelectedIngredient(currentIngredient)
}
}, [currentProductRecipe])
}
}, [currentProductRecipe, ingredients])
const handleSubmit = (e: any) => {
e.preventDefault()
@ -101,24 +123,16 @@ const AddRecipeDrawer = (props: Props) => {
handleClose()
dispatch(resetProductVariant())
setFormData(initialData)
}
const handleInputChange = (e: any) => {
setFormData({
...formData,
[e.target.name]: e.target.value
})
setSelectedIngredient(null) // Reset selected ingredient
setIngredientInput('') // Reset input
}
const setTitleDrawer = (recipe: any) => {
const addOrEdit = currentProductRecipe.id ? 'Edit ' : 'Add '
let title = 'Original'
if (recipe?.name) {
title = recipe?.name
}
return addOrEdit + title
}
@ -144,13 +158,14 @@ const AddRecipeDrawer = (props: Props) => {
<Typography color='text.primary' className='font-medium'>
Basic Information
</Typography>
<Autocomplete
options={outletOptions}
loading={outletsLoading}
getOptionLabel={option => option.name}
value={outletOptions.find(p => p.id === formData.outlet_id) || null}
onInputChange={(event, newOutlettInput) => {
setOutletInput(newOutlettInput)
onInputChange={(event, newOutletInput) => {
setOutletInput(newOutletInput)
}}
onChange={(event, newValue) => {
setFormData({
@ -161,7 +176,6 @@ const AddRecipeDrawer = (props: Props) => {
renderInput={params => (
<CustomTextField
{...params}
className=''
label='Outlet'
fullWidth
InputProps={{
@ -171,24 +185,35 @@ const AddRecipeDrawer = (props: Props) => {
/>
)}
/>
{/* Perbaiki Autocomplete untuk Ingredients */}
<Autocomplete
options={ingredientOptions || []}
loading={ingredientsLoading}
getOptionLabel={option => option.name}
value={ingredientOptions?.find(p => p.id === formData.ingredient_id) || null}
value={selectedIngredient}
onInputChange={(event, newIngredientInput) => {
setIngredientInput(newIngredientInput)
}}
onChange={(event, newValue) => {
setSelectedIngredient(newValue) // Set selected ingredient
setFormData({
...formData,
ingredient_id: newValue?.id || ''
})
// Clear input search setelah selection
if (newValue) {
setIngredientInput('')
}
}}
// Tambahkan props untuk mencegah clear on blur
clearOnBlur={false}
// Handle case ketika input kosong tapi ada selected value
inputValue={selectedIngredient ? selectedIngredient.name : ingredientInput}
renderInput={params => (
<CustomTextField
{...params}
className=''
label='Ingredient'
fullWidth
InputProps={{
@ -198,6 +223,18 @@ const AddRecipeDrawer = (props: Props) => {
/>
)}
/>
{/* Unit Field - Disabled, value from selected ingredient */}
<CustomTextField
label='Unit'
fullWidth
disabled
value={selectedIngredient?.unit?.name || ''}
InputProps={{
readOnly: true
}}
/>
<CustomTextField
type='number'
label='Quantity'
@ -205,6 +242,15 @@ const AddRecipeDrawer = (props: Props) => {
value={formData.quantity}
onChange={e => setFormData({ ...formData, quantity: Number(e.target.value) })}
/>
<CustomTextField
type='number'
label='Waste'
fullWidth
value={formData.waste}
onChange={e => setFormData({ ...formData, waste: Number(e.target.value) })}
/>
<div className='flex items-center gap-4'>
<Button
variant='contained'

View File

@ -161,7 +161,7 @@ const ProductDetail = () => {
<TableCell className='font-semibold text-center'>
<div className='flex items-center justify-center gap-2'>
<i className='tabler-package text-blue-600' />
Stock Available
Waste
</div>
</TableCell>
<TableCell className='font-semibold text-right'>
@ -197,12 +197,7 @@ const ProductDetail = () => {
</TableCell>
<TableCell className='text-center'>{formatCurrency(item.ingredient.cost)}</TableCell>
<TableCell className='text-center'>
<Chip
label={item.ingredient.stock}
size='small'
color={item.ingredient.stock > 5 ? 'success' : 'warning'}
variant='outlined'
/>
<Chip label={item.waste ?? 0} size='small' color={'success'} variant='outlined' />
</TableCell>
<TableCell className='text-right font-medium'>
{formatCurrency(item.ingredient.cost * item.quantity)}

View File

@ -1,25 +1,40 @@
'use client'
import Grid from '@mui/material/Grid2'
import PurchaseDetailInformation from './PurchaseDetailInformation'
import PurchaseDetailSendPayment from './PurchaseDetailSendPayment'
import PurchaseDetailLog from './PurchaseDetailLog'
import PurchaseDetailTransaction from './PurchaseDetailTransaction'
import { useParams } from 'next/navigation'
import { usePurchaseOrderById } from '@/services/queries/purchaseOrder'
import Loading from '@/components/layout/shared/Loading'
const PurchaseDetailContent = () => {
const params = useParams()
const { data, isLoading, error, isFetching } = usePurchaseOrderById(params.id as string)
return (
<>
{isLoading ? (
<Loading />
) : (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<PurchaseDetailInformation />
<PurchaseDetailInformation data={data} />
</Grid>
{data?.status == 'sent' && (
<Grid size={{ xs: 12 }}>
<PurchaseDetailSendPayment />
</Grid>
<Grid size={{ xs: 12 }}>
)}
{/* <Grid size={{ xs: 12 }}>
<PurchaseDetailTransaction />
</Grid>
<Grid size={{ xs: 12 }}>
<PurchaseDetailLog />
</Grid> */}
</Grid>
</Grid>
)}
</>
)
}

View File

@ -1,3 +1,5 @@
'use client'
import React from 'react'
import {
Card,
@ -15,87 +17,62 @@ import {
IconButton
} from '@mui/material'
import Grid from '@mui/material/Grid2'
import { PurchaseOrder } from '@/types/services/purchaseOrder'
interface Product {
produk: string
deskripsi: string
kuantitas: number
satuan: string
discount: string
harga: number
pajak: string
jumlah: number
interface Props {
data?: PurchaseOrder
}
interface PurchaseData {
vendor: string
nomor: string
tglTransaksi: string
tglJatuhTempo: string
gudang: string
status: string
}
const PurchaseDetailInformation = ({ data }: Props) => {
const purchaseOrder = data
const PurchaseDetailInformation: React.FC = () => {
const purchaseData: PurchaseData = {
vendor: 'Bagas Rizki Sihotang S.Farm Widodo',
nomor: 'PI/00053',
tglTransaksi: '08/09/2025',
tglJatuhTempo: '06/10/2025',
gudang: 'Unassigned',
status: 'Belum Dibayar'
// Helper functions
const formatDate = (dateString: string): string => {
const date = new Date(dateString)
return date.toLocaleDateString('id-ID', {
day: '2-digit',
month: '2-digit',
year: 'numeric'
})
}
const products: Product[] = [
{
produk: 'CB1 - Chelsea Boots',
deskripsi: 'Ukuran XS',
kuantitas: 3,
satuan: 'Pcs',
discount: '0%',
harga: 299000,
pajak: 'PPN',
jumlah: 897000
},
{
produk: 'CB1 - Chelsea Boots',
deskripsi: 'Ukuran M',
kuantitas: 1,
satuan: 'Pcs',
discount: '0%',
harga: 299000,
pajak: 'PPN',
jumlah: 299000
},
{
produk: 'KH1 - Kneel High Boots',
deskripsi: 'Ukuran XL',
kuantitas: 1,
satuan: 'Pcs',
discount: '0%',
harga: 299000,
pajak: 'PPN',
jumlah: 299000
}
]
const totalKuantitas: number = products.reduce((sum, product) => sum + product.kuantitas, 0)
const subTotal: number = 1495000
const ppn: number = 98670
const total: number = 1593670
const sisaTagihan: number = 1593670
const formatCurrency = (amount: number): string => {
return new Intl.NumberFormat('id-ID').format(amount)
}
const getStatusLabel = (status: string): string => {
const statusMap: Record<string, string> = {
draft: 'Draft',
sent: 'Dikirim',
approved: 'Disetujui',
received: 'Diterima',
cancelled: 'Dibatalkan'
}
return statusMap[status] || status
}
const getStatusColor = (status: string): 'error' | 'success' | 'warning' | 'info' | 'default' => {
const colorMap: Record<string, 'error' | 'success' | 'warning' | 'info' | 'default'> = {
draft: 'default',
sent: 'warning',
approved: 'success',
received: 'info',
cancelled: 'error'
}
return colorMap[status] || 'info'
}
// Calculations
const totalQuantity = (purchaseOrder?.items ?? []).reduce((sum, item) => sum + (item?.quantity ?? 0), 0)
const total = (purchaseOrder?.items ?? []).reduce((sum, item) => sum + (item?.amount ?? 0) * item?.quantity, 0)
return (
<Card sx={{ width: '100%' }}>
<CardHeader
title={
<Box display='flex' justifyContent='space-between' alignItems='center'>
<Typography variant='h5' color='error' sx={{ fontWeight: 'bold' }}>
Belum Dibayar
<Typography variant='h5' color={getStatusColor(purchaseOrder?.status ?? '')} sx={{ fontWeight: 'bold' }}>
{getStatusLabel(purchaseOrder?.status ?? '')}
</Typography>
<Box>
<Button startIcon={<i className='tabler-share' />} variant='outlined' size='small' sx={{ mr: 1 }}>
@ -121,24 +98,15 @@ const PurchaseDetailInformation: React.FC = () => {
Vendor
</Typography>
<Typography variant='body1' color='primary' sx={{ fontWeight: 'medium', cursor: 'pointer' }}>
{purchaseData.vendor}
{purchaseOrder?.vendor?.name ?? ''}
</Typography>
</Box>
<Box sx={{ mb: 2 }}>
<Typography variant='subtitle2' color='text.secondary'>
Tgl. Transaksi
</Typography>
<Typography variant='body1'>{purchaseData.tglTransaksi}</Typography>
</Box>
<Box>
<Typography variant='subtitle2' color='text.secondary'>
Gudang
</Typography>
<Typography variant='body1' color='primary' sx={{ cursor: 'pointer' }}>
{purchaseData.gudang}
Tgl. Transaksi
</Typography>
<Typography variant='body1'>{formatDate(purchaseOrder?.transaction_date ?? '')}</Typography>
</Box>
</Grid>
@ -147,14 +115,14 @@ const PurchaseDetailInformation: React.FC = () => {
<Typography variant='subtitle2' color='text.secondary'>
Nomor
</Typography>
<Typography variant='body1'>{purchaseData.nomor}</Typography>
<Typography variant='body1'>{purchaseOrder?.po_number}</Typography>
</Box>
<Box>
<Typography variant='subtitle2' color='text.secondary'>
Tgl. Jatuh Tempo
</Typography>
<Typography variant='body1'>{purchaseData.tglJatuhTempo}</Typography>
<Typography variant='body1'>{formatDate(purchaseOrder?.due_date ?? '')}</Typography>
</Box>
</Grid>
</Grid>
@ -168,43 +136,38 @@ const PurchaseDetailInformation: React.FC = () => {
<TableCell>Deskripsi</TableCell>
<TableCell align='center'>Kuantitas</TableCell>
<TableCell align='center'>Satuan</TableCell>
<TableCell align='center'>Discount</TableCell>
<TableCell align='right'>Harga</TableCell>
<TableCell align='center'>Pajak</TableCell>
<TableCell align='right'>Jumlah</TableCell>
</TableRow>
</TableHead>
<TableBody>
{products.map((product, index) => (
<TableRow key={index}>
{(purchaseOrder?.items ?? []).map((item, index) => {
return (
<TableRow key={item.id}>
<TableCell>
<Typography variant='body2' color='primary' sx={{ cursor: 'pointer' }}>
{product.produk}
{item.ingredient.name}
</Typography>
</TableCell>
<TableCell>{product.deskripsi}</TableCell>
<TableCell align='center'>{product.kuantitas}</TableCell>
<TableCell align='center'>{product.satuan}</TableCell>
<TableCell align='center'>{product.discount}</TableCell>
<TableCell align='right'>{formatCurrency(product.harga)}</TableCell>
<TableCell align='center'>{product.pajak}</TableCell>
<TableCell align='right'>{formatCurrency(product.jumlah)}</TableCell>
<TableCell>{item.description}</TableCell>
<TableCell align='center'>{item.quantity}</TableCell>
<TableCell align='center'>{item.unit.name}</TableCell>
<TableCell align='right'>{formatCurrency(item.amount)}</TableCell>
<TableCell align='right'>{formatCurrency(item.amount * item.quantity)}</TableCell>
</TableRow>
))}
)
})}
{/* Total Kuantitas Row */}
{/* Total Quantity Row */}
<TableRow>
<TableCell colSpan={2} sx={{ fontWeight: 'bold', borderTop: '2px solid #e0e0e0' }}>
Total Kuantitas
</TableCell>
<TableCell align='center' sx={{ fontWeight: 'bold', borderTop: '2px solid #e0e0e0' }}>
{totalKuantitas}
{totalQuantity}
</TableCell>
<TableCell sx={{ borderTop: '2px solid #e0e0e0' }}></TableCell>
<TableCell sx={{ borderTop: '2px solid #e0e0e0' }}></TableCell>
<TableCell sx={{ borderTop: '2px solid #e0e0e0' }}></TableCell>
<TableCell sx={{ borderTop: '2px solid #e0e0e0' }}></TableCell>
<TableCell sx={{ borderTop: '2px solid #e0e0e0' }}></TableCell>
</TableRow>
</TableBody>
</Table>
@ -222,82 +185,19 @@ const PurchaseDetailInformation: React.FC = () => {
justifyContent: 'space-between',
alignItems: 'center',
py: 2,
borderBottom: '1px solid #e0e0e0',
'&:hover': {
backgroundColor: 'rgba(0, 0, 0, 0.04)',
transition: 'background-color 0.15s ease'
}
}}
>
<Typography variant='body1' sx={{ fontWeight: 'medium' }}>
Sub Total
</Typography>
<Typography variant='body1' sx={{ fontWeight: 'medium' }}>
{formatCurrency(subTotal)}
</Typography>
</Box>
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
py: 2,
borderBottom: '1px solid #e0e0e0',
'&:hover': {
backgroundColor: 'rgba(0, 0, 0, 0.04)',
transition: 'background-color 0.15s ease'
}
}}
>
<Typography variant='body1' sx={{ fontWeight: 'medium' }}>
PPN
</Typography>
<Typography variant='body1' sx={{ fontWeight: 'medium' }}>
{formatCurrency(ppn)}
</Typography>
</Box>
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
py: 2,
borderBottom: '1px solid #e0e0e0',
'&:hover': {
backgroundColor: 'rgba(0, 0, 0, 0.04)',
transition: 'background-color 0.15s ease'
}
}}
>
<Typography variant='body1' sx={{ fontWeight: 'bold' }}>
<Typography variant='h6' sx={{ fontWeight: 'bold' }}>
Total
</Typography>
<Typography variant='body1' sx={{ fontWeight: 'bold' }}>
<Typography variant='h6' sx={{ fontWeight: 'bold' }}>
{formatCurrency(total)}
</Typography>
</Box>
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
py: 2,
'&:hover': {
backgroundColor: 'rgba(0, 0, 0, 0.04)',
transition: 'background-color 0.15s ease'
}
}}
>
<Typography variant='h6' sx={{ fontWeight: 'bold' }}>
Sisa Tagihan
</Typography>
<Typography variant='h6' sx={{ fontWeight: 'bold' }}>
{formatCurrency(sisaTagihan)}
</Typography>
</Box>
</Box>
</Grid>
</Grid>

View File

@ -15,7 +15,10 @@ import {
TableHead,
TableRow,
Paper,
CircularProgress
CircularProgress,
Alert,
Popover,
Divider
} from '@mui/material'
import Grid from '@mui/material/Grid2'
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
@ -27,88 +30,113 @@ import { useIngredients } from '@/services/queries/ingredients'
import { useUnits } from '@/services/queries/units'
import { useFilesMutation } from '@/services/mutations/files'
import { usePurchaseOrdersMutation } from '@/services/mutations/purchaseOrder'
export interface PurchaseOrderRequest {
vendor_id: string // uuid.UUID
po_number: string
transaction_date: string // ISO date string
due_date: string // ISO date string
reference?: string
status?: 'draft' | 'sent' | 'approved' | 'received' | 'cancelled'
message?: string
items: PurchaseOrderItemRequest[]
attachment_file_ids?: string[] // uuid.UUID[]
}
export interface PurchaseOrderItemRequest {
ingredient_id: string // uuid.UUID
description?: string
quantity: number
unit_id: string // uuid.UUID
amount: number
}
export type IngredientItem = {
id: string
organization_id: string
outlet_id: string
name: string
unit_id: string
cost: number
stock: number
is_semi_finished: boolean
is_active: boolean
metadata: Record<string, unknown>
created_at: string
updated_at: string
unit: Unit
}
import { PurchaseOrderFormData, PurchaseOrderFormItem, PurchaseOrderRequest } from '@/types/services/purchaseOrder'
import { IngredientItem } from '@/types/services/ingredient'
export type Unit = {
id: string
name: string
// Add other unit properties as needed
}
// Internal form state interface for UI management
interface PurchaseOrderFormData {
vendor: { label: string; value: string } | null
po_number: string
transaction_date: string
due_date: string
reference: string
status: 'draft' | 'sent' | 'approved' | 'received' | 'cancelled'
showPesan: boolean
showAttachment: boolean
message: string
items: PurchaseOrderFormItem[]
attachment_file_ids: string[]
interface ValidationErrors {
vendor?: string
po_number?: string
transaction_date?: string
due_date?: string
items?: string
general?: string
}
interface PurchaseOrderFormItem {
id: number // for UI tracking
ingredient: { label: string; value: string; originalData?: IngredientItem } | null
description: string
quantity: number
unit: { label: string; value: string } | null
amount: number
total: number // calculated field for UI
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: 'draft',
// Bottom section toggles
status: 'sent',
showPesan: false,
showAttachment: false,
message: '',
// Items
items: [
{
id: 1,
@ -154,7 +182,7 @@ const PurchaseAddForm: React.FC = () => {
label: ingredient.name,
value: ingredient.id,
id: ingredient.id,
originalData: ingredient // This includes the full IngredientItem with unit, cost, etc.
originalData: ingredient
}))
}, [ingredients, isLoadingIngredients])
@ -172,12 +200,78 @@ const PurchaseAddForm: React.FC = () => {
)
}, [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 => {
@ -185,7 +279,6 @@ const PurchaseAddForm: React.FC = () => {
const newItems = [...prev.items]
newItems[index] = { ...newItems[index], [field]: value }
// Auto-calculate total if amount or quantity changes
if (field === 'amount' || field === 'quantity') {
const item = newItems[index]
item.total = item.amount * item.quantity
@ -193,30 +286,31 @@ const PurchaseAddForm: React.FC = () => {
return { ...prev, items: newItems }
})
if (errors.items) {
setErrors(prev => ({
...prev,
items: undefined
}))
}
}
const handleIngredientSelection = (index: number, selectedIngredient: any) => {
handleItemChange(index, 'ingredient', selectedIngredient)
// Auto-populate related fields if available in the ingredient data
if (selectedIngredient) {
const ingredientData: IngredientItem = selectedIngredient.originalData || selectedIngredient
// Auto-fill unit based on IngredientItem structure
if (ingredientData.unit_id || ingredientData.unit) {
let unitToFind = null
// If ingredient has unit object (populated relation)
if (ingredientData.unit && typeof ingredientData.unit === 'object') {
unitToFind = ingredientData.unit
}
// If ingredient has unit_id, find the unit from unitOptions
else if (ingredientData.unit_id) {
} else if (ingredientData.unit_id) {
unitToFind = unitOptions.find(option => option.value === ingredientData.unit_id)
}
if (unitToFind) {
// Create unit option object
const unitOption = {
label: (unitToFind as any).label || (unitToFind as any).name || (unitToFind as any).unit_name,
value: (unitToFind as any).value || ingredientData.unit_id
@ -226,12 +320,10 @@ const PurchaseAddForm: React.FC = () => {
}
}
// Auto-fill amount with cost from IngredientItem
if (ingredientData.cost !== undefined && ingredientData.cost !== null) {
handleItemChange(index, 'amount', ingredientData.cost)
}
// Auto-fill description with ingredient name
if (ingredientData.name) {
handleItemChange(index, 'description', ingredientData.name)
}
@ -261,7 +353,6 @@ const PurchaseAddForm: React.FC = () => {
}))
}
// Function to get selected vendor data
const getSelectedVendorData = () => {
if (!formData.vendor?.value || !vendors) return null
const selectedVendor = vendors.find(vendor => vendor.id === (formData?.vendor?.value ?? ''))
@ -280,29 +371,26 @@ const PurchaseAddForm: React.FC = () => {
const formData = new FormData()
formData.append('file', file)
formData.append('file_type', 'image')
formData.append('description', 'Purchase image')
formData.append('description', 'Gambar Purchase Order')
mutate(formData, {
onSuccess: data => {
// pemakaian:
setFormData(prev => ({
...prev,
attachment_file_ids: upsertAttachment(prev.attachment_file_ids, data.id)
}))
setImageUrl(data.file_url)
resolve(data.id) // <-- balikin id file yang berhasil diupload
resolve(data.id)
},
onError: error => {
reject(error) // biar async/await bisa tangkep error
reject(error)
}
})
})
}
// Calculate subtotal from items
const subtotal = formData.items.reduce((sum, item) => sum + (item.total || 0), 0)
// Convert form data to API request format
const convertToApiRequest = (): PurchaseOrderRequest => {
return {
vendor_id: formData.vendor?.value || '',
@ -313,7 +401,7 @@ const PurchaseAddForm: React.FC = () => {
status: formData.status,
message: formData.message || undefined,
items: formData.items
.filter(item => item.ingredient && item.unit) // Only include valid items
.filter(item => item.ingredient && item.unit)
.map(item => ({
ingredient_id: item.ingredient!.value,
description: item.description || undefined,
@ -326,19 +414,46 @@ const PurchaseAddForm: React.FC = () => {
}
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 */}
{/* Row 1 - Vendor and PO Number */}
<Grid size={{ xs: 12, sm: 6, md: 6 }}>
<CustomAutocomplete
fullWidth
@ -348,16 +463,18 @@ const PurchaseAddForm: React.FC = () => {
handleInputChange('vendor', newValue)
if (newValue?.value) {
const selectedVendorData = vendors?.find(vendor => vendor.id === newValue.value)
console.log('Vendor selected:', selectedVendorData)
console.log('Vendor terpilih:', selectedVendorData)
}
}}
loading={isLoadingVendors}
renderInput={params => (
<CustomTextField
{...params}
label='Vendor'
placeholder={isLoadingVendors ? 'Memuat vendor...' : 'Pilih kontak'}
label='Vendor *'
placeholder={isLoadingVendors ? 'Memuat vendor...' : 'Pilih vendor'}
fullWidth
error={!!errors.vendor}
helperText={errors.vendor}
/>
)}
/>
@ -387,9 +504,11 @@ const PurchaseAddForm: React.FC = () => {
<Grid size={{ xs: 12, sm: 6, md: 6 }}>
<CustomTextField
fullWidth
label='PO Number'
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>
@ -397,7 +516,7 @@ const PurchaseAddForm: React.FC = () => {
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
<CustomTextField
fullWidth
label='Transaction Date'
label='Tanggal Transaksi *'
type='date'
value={formData.transaction_date}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
@ -406,25 +525,29 @@ const PurchaseAddForm: React.FC = () => {
InputLabelProps={{
shrink: true
}}
error={!!errors.transaction_date}
helperText={errors.transaction_date}
/>
</Grid>
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
<CustomTextField
fullWidth
label='Due Date'
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='Reference'
placeholder='Reference'
label='Referensi'
placeholder='Referensi'
value={formData.reference}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('reference', e.target.value)}
/>
@ -433,18 +556,24 @@ const PurchaseAddForm: React.FC = () => {
{/* ITEMS TABLE SECTION */}
<Grid size={{ xs: 12 }} sx={{ mt: 4 }}>
<Typography variant='h6' sx={{ mb: 2, fontWeight: 600 }}>
Purchase Order Items
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 }}>Ingredient</TableCell>
<TableCell sx={{ fontWeight: 'bold', minWidth: 150 }}>Description</TableCell>
<TableCell sx={{ fontWeight: 'bold', width: 100 }}>Quantity</TableCell>
<TableCell sx={{ fontWeight: 'bold', width: 120 }}>Unit</TableCell>
<TableCell sx={{ fontWeight: 'bold', width: 120 }}>Amount</TableCell>
<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>
@ -472,7 +601,7 @@ const PurchaseAddForm: React.FC = () => {
renderInput={params => (
<CustomTextField
{...params}
placeholder={isLoadingIngredients ? 'Loading ingredients...' : 'Select Ingredient'}
placeholder={isLoadingIngredients ? 'Memuat bahan...' : 'Pilih Bahan'}
InputProps={{
...params.InputProps,
endAdornment: (
@ -495,7 +624,7 @@ const PurchaseAddForm: React.FC = () => {
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
handleItemChange(index, 'description', e.target.value)
}
placeholder='Description'
placeholder='Deskripsi'
/>
</TableCell>
<TableCell>
@ -524,7 +653,7 @@ const PurchaseAddForm: React.FC = () => {
renderInput={params => (
<CustomTextField
{...params}
placeholder={isLoadingUnits ? 'Loading units...' : 'Select...'}
placeholder={isLoadingUnits ? 'Memuat satuan...' : 'Pilih satuan...'}
InputProps={{
...params.InputProps,
endAdornment: (
@ -554,8 +683,10 @@ const PurchaseAddForm: React.FC = () => {
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>
@ -596,7 +727,7 @@ const PurchaseAddForm: React.FC = () => {
sx={{ mt: 1 }}
disabled={isLoadingIngredients || isLoadingUnits}
>
Add Item
Tambah Item
</Button>
</Grid>
@ -636,7 +767,7 @@ const PurchaseAddForm: React.FC = () => {
<i className='tabler-chevron-right w-4 h-4' />
)}
</Box>
Message
Pesan
</Button>
{formData.showPesan && (
<Box sx={{ mt: 2 }}>
@ -644,7 +775,7 @@ const PurchaseAddForm: React.FC = () => {
fullWidth
multiline
rows={3}
placeholder='Add message...'
placeholder='Tambahkan pesan...'
value={formData.message || ''}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
handleInputChange('message', e.target.value)
@ -685,7 +816,7 @@ const PurchaseAddForm: React.FC = () => {
<i className='tabler-chevron-right w-4 h-4' />
)}
</Box>
Attachment
Lampiran
</Button>
{formData.showAttachment && (
<ImageUpload
@ -693,8 +824,8 @@ const PurchaseAddForm: React.FC = () => {
maxFileSize={1 * 1024 * 1024}
showUrlOption={false}
currentImageUrl={imageUrl}
dragDropText='Drop your image here'
browseButtonText='Choose Image'
dragDropText='Letakkan gambar Anda di sini'
browseButtonText='Pilih Gambar'
/>
)}
</Box>
@ -759,6 +890,7 @@ const PurchaseAddForm: React.FC = () => {
color='primary'
fullWidth
onClick={handleSave}
disabled={createPurchaseOrder.isPending}
sx={{
textTransform: 'none',
fontWeight: 600,
@ -770,13 +902,28 @@ const PurchaseAddForm: React.FC = () => {
}
}}
>
Save
{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>
)

View File

@ -107,14 +107,16 @@ const DebouncedInput = ({
// Status color mapping
const getStatusColor = (status: string) => {
switch (status) {
case 'Draft':
case 'draft':
return 'secondary'
case 'Disetujui':
case 'approved':
return 'primary'
case 'Dikirim Sebagian':
case 'sent':
return 'warning'
case 'Selesai':
case 'received':
return 'success'
case 'cancelled':
return 'error'
default:
return 'default'
}
@ -210,7 +212,8 @@ const PurchaseOrderListTable = () => {
variant='text'
color='primary'
className='p-0 min-w-0 font-medium normal-case justify-start'
onClick={() => handlePOClick(row.original.id.toString())}
component={Link}
href={getLocalizedUrl(`/apps/purchase/purchase-orders/${row.original.id}/detail`, locale as Locale)}
sx={{
textTransform: 'none',
fontWeight: 500,