efril #7
@ -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
|
||||
@ -7,6 +7,14 @@ import Menu from '@mui/material/Menu'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import { styled } from '@mui/material/styles'
|
||||
|
||||
function toTitleCase(str: string): string {
|
||||
return str
|
||||
.toLowerCase()
|
||||
.split(/\s+/) // split by spaces
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
const DropdownButton = styled(Button)(({ theme }) => ({
|
||||
textTransform: 'none',
|
||||
fontWeight: 400,
|
||||
@ -102,7 +110,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
||||
})
|
||||
}}
|
||||
>
|
||||
{status}
|
||||
{toTitleCase(status)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
@ -135,7 +143,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
||||
})
|
||||
}}
|
||||
>
|
||||
{status}
|
||||
{toTitleCase(status)}
|
||||
</Button>
|
||||
))}
|
||||
|
||||
@ -158,7 +166,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
||||
})
|
||||
}}
|
||||
>
|
||||
{isDropdownItemSelected ? selectedStatus : dropdownLabel}
|
||||
{isDropdownItemSelected ? toTitleCase(selectedStatus) : dropdownLabel}
|
||||
</DropdownButton>
|
||||
|
||||
<Menu
|
||||
@ -187,7 +195,7 @@ const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
|
||||
color: selectedStatus === status ? 'primary.main' : 'text.primary'
|
||||
}}
|
||||
>
|
||||
{status}
|
||||
{toTitleCase(status)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Menu>
|
||||
|
||||
@ -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`}
|
||||
|
||||
@ -9,6 +9,7 @@ import orderReducer from '@/redux-store/slices/order'
|
||||
import productRecipeReducer from '@/redux-store/slices/productRecipe'
|
||||
import organizationReducer from '@/redux-store/slices/organization'
|
||||
import userReducer from '@/redux-store/slices/user'
|
||||
import vendorReducer from '@/redux-store/slices/vendor'
|
||||
|
||||
export const store = configureStore({
|
||||
reducer: {
|
||||
@ -19,7 +20,8 @@ export const store = configureStore({
|
||||
orderReducer,
|
||||
productRecipeReducer,
|
||||
organizationReducer,
|
||||
userReducer
|
||||
userReducer,
|
||||
vendorReducer
|
||||
},
|
||||
middleware: getDefaultMiddleware => getDefaultMiddleware({ serializableCheck: false })
|
||||
})
|
||||
|
||||
43
src/redux-store/slices/vendor.ts
Normal file
43
src/redux-store/slices/vendor.ts
Normal file
@ -0,0 +1,43 @@
|
||||
// Third-party Imports
|
||||
import type { PayloadAction } from '@reduxjs/toolkit'
|
||||
import { createSlice } from '@reduxjs/toolkit'
|
||||
|
||||
// Type Imports
|
||||
|
||||
// Data Imports
|
||||
import { Vendor } from '../../types/services/vendor'
|
||||
|
||||
const initialState: { currentVendor: Vendor } = {
|
||||
currentVendor: {
|
||||
id: '',
|
||||
organization_id: '',
|
||||
name: '',
|
||||
email: '',
|
||||
phone_number: '',
|
||||
address: '',
|
||||
contact_person: '',
|
||||
tax_number: '',
|
||||
payment_terms: '',
|
||||
notes: '',
|
||||
is_active: true,
|
||||
created_at: '',
|
||||
updated_at: ''
|
||||
}
|
||||
}
|
||||
|
||||
export const VendorSlice = createSlice({
|
||||
name: 'vendor',
|
||||
initialState,
|
||||
reducers: {
|
||||
setVendor: (state, action: PayloadAction<Vendor>) => {
|
||||
state.currentVendor = action.payload
|
||||
},
|
||||
resetVendor: state => {
|
||||
state.currentVendor = initialState.currentVendor
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export const { setVendor, resetVendor } = VendorSlice.actions
|
||||
|
||||
export default VendorSlice.reducer
|
||||
@ -6,7 +6,7 @@ const getToken = () => {
|
||||
}
|
||||
|
||||
export const api = axios.create({
|
||||
baseURL: 'https://api-pos.apskel.id/api/v1',
|
||||
baseURL: 'http://127.0.0.1:4000/api/v1',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
|
||||
52
src/services/mutations/account.ts
Normal file
52
src/services/mutations/account.ts
Normal file
@ -0,0 +1,52 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'react-toastify'
|
||||
import { api } from '../api'
|
||||
import { AccountRequest } from '../queries/chartOfAccountType'
|
||||
|
||||
export const useAccountsMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createAccount = useMutation({
|
||||
mutationFn: async (newAccount: AccountRequest) => {
|
||||
const response = await api.post('/accounts', newAccount)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Account created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['accounts'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
const updateAccount = useMutation({
|
||||
mutationFn: async ({ id, payload }: { id: string; payload: AccountRequest }) => {
|
||||
const response = await api.put(`/accounts/${id}`, payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Account updated successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['accounts'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||
}
|
||||
})
|
||||
|
||||
const deleteAccount = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await api.delete(`/accounts/${id}`)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Account deleted successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['accounts'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createAccount, updateAccount, deleteAccount }
|
||||
}
|
||||
24
src/services/mutations/purchaseOrder.ts
Normal file
24
src/services/mutations/purchaseOrder.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'react-toastify'
|
||||
import { api } from '../api'
|
||||
import { PurchaseOrderRequest } from '@/types/services/purchaseOrder'
|
||||
|
||||
export const usePurchaseOrdersMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createPurchaseOrder = useMutation({
|
||||
mutationFn: async (newPurchaseOrder: PurchaseOrderRequest) => {
|
||||
const response = await api.post('/purchase-orders', newPurchaseOrder)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Purchase Order created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['purchase-orders'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createPurchaseOrder }
|
||||
}
|
||||
52
src/services/mutations/unitConventor.ts
Normal file
52
src/services/mutations/unitConventor.ts
Normal file
@ -0,0 +1,52 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'react-toastify'
|
||||
import { api } from '../api'
|
||||
import { IngredientUnitConverterRequest } from '@/types/services/productRecipe'
|
||||
|
||||
export const useUnitConventorMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createUnitConventer = useMutation({
|
||||
mutationFn: async (newUnitConventer: IngredientUnitConverterRequest) => {
|
||||
const response = await api.post('/unit-converters', newUnitConventer)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('UnitConventer created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['unitConventers'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
const updateUnitConventer = useMutation({
|
||||
mutationFn: async ({ id, payload }: { id: string; payload: IngredientUnitConverterRequest }) => {
|
||||
const response = await api.put(`/unit-converters/${id}`, payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('UnitConventer updated successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['unit-converters'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||
}
|
||||
})
|
||||
|
||||
const deleteUnitConventer = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await api.delete(`/unit-converters/${id}`)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('UnitConventer deleted successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['unitConventers'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createUnitConventer, updateUnitConventer, deleteUnitConventer }
|
||||
}
|
||||
52
src/services/mutations/vendor.ts
Normal file
52
src/services/mutations/vendor.ts
Normal file
@ -0,0 +1,52 @@
|
||||
import { VendorRequest } from '@/types/services/vendor'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'react-toastify'
|
||||
import { api } from '../api'
|
||||
|
||||
export const useVendorsMutation = () => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const createVendor = useMutation({
|
||||
mutationFn: async (newVendor: VendorRequest) => {
|
||||
const response = await api.post('/vendors', newVendor)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Vendor created successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['vendors'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Create failed')
|
||||
}
|
||||
})
|
||||
|
||||
const updateVendor = useMutation({
|
||||
mutationFn: async ({ id, payload }: { id: string; payload: VendorRequest }) => {
|
||||
const response = await api.put(`/vendors/${id}`, payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Vendor updated successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['vendors'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Update failed')
|
||||
}
|
||||
})
|
||||
|
||||
const deleteVendor = useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const response = await api.delete(`/vendors/${id}`)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success('Vendor deleted successfully!')
|
||||
queryClient.invalidateQueries({ queryKey: ['vendors'] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error.response?.data?.errors?.[0]?.cause || 'Delete failed')
|
||||
}
|
||||
})
|
||||
|
||||
return { createVendor, updateVendor, deleteVendor }
|
||||
}
|
||||
36
src/services/queries/account.ts
Normal file
36
src/services/queries/account.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
import { Accounts } from '@/types/services/chartOfAccount'
|
||||
|
||||
interface AccountQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export function useAccounts(params: AccountQueryParams = {}) {
|
||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||
|
||||
return useQuery<Accounts>({
|
||||
queryKey: ['accounts', { page, limit, search, ...filters }],
|
||||
queryFn: async () => {
|
||||
const queryParams = new URLSearchParams()
|
||||
|
||||
queryParams.append('page', page.toString())
|
||||
queryParams.append('limit', limit.toString())
|
||||
|
||||
if (search) {
|
||||
queryParams.append('search', search)
|
||||
}
|
||||
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
queryParams.append(key, value.toString())
|
||||
}
|
||||
})
|
||||
|
||||
const res = await api.get(`/accounts?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
36
src/services/queries/chartOfAccount.ts
Normal file
36
src/services/queries/chartOfAccount.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
import { ChartOfAccounts } from '@/types/services/chartOfAccount'
|
||||
|
||||
interface ChartOfAccountQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export function useChartOfAccount(params: ChartOfAccountQueryParams = {}) {
|
||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||
|
||||
return useQuery<ChartOfAccounts>({
|
||||
queryKey: ['chart-of-accounts', { page, limit, search, ...filters }],
|
||||
queryFn: async () => {
|
||||
const queryParams = new URLSearchParams()
|
||||
|
||||
queryParams.append('page', page.toString())
|
||||
queryParams.append('limit', limit.toString())
|
||||
|
||||
if (search) {
|
||||
queryParams.append('search', search)
|
||||
}
|
||||
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
queryParams.append(key, value.toString())
|
||||
}
|
||||
})
|
||||
|
||||
const res = await api.get(`/chart-of-accounts?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
45
src/services/queries/chartOfAccountType.ts
Normal file
45
src/services/queries/chartOfAccountType.ts
Normal file
@ -0,0 +1,45 @@
|
||||
import { ChartOfAccountTypes } from '@/types/services/chartOfAccount'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
|
||||
interface ChartOfAccountQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export function useChartOfAccountTypes(params: ChartOfAccountQueryParams = {}) {
|
||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||
|
||||
return useQuery<ChartOfAccountTypes>({
|
||||
queryKey: ['chart-of-account-types', { page, limit, search, ...filters }],
|
||||
queryFn: async () => {
|
||||
const queryParams = new URLSearchParams()
|
||||
|
||||
queryParams.append('page', page.toString())
|
||||
queryParams.append('limit', limit.toString())
|
||||
|
||||
if (search) {
|
||||
queryParams.append('search', search)
|
||||
}
|
||||
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
queryParams.append(key, value.toString())
|
||||
}
|
||||
})
|
||||
|
||||
const res = await api.get(`/chart-of-account-types?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export interface AccountRequest {
|
||||
chart_of_account_id: string
|
||||
name: string
|
||||
number: string
|
||||
account_type: string
|
||||
opening_balance: number
|
||||
description: string
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Ingredients } from '../../types/services/ingredient'
|
||||
import { api } from '../api'
|
||||
import { Ingredient } from '@/types/services/productRecipe'
|
||||
|
||||
interface IngredientsQueryParams {
|
||||
page?: number
|
||||
@ -34,3 +35,13 @@ export function useIngredients(params: IngredientsQueryParams = {}) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function useIngredientById(id: string) {
|
||||
return useQuery<Ingredient>({
|
||||
queryKey: ['ingredients', id],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/ingredients/${id}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
51
src/services/queries/purchaseOrder.ts
Normal file
51
src/services/queries/purchaseOrder.ts
Normal file
@ -0,0 +1,51 @@
|
||||
import { PurchaseOrder, PurchaseOrders } from '@/types/services/purchaseOrder'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
|
||||
interface PurchaseOrderQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
status?: string
|
||||
}
|
||||
|
||||
export function usePurchaseOrders(params: PurchaseOrderQueryParams = {}) {
|
||||
const { page = 1, limit = 10, search = '', status = '', ...filters } = params
|
||||
|
||||
return useQuery<PurchaseOrders>({
|
||||
queryKey: ['purchase-orders', { page, limit, search, status, ...filters }],
|
||||
queryFn: async () => {
|
||||
const queryParams = new URLSearchParams()
|
||||
|
||||
queryParams.append('page', page.toString())
|
||||
queryParams.append('limit', limit.toString())
|
||||
|
||||
if (search) {
|
||||
queryParams.append('search', search)
|
||||
}
|
||||
|
||||
if (status) {
|
||||
queryParams.append('status', status)
|
||||
}
|
||||
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
queryParams.append(key, value.toString())
|
||||
}
|
||||
})
|
||||
|
||||
const res = await api.get(`/purchase-orders?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
})
|
||||
}
|
||||
13
src/services/queries/unitConverter.ts
Normal file
13
src/services/queries/unitConverter.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import { UnitConversion } from '@/types/services/productRecipe'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
|
||||
export function useUnitConverterByIngredient(IngredientId: string) {
|
||||
return useQuery<UnitConversion[]>({
|
||||
queryKey: ['unit-converters/ingredient', IngredientId],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/unit-converters/ingredient/${IngredientId}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
56
src/services/queries/vendor.ts
Normal file
56
src/services/queries/vendor.ts
Normal file
@ -0,0 +1,56 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
import { Vendor, Vendors } from '@/types/services/vendor'
|
||||
|
||||
interface VendorQueryParams {
|
||||
page?: number
|
||||
limit?: number
|
||||
search?: string
|
||||
}
|
||||
|
||||
export function useVendors(params: VendorQueryParams = {}) {
|
||||
const { page = 1, limit = 10, search = '', ...filters } = params
|
||||
|
||||
return useQuery<Vendors>({
|
||||
queryKey: ['vendors', { page, limit, search, ...filters }],
|
||||
queryFn: async () => {
|
||||
const queryParams = new URLSearchParams()
|
||||
|
||||
queryParams.append('page', page.toString())
|
||||
queryParams.append('limit', limit.toString())
|
||||
|
||||
if (search) {
|
||||
queryParams.append('search', search)
|
||||
}
|
||||
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
queryParams.append(key, value.toString())
|
||||
}
|
||||
})
|
||||
|
||||
const res = await api.get(`/vendors?${queryParams.toString()}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function useVendorActive() {
|
||||
return useQuery<Vendor[]>({
|
||||
queryKey: ['vendors/active'],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/vendors/active`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function useVendorById(id: string) {
|
||||
return useQuery<Vendor>({
|
||||
queryKey: ['vendors', id],
|
||||
queryFn: async () => {
|
||||
const res = await api.get(`/vendors/${id}`)
|
||||
return res.data.data
|
||||
}
|
||||
})
|
||||
}
|
||||
@ -10,49 +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
|
||||
discount: string
|
||||
harga: number
|
||||
pajak: { label: string; value: string } | null
|
||||
waste: { label: string; value: string } | null
|
||||
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
|
||||
|
||||
64
src/types/services/chartOfAccount.ts
Normal file
64
src/types/services/chartOfAccount.ts
Normal file
@ -0,0 +1,64 @@
|
||||
export interface ChartOfAccountType {
|
||||
id: string
|
||||
name: string
|
||||
code: string
|
||||
description: string
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface ChartOfAccountTypes {
|
||||
data: ChartOfAccountType[]
|
||||
limit: number
|
||||
page: number
|
||||
total: number
|
||||
}
|
||||
|
||||
export interface ChartOfAccount {
|
||||
id: string
|
||||
organization_id: string
|
||||
outlet_id: string
|
||||
chart_of_account_type_id: string
|
||||
parent_id: string
|
||||
name: string
|
||||
code: string
|
||||
description: string
|
||||
is_active: boolean
|
||||
is_system: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
chart_of_account_type: ChartOfAccountType
|
||||
}
|
||||
|
||||
export interface ChartOfAccounts {
|
||||
data: ChartOfAccount[]
|
||||
limit: number
|
||||
page: number
|
||||
total: number
|
||||
}
|
||||
|
||||
export interface Account {
|
||||
id: string
|
||||
organization_id: string
|
||||
outlet_id: string
|
||||
chart_of_account_id: string
|
||||
name: string
|
||||
number: string
|
||||
account_type: string
|
||||
opening_balance: number
|
||||
current_balance: number
|
||||
description: string
|
||||
is_active: true
|
||||
is_system: false
|
||||
created_at: string
|
||||
updated_at: string
|
||||
chart_of_account: ChartOfAccount
|
||||
}
|
||||
|
||||
export interface Accounts {
|
||||
data: Account[]
|
||||
limit: number
|
||||
page: number
|
||||
total: number
|
||||
}
|
||||
@ -1,56 +1,103 @@
|
||||
export interface Product {
|
||||
ID: string;
|
||||
OrganizationID: string;
|
||||
CategoryID: string;
|
||||
SKU: string;
|
||||
Name: string;
|
||||
Description: string | null;
|
||||
Price: number;
|
||||
Cost: number;
|
||||
BusinessType: string;
|
||||
ImageURL: string;
|
||||
PrinterType: string;
|
||||
UnitID: string | null;
|
||||
HasIngredients: boolean;
|
||||
Metadata: Record<string, any>;
|
||||
IsActive: boolean;
|
||||
CreatedAt: string; // ISO date string
|
||||
UpdatedAt: string; // ISO date string
|
||||
ID: string
|
||||
OrganizationID: string
|
||||
CategoryID: string
|
||||
SKU: string
|
||||
Name: string
|
||||
Description: string | null
|
||||
Price: number
|
||||
Cost: number
|
||||
BusinessType: string
|
||||
ImageURL: string
|
||||
PrinterType: string
|
||||
UnitID: string | null
|
||||
HasIngredients: boolean
|
||||
Metadata: Record<string, any>
|
||||
IsActive: boolean
|
||||
CreatedAt: string // ISO date string
|
||||
UpdatedAt: string // ISO date string
|
||||
}
|
||||
|
||||
export interface Ingredient {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
outlet_id: string | null;
|
||||
name: string;
|
||||
unit_id: string;
|
||||
cost: number;
|
||||
stock: number;
|
||||
is_semi_finished: boolean;
|
||||
is_active: boolean;
|
||||
metadata: Record<string, any>;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
id: string
|
||||
organization_id: string
|
||||
outlet_id: string | null
|
||||
name: string
|
||||
unit_id: string
|
||||
cost: number
|
||||
stock: number
|
||||
is_semi_finished: boolean
|
||||
is_active: boolean
|
||||
metadata: Record<string, any>
|
||||
created_at: string
|
||||
updated_at: string
|
||||
unit: IngredientUnit
|
||||
}
|
||||
|
||||
export interface ProductRecipe {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
outlet_id: string | null;
|
||||
product_id: string;
|
||||
variant_id: string | null;
|
||||
ingredient_id: string;
|
||||
quantity: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
product: Product;
|
||||
ingredient: Ingredient;
|
||||
id: string
|
||||
organization_id: string
|
||||
outlet_id: string | null
|
||||
product_id: string
|
||||
variant_id: string | null
|
||||
ingredient_id: string
|
||||
quantity: number
|
||||
waste: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
product: Product
|
||||
ingredient: Ingredient
|
||||
}
|
||||
|
||||
export interface ProductRecipeRequest {
|
||||
product_id: string;
|
||||
variant_id: string | null;
|
||||
ingredient_id: string;
|
||||
quantity: number;
|
||||
outlet_id: string | null;
|
||||
product_id: string
|
||||
variant_id: string | null
|
||||
ingredient_id: string
|
||||
quantity: number
|
||||
outlet_id: string | null
|
||||
waste: number
|
||||
}
|
||||
|
||||
export interface IngredientUnit {
|
||||
id: string
|
||||
organization_id: string
|
||||
outlet_id: string
|
||||
name: string
|
||||
abbreviation: string
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface IngredientUnitConverterRequest {
|
||||
ingredient_id: string
|
||||
from_unit_id: string
|
||||
to_unit_id: string
|
||||
conversion_factor: number
|
||||
}
|
||||
|
||||
export interface UnitConversion {
|
||||
id: string
|
||||
organization_id: string
|
||||
ingredient_id: string
|
||||
from_unit_id: string
|
||||
to_unit_id: string
|
||||
conversion_factor: number
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
created_by: string
|
||||
updated_by: string
|
||||
from_unit: UnitConversionFrom
|
||||
to_unit: UnitConversionTo
|
||||
}
|
||||
|
||||
export interface UnitConversionFrom {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface UnitConversionTo {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
120
src/types/services/purchaseOrder.ts
Normal file
120
src/types/services/purchaseOrder.ts
Normal file
@ -0,0 +1,120 @@
|
||||
import { IngredientItem } from './ingredient'
|
||||
import { Vendor } from './vendor'
|
||||
|
||||
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 interface PurchaseOrders {
|
||||
purchase_orders: PurchaseOrder[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
export interface PurchaseOrder {
|
||||
id: string
|
||||
organization_id: string
|
||||
vendor_id: string
|
||||
po_number: string
|
||||
transaction_date: string // RFC3339
|
||||
due_date: string // RFC3339
|
||||
reference: string | null
|
||||
status: string
|
||||
message: string | null
|
||||
total_amount: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
vendor: Vendor
|
||||
items: PurchaseOrderItem[]
|
||||
attachments: PurchaseOrderAttachment[]
|
||||
}
|
||||
|
||||
export interface PurchaseOrderItem {
|
||||
id: string
|
||||
purchase_order_id: string
|
||||
ingredient_id: string
|
||||
description: string
|
||||
quantity: number
|
||||
unit_id: string
|
||||
amount: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
ingredient: PurchaseOrderIngredient
|
||||
unit: PurchaseOrderUnit
|
||||
}
|
||||
|
||||
export interface PurchaseOrderIngredient {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface PurchaseOrderUnit {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface PurchaseOrderAttachment {
|
||||
id: string
|
||||
purchase_order_id: string
|
||||
file_id: string
|
||||
created_at: string
|
||||
file: PurchaseOrderFile
|
||||
}
|
||||
|
||||
export interface PurchaseOrderFile {
|
||||
id: string
|
||||
organization_id: string
|
||||
user_id: string
|
||||
file_name: string
|
||||
original_name: string
|
||||
file_url: string
|
||||
file_size: number
|
||||
mime_type: string
|
||||
file_type: string
|
||||
upload_path: string
|
||||
is_public: boolean
|
||||
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
|
||||
}
|
||||
35
src/types/services/vendor.ts
Normal file
35
src/types/services/vendor.ts
Normal file
@ -0,0 +1,35 @@
|
||||
export interface Vendor {
|
||||
id: string
|
||||
organization_id: string
|
||||
name: string
|
||||
email?: string
|
||||
phone_number?: string
|
||||
address?: string
|
||||
contact_person?: string
|
||||
tax_number?: string
|
||||
payment_terms?: string
|
||||
notes?: string
|
||||
is_active: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface Vendors {
|
||||
vendors: Vendor[]
|
||||
total_count: number
|
||||
page: number
|
||||
limit: number
|
||||
total_pages: number
|
||||
}
|
||||
|
||||
export interface VendorRequest {
|
||||
name: string
|
||||
email?: string
|
||||
phone_number?: string
|
||||
address?: string
|
||||
contact_person?: string
|
||||
tax_number?: string
|
||||
payment_terms?: string
|
||||
notes?: string
|
||||
is_active: boolean
|
||||
}
|
||||
@ -5,7 +5,6 @@ import { useState, useEffect } from 'react'
|
||||
import Button from '@mui/material/Button'
|
||||
import Drawer from '@mui/material/Drawer'
|
||||
import IconButton from '@mui/material/IconButton'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Box from '@mui/material/Box'
|
||||
|
||||
@ -15,64 +14,52 @@ import { useForm, Controller } from 'react-hook-form'
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
|
||||
|
||||
// Account Type
|
||||
export type AccountType = {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
category: string
|
||||
balance: string
|
||||
}
|
||||
import { AccountRequest } from '@/services/queries/chartOfAccountType'
|
||||
import { useChartOfAccount } from '@/services/queries/chartOfAccount'
|
||||
import { Account, ChartOfAccount } from '@/types/services/chartOfAccount'
|
||||
import { useAccountsMutation } from '@/services/mutations/account'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
accountData?: AccountType[]
|
||||
setData: (data: AccountType[]) => void
|
||||
editingAccount?: AccountType | null
|
||||
accountData?: Account[]
|
||||
setData: (data: Account[]) => void
|
||||
editingAccount?: Account | null
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
code: string
|
||||
category: string
|
||||
parentAccount?: string
|
||||
account_type: string
|
||||
opening_balance: number
|
||||
description: string
|
||||
chart_of_account_id: string
|
||||
}
|
||||
|
||||
// Categories available for accounts
|
||||
const accountCategories = [
|
||||
'Kas & Bank',
|
||||
'Piutang',
|
||||
'Persediaan',
|
||||
'Aset Tetap',
|
||||
'Hutang',
|
||||
'Ekuitas',
|
||||
'Pendapatan',
|
||||
'Beban'
|
||||
]
|
||||
|
||||
// Parent accounts (dummy data for dropdown)
|
||||
const parentAccounts = [
|
||||
{ id: 1, code: '1-10001', name: 'Kas' },
|
||||
{ id: 2, code: '1-10002', name: 'Bank BCA' },
|
||||
{ id: 3, code: '1-10003', name: 'Bank Mandiri' },
|
||||
{ id: 4, code: '1-10101', name: 'Piutang Usaha' },
|
||||
{ id: 5, code: '1-10201', name: 'Persediaan Barang' },
|
||||
{ id: 6, code: '2-20001', name: 'Hutang Usaha' },
|
||||
{ id: 7, code: '3-30001', name: 'Modal Pemilik' },
|
||||
{ id: 8, code: '4-40001', name: 'Penjualan' },
|
||||
{ id: 9, code: '5-50001', name: 'Beban Gaji' }
|
||||
]
|
||||
|
||||
// Vars
|
||||
const initialData = {
|
||||
name: '',
|
||||
code: '',
|
||||
category: '',
|
||||
parentAccount: ''
|
||||
account_type: '',
|
||||
opening_balance: 0,
|
||||
description: '',
|
||||
chart_of_account_id: ''
|
||||
}
|
||||
|
||||
// Static Account Types
|
||||
const staticAccountTypes = [
|
||||
{ id: '1', name: 'Cash', code: 'cash', description: 'Cash account' },
|
||||
{ id: '2', name: 'Wallet', code: 'wallet', description: 'Digital wallet account' },
|
||||
{ id: '3', name: 'Bank', code: 'bank', description: 'Bank account' },
|
||||
{ id: '4', name: 'Credit', code: 'credit', description: 'Credit account' },
|
||||
{ id: '5', name: 'Debit', code: 'debit', description: 'Debit account' },
|
||||
{ id: '6', name: 'Asset', code: 'asset', description: 'Asset account' },
|
||||
{ id: '7', name: 'Liability', code: 'liability', description: 'Liability account' },
|
||||
{ id: '8', name: 'Equity', code: 'equity', description: 'Equity account' },
|
||||
{ id: '9', name: 'Revenue', code: 'revenue', description: 'Revenue account' },
|
||||
{ id: '10', name: 'Expense', code: 'expense', description: 'Expense account' }
|
||||
]
|
||||
|
||||
const AccountFormDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, accountData, setData, editingAccount } = props
|
||||
@ -80,6 +67,28 @@ const AccountFormDrawer = (props: Props) => {
|
||||
// Determine if we're editing
|
||||
const isEdit = !!editingAccount
|
||||
|
||||
const { data: accounts, isLoading: isLoadingAccounts } = useChartOfAccount({
|
||||
page: 1,
|
||||
limit: 100
|
||||
})
|
||||
|
||||
const { createAccount, updateAccount } = useAccountsMutation()
|
||||
|
||||
// Use static account types
|
||||
const accountTypeOptions = staticAccountTypes
|
||||
|
||||
// Process chart of accounts for the dropdown
|
||||
const chartOfAccountOptions = accounts?.data.length
|
||||
? accounts.data
|
||||
.filter(account => account.is_active) // Only show active accounts
|
||||
.map(account => ({
|
||||
id: account.id,
|
||||
code: account.code,
|
||||
name: account.name,
|
||||
description: account.description
|
||||
}))
|
||||
: []
|
||||
|
||||
// Hooks
|
||||
const {
|
||||
control,
|
||||
@ -97,9 +106,11 @@ const AccountFormDrawer = (props: Props) => {
|
||||
// Populate form with existing data
|
||||
resetForm({
|
||||
name: editingAccount.name,
|
||||
code: editingAccount.code,
|
||||
category: editingAccount.category,
|
||||
parentAccount: ''
|
||||
code: editingAccount.number,
|
||||
account_type: editingAccount.account_type,
|
||||
opening_balance: editingAccount.opening_balance,
|
||||
description: editingAccount.description || '',
|
||||
chart_of_account_id: editingAccount.chart_of_account_id
|
||||
})
|
||||
} else {
|
||||
// Reset to initial data for new account
|
||||
@ -110,36 +121,41 @@ const AccountFormDrawer = (props: Props) => {
|
||||
|
||||
const onSubmit = (data: FormValidateType) => {
|
||||
if (isEdit && editingAccount) {
|
||||
// Update existing account
|
||||
const updatedAccounts =
|
||||
accountData?.map(account =>
|
||||
account.id === editingAccount.id
|
||||
? {
|
||||
...account,
|
||||
code: data.code,
|
||||
const accountRequest: AccountRequest = {
|
||||
chart_of_account_id: data.chart_of_account_id,
|
||||
name: data.name,
|
||||
category: data.category
|
||||
number: data.code,
|
||||
account_type: data.account_type,
|
||||
opening_balance: data.opening_balance,
|
||||
description: data.description
|
||||
}
|
||||
: account
|
||||
) || []
|
||||
|
||||
setData(updatedAccounts)
|
||||
} else {
|
||||
// Create new account
|
||||
const newAccount: AccountType = {
|
||||
id: accountData?.length ? Math.max(...accountData.map(a => a.id)) + 1 : 1,
|
||||
code: data.code,
|
||||
name: data.name,
|
||||
category: data.category,
|
||||
balance: '0'
|
||||
}
|
||||
|
||||
setData([...(accountData ?? []), newAccount])
|
||||
}
|
||||
|
||||
updateAccount.mutate(
|
||||
{ id: editingAccount.id, payload: accountRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new account - this would typically be sent as AccountRequest to API
|
||||
const accountRequest: AccountRequest = {
|
||||
chart_of_account_id: data.chart_of_account_id,
|
||||
name: data.name,
|
||||
number: data.code,
|
||||
account_type: data.account_type,
|
||||
opening_balance: data.opening_balance,
|
||||
description: data.description
|
||||
}
|
||||
createAccount.mutate(accountRequest, {
|
||||
onSuccess: () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
@ -225,55 +241,127 @@ const AccountFormDrawer = (props: Props) => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Kategori */}
|
||||
{/* Tipe Akun */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Kategori <span className='text-red-500'>*</span>
|
||||
Tipe Akun <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='category'
|
||||
name='account_type'
|
||||
control={control}
|
||||
rules={{ required: true }}
|
||||
render={({ field: { onChange, value, ...field } }) => (
|
||||
<CustomAutocomplete
|
||||
{...field}
|
||||
options={accountCategories}
|
||||
value={value || null}
|
||||
onChange={(_, newValue) => onChange(newValue || '')}
|
||||
options={accountTypeOptions}
|
||||
value={accountTypeOptions.find(option => option.code === value) || null}
|
||||
onChange={(_, newValue) => onChange(newValue?.code || '')}
|
||||
getOptionLabel={option => option.name}
|
||||
renderOption={(props, option) => (
|
||||
<Box component='li' {...props}>
|
||||
<div>
|
||||
<Typography variant='body2'>{option.name}</Typography>
|
||||
</div>
|
||||
</Box>
|
||||
)}
|
||||
renderInput={params => (
|
||||
<CustomTextField
|
||||
{...params}
|
||||
placeholder='Pilih kategori'
|
||||
{...(errors.category && { error: true, helperText: 'Field ini wajib diisi.' })}
|
||||
placeholder='Pilih tipe akun'
|
||||
{...(errors.account_type && { error: true, helperText: 'Field ini wajib diisi.' })}
|
||||
/>
|
||||
)}
|
||||
isOptionEqualToValue={(option, value) => option === value}
|
||||
isOptionEqualToValue={(option, value) => option.code === value.code}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sub Akun dari */}
|
||||
{/* Chart of Account */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Sub Akun dari
|
||||
Chart of Account <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='parentAccount'
|
||||
name='chart_of_account_id'
|
||||
control={control}
|
||||
rules={{ required: true }}
|
||||
render={({ field: { onChange, value, ...field } }) => (
|
||||
<CustomAutocomplete
|
||||
{...field}
|
||||
options={parentAccounts}
|
||||
value={parentAccounts.find(account => `${account.code} ${account.name}` === value) || null}
|
||||
onChange={(_, newValue) => onChange(newValue ? `${newValue.code} ${newValue.name}` : '')}
|
||||
getOptionLabel={option => `${option.code} ${option.name}`}
|
||||
renderInput={params => <CustomTextField {...params} placeholder='Pilih akun' />}
|
||||
isOptionEqualToValue={(option, value) =>
|
||||
`${option.code} ${option.name}` === `${value.code} ${value.name}`
|
||||
}
|
||||
loading={isLoadingAccounts}
|
||||
options={chartOfAccountOptions}
|
||||
value={chartOfAccountOptions.find(option => option.id === value) || null}
|
||||
onChange={(_, newValue) => onChange(newValue?.id || '')}
|
||||
getOptionLabel={option => `${option.code} - ${option.name}`}
|
||||
renderOption={(props, option) => (
|
||||
<Box component='li' {...props}>
|
||||
<div>
|
||||
<Typography variant='body2'>
|
||||
{option.code} - {option.name}
|
||||
</Typography>
|
||||
{option.description && (
|
||||
<Typography variant='caption' color='textSecondary'>
|
||||
{option.description}
|
||||
</Typography>
|
||||
)}
|
||||
</div>
|
||||
</Box>
|
||||
)}
|
||||
renderInput={params => (
|
||||
<CustomTextField
|
||||
{...params}
|
||||
placeholder={isLoadingAccounts ? 'Loading chart of accounts...' : 'Pilih chart of account'}
|
||||
{...(errors.chart_of_account_id && { error: true, helperText: 'Field ini wajib diisi.' })}
|
||||
/>
|
||||
)}
|
||||
isOptionEqualToValue={(option, value) => option.id === value.id}
|
||||
disabled={isLoadingAccounts}
|
||||
noOptionsText={isLoadingAccounts ? 'Loading...' : 'Tidak ada chart of account tersedia'}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Opening Balance */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Saldo Awal <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='opening_balance'
|
||||
control={control}
|
||||
rules={{ required: true, min: 0 }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='number'
|
||||
placeholder='0'
|
||||
onChange={e => field.onChange(Number(e.target.value))}
|
||||
{...(errors.opening_balance && {
|
||||
error: true,
|
||||
helperText:
|
||||
errors.opening_balance.type === 'min'
|
||||
? 'Saldo awal tidak boleh negatif.'
|
||||
: 'Field ini wajib diisi.'
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Deskripsi */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Deskripsi
|
||||
</Typography>
|
||||
<Controller
|
||||
name='description'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField {...field} fullWidth multiline rows={3} placeholder='Deskripsi akun' />
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -41,6 +41,11 @@ import TablePaginationComponent from '@/components/TablePaginationComponent'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import AccountFormDrawer from './AccountFormDrawer'
|
||||
import { useChartOfAccount } from '@/services/queries/chartOfAccount'
|
||||
import { Account, ChartOfAccount } from '@/types/services/chartOfAccount'
|
||||
import { useAccounts } from '@/services/queries/account'
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
import { useChartOfAccountTypes } from '@/services/queries/chartOfAccountType'
|
||||
|
||||
// Account Type
|
||||
export type AccountType = {
|
||||
@ -60,119 +65,10 @@ declare module '@tanstack/table-core' {
|
||||
}
|
||||
}
|
||||
|
||||
type AccountTypeWithAction = AccountType & {
|
||||
type AccountTypeWithAction = Account & {
|
||||
actions?: string
|
||||
}
|
||||
|
||||
// Dummy Account Data
|
||||
export const accountsData: AccountType[] = [
|
||||
{
|
||||
id: 1,
|
||||
code: '1-10001',
|
||||
name: 'Kas',
|
||||
category: 'Kas & Bank',
|
||||
balance: '20000000'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
code: '1-10002',
|
||||
name: 'Bank BCA',
|
||||
category: 'Kas & Bank',
|
||||
balance: '150000000'
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
code: '1-10003',
|
||||
name: 'Bank Mandiri',
|
||||
category: 'Kas & Bank',
|
||||
balance: '75000000'
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
code: '1-10101',
|
||||
name: 'Piutang Usaha',
|
||||
category: 'Piutang',
|
||||
balance: '50000000'
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
code: '1-10102',
|
||||
name: 'Piutang Karyawan',
|
||||
category: 'Piutang',
|
||||
balance: '5000000'
|
||||
},
|
||||
{
|
||||
id: 6,
|
||||
code: '1-10201',
|
||||
name: 'Persediaan Barang',
|
||||
category: 'Persediaan',
|
||||
balance: '100000000'
|
||||
},
|
||||
{
|
||||
id: 7,
|
||||
code: '1-10301',
|
||||
name: 'Peralatan Kantor',
|
||||
category: 'Aset Tetap',
|
||||
balance: '25000000'
|
||||
},
|
||||
{
|
||||
id: 8,
|
||||
code: '1-10302',
|
||||
name: 'Kendaraan',
|
||||
category: 'Aset Tetap',
|
||||
balance: '200000000'
|
||||
},
|
||||
{
|
||||
id: 9,
|
||||
code: '2-20001',
|
||||
name: 'Hutang Usaha',
|
||||
category: 'Hutang',
|
||||
balance: '-30000000'
|
||||
},
|
||||
{
|
||||
id: 10,
|
||||
code: '2-20002',
|
||||
name: 'Hutang Gaji',
|
||||
category: 'Hutang',
|
||||
balance: '-15000000'
|
||||
},
|
||||
{
|
||||
id: 11,
|
||||
code: '3-30001',
|
||||
name: 'Modal Pemilik',
|
||||
category: 'Ekuitas',
|
||||
balance: '500000000'
|
||||
},
|
||||
{
|
||||
id: 12,
|
||||
code: '4-40001',
|
||||
name: 'Penjualan',
|
||||
category: 'Pendapatan',
|
||||
balance: '250000000'
|
||||
},
|
||||
{
|
||||
id: 13,
|
||||
code: '5-50001',
|
||||
name: 'Beban Gaji',
|
||||
category: 'Beban',
|
||||
balance: '-80000000'
|
||||
},
|
||||
{
|
||||
id: 14,
|
||||
code: '5-50002',
|
||||
name: 'Beban Listrik',
|
||||
category: 'Beban',
|
||||
balance: '-5000000'
|
||||
},
|
||||
{
|
||||
id: 15,
|
||||
code: '5-50003',
|
||||
name: 'Beban Telepon',
|
||||
category: 'Beban',
|
||||
balance: '-2000000'
|
||||
}
|
||||
]
|
||||
|
||||
// Styled Components
|
||||
const Icon = styled('i')({})
|
||||
|
||||
@ -242,16 +138,6 @@ const getCategoryColor = (category: string) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Format currency
|
||||
const formatCurrency = (amount: string) => {
|
||||
const numAmount = parseInt(amount)
|
||||
return new Intl.NumberFormat('id-ID', {
|
||||
style: 'currency',
|
||||
currency: 'IDR',
|
||||
minimumFractionDigits: 0
|
||||
}).format(Math.abs(numAmount))
|
||||
}
|
||||
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<AccountTypeWithAction>()
|
||||
|
||||
@ -261,53 +147,25 @@ const AccountListTable = () => {
|
||||
// States
|
||||
const [addAccountOpen, setAddAccountOpen] = useState(false)
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [currentPage, setCurrentPage] = useState(0)
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [openConfirm, setOpenConfirm] = useState(false)
|
||||
const [accountId, setAccountId] = useState('')
|
||||
const [search, setSearch] = useState('')
|
||||
const [categoryFilter, setCategoryFilter] = useState<string>('Semua')
|
||||
const [filteredData, setFilteredData] = useState<AccountType[]>(accountsData)
|
||||
const [data, setData] = useState<AccountType[]>(accountsData)
|
||||
const [editingAccount, setEditingAccount] = useState<AccountType | null>(null)
|
||||
const [editingAccount, setEditingAccount] = useState<Account | null>(null)
|
||||
|
||||
const { data, isLoading } = useAccounts({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
// Get unique categories for filter
|
||||
const categories = useMemo(() => {
|
||||
const uniqueCategories = [...new Set(data.map(account => account.category))]
|
||||
return ['Semua', ...uniqueCategories]
|
||||
}, [data])
|
||||
|
||||
// Filter data based on search and category
|
||||
useEffect(() => {
|
||||
let filtered = data
|
||||
|
||||
// Filter by search
|
||||
if (search) {
|
||||
filtered = filtered.filter(
|
||||
account =>
|
||||
account.code.toLowerCase().includes(search.toLowerCase()) ||
|
||||
account.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
account.category.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
}
|
||||
|
||||
// Filter by category
|
||||
if (categoryFilter !== 'Semua') {
|
||||
filtered = filtered.filter(account => account.category === categoryFilter)
|
||||
}
|
||||
|
||||
setFilteredData(filtered)
|
||||
setCurrentPage(0)
|
||||
}, [search, categoryFilter, data])
|
||||
|
||||
const totalCount = filteredData.length
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = currentPage * pageSize
|
||||
return filteredData.slice(startIndex, startIndex + pageSize)
|
||||
}, [filteredData, currentPage, pageSize])
|
||||
const accounts = data?.data ?? []
|
||||
const totalCount = data?.total ?? 0
|
||||
|
||||
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||
setCurrentPage(newPage)
|
||||
@ -319,12 +177,8 @@ const AccountListTable = () => {
|
||||
setCurrentPage(0)
|
||||
}, [])
|
||||
|
||||
const handleDelete = () => {
|
||||
setOpenConfirm(false)
|
||||
}
|
||||
|
||||
// Handle row click for edit
|
||||
const handleRowClick = (account: AccountType, event: React.MouseEvent) => {
|
||||
const handleRowClick = (account: Account, event: React.MouseEvent) => {
|
||||
// Don't trigger row click if clicking on checkbox or link
|
||||
const target = event.target as HTMLElement
|
||||
if (target.closest('input[type="checkbox"]') || target.closest('a') || target.closest('button')) {
|
||||
@ -365,13 +219,17 @@ const AccountListTable = () => {
|
||||
/>
|
||||
)
|
||||
},
|
||||
columnHelper.accessor('code', {
|
||||
columnHelper.accessor('number', {
|
||||
header: 'Kode Akun',
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
className='p-0 min-w-0 font-medium normal-case justify-start'
|
||||
onClick={() => {
|
||||
setEditingAccount(row.original)
|
||||
setAddAccountOpen(true)
|
||||
}}
|
||||
sx={{
|
||||
textTransform: 'none',
|
||||
fontWeight: 500,
|
||||
@ -381,7 +239,7 @@ const AccountListTable = () => {
|
||||
}
|
||||
}}
|
||||
>
|
||||
{row.original.code}
|
||||
{row.original.number}
|
||||
</Button>
|
||||
)
|
||||
}),
|
||||
@ -393,26 +251,21 @@ const AccountListTable = () => {
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('category', {
|
||||
columnHelper.accessor('chart_of_account.name', {
|
||||
header: 'Kategori',
|
||||
cell: ({ row }) => (
|
||||
<Chip
|
||||
variant='tonal'
|
||||
label={row.original.category}
|
||||
size='small'
|
||||
color={getCategoryColor(row.original.category) as any}
|
||||
className='capitalize'
|
||||
/>
|
||||
<Typography color='text.primary' className='font-medium'>
|
||||
{row.original.chart_of_account.name}
|
||||
</Typography>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('balance', {
|
||||
columnHelper.accessor('current_balance', {
|
||||
header: 'Saldo',
|
||||
cell: ({ row }) => {
|
||||
const balance = parseInt(row.original.balance)
|
||||
return (
|
||||
<Typography className='font-medium text-right text-primary'>
|
||||
{balance < 0 ? '-' : ''}
|
||||
{formatCurrency(row.original.balance)}
|
||||
{row.original.current_balance < 0 ? '-' : ''}
|
||||
{formatCurrency(row.original.current_balance)}
|
||||
</Typography>
|
||||
)
|
||||
}
|
||||
@ -422,7 +275,7 @@ const AccountListTable = () => {
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: paginatedData as AccountType[],
|
||||
data: accounts as Account[],
|
||||
columns,
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter
|
||||
@ -484,6 +337,9 @@ const AccountListTable = () => {
|
||||
</div>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
{isLoading ? (
|
||||
<Loading />
|
||||
) : (
|
||||
<table className={tableStyles.table}>
|
||||
<thead>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
@ -512,7 +368,7 @@ const AccountListTable = () => {
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
{filteredData.length === 0 ? (
|
||||
{accounts.length === 0 ? (
|
||||
<tbody>
|
||||
<tr>
|
||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||
@ -541,6 +397,7 @@ const AccountListTable = () => {
|
||||
</tbody>
|
||||
)}
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TablePagination
|
||||
@ -558,13 +415,14 @@ const AccountListTable = () => {
|
||||
onPageChange={handlePageChange}
|
||||
onRowsPerPageChange={handlePageSizeChange}
|
||||
rowsPerPageOptions={[10, 25, 50]}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Card>
|
||||
<AccountFormDrawer
|
||||
open={addAccountOpen}
|
||||
handleClose={handleCloseDrawer}
|
||||
accountData={data}
|
||||
setData={setData}
|
||||
accountData={accounts}
|
||||
setData={() => {}}
|
||||
editingAccount={editingAccount}
|
||||
/>
|
||||
</>
|
||||
|
||||
@ -11,16 +11,18 @@ import FormControl from '@mui/material/FormControl'
|
||||
import InputLabel from '@mui/material/InputLabel'
|
||||
import Select from '@mui/material/Select'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import CircularProgress from '@mui/material/CircularProgress'
|
||||
import CashBankCard from './CashBankCard' // Adjust import path as needed
|
||||
import CustomTextField from '@/@core/components/mui/TextField'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import { Locale } from '@/configs/i18n'
|
||||
import { useParams } from 'next/navigation'
|
||||
import AccountFormDrawer, { AccountType } from '../account/AccountFormDrawer'
|
||||
import { accountsData } from '../account/AccountListTable'
|
||||
import AccountFormDrawer from '../account/AccountFormDrawer'
|
||||
import { Button } from '@mui/material'
|
||||
import { Account } from '@/types/services/chartOfAccount'
|
||||
import { useAccounts } from '@/services/queries/account'
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
|
||||
// Types
|
||||
interface BankAccount {
|
||||
id: string
|
||||
title: string
|
||||
@ -41,188 +43,28 @@ interface BankAccount {
|
||||
status: 'active' | 'inactive' | 'blocked'
|
||||
}
|
||||
|
||||
// Dummy Data
|
||||
const dummyAccounts: BankAccount[] = [
|
||||
{
|
||||
id: '1',
|
||||
title: 'Giro',
|
||||
accountNumber: '1-10003',
|
||||
balances: [
|
||||
{ amount: '7.313.321', label: 'Saldo di bank' },
|
||||
{ amount: '30.631.261', label: 'Saldo di kledo' }
|
||||
],
|
||||
chartData: [
|
||||
{
|
||||
name: 'Saldo',
|
||||
data: [
|
||||
20000000, 21000000, 20500000, 20800000, 21500000, 22000000, 25000000, 26000000, 28000000, 29000000, 30000000,
|
||||
31000000
|
||||
]
|
||||
// Static chart data for fallback/demo purposes
|
||||
const generateChartData = (accountType: string, balance: number) => {
|
||||
const baseValue = balance || 1000000
|
||||
const variation = baseValue * 0.2
|
||||
|
||||
return Array.from({ length: 12 }, (_, i) => {
|
||||
const randomVariation = (Math.random() - 0.5) * variation
|
||||
return Math.max(baseValue + randomVariation, baseValue * 0.5)
|
||||
})
|
||||
}
|
||||
],
|
||||
categories: ['Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des', 'Jan', 'Feb', 'Mar'],
|
||||
chartColor: '#ff6b9d',
|
||||
currency: 'IDR',
|
||||
accountType: 'giro',
|
||||
bank: 'Bank Mandiri',
|
||||
status: 'active'
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
title: 'Tabungan Premium',
|
||||
accountNumber: 'SAV-001234',
|
||||
balances: [
|
||||
{ amount: 15420000, label: 'Saldo Tersedia' },
|
||||
{ amount: 18750000, label: 'Total Saldo' }
|
||||
],
|
||||
chartData: [
|
||||
{
|
||||
name: 'Balance',
|
||||
data: [
|
||||
12000000, 13500000, 14200000, 15000000, 15800000, 16200000, 17000000, 17500000, 18000000, 18200000, 18500000,
|
||||
18750000
|
||||
]
|
||||
|
||||
const getChartColor = (accountType: string) => {
|
||||
const colors = {
|
||||
giro: '#ff6b9d',
|
||||
savings: '#4285f4',
|
||||
investment: '#00bcd4',
|
||||
credit: '#ff9800',
|
||||
cash: '#4caf50'
|
||||
}
|
||||
],
|
||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],
|
||||
chartColor: '#4285f4',
|
||||
currency: 'IDR',
|
||||
accountType: 'savings',
|
||||
bank: 'Bank BCA',
|
||||
status: 'active'
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
title: 'Investment Portfolio',
|
||||
accountNumber: 'INV-789012',
|
||||
balances: [
|
||||
{ amount: 125000, label: 'Portfolio Value' },
|
||||
{ amount: 8750, label: 'Total Gains' }
|
||||
],
|
||||
chartData: [
|
||||
{
|
||||
name: 'Portfolio Value',
|
||||
data: [110000, 115000, 112000, 118000, 122000, 119000, 125000, 128000, 126000, 130000, 127000, 125000]
|
||||
return colors[accountType as keyof typeof colors] || '#757575'
|
||||
}
|
||||
],
|
||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
|
||||
currency: 'USD',
|
||||
accountType: 'investment',
|
||||
bank: 'Charles Schwab',
|
||||
status: 'active'
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
title: 'Kartu Kredit Platinum',
|
||||
accountNumber: 'CC-456789',
|
||||
balances: [
|
||||
{ amount: 2500000, label: 'Saldo Saat Ini' },
|
||||
{ amount: 47500000, label: 'Limit Tersedia' }
|
||||
],
|
||||
chartData: [
|
||||
{
|
||||
name: 'Spending',
|
||||
data: [
|
||||
1200000, 1800000, 2200000, 1900000, 2100000, 2400000, 2800000, 2600000, 2300000, 2500000, 2700000, 2500000
|
||||
]
|
||||
}
|
||||
],
|
||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],
|
||||
currency: 'IDR',
|
||||
accountType: 'credit',
|
||||
bank: 'Bank BNI',
|
||||
status: 'active'
|
||||
},
|
||||
{
|
||||
id: '5',
|
||||
title: 'Deposito Berjangka',
|
||||
accountNumber: 'DEP-334455',
|
||||
balances: [
|
||||
{ amount: 50000000, label: 'Pokok Deposito' },
|
||||
{ amount: 2500000, label: 'Bunga Terkumpul' }
|
||||
],
|
||||
chartData: [
|
||||
{
|
||||
name: 'Deposito Growth',
|
||||
data: [
|
||||
50000000, 50200000, 50420000, 50650000, 50880000, 51120000, 51360000, 51610000, 51860000, 52120000, 52380000,
|
||||
52500000
|
||||
]
|
||||
}
|
||||
],
|
||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],
|
||||
currency: 'IDR',
|
||||
accountType: 'savings',
|
||||
bank: 'Bank BRI',
|
||||
status: 'active'
|
||||
},
|
||||
{
|
||||
id: '6',
|
||||
title: 'Cash Management',
|
||||
accountNumber: 'CSH-111222',
|
||||
balances: [{ amount: 5000, label: 'Available Cash' }],
|
||||
chartData: [
|
||||
{
|
||||
name: 'Cash Flow',
|
||||
data: [4000, 4500, 4200, 4800, 5200, 4900, 5000, 5300, 5100, 5400, 5200, 5000]
|
||||
}
|
||||
],
|
||||
categories: ['Q1', 'Q2', 'Q3', 'Q4', 'Q1', 'Q2', 'Q3', 'Q4', 'Q1', 'Q2', 'Q3', 'Q4'],
|
||||
chartColor: '#00bcd4',
|
||||
currency: 'USD',
|
||||
accountType: 'cash',
|
||||
bank: 'Wells Fargo',
|
||||
status: 'active'
|
||||
},
|
||||
{
|
||||
id: '7',
|
||||
title: 'Rekening Bisnis',
|
||||
accountNumber: 'BIZ-998877',
|
||||
balances: [
|
||||
{ amount: 85000000, label: 'Saldo Operasional' },
|
||||
{ amount: 15000000, label: 'Dana Cadangan' }
|
||||
],
|
||||
chartData: [
|
||||
{
|
||||
name: 'Business Account',
|
||||
data: [
|
||||
70000000, 75000000, 80000000, 82000000, 85000000, 88000000, 90000000, 87000000, 85000000, 89000000, 92000000,
|
||||
100000000
|
||||
]
|
||||
}
|
||||
],
|
||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],
|
||||
chartColor: '#ff9800',
|
||||
currency: 'IDR',
|
||||
accountType: 'giro',
|
||||
bank: 'Bank Mandiri',
|
||||
status: 'active'
|
||||
},
|
||||
{
|
||||
id: '8',
|
||||
title: 'Tabungan Pendidikan',
|
||||
accountNumber: 'EDU-567890',
|
||||
balances: [
|
||||
{ amount: 25000000, label: 'Dana Pendidikan' },
|
||||
{ amount: 3500000, label: 'Bunga Terkumpul' }
|
||||
],
|
||||
chartData: [
|
||||
{
|
||||
name: 'Education Savings',
|
||||
data: [
|
||||
20000000, 21000000, 22000000, 23000000, 24000000, 24500000, 25000000, 25500000, 26000000, 27000000, 28000000,
|
||||
28500000
|
||||
]
|
||||
}
|
||||
],
|
||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],
|
||||
chartColor: '#3f51b5',
|
||||
currency: 'IDR',
|
||||
accountType: 'savings',
|
||||
bank: 'Bank BCA',
|
||||
status: 'inactive'
|
||||
}
|
||||
]
|
||||
|
||||
const DebouncedInput = ({
|
||||
value: initialValue,
|
||||
onChange,
|
||||
@ -251,28 +93,122 @@ const DebouncedInput = ({
|
||||
|
||||
return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
|
||||
}
|
||||
|
||||
const CashBankList = () => {
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [editingAccount, setEditingAccount] = useState<AccountType | null>(null)
|
||||
const [editingAccount, setEditingAccount] = useState<Account | null>(null)
|
||||
const [addAccountOpen, setAddAccountOpen] = useState(false)
|
||||
const [data, setData] = useState<AccountType[]>(accountsData)
|
||||
const [data, setData] = useState<Account[]>([])
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
// Use the accounts hook with search parameter
|
||||
const { data: accountsResponse, isLoading } = useAccounts({
|
||||
page: 1,
|
||||
limit: 10,
|
||||
search: searchQuery
|
||||
})
|
||||
|
||||
const handleCloseDrawer = () => {
|
||||
setAddAccountOpen(false)
|
||||
setEditingAccount(null)
|
||||
}
|
||||
|
||||
// Filter and search logic
|
||||
// Transform API data to match our BankAccount interface
|
||||
const transformedAccounts = useMemo((): BankAccount[] => {
|
||||
if (!accountsResponse?.data) return []
|
||||
|
||||
return accountsResponse.data.map((account: Account) => {
|
||||
const chartData = generateChartData(account.account_type, account.current_balance)
|
||||
|
||||
// Map account type to display type
|
||||
const typeMapping = {
|
||||
current_asset: 'giro' as const,
|
||||
non_current_asset: 'investment' as const,
|
||||
current_liability: 'credit' as const,
|
||||
non_current_liability: 'credit' as const,
|
||||
other_current_asset: 'cash' as const,
|
||||
other_current_liability: 'credit' as const,
|
||||
equity: 'savings' as const,
|
||||
revenue: 'savings' as const,
|
||||
expense: 'cash' as const
|
||||
}
|
||||
const displayAccountType = typeMapping[account.account_type as keyof typeof typeMapping] || 'giro'
|
||||
|
||||
// Get bank name from account
|
||||
const getBankName = (acc: Account): string => {
|
||||
if (acc.chart_of_account?.name) {
|
||||
return acc.chart_of_account.name
|
||||
}
|
||||
|
||||
const typeToBank = {
|
||||
current_asset: 'Bank Account',
|
||||
non_current_asset: 'Investment Account',
|
||||
current_liability: 'Credit Account',
|
||||
other_current_asset: 'Cash Account',
|
||||
equity: 'Equity Account',
|
||||
revenue: 'Revenue Account',
|
||||
expense: 'Expense Account'
|
||||
}
|
||||
|
||||
return typeToBank[acc.account_type as keyof typeof typeToBank] || 'General Account'
|
||||
}
|
||||
|
||||
// Create balance information
|
||||
const balances = []
|
||||
|
||||
if (account.current_balance !== account.opening_balance) {
|
||||
balances.push({
|
||||
amount: formatCurrency(account.current_balance),
|
||||
label: 'Saldo Saat Ini'
|
||||
})
|
||||
balances.push({
|
||||
amount: formatCurrency(account.opening_balance),
|
||||
label: 'Saldo Awal'
|
||||
})
|
||||
} else {
|
||||
balances.push({
|
||||
amount: formatCurrency(account.current_balance),
|
||||
label: 'Saldo'
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
id: account.id,
|
||||
title: account.name,
|
||||
accountNumber: account.number,
|
||||
balances,
|
||||
chartData: [
|
||||
{
|
||||
name: 'Saldo',
|
||||
data: chartData
|
||||
}
|
||||
],
|
||||
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'],
|
||||
chartColor: getChartColor(account.account_type),
|
||||
currency: 'IDR', // Assuming IDR as default, adjust as needed
|
||||
accountType: displayAccountType,
|
||||
bank: getBankName(account),
|
||||
status: account.is_active ? 'active' : 'inactive'
|
||||
}
|
||||
})
|
||||
}, [accountsResponse])
|
||||
|
||||
// Filter accounts based on search (if not handled by API)
|
||||
const filteredAccounts = useMemo(() => {
|
||||
return dummyAccounts.filter(account => {
|
||||
if (!searchQuery || accountsResponse) {
|
||||
// If using API search or no search, return transformed accounts as is
|
||||
return transformedAccounts
|
||||
}
|
||||
|
||||
// Local filtering fallback
|
||||
return transformedAccounts.filter(account => {
|
||||
const matchesSearch =
|
||||
account.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
account.accountNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
account.bank.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
return matchesSearch
|
||||
})
|
||||
}, [searchQuery])
|
||||
}, [transformedAccounts, searchQuery, accountsResponse])
|
||||
|
||||
return (
|
||||
<>
|
||||
@ -283,8 +219,16 @@ const CashBankList = () => {
|
||||
<DebouncedInput
|
||||
value={searchQuery}
|
||||
onChange={value => setSearchQuery(value as string)}
|
||||
placeholder='Cari '
|
||||
placeholder='Cari akun...'
|
||||
className='max-sm:is-full'
|
||||
disabled={isLoading}
|
||||
InputProps={{
|
||||
startAdornment: (
|
||||
<InputAdornment position='start'>
|
||||
<i className='tabler-search' />
|
||||
</InputAdornment>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<Box>
|
||||
<Button
|
||||
@ -295,6 +239,7 @@ const CashBankList = () => {
|
||||
setEditingAccount(null)
|
||||
setAddAccountOpen(true)
|
||||
}}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Tambah Akun
|
||||
</Button>
|
||||
@ -302,7 +247,15 @@ const CashBankList = () => {
|
||||
</div>
|
||||
</Box>
|
||||
|
||||
{/* Loading State */}
|
||||
{isLoading && (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* Account Cards */}
|
||||
{!isLoading && (
|
||||
<Grid container spacing={3}>
|
||||
{filteredAccounts.length > 0 ? (
|
||||
filteredAccounts.map(account => (
|
||||
@ -331,16 +284,40 @@ const CashBankList = () => {
|
||||
}}
|
||||
>
|
||||
<Typography variant='h6' color='text.secondary' gutterBottom>
|
||||
Tidak ada akun yang ditemukan
|
||||
{searchQuery ? 'Tidak ada akun yang ditemukan' : 'Belum ada akun'}
|
||||
</Typography>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
Coba ubah kata kunci pencarian atau filter yang digunakan
|
||||
{searchQuery
|
||||
? 'Coba ubah kata kunci pencarian yang digunakan'
|
||||
: 'Mulai dengan menambahkan akun baru'}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Grid>
|
||||
)}
|
||||
</Grid>
|
||||
)}
|
||||
|
||||
{/* Error State (if needed) */}
|
||||
{!isLoading && !accountsResponse && (
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<Box
|
||||
sx={{
|
||||
textAlign: 'center',
|
||||
py: 8,
|
||||
backgroundColor: 'error.light',
|
||||
borderRadius: 2,
|
||||
color: 'error.contrastText'
|
||||
}}
|
||||
>
|
||||
<Typography variant='h6' gutterBottom>
|
||||
Terjadi kesalahan saat memuat data
|
||||
</Typography>
|
||||
<Typography variant='body2'>Silakan coba lagi atau hubungi administrator</Typography>
|
||||
</Box>
|
||||
</Grid>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<AccountFormDrawer
|
||||
open={addAccountOpen}
|
||||
handleClose={handleCloseDrawer}
|
||||
|
||||
@ -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'
|
||||
|
||||
@ -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)}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
// React Imports
|
||||
import { useState } from 'react'
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Button from '@mui/material/Button'
|
||||
@ -17,101 +17,121 @@ import { useForm, Controller } from 'react-hook-form'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import { Ingredient } from '@/types/services/productRecipe'
|
||||
import { useUnits } from '@/services/queries/units'
|
||||
import { useUnitConventorMutation } from '@/services/mutations/unitConventor'
|
||||
|
||||
// Interface Integration
|
||||
export interface IngredientUnitConverterRequest {
|
||||
ingredient_id: string
|
||||
from_unit_id: string
|
||||
to_unit_id: string
|
||||
conversion_factor: number
|
||||
}
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
setData?: (data: any) => void
|
||||
setData?: (data: IngredientUnitConverterRequest) => void
|
||||
data?: Ingredient // Contains ingredientId, unit info, and cost
|
||||
}
|
||||
|
||||
type UnitConversionType = {
|
||||
satuan: string
|
||||
satuan: string // This will be from_unit_id
|
||||
quantity: number
|
||||
unit: string
|
||||
hargaBeli: number
|
||||
unit: string // This will be to_unit_id (from data)
|
||||
hargaBeli: number // Calculated as factor * ingredientCost
|
||||
hargaJual: number
|
||||
isDefault: boolean
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
conversions: UnitConversionType[]
|
||||
}
|
||||
|
||||
// Vars
|
||||
const initialConversion: UnitConversionType = {
|
||||
satuan: 'Box',
|
||||
quantity: 12,
|
||||
unit: 'Pcs',
|
||||
hargaBeli: 3588000,
|
||||
hargaJual: 5988000,
|
||||
isDefault: false
|
||||
}
|
||||
|
||||
const IngedientUnitConversionDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, setData } = props
|
||||
const { open, handleClose, setData, data } = props
|
||||
|
||||
// Extract values from data prop with safe defaults
|
||||
const ingredientId = data?.id || ''
|
||||
const toUnitId = data?.unit_id || data?.unit?.id || ''
|
||||
const ingredientCost = data?.cost || 0
|
||||
|
||||
const {
|
||||
data: units,
|
||||
isLoading,
|
||||
error,
|
||||
isFetching
|
||||
} = useUnits({
|
||||
page: 1,
|
||||
limit: 20
|
||||
})
|
||||
|
||||
// Vars - initial state with values from data
|
||||
const getInitialConversion = () => ({
|
||||
satuan: '',
|
||||
quantity: 1,
|
||||
unit: toUnitId, // Set from data
|
||||
hargaBeli: ingredientCost, // Will be calculated as factor * ingredientCost
|
||||
hargaJual: 0,
|
||||
isDefault: true
|
||||
})
|
||||
|
||||
// States
|
||||
const [conversions, setConversions] = useState<UnitConversionType[]>([initialConversion])
|
||||
const [conversion, setConversion] = useState<UnitConversionType>(getInitialConversion())
|
||||
const { createUnitConventer } = useUnitConventorMutation()
|
||||
|
||||
// Hooks
|
||||
const {
|
||||
control,
|
||||
reset: resetForm,
|
||||
handleSubmit,
|
||||
setValue,
|
||||
formState: { errors }
|
||||
} = useForm<FormValidateType>({
|
||||
defaultValues: {
|
||||
conversions: [initialConversion]
|
||||
}
|
||||
} = useForm<UnitConversionType>({
|
||||
defaultValues: getInitialConversion()
|
||||
})
|
||||
|
||||
// Update form when data changes
|
||||
useEffect(() => {
|
||||
if (toUnitId || ingredientCost) {
|
||||
const updatedConversion = getInitialConversion()
|
||||
setConversion(updatedConversion)
|
||||
resetForm(updatedConversion)
|
||||
}
|
||||
}, [toUnitId, ingredientCost, resetForm])
|
||||
|
||||
// Functions untuk konversi unit
|
||||
const handleTambahBaris = () => {
|
||||
const newConversion: UnitConversionType = {
|
||||
satuan: '',
|
||||
quantity: 0,
|
||||
unit: '',
|
||||
hargaBeli: 0,
|
||||
hargaJual: 0,
|
||||
isDefault: false
|
||||
}
|
||||
setConversions([...conversions, newConversion])
|
||||
const handleChangeConversion = (field: keyof UnitConversionType, value: any) => {
|
||||
const newConversion = { ...conversion, [field]: value }
|
||||
setConversion(newConversion)
|
||||
setValue(field, value)
|
||||
}
|
||||
|
||||
const handleHapusBaris = (index: number) => {
|
||||
if (conversions.length > 1) {
|
||||
const newConversions = conversions.filter((_, i) => i !== index)
|
||||
setConversions(newConversions)
|
||||
}
|
||||
const onSubmit = (data: UnitConversionType) => {
|
||||
// Transform form data to IngredientUnitConverterRequest
|
||||
const converterRequest: IngredientUnitConverterRequest = {
|
||||
ingredient_id: ingredientId,
|
||||
from_unit_id: conversion.satuan,
|
||||
to_unit_id: toUnitId, // Use toUnitId from data prop
|
||||
conversion_factor: conversion.quantity
|
||||
}
|
||||
|
||||
const handleChangeConversion = (index: number, field: keyof UnitConversionType, value: any) => {
|
||||
const newConversions = [...conversions]
|
||||
newConversions[index] = { ...newConversions[index], [field]: value }
|
||||
setConversions(newConversions)
|
||||
}
|
||||
console.log('Unit conversion request:', converterRequest)
|
||||
|
||||
const handleToggleDefault = (index: number) => {
|
||||
const newConversions = conversions.map((conversion, i) => ({
|
||||
...conversion,
|
||||
isDefault: i === index
|
||||
}))
|
||||
setConversions(newConversions)
|
||||
}
|
||||
|
||||
const onSubmit = (data: FormValidateType) => {
|
||||
console.log('Unit conversions:', conversions)
|
||||
if (setData) {
|
||||
setData(conversions)
|
||||
}
|
||||
// if (setData) {
|
||||
// setData(converterRequest)
|
||||
// }
|
||||
createUnitConventer.mutate(converterRequest, {
|
||||
onSuccess: () => {
|
||||
handleClose()
|
||||
resetForm(getInitialConversion())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
setConversions([initialConversion])
|
||||
resetForm({ conversions: [initialConversion] })
|
||||
const resetData = getInitialConversion()
|
||||
setConversion(resetData)
|
||||
resetForm(resetData)
|
||||
}
|
||||
|
||||
const formatNumber = (value: number) => {
|
||||
@ -122,6 +142,12 @@ const IngedientUnitConversionDrawer = (props: Props) => {
|
||||
return parseInt(value.replace(/\./g, '')) || 0
|
||||
}
|
||||
|
||||
// Calculate total purchase price: factor * ingredientCost
|
||||
const totalPurchasePrice = conversion.quantity * ingredientCost
|
||||
|
||||
// Validation to ensure all required fields are provided
|
||||
const isValidForSubmit = ingredientId && conversion.satuan && toUnitId && conversion.quantity > 0
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
@ -155,17 +181,37 @@ const IngedientUnitConversionDrawer = (props: Props) => {
|
||||
<i className='tabler-x text-2xl text-textPrimary' />
|
||||
</IconButton>
|
||||
</div>
|
||||
{!ingredientId && (
|
||||
<Box sx={{ px: 3, pb: 2 }}>
|
||||
<Typography variant='body2' color='error'>
|
||||
Warning: Ingredient data is required for conversion
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
{ingredientId && (
|
||||
<Box sx={{ px: 3, pb: 2 }}>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
Converting for: {data?.name || `Ingredient ${ingredientId}`}
|
||||
</Typography>
|
||||
{ingredientCost > 0 && (
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
Base cost per {units?.data.find(u => u.id === toUnitId)?.name || 'unit'}: Rp{' '}
|
||||
{formatNumber(ingredientCost)}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Scrollable Content */}
|
||||
<Box sx={{ flex: 1, overflowY: 'auto' }}>
|
||||
<form id='unit-conversion-form' onSubmit={handleSubmit(data => onSubmit(data))}>
|
||||
<form id='unit-conversion-form' onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Header Kolom */}
|
||||
<Grid container spacing={2} alignItems='center' className='bg-gray-50 p-3 rounded-lg'>
|
||||
<Grid size={2}>
|
||||
<Typography variant='body2' fontWeight='medium'>
|
||||
Satuan
|
||||
From Unit
|
||||
</Typography>
|
||||
</Grid>
|
||||
<Grid size={1} className='text-center'>
|
||||
@ -175,20 +221,20 @@ const IngedientUnitConversionDrawer = (props: Props) => {
|
||||
</Grid>
|
||||
<Grid size={1.5}>
|
||||
<Typography variant='body2' fontWeight='medium'>
|
||||
Jumlah
|
||||
Factor
|
||||
</Typography>
|
||||
</Grid>
|
||||
<Grid size={1.5}>
|
||||
<Typography variant='body2' fontWeight='medium'>
|
||||
Unit
|
||||
To Unit
|
||||
</Typography>
|
||||
</Grid>
|
||||
<Grid size={2}>
|
||||
<Grid size={2.5}>
|
||||
<Typography variant='body2' fontWeight='medium'>
|
||||
Harga Beli
|
||||
</Typography>
|
||||
</Grid>
|
||||
<Grid size={2}>
|
||||
<Grid size={2.5}>
|
||||
<Typography variant='body2' fontWeight='medium'>
|
||||
Harga Jual
|
||||
</Typography>
|
||||
@ -198,37 +244,48 @@ const IngedientUnitConversionDrawer = (props: Props) => {
|
||||
Default
|
||||
</Typography>
|
||||
</Grid>
|
||||
<Grid size={1}>
|
||||
</Grid>
|
||||
|
||||
{/* Form Input Row */}
|
||||
<Grid container spacing={2} alignItems='center' className='py-2'>
|
||||
{/* From Unit (Satuan) */}
|
||||
<Grid size={2}>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Typography variant='body2' fontWeight='medium'>
|
||||
Action
|
||||
1
|
||||
</Typography>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
{/* Baris Konversi */}
|
||||
{conversions.map((conversion, index) => (
|
||||
<Grid container spacing={2} alignItems='center' key={index} className='py-2'>
|
||||
<Grid size={0.5}>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
{index + 1}
|
||||
</Typography>
|
||||
</Grid>
|
||||
|
||||
{/* Satuan */}
|
||||
<Grid size={1.5}>
|
||||
<Controller
|
||||
name='satuan'
|
||||
control={control}
|
||||
rules={{ required: 'From unit wajib dipilih' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
select
|
||||
fullWidth
|
||||
size='small'
|
||||
value={conversion.satuan}
|
||||
onChange={e => handleChangeConversion(index, 'satuan', e.target.value)}
|
||||
error={!!errors.satuan}
|
||||
onChange={e => {
|
||||
field.onChange(e.target.value)
|
||||
handleChangeConversion('satuan', e.target.value)
|
||||
}}
|
||||
>
|
||||
<MenuItem value='Box'>Box</MenuItem>
|
||||
<MenuItem value='Kg'>Kg</MenuItem>
|
||||
<MenuItem value='Liter'>Liter</MenuItem>
|
||||
<MenuItem value='Pack'>Pack</MenuItem>
|
||||
<MenuItem value='Pcs'>Pcs</MenuItem>
|
||||
{units?.data
|
||||
.filter(unit => unit.id !== toUnitId) // Prevent selecting same unit as target
|
||||
.map(unit => (
|
||||
<MenuItem key={unit.id} value={unit.id}>
|
||||
{unit.name}
|
||||
</MenuItem>
|
||||
)) ?? []}
|
||||
</CustomTextField>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{errors.satuan && (
|
||||
<Typography variant='caption' color='error' className='mt-1'>
|
||||
{errors.satuan.message}
|
||||
</Typography>
|
||||
)}
|
||||
</Grid>
|
||||
|
||||
{/* Tanda sama dengan */}
|
||||
@ -236,59 +293,106 @@ const IngedientUnitConversionDrawer = (props: Props) => {
|
||||
<Typography variant='h6'>=</Typography>
|
||||
</Grid>
|
||||
|
||||
{/* Quantity */}
|
||||
{/* Conversion Factor (Quantity) */}
|
||||
<Grid size={1.5}>
|
||||
<Controller
|
||||
name='quantity'
|
||||
control={control}
|
||||
rules={{
|
||||
required: 'Conversion factor wajib diisi',
|
||||
min: { value: 0.01, message: 'Minimal 0.01' }
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
size='small'
|
||||
type='number'
|
||||
value={conversion.quantity}
|
||||
onChange={e => handleChangeConversion(index, 'quantity', parseInt(e.target.value) || 0)}
|
||||
error={!!errors.quantity}
|
||||
onChange={e => {
|
||||
const value = parseFloat(e.target.value) || 0
|
||||
field.onChange(value)
|
||||
handleChangeConversion('quantity', value)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{errors.quantity && (
|
||||
<Typography variant='caption' color='error' className='mt-1'>
|
||||
{errors.quantity.message}
|
||||
</Typography>
|
||||
)}
|
||||
</Grid>
|
||||
|
||||
{/* Unit */}
|
||||
{/* To Unit - Disabled because it comes from data */}
|
||||
<Grid size={1.5}>
|
||||
<CustomTextField
|
||||
select
|
||||
fullWidth
|
||||
size='small'
|
||||
value={conversion.unit}
|
||||
onChange={e => handleChangeConversion(index, 'unit', e.target.value)}
|
||||
value={toUnitId}
|
||||
disabled
|
||||
InputProps={{
|
||||
sx: { backgroundColor: 'grey.100' }
|
||||
}}
|
||||
>
|
||||
<MenuItem value='Pcs'>Pcs</MenuItem>
|
||||
<MenuItem value='Kg'>Kg</MenuItem>
|
||||
<MenuItem value='Gram'>Gram</MenuItem>
|
||||
<MenuItem value='Liter'>Liter</MenuItem>
|
||||
<MenuItem value='ML'>ML</MenuItem>
|
||||
{units?.data.map(unit => (
|
||||
<MenuItem key={unit.id} value={unit.id}>
|
||||
{unit.name}
|
||||
</MenuItem>
|
||||
)) ?? []}
|
||||
</CustomTextField>
|
||||
</Grid>
|
||||
|
||||
{/* Harga Beli */}
|
||||
<Grid size={2}>
|
||||
{/* Harga Beli - Calculated as factor * ingredientCost */}
|
||||
<Grid size={2.5}>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
size='small'
|
||||
value={formatNumber(conversion.hargaBeli)}
|
||||
onChange={e => handleChangeConversion(index, 'hargaBeli', parseNumber(e.target.value))}
|
||||
value={formatNumber(totalPurchasePrice)}
|
||||
disabled
|
||||
InputProps={{
|
||||
sx: { backgroundColor: 'grey.100' }
|
||||
}}
|
||||
placeholder='Calculated purchase price'
|
||||
/>
|
||||
</Grid>
|
||||
|
||||
{/* Harga Jual */}
|
||||
<Grid size={2}>
|
||||
<Grid size={2.5}>
|
||||
<Controller
|
||||
name='hargaJual'
|
||||
control={control}
|
||||
rules={{
|
||||
min: { value: 0, message: 'Tidak boleh negatif' }
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
size='small'
|
||||
error={!!errors.hargaJual}
|
||||
value={formatNumber(conversion.hargaJual)}
|
||||
onChange={e => handleChangeConversion(index, 'hargaJual', parseNumber(e.target.value))}
|
||||
onChange={e => {
|
||||
const value = parseNumber(e.target.value)
|
||||
field.onChange(value)
|
||||
handleChangeConversion('hargaJual', value)
|
||||
}}
|
||||
placeholder='Optional'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{errors.hargaJual && (
|
||||
<Typography variant='caption' color='error' className='mt-1'>
|
||||
{errors.hargaJual.message}
|
||||
</Typography>
|
||||
)}
|
||||
</Grid>
|
||||
|
||||
{/* Default Star */}
|
||||
<Grid size={1} className='text-center'>
|
||||
<IconButton
|
||||
size='small'
|
||||
onClick={() => handleToggleDefault(index)}
|
||||
onClick={() => handleChangeConversion('isDefault', !conversion.isDefault)}
|
||||
sx={{
|
||||
color: conversion.isDefault ? 'warning.main' : 'grey.400'
|
||||
}}
|
||||
@ -296,48 +400,67 @@ const IngedientUnitConversionDrawer = (props: Props) => {
|
||||
<i className={conversion.isDefault ? 'tabler-star-filled' : 'tabler-star'} />
|
||||
</IconButton>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
{/* Delete Button */}
|
||||
<Grid size={1} className='text-center'>
|
||||
{conversions.length > 1 && (
|
||||
<IconButton
|
||||
size='small'
|
||||
onClick={() => handleHapusBaris(index)}
|
||||
sx={{
|
||||
color: 'error.main',
|
||||
border: 1,
|
||||
borderColor: 'error.main',
|
||||
'&:hover': {
|
||||
backgroundColor: 'error.light',
|
||||
borderColor: 'error.main'
|
||||
}
|
||||
}}
|
||||
>
|
||||
<i className='tabler-trash' />
|
||||
</IconButton>
|
||||
{/* Conversion Preview */}
|
||||
{conversion.quantity > 0 && conversion.satuan && toUnitId && (
|
||||
<Box className='bg-green-50 p-4 rounded-lg border-l-4 border-green-500'>
|
||||
<Typography variant='body2' fontWeight='medium' className='mb-2'>
|
||||
Conversion Preview:
|
||||
</Typography>
|
||||
<Typography variant='body2' className='mb-1'>
|
||||
<strong>1 {units?.data.find(u => u.id === conversion.satuan)?.name || 'Unit'}</strong> ={' '}
|
||||
<strong>
|
||||
{conversion.quantity} {units?.data.find(u => u.id === toUnitId)?.name || 'Unit'}
|
||||
</strong>
|
||||
</Typography>
|
||||
<Typography variant='caption' color='text.secondary'>
|
||||
Conversion Factor: {conversion.quantity}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</Grid>
|
||||
</Grid>
|
||||
))}
|
||||
|
||||
{/* Tambah Baris Button */}
|
||||
<div className='flex items-center justify-start'>
|
||||
<Button
|
||||
variant='outlined'
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
onClick={handleTambahBaris}
|
||||
sx={{
|
||||
color: 'primary.main',
|
||||
borderColor: 'primary.main',
|
||||
'&:hover': {
|
||||
backgroundColor: 'primary.light',
|
||||
borderColor: 'primary.main'
|
||||
}
|
||||
}}
|
||||
>
|
||||
Tambah baris
|
||||
</Button>
|
||||
</div>
|
||||
{/* Price Summary */}
|
||||
{conversion.quantity > 0 && (ingredientCost > 0 || conversion.hargaJual > 0) && (
|
||||
<Box className='bg-blue-50 p-4 rounded-lg border-l-4 border-blue-500'>
|
||||
<Typography variant='body2' fontWeight='medium' className='mb-2'>
|
||||
Price Summary:
|
||||
</Typography>
|
||||
{ingredientCost > 0 && (
|
||||
<>
|
||||
<Typography variant='body2'>
|
||||
Total Purchase Price (1 {units?.data.find(u => u.id === conversion.satuan)?.name || 'From Unit'}):
|
||||
Rp {formatNumber(totalPurchasePrice)}
|
||||
</Typography>
|
||||
<Typography variant='body2'>
|
||||
Unit Cost per {units?.data.find(u => u.id === toUnitId)?.name || 'To Unit'}: Rp{' '}
|
||||
{formatNumber(ingredientCost)}
|
||||
</Typography>
|
||||
</>
|
||||
)}
|
||||
{conversion.hargaJual > 0 && (
|
||||
<>
|
||||
<Typography variant='body2'>
|
||||
Total Selling Price (1 {units?.data.find(u => u.id === conversion.satuan)?.name || 'From Unit'}):
|
||||
Rp {formatNumber(conversion.hargaJual)}
|
||||
</Typography>
|
||||
<Typography variant='body2'>
|
||||
Unit Selling Price per {units?.data.find(u => u.id === toUnitId)?.name || 'To Unit'}: Rp{' '}
|
||||
{formatNumber(Math.round(conversion.hargaJual / conversion.quantity))}
|
||||
</Typography>
|
||||
</>
|
||||
)}
|
||||
{ingredientCost > 0 && conversion.hargaJual > 0 && (
|
||||
<Typography variant='body2' className='mt-2 text-blue-700'>
|
||||
Total Margin: Rp {formatNumber(conversion.hargaJual - totalPurchasePrice)} (
|
||||
{totalPurchasePrice > 0
|
||||
? (((conversion.hargaJual - totalPurchasePrice) / totalPurchasePrice) * 100).toFixed(1)
|
||||
: 0}
|
||||
%)
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</Box>
|
||||
@ -355,13 +478,21 @@ const IngedientUnitConversionDrawer = (props: Props) => {
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center gap-4'>
|
||||
<Button variant='contained' type='submit' form='unit-conversion-form'>
|
||||
Simpan
|
||||
<Button variant='contained' type='submit' form='unit-conversion-form' disabled={!isValidForSubmit}>
|
||||
Simpan Konversi
|
||||
</Button>
|
||||
<Button variant='tonal' color='error' onClick={() => handleReset()}>
|
||||
<Button variant='tonal' color='error' onClick={handleReset}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
{!isValidForSubmit && (
|
||||
<Typography variant='caption' color='error' className='mt-2'>
|
||||
Please fill in all required fields: {!ingredientId && 'Ingredient Data, '}
|
||||
{!conversion.satuan && 'From Unit, '}
|
||||
{!toUnitId && 'To Unit (from ingredient data), '}
|
||||
{conversion.quantity <= 0 && 'Conversion Factor'}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</Drawer>
|
||||
)
|
||||
|
||||
@ -1,14 +1,19 @@
|
||||
import { Ingredient } from '@/types/services/productRecipe'
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
import { Card, CardHeader, Chip, Typography } from '@mui/material'
|
||||
|
||||
const IngredientDetailInfo = () => {
|
||||
interface Props {
|
||||
data: Ingredient | undefined
|
||||
}
|
||||
|
||||
const IngredientDetailInfo = ({ data }: Props) => {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader
|
||||
title={
|
||||
<div className='flex items-center gap-3'>
|
||||
<Typography variant='h4' component='h1' className='font-bold'>
|
||||
Tepung Terigu
|
||||
{data?.name ?? '-'}
|
||||
</Typography>
|
||||
<Chip label={'Active'} color={'success'} size='small' />
|
||||
</div>
|
||||
@ -17,7 +22,7 @@ const IngredientDetailInfo = () => {
|
||||
<div className='flex flex-col gap-1 mt-2'>
|
||||
<div className='flex gap-4'>
|
||||
<Typography variant='body2'>
|
||||
<span className='font-semibold'>Cost:</span> {formatCurrency(5000)}
|
||||
<span className='font-semibold'>Cost:</span> {formatCurrency(data?.cost ?? 0)}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -2,11 +2,19 @@
|
||||
import React, { useState } from 'react'
|
||||
import { Card, CardContent, CardHeader, Typography, Button, Box, Stack } from '@mui/material'
|
||||
import IngedientUnitConversionDrawer from './IngedientUnitConversionDrawer' // Sesuaikan dengan path file Anda
|
||||
import { Ingredient } from '@/types/services/productRecipe'
|
||||
import { useUnitConverterByIngredient } from '@/services/queries/unitConverter'
|
||||
|
||||
const IngredientDetailUnit = () => {
|
||||
interface Props {
|
||||
data: Ingredient | undefined
|
||||
}
|
||||
|
||||
const IngredientDetailUnit = ({ data }: Props) => {
|
||||
// State untuk mengontrol drawer
|
||||
const [openConversionDrawer, setOpenConversionDrawer] = useState(false)
|
||||
|
||||
const { data: unitConverters, isLoading } = useUnitConverterByIngredient(data?.id as string)
|
||||
|
||||
// Function untuk membuka drawer
|
||||
const handleOpenConversionDrawer = () => {
|
||||
setOpenConversionDrawer(true)
|
||||
@ -34,9 +42,19 @@ const IngredientDetailUnit = () => {
|
||||
Satuan Dasar
|
||||
</Typography>
|
||||
<Typography variant='body1' sx={{ fontWeight: 'medium' }}>
|
||||
: Pcs
|
||||
: {data?.unit.name ?? '-'}
|
||||
</Typography>
|
||||
</Box>
|
||||
{unitConverters?.map(unitConverter => (
|
||||
<Box sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<Typography variant='body1' color='text.secondary'>
|
||||
1 {unitConverter.from_unit.name}
|
||||
</Typography>
|
||||
<Typography variant='body1' sx={{ fontWeight: 'medium' }}>
|
||||
: {unitConverter.conversion_factor} {unitConverter.to_unit.name}
|
||||
</Typography>
|
||||
</Box>
|
||||
)) ?? []}
|
||||
</Stack>
|
||||
|
||||
<Button
|
||||
@ -61,6 +79,7 @@ const IngredientDetailUnit = () => {
|
||||
open={openConversionDrawer}
|
||||
handleClose={handleCloseConversionDrawer}
|
||||
setData={handleSetConversionData}
|
||||
data={data}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
|
||||
@ -6,11 +6,18 @@ import IngredientDetailInfo from './IngredientDetailInfo'
|
||||
import IngredientDetailUnit from './IngredientDetailUnit'
|
||||
import IngredientDetailStockAdjustmentDrawer from './IngredientDetailStockAdjustmentDrawer' // Sesuaikan dengan path file Anda
|
||||
import { Button } from '@mui/material'
|
||||
import { useParams } from 'next/navigation'
|
||||
import { useIngredientById } from '@/services/queries/ingredients'
|
||||
|
||||
const IngredientDetail = () => {
|
||||
// State untuk mengontrol stock adjustment drawer
|
||||
const [openStockAdjustmentDrawer, setOpenStockAdjustmentDrawer] = useState(false)
|
||||
|
||||
const params = useParams()
|
||||
const id = params?.id
|
||||
|
||||
const { data, isLoading } = useIngredientById(id as string)
|
||||
|
||||
// Function untuk membuka stock adjustment drawer
|
||||
const handleOpenStockAdjustmentDrawer = () => {
|
||||
setOpenStockAdjustmentDrawer(true)
|
||||
@ -32,7 +39,7 @@ const IngredientDetail = () => {
|
||||
<>
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={{ xs: 12, lg: 8, md: 7 }}>
|
||||
<IngredientDetailInfo />
|
||||
<IngredientDetailInfo data={data} />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, lg: 4, md: 5 }}>
|
||||
<Button
|
||||
@ -51,7 +58,7 @@ const IngredientDetail = () => {
|
||||
>
|
||||
Penyesuaian Stok
|
||||
</Button>
|
||||
<IngredientDetailUnit />
|
||||
<IngredientDetailUnit data={data} />
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
|
||||
@ -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>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@ -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>
|
||||
|
||||
121
src/views/apps/purchase/purchase-form copy/PurchaseAddForm.tsx
Normal file
121
src/views/apps/purchase/purchase-form copy/PurchaseAddForm.tsx
Normal file
@ -0,0 +1,121 @@
|
||||
'use client'
|
||||
|
||||
import React, { useState } from 'react'
|
||||
import { Card, CardContent } from '@mui/material'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import { IngredientItem, PurchaseOrderFormData } from '@/types/apps/purchaseOrderTypes'
|
||||
import PurchaseBasicInfo from './PurchaseBasicInfo'
|
||||
import PurchaseIngredientsTable from './PurchaseIngredientsTable'
|
||||
import PurchaseSummary from './PurchaseSummary'
|
||||
|
||||
const PurchaseAddForm: React.FC = () => {
|
||||
const [formData, setFormData] = useState<PurchaseOrderFormData>({
|
||||
vendor: null,
|
||||
nomor: 'PO/00043',
|
||||
tglTransaksi: '2025-09-09',
|
||||
tglJatuhTempo: '2025-09-10',
|
||||
referensi: '',
|
||||
termin: null,
|
||||
hargaTermasukPajak: true,
|
||||
// Shipping info
|
||||
showShippingInfo: false,
|
||||
tanggalPengiriman: '',
|
||||
ekspedisi: null,
|
||||
noResi: '',
|
||||
// Bottom section toggles
|
||||
showPesan: false,
|
||||
showAttachment: false,
|
||||
showTambahDiskon: false,
|
||||
showBiayaPengiriman: false,
|
||||
showBiayaTransaksi: false,
|
||||
showUangMuka: false,
|
||||
pesan: '',
|
||||
// Ingredient items (updated from productItems)
|
||||
ingredientItems: [
|
||||
{
|
||||
id: 1,
|
||||
ingredient: null,
|
||||
deskripsi: '',
|
||||
kuantitas: 1,
|
||||
satuan: null,
|
||||
discount: '0',
|
||||
harga: 0,
|
||||
pajak: null,
|
||||
waste: null,
|
||||
total: 0
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
const handleInputChange = (field: keyof PurchaseOrderFormData, value: any): void => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[field]: value
|
||||
}))
|
||||
}
|
||||
|
||||
const handleIngredientChange = (index: number, field: keyof IngredientItem, value: any): void => {
|
||||
setFormData(prev => {
|
||||
const newItems = [...prev.ingredientItems]
|
||||
newItems[index] = { ...newItems[index], [field]: value }
|
||||
|
||||
// Auto-calculate total if price or quantity changes
|
||||
if (field === 'harga' || field === 'kuantitas') {
|
||||
const item = newItems[index]
|
||||
item.total = item.harga * item.kuantitas
|
||||
}
|
||||
|
||||
return { ...prev, ingredientItems: newItems }
|
||||
})
|
||||
}
|
||||
|
||||
const addIngredientItem = (): void => {
|
||||
const newItem: IngredientItem = {
|
||||
id: Date.now(),
|
||||
ingredient: null,
|
||||
deskripsi: '',
|
||||
kuantitas: 1,
|
||||
satuan: null,
|
||||
discount: '0%',
|
||||
harga: 0,
|
||||
pajak: null,
|
||||
waste: null,
|
||||
total: 0
|
||||
}
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
ingredientItems: [...prev.ingredientItems, newItem]
|
||||
}))
|
||||
}
|
||||
|
||||
const removeIngredientItem = (index: number): void => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
ingredientItems: prev.ingredientItems.filter((_, i) => i !== index)
|
||||
}))
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Grid container spacing={3}>
|
||||
{/* Basic Info Section */}
|
||||
<PurchaseBasicInfo formData={formData} handleInputChange={handleInputChange} />
|
||||
|
||||
{/* Ingredients Table Section */}
|
||||
<PurchaseIngredientsTable
|
||||
formData={formData}
|
||||
handleIngredientChange={handleIngredientChange}
|
||||
addIngredientItem={addIngredientItem}
|
||||
removeIngredientItem={removeIngredientItem}
|
||||
/>
|
||||
|
||||
{/* Summary Section */}
|
||||
<PurchaseSummary formData={formData} handleInputChange={handleInputChange} />
|
||||
</Grid>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
export default PurchaseAddForm
|
||||
197
src/views/apps/purchase/purchase-form copy/PurchaseBasicInfo.tsx
Normal file
197
src/views/apps/purchase/purchase-form copy/PurchaseBasicInfo.tsx
Normal file
@ -0,0 +1,197 @@
|
||||
'use client'
|
||||
|
||||
import React from 'react'
|
||||
import { Button, Switch, FormControlLabel } from '@mui/material'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
|
||||
import CustomTextField from '@/@core/components/mui/TextField'
|
||||
import { DropdownOption, PurchaseOrderFormData } from '@/types/apps/purchaseOrderTypes'
|
||||
|
||||
interface PurchaseBasicInfoProps {
|
||||
formData: PurchaseOrderFormData
|
||||
handleInputChange: (field: keyof PurchaseOrderFormData, value: any) => void
|
||||
}
|
||||
|
||||
const PurchaseBasicInfo: React.FC<PurchaseBasicInfoProps> = ({ formData, handleInputChange }) => {
|
||||
// Sample data for dropdowns
|
||||
const vendorOptions: DropdownOption[] = [
|
||||
{ label: 'Vendor A', value: 'vendor_a' },
|
||||
{ label: 'Vendor B', value: 'vendor_b' },
|
||||
{ label: 'Vendor C', value: 'vendor_c' }
|
||||
]
|
||||
|
||||
const terminOptions: DropdownOption[] = [
|
||||
{ label: 'Net 30', value: 'net_30' },
|
||||
{ label: 'Net 15', value: 'net_15' },
|
||||
{ label: 'Net 60', value: 'net_60' },
|
||||
{ label: 'Cash on Delivery', value: 'cod' }
|
||||
]
|
||||
|
||||
const ekspedisiOptions: DropdownOption[] = [
|
||||
{ label: 'JNE', value: 'jne' },
|
||||
{ label: 'J&T Express', value: 'jnt' },
|
||||
{ label: 'SiCepat', value: 'sicepat' },
|
||||
{ label: 'Pos Indonesia', value: 'pos' },
|
||||
{ label: 'TIKI', value: 'tiki' }
|
||||
]
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Row 1 - Vendor dan Nomor */}
|
||||
<Grid size={{ xs: 12, sm: 6, md: 6 }}>
|
||||
<CustomAutocomplete
|
||||
fullWidth
|
||||
options={vendorOptions}
|
||||
value={formData.vendor}
|
||||
onChange={(event, newValue) => handleInputChange('vendor', newValue)}
|
||||
renderInput={params => <CustomTextField {...params} label='Vendor' placeholder='Pilih kontak' fullWidth />}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 6, md: 6 }}>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
label='Nomor'
|
||||
value={formData.nomor}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('nomor', e.target.value)}
|
||||
InputProps={{
|
||||
readOnly: true
|
||||
}}
|
||||
/>
|
||||
</Grid>
|
||||
|
||||
{/* Row 2 - Tgl. Transaksi, Tgl. Jatuh Tempo, Termin */}
|
||||
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
label='Tgl. Transaksi'
|
||||
type='date'
|
||||
value={formData.tglTransaksi}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('tglTransaksi', e.target.value)}
|
||||
InputLabelProps={{
|
||||
shrink: true
|
||||
}}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
label='Tgl. Jatuh Tempo'
|
||||
type='date'
|
||||
value={formData.tglJatuhTempo}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('tglJatuhTempo', e.target.value)}
|
||||
InputLabelProps={{
|
||||
shrink: true
|
||||
}}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
|
||||
<CustomAutocomplete
|
||||
fullWidth
|
||||
options={terminOptions}
|
||||
value={formData.termin}
|
||||
onChange={(event, newValue) => handleInputChange('termin', newValue)}
|
||||
renderInput={params => <CustomTextField {...params} label='Termin' placeholder='Net 30' fullWidth />}
|
||||
/>
|
||||
</Grid>
|
||||
|
||||
{/* Row 3 - Tampilkan Informasi Pengiriman */}
|
||||
<Grid size={12}>
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
onClick={() => handleInputChange('showShippingInfo', !formData.showShippingInfo)}
|
||||
sx={{
|
||||
textTransform: 'none',
|
||||
fontSize: '14px',
|
||||
fontWeight: 500,
|
||||
padding: '8px 0',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 1
|
||||
}}
|
||||
>
|
||||
{formData.showShippingInfo ? '−' : '+'} {formData.showShippingInfo ? 'Sembunyikan' : 'Tampilkan'} Informasi
|
||||
Pengiriman
|
||||
</Button>
|
||||
</Grid>
|
||||
|
||||
{/* Shipping Information - Conditional */}
|
||||
{formData.showShippingInfo && (
|
||||
<>
|
||||
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
label='Tanggal Pengiriman'
|
||||
type='date'
|
||||
placeholder='Pilih tanggal'
|
||||
value={formData.tanggalPengiriman}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
handleInputChange('tanggalPengiriman', e.target.value)
|
||||
}
|
||||
InputLabelProps={{
|
||||
shrink: true
|
||||
}}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
|
||||
<CustomAutocomplete
|
||||
fullWidth
|
||||
options={ekspedisiOptions}
|
||||
value={formData.ekspedisi}
|
||||
onChange={(event, newValue) => handleInputChange('ekspedisi', newValue)}
|
||||
renderInput={params => (
|
||||
<CustomTextField {...params} label='Ekspedisi' placeholder='Pilih ekspedisi' fullWidth />
|
||||
)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
label='No. Resi'
|
||||
placeholder='No. Resi'
|
||||
value={formData.noResi}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('noResi', e.target.value)}
|
||||
/>
|
||||
</Grid>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Row 4 - Referensi, SKU, Switch Pajak */}
|
||||
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
label='Referensi'
|
||||
placeholder='Referensi'
|
||||
value={formData.referensi}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('referensi', e.target.value)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 4, md: 4 }}>
|
||||
<CustomTextField fullWidth label='SKU' placeholder='Scan Barcode/SKU' variant='outlined' />
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, sm: 4, md: 4 }} sx={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={formData.hargaTermasukPajak}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
handleInputChange('hargaTermasukPajak', e.target.checked)
|
||||
}
|
||||
color='primary'
|
||||
/>
|
||||
}
|
||||
label='Harga termasuk pajak'
|
||||
sx={{
|
||||
marginLeft: 0,
|
||||
'& .MuiFormControlLabel-label': {
|
||||
fontSize: '14px',
|
||||
color: 'text.secondary'
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Grid>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default PurchaseBasicInfo
|
||||
@ -0,0 +1,225 @@
|
||||
'use client'
|
||||
|
||||
import React from 'react'
|
||||
import {
|
||||
Button,
|
||||
Typography,
|
||||
IconButton,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Paper
|
||||
} from '@mui/material'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
|
||||
import CustomTextField from '@/@core/components/mui/TextField'
|
||||
import { IngredientItem, PurchaseOrderFormData } from '@/types/apps/purchaseOrderTypes'
|
||||
|
||||
interface PurchaseIngredientsTableProps {
|
||||
formData: PurchaseOrderFormData
|
||||
handleIngredientChange: (index: number, field: keyof IngredientItem, value: any) => void
|
||||
addIngredientItem: () => void
|
||||
removeIngredientItem: (index: number) => void
|
||||
}
|
||||
|
||||
const PurchaseIngredientsTable: React.FC<PurchaseIngredientsTableProps> = ({
|
||||
formData,
|
||||
handleIngredientChange,
|
||||
addIngredientItem,
|
||||
removeIngredientItem
|
||||
}) => {
|
||||
const ingredientOptions = [
|
||||
{ label: 'Tepung Terigu Premium', value: 'tepung_terigu_premium' },
|
||||
{ label: 'Gula Pasir Halus', value: 'gula_pasir_halus' },
|
||||
{ label: 'Mentega Unsalted', value: 'mentega_unsalted' },
|
||||
{ label: 'Telur Ayam Grade A', value: 'telur_ayam_grade_a' },
|
||||
{ label: 'Vanilla Extract', value: 'vanilla_extract' },
|
||||
{ label: 'Coklat Chips', value: 'coklat_chips' }
|
||||
]
|
||||
|
||||
const satuanOptions = [
|
||||
{ label: 'KG', value: 'kg' },
|
||||
{ label: 'GRAM', value: 'gram' },
|
||||
{ label: 'LITER', value: 'liter' },
|
||||
{ label: 'ML', value: 'ml' },
|
||||
{ label: 'PCS', value: 'pcs' },
|
||||
{ label: 'PACK', value: 'pack' }
|
||||
]
|
||||
|
||||
const pajakOptions = [
|
||||
{ label: 'PPN 11%', value: 'ppn_11' },
|
||||
{ label: 'PPN 0%', value: 'ppn_0' },
|
||||
{ label: 'Bebas Pajak', value: 'tax_free' }
|
||||
]
|
||||
|
||||
const wasteOptions = [
|
||||
{ label: '2%', value: '2' },
|
||||
{ label: '5%', value: '5' },
|
||||
{ label: '10%', value: '10' },
|
||||
{ label: '15%', value: '15' },
|
||||
{ label: 'Custom', value: 'custom' }
|
||||
]
|
||||
|
||||
return (
|
||||
<Grid size={{ xs: 12 }} sx={{ mt: 4 }}>
|
||||
<Typography variant='h6' sx={{ mb: 2, fontWeight: 600 }}>
|
||||
Bahan Baku / Ingredients
|
||||
</Typography>
|
||||
|
||||
<TableContainer component={Paper} variant='outlined'>
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow sx={{ backgroundColor: 'grey.50' }}>
|
||||
<TableCell sx={{ fontWeight: 'bold', minWidth: 180 }}>Bahan Baku</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: 100 }}>Discount</TableCell>
|
||||
<TableCell sx={{ fontWeight: 'bold', width: 120 }}>Harga</TableCell>
|
||||
<TableCell sx={{ fontWeight: 'bold', width: 120 }}>Pajak</TableCell>
|
||||
<TableCell sx={{ fontWeight: 'bold', width: 120 }}>Waste</TableCell>
|
||||
<TableCell sx={{ fontWeight: 'bold', width: 100, textAlign: 'right' }}>Total</TableCell>
|
||||
<TableCell sx={{ width: 50 }}></TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{formData.ingredientItems.map((item: IngredientItem, index: number) => (
|
||||
<TableRow key={item.id}>
|
||||
<TableCell>
|
||||
<CustomAutocomplete
|
||||
size='small'
|
||||
options={ingredientOptions}
|
||||
value={item.ingredient}
|
||||
onChange={(event, newValue) => handleIngredientChange(index, 'ingredient', newValue)}
|
||||
renderInput={params => <CustomTextField {...params} placeholder='Pilih Bahan Baku' />}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
size='small'
|
||||
value={item.deskripsi}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
handleIngredientChange(index, 'deskripsi', e.target.value)
|
||||
}
|
||||
placeholder='Deskripsi'
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
size='small'
|
||||
type='number'
|
||||
value={item.kuantitas}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
handleIngredientChange(index, 'kuantitas', parseInt(e.target.value) || 1)
|
||||
}
|
||||
inputProps={{ min: 1 }}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<CustomAutocomplete
|
||||
size='small'
|
||||
options={satuanOptions}
|
||||
value={item.satuan}
|
||||
onChange={(event, newValue) => handleIngredientChange(index, 'satuan', newValue)}
|
||||
renderInput={params => <CustomTextField {...params} placeholder='Pilih...' />}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
size='small'
|
||||
value={item.discount}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
handleIngredientChange(index, 'discount', e.target.value)
|
||||
}
|
||||
placeholder='0%'
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
size='small'
|
||||
type='number'
|
||||
value={item.harga === 0 ? '' : item.harga?.toString() || ''}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const value = e.target.value
|
||||
|
||||
if (value === '') {
|
||||
handleIngredientChange(index, 'harga', null)
|
||||
return
|
||||
}
|
||||
|
||||
const numericValue = parseFloat(value)
|
||||
handleIngredientChange(index, 'harga', isNaN(numericValue) ? 0 : numericValue)
|
||||
}}
|
||||
inputProps={{ min: 0, step: 'any' }}
|
||||
placeholder='0'
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<CustomAutocomplete
|
||||
size='small'
|
||||
options={pajakOptions}
|
||||
value={item.pajak}
|
||||
onChange={(event, newValue) => handleIngredientChange(index, 'pajak', newValue)}
|
||||
renderInput={params => <CustomTextField {...params} placeholder='...' />}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<CustomAutocomplete
|
||||
size='small'
|
||||
options={wasteOptions}
|
||||
value={item.waste}
|
||||
onChange={(event, newValue) => handleIngredientChange(index, 'waste', newValue)}
|
||||
renderInput={params => <CustomTextField {...params} placeholder='...' />}
|
||||
/>
|
||||
</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={() => removeIngredientItem(index)}
|
||||
disabled={formData.ingredientItems.length === 1}
|
||||
>
|
||||
<i className='tabler-trash' />
|
||||
</IconButton>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
|
||||
{/* Add New Item Button */}
|
||||
<Button
|
||||
startIcon={<i className='tabler-plus' />}
|
||||
onClick={addIngredientItem}
|
||||
variant='outlined'
|
||||
size='small'
|
||||
sx={{ mt: 1 }}
|
||||
>
|
||||
Tambah bahan baku
|
||||
</Button>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default PurchaseIngredientsTable
|
||||
589
src/views/apps/purchase/purchase-form copy/PurchaseSummary.tsx
Normal file
589
src/views/apps/purchase/purchase-form copy/PurchaseSummary.tsx
Normal file
@ -0,0 +1,589 @@
|
||||
'use client'
|
||||
|
||||
import React from 'react'
|
||||
import { Button, Typography, Box, ToggleButton, ToggleButtonGroup, InputAdornment, IconButton } from '@mui/material'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import CustomTextField from '@/@core/components/mui/TextField'
|
||||
import { PurchaseOrderFormData, TransactionCost } from '@/types/apps/purchaseOrderTypes'
|
||||
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
|
||||
import ImageUpload from '@/components/ImageUpload'
|
||||
|
||||
interface PurchaseSummaryProps {
|
||||
formData: PurchaseOrderFormData
|
||||
handleInputChange: (field: keyof PurchaseOrderFormData, value: any) => void
|
||||
}
|
||||
|
||||
const PurchaseSummary: React.FC<PurchaseSummaryProps> = ({ formData, handleInputChange }) => {
|
||||
// Initialize transaction costs if not exist
|
||||
const transactionCosts = formData.transactionCosts || []
|
||||
|
||||
// Options for transaction cost types
|
||||
const transactionCostOptions = [
|
||||
{ label: 'Biaya Admin', value: 'admin' },
|
||||
{ label: 'Pajak', value: 'pajak' },
|
||||
{ label: 'Materai', value: 'materai' },
|
||||
{ label: 'Lainnya', value: 'lainnya' }
|
||||
]
|
||||
|
||||
// Add new transaction cost
|
||||
const addTransactionCost = () => {
|
||||
const newCost: TransactionCost = {
|
||||
id: Date.now().toString(),
|
||||
type: '',
|
||||
name: '',
|
||||
amount: ''
|
||||
}
|
||||
handleInputChange('transactionCosts', [...transactionCosts, newCost])
|
||||
}
|
||||
|
||||
// Remove transaction cost
|
||||
const removeTransactionCost = (id: string) => {
|
||||
const filtered = transactionCosts.filter((cost: TransactionCost) => cost.id !== id)
|
||||
handleInputChange('transactionCosts', filtered)
|
||||
}
|
||||
|
||||
// Update transaction cost
|
||||
const updateTransactionCost = (id: string, field: keyof TransactionCost, value: string) => {
|
||||
const updated = transactionCosts.map((cost: TransactionCost) =>
|
||||
cost.id === id ? { ...cost, [field]: value } : cost
|
||||
)
|
||||
handleInputChange('transactionCosts', updated)
|
||||
}
|
||||
|
||||
// Calculate discount amount based on percentage or fixed amount
|
||||
const calculateDiscount = () => {
|
||||
if (!formData.discountValue) return 0
|
||||
|
||||
const subtotal = formData.subtotal || 0
|
||||
if (formData.discountType === 'percentage') {
|
||||
return (subtotal * parseFloat(formData.discountValue)) / 100
|
||||
}
|
||||
return parseFloat(formData.discountValue)
|
||||
}
|
||||
|
||||
const discountAmount = calculateDiscount()
|
||||
const shippingCost = parseFloat(formData.shippingCost || '0')
|
||||
|
||||
// Calculate total transaction costs
|
||||
const totalTransactionCost = transactionCosts.reduce((sum: number, cost: TransactionCost) => {
|
||||
return sum + parseFloat(cost.amount || '0')
|
||||
}, 0)
|
||||
|
||||
const downPayment = parseFloat(formData.downPayment || '0')
|
||||
|
||||
// Calculate total (subtotal - discount + shipping + transaction costs)
|
||||
const total = (formData.subtotal || 0) - discountAmount + shippingCost + totalTransactionCost
|
||||
|
||||
// Calculate remaining balance (total - down payment)
|
||||
const remainingBalance = total - downPayment
|
||||
|
||||
const handleUpload = async (file: File): Promise<string> => {
|
||||
// Simulate upload
|
||||
return new Promise(resolve => {
|
||||
setTimeout(() => {
|
||||
resolve(URL.createObjectURL(file))
|
||||
}, 1000)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Grid size={12} sx={{ mt: 4 }}>
|
||||
<Grid container spacing={3}>
|
||||
{/* Left Side - Pesan and Attachment */}
|
||||
<Grid size={{ xs: 12, md: 7 }}>
|
||||
{/* Pesan 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.pesan || ''}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange('pesan', 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>
|
||||
Attachment
|
||||
</Button>
|
||||
{formData.showAttachment && (
|
||||
<ImageUpload
|
||||
onUpload={handleUpload}
|
||||
maxFileSize={1 * 1024 * 1024} // 1MB
|
||||
showUrlOption={false}
|
||||
dragDropText='Drop your image here'
|
||||
browseButtonText='Choose Image'
|
||||
/>
|
||||
)}
|
||||
</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(formData.subtotal || 0)}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* Additional Options */}
|
||||
<Box>
|
||||
{/* Tambah Diskon */}
|
||||
<Box
|
||||
sx={{
|
||||
py: 2,
|
||||
borderBottom: '1px solid #e0e0e0',
|
||||
'&:hover': {
|
||||
backgroundColor: '#f8f8f8'
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left' }}
|
||||
onClick={() => handleInputChange('showTambahDiskon', !formData.showTambahDiskon)}
|
||||
>
|
||||
{formData.showTambahDiskon ? '- Sembunyikan Diskon' : '+ Tambahan Diskon'}
|
||||
</Button>
|
||||
|
||||
{/* Show input form when showTambahDiskon is true */}
|
||||
{formData.showTambahDiskon && (
|
||||
<Box sx={{ mt: 2 }}>
|
||||
<Box sx={{ display: 'flex', gap: 1, alignItems: 'center', mb: 1 }}>
|
||||
<CustomTextField
|
||||
size='small'
|
||||
placeholder='0'
|
||||
value={formData.discountValue || ''}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
handleInputChange('discountValue', e.target.value)
|
||||
}
|
||||
sx={{ flex: 1 }}
|
||||
InputProps={{
|
||||
endAdornment:
|
||||
formData.discountType === 'percentage' ? (
|
||||
<InputAdornment position='end'>%</InputAdornment>
|
||||
) : undefined
|
||||
}}
|
||||
/>
|
||||
<ToggleButtonGroup
|
||||
value={formData.discountType || 'percentage'}
|
||||
exclusive
|
||||
onChange={(_, newValue) => {
|
||||
if (newValue) handleInputChange('discountType', newValue)
|
||||
}}
|
||||
size='small'
|
||||
>
|
||||
<ToggleButton value='percentage' sx={{ px: 2 }}>
|
||||
%
|
||||
</ToggleButton>
|
||||
<ToggleButton value='fixed' sx={{ px: 2 }}>
|
||||
Rp
|
||||
</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Biaya Pengiriman */}
|
||||
<Box
|
||||
sx={{
|
||||
py: 2,
|
||||
borderBottom: '1px solid #e0e0e0',
|
||||
'&:hover': {
|
||||
backgroundColor: '#f8f8f8'
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left' }}
|
||||
onClick={() => handleInputChange('showBiayaPengiriman', !formData.showBiayaPengiriman)}
|
||||
>
|
||||
{formData.showBiayaPengiriman ? '- Sembunyikan Biaya Pengiriman' : '+ Biaya pengiriman'}
|
||||
</Button>
|
||||
|
||||
{/* Show input form when showBiayaPengiriman is true */}
|
||||
{formData.showBiayaPengiriman && (
|
||||
<Box sx={{ mt: 2, display: 'flex', alignItems: 'center', gap: 2 }}>
|
||||
<Typography variant='body2' sx={{ minWidth: '140px' }}>
|
||||
Biaya pengiriman
|
||||
</Typography>
|
||||
<CustomTextField
|
||||
size='small'
|
||||
placeholder='0'
|
||||
value={formData.shippingCost || ''}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
handleInputChange('shippingCost', e.target.value)
|
||||
}
|
||||
sx={{ flex: 1 }}
|
||||
InputProps={{
|
||||
startAdornment: <InputAdornment position='start'>Rp</InputAdornment>
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Biaya Transaksi - Multiple */}
|
||||
<Box
|
||||
sx={{
|
||||
py: 2,
|
||||
borderBottom: '1px solid #e0e0e0',
|
||||
'&:hover': {
|
||||
backgroundColor: '#f8f8f8'
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left' }}
|
||||
onClick={() => {
|
||||
if (!formData.showBiayaTransaksi) {
|
||||
handleInputChange('showBiayaTransaksi', true)
|
||||
if (transactionCosts.length === 0) {
|
||||
addTransactionCost()
|
||||
}
|
||||
} else {
|
||||
handleInputChange('showBiayaTransaksi', false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{formData.showBiayaTransaksi ? '- Sembunyikan Biaya Transaksi' : '+ Biaya Transaksi'}
|
||||
</Button>
|
||||
|
||||
{/* Show multiple transaction cost inputs */}
|
||||
{formData.showBiayaTransaksi && (
|
||||
<Box sx={{ mt: 2 }}>
|
||||
{transactionCosts.map((cost: TransactionCost, index: number) => (
|
||||
<Box key={cost.id} sx={{ display: 'flex', gap: 1, alignItems: 'center', mb: 2 }}>
|
||||
{/* Remove button */}
|
||||
<IconButton
|
||||
size='small'
|
||||
onClick={() => removeTransactionCost(cost.id)}
|
||||
sx={{
|
||||
color: 'error.main',
|
||||
border: '1px solid',
|
||||
borderColor: 'error.main',
|
||||
borderRadius: '50%',
|
||||
width: 28,
|
||||
height: 28,
|
||||
'&:hover': {
|
||||
backgroundColor: 'error.lighter'
|
||||
}
|
||||
}}
|
||||
>
|
||||
<i className='tabler-trash' />
|
||||
</IconButton>
|
||||
|
||||
{/* Type AutoComplete */}
|
||||
<CustomAutocomplete
|
||||
size='small'
|
||||
options={transactionCostOptions}
|
||||
getOptionLabel={option => (typeof option === 'string' ? option : option.label)}
|
||||
value={transactionCostOptions.find(option => option.value === cost.type) || null}
|
||||
onChange={(_, newValue) => {
|
||||
updateTransactionCost(cost.id, 'type', newValue ? newValue.value : '')
|
||||
}}
|
||||
renderInput={params => (
|
||||
<CustomTextField {...params} size='small' placeholder='Pilih biaya transaksi...' />
|
||||
)}
|
||||
sx={{ minWidth: 180 }}
|
||||
noOptionsText='Tidak ada pilihan'
|
||||
/>
|
||||
|
||||
{/* Name input */}
|
||||
<CustomTextField
|
||||
size='small'
|
||||
placeholder='Nama'
|
||||
value={cost.name}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
updateTransactionCost(cost.id, 'name', e.target.value)
|
||||
}
|
||||
sx={{ flex: 1 }}
|
||||
/>
|
||||
|
||||
{/* Amount input */}
|
||||
<CustomTextField
|
||||
size='small'
|
||||
placeholder='0'
|
||||
value={cost.amount}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
updateTransactionCost(cost.id, 'amount', e.target.value)
|
||||
}
|
||||
sx={{ width: 120 }}
|
||||
InputProps={{
|
||||
startAdornment: <InputAdornment position='start'>Rp</InputAdornment>
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
))}
|
||||
|
||||
{/* Add more button */}
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
onClick={addTransactionCost}
|
||||
sx={{
|
||||
textTransform: 'none',
|
||||
fontSize: '13px',
|
||||
mt: 1
|
||||
}}
|
||||
>
|
||||
+ Tambah biaya transaksi lain
|
||||
</Button>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</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(total)}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* Uang Muka */}
|
||||
<Box
|
||||
sx={{
|
||||
py: 2,
|
||||
borderBottom: '1px solid #e0e0e0',
|
||||
'&:hover': {
|
||||
backgroundColor: '#f8f8f8'
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left' }}
|
||||
onClick={() => handleInputChange('showUangMuka', !formData.showUangMuka)}
|
||||
>
|
||||
{formData.showUangMuka ? '- Sembunyikan Uang Muka' : '+ Uang Muka'}
|
||||
</Button>
|
||||
{formData.showUangMuka && (
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||
{/* Dropdown */}
|
||||
<CustomAutocomplete
|
||||
size='small'
|
||||
options={[{ label: '1-10003 Gi...', value: '1-10003' }]}
|
||||
getOptionLabel={option => (typeof option === 'string' ? option : option.label)}
|
||||
value={{ label: '1-10003 Gi...', value: '1-10003' }}
|
||||
onChange={(_, newValue) => {
|
||||
// Handle change if needed
|
||||
}}
|
||||
renderInput={params => <CustomTextField {...params} size='small' />}
|
||||
sx={{ minWidth: 120 }}
|
||||
/>
|
||||
|
||||
{/* Amount input */}
|
||||
<CustomTextField
|
||||
size='small'
|
||||
placeholder='0'
|
||||
value={formData.downPayment || '0'}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
handleInputChange('downPayment', e.target.value)
|
||||
}
|
||||
sx={{ width: '80px' }}
|
||||
inputProps={{
|
||||
style: { textAlign: 'center' }
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Percentage/Fixed toggle */}
|
||||
<ToggleButtonGroup
|
||||
value={formData.downPaymentType || 'fixed'}
|
||||
exclusive
|
||||
onChange={(_, newValue) => {
|
||||
if (newValue) handleInputChange('downPaymentType', newValue)
|
||||
}}
|
||||
size='small'
|
||||
>
|
||||
<ToggleButton value='percentage' sx={{ px: 1.5 }}>
|
||||
%
|
||||
</ToggleButton>
|
||||
<ToggleButton value='fixed' sx={{ px: 1.5 }}>
|
||||
Rp
|
||||
</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
</Box>
|
||||
|
||||
{/* Right side text */}
|
||||
<Typography
|
||||
variant='body1'
|
||||
sx={{
|
||||
fontSize: '16px',
|
||||
fontWeight: 400
|
||||
}}
|
||||
>
|
||||
Uang muka {downPayment > 0 ? downPayment.toLocaleString('id-ID') : '0'}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Sisa Tagihan */}
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
py: 2,
|
||||
backgroundColor: '#f5f5f5',
|
||||
borderRadius: '4px',
|
||||
mb: 3,
|
||||
'&:hover': {
|
||||
backgroundColor: '#eeeeee'
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Typography variant='body1' color='text.primary' sx={{ fontSize: '16px', fontWeight: 600 }}>
|
||||
Sisa Tagihan
|
||||
</Typography>
|
||||
<Typography variant='body1' fontWeight={600} sx={{ fontSize: '16px', textAlign: 'right' }}>
|
||||
{new Intl.NumberFormat('id-ID', {
|
||||
style: 'currency',
|
||||
currency: 'IDR',
|
||||
minimumFractionDigits: 0
|
||||
}).format(remainingBalance)}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* Save Button */}
|
||||
<Button
|
||||
variant='contained'
|
||||
color='primary'
|
||||
fullWidth
|
||||
sx={{
|
||||
textTransform: 'none',
|
||||
fontWeight: 600,
|
||||
py: 1.5,
|
||||
boxShadow: 'none',
|
||||
'&:hover': {
|
||||
boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
|
||||
}
|
||||
}}
|
||||
>
|
||||
Simpan
|
||||
</Button>
|
||||
</Box>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default PurchaseSummary
|
||||
@ -1,118 +1,929 @@
|
||||
'use client'
|
||||
|
||||
import React, { useState } from 'react'
|
||||
import { Card, CardContent } from '@mui/material'
|
||||
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 { IngredientItem, PurchaseOrderFormData } from '@/types/apps/purchaseOrderTypes'
|
||||
import PurchaseBasicInfo from './PurchaseBasicInfo'
|
||||
import PurchaseIngredientsTable from './PurchaseIngredientsTable'
|
||||
import PurchaseSummary from './PurchaseSummary'
|
||||
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,
|
||||
nomor: 'PO/00043',
|
||||
tglTransaksi: '2025-09-09',
|
||||
tglJatuhTempo: '2025-09-10',
|
||||
referensi: '',
|
||||
termin: null,
|
||||
hargaTermasukPajak: true,
|
||||
// Shipping info
|
||||
showShippingInfo: false,
|
||||
tanggalPengiriman: '',
|
||||
ekspedisi: null,
|
||||
noResi: '',
|
||||
// Bottom section toggles
|
||||
po_number: '',
|
||||
transaction_date: '',
|
||||
due_date: '',
|
||||
reference: '',
|
||||
status: 'sent',
|
||||
showPesan: false,
|
||||
showAttachment: false,
|
||||
showTambahDiskon: false,
|
||||
showBiayaPengiriman: false,
|
||||
showBiayaTransaksi: false,
|
||||
showUangMuka: false,
|
||||
pesan: '',
|
||||
// Ingredient items (updated from productItems)
|
||||
ingredientItems: [
|
||||
message: '',
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
ingredient: null,
|
||||
deskripsi: '',
|
||||
kuantitas: 1,
|
||||
satuan: null,
|
||||
discount: '0',
|
||||
harga: 0,
|
||||
pajak: null,
|
||||
waste: 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 handleIngredientChange = (index: number, field: keyof IngredientItem, value: any): void => {
|
||||
const handleItemChange = (index: number, field: keyof PurchaseOrderFormItem, value: any): void => {
|
||||
setFormData(prev => {
|
||||
const newItems = [...prev.ingredientItems]
|
||||
const newItems = [...prev.items]
|
||||
newItems[index] = { ...newItems[index], [field]: value }
|
||||
|
||||
// Auto-calculate total if price or quantity changes
|
||||
if (field === 'harga' || field === 'kuantitas') {
|
||||
if (field === 'amount' || field === 'quantity') {
|
||||
const item = newItems[index]
|
||||
item.total = item.harga * item.kuantitas
|
||||
item.total = item.amount * item.quantity
|
||||
}
|
||||
|
||||
return { ...prev, ingredientItems: newItems }
|
||||
return { ...prev, items: newItems }
|
||||
})
|
||||
|
||||
if (errors.items) {
|
||||
setErrors(prev => ({
|
||||
...prev,
|
||||
items: undefined
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
const addIngredientItem = (): void => {
|
||||
const newItem: IngredientItem = {
|
||||
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,
|
||||
deskripsi: '',
|
||||
kuantitas: 1,
|
||||
satuan: null,
|
||||
discount: '0%',
|
||||
harga: 0,
|
||||
pajak: null,
|
||||
waste: null,
|
||||
description: '',
|
||||
quantity: 1,
|
||||
unit: null,
|
||||
amount: 0,
|
||||
total: 0
|
||||
}
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
ingredientItems: [...prev.ingredientItems, newItem]
|
||||
items: [...prev.items, newItem]
|
||||
}))
|
||||
}
|
||||
|
||||
const removeIngredientItem = (index: number): void => {
|
||||
const removeItem = (index: number): void => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
ingredientItems: prev.ingredientItems.filter((_, i) => i !== index)
|
||||
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 */}
|
||||
<PurchaseBasicInfo formData={formData} handleInputChange={handleInputChange} />
|
||||
|
||||
{/* Ingredients Table Section */}
|
||||
<PurchaseIngredientsTable
|
||||
formData={formData}
|
||||
handleIngredientChange={handleIngredientChange}
|
||||
addIngredientItem={addIngredientItem}
|
||||
removeIngredientItem={removeIngredientItem}
|
||||
{/* 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}
|
||||
/>
|
||||
|
||||
{/* Summary Section */}
|
||||
<PurchaseSummary formData={formData} handleInputChange={handleInputChange} />
|
||||
)}
|
||||
/>
|
||||
{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>
|
||||
)
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
'use client'
|
||||
|
||||
import React from 'react'
|
||||
import { Button, Switch, FormControlLabel } from '@mui/material'
|
||||
import { Button, Switch, FormControlLabel, Box, Typography } from '@mui/material'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
|
||||
import CustomTextField from '@/@core/components/mui/TextField'
|
||||
import { DropdownOption, PurchaseOrderFormData } from '@/types/apps/purchaseOrderTypes'
|
||||
import { useVendorActive } from '@/services/queries/vendor'
|
||||
|
||||
interface PurchaseBasicInfoProps {
|
||||
formData: PurchaseOrderFormData
|
||||
@ -13,12 +14,22 @@ interface PurchaseBasicInfoProps {
|
||||
}
|
||||
|
||||
const PurchaseBasicInfo: React.FC<PurchaseBasicInfoProps> = ({ formData, handleInputChange }) => {
|
||||
// Sample data for dropdowns
|
||||
const vendorOptions: DropdownOption[] = [
|
||||
{ label: 'Vendor A', value: 'vendor_a' },
|
||||
{ label: 'Vendor B', value: 'vendor_b' },
|
||||
{ label: 'Vendor C', value: 'vendor_c' }
|
||||
]
|
||||
const { data: vendors, isLoading } = useVendorActive()
|
||||
|
||||
// Transform vendors data to dropdown options
|
||||
const vendorOptions: DropdownOption[] =
|
||||
vendors?.map(vendor => ({
|
||||
label: vendor.name,
|
||||
value: vendor.id
|
||||
})) || []
|
||||
|
||||
// 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 ?? ''))
|
||||
return selectedVendor
|
||||
}
|
||||
|
||||
const terminOptions: DropdownOption[] = [
|
||||
{ label: 'Net 30', value: 'net_30' },
|
||||
@ -43,9 +54,53 @@ const PurchaseBasicInfo: React.FC<PurchaseBasicInfoProps> = ({ formData, handleI
|
||||
fullWidth
|
||||
options={vendorOptions}
|
||||
value={formData.vendor}
|
||||
onChange={(event, newValue) => handleInputChange('vendor', newValue)}
|
||||
renderInput={params => <CustomTextField {...params} label='Vendor' placeholder='Pilih kontak' fullWidth />}
|
||||
onChange={(event, newValue) => {
|
||||
handleInputChange('vendor', newValue)
|
||||
|
||||
// Optional: Bisa langsung akses full data vendor saat berubah
|
||||
if (newValue?.value) {
|
||||
const selectedVendorData = vendors?.find(vendor => vendor.id === newValue.value)
|
||||
console.log('Vendor selected:', selectedVendorData)
|
||||
// Atau bisa trigger callback lain jika dibutuhkan
|
||||
}
|
||||
}}
|
||||
loading={isLoading}
|
||||
renderInput={params => (
|
||||
<CustomTextField
|
||||
{...params}
|
||||
label='Vendor'
|
||||
placeholder={isLoading ? 'Loading vendors...' : 'Pilih kontak'}
|
||||
fullWidth
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{getSelectedVendorData() && (
|
||||
<Box className='space-y-1 mt-3'>
|
||||
{/* Nama Perum */}
|
||||
<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>
|
||||
|
||||
{/* Alamat */}
|
||||
<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>
|
||||
|
||||
{/* Nomor Telepon */}
|
||||
<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
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import React from 'react'
|
||||
import React, { useMemo } from 'react'
|
||||
import {
|
||||
Button,
|
||||
Typography,
|
||||
@ -11,12 +11,14 @@ import {
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Paper
|
||||
Paper,
|
||||
CircularProgress
|
||||
} from '@mui/material'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
|
||||
import CustomTextField from '@/@core/components/mui/TextField'
|
||||
import { IngredientItem, PurchaseOrderFormData } from '@/types/apps/purchaseOrderTypes'
|
||||
import { useIngredients } from '@/services/queries/ingredients'
|
||||
|
||||
interface PurchaseIngredientsTableProps {
|
||||
formData: PurchaseOrderFormData
|
||||
@ -31,14 +33,21 @@ const PurchaseIngredientsTable: React.FC<PurchaseIngredientsTableProps> = ({
|
||||
addIngredientItem,
|
||||
removeIngredientItem
|
||||
}) => {
|
||||
const ingredientOptions = [
|
||||
{ label: 'Tepung Terigu Premium', value: 'tepung_terigu_premium' },
|
||||
{ label: 'Gula Pasir Halus', value: 'gula_pasir_halus' },
|
||||
{ label: 'Mentega Unsalted', value: 'mentega_unsalted' },
|
||||
{ label: 'Telur Ayam Grade A', value: 'telur_ayam_grade_a' },
|
||||
{ label: 'Vanilla Extract', value: 'vanilla_extract' },
|
||||
{ label: 'Coklat Chips', value: 'coklat_chips' }
|
||||
]
|
||||
const { data: ingredients, isLoading } = useIngredients()
|
||||
|
||||
// Transform ingredients data to autocomplete options format
|
||||
const ingredientOptions = useMemo(() => {
|
||||
if (!ingredients || isLoading) {
|
||||
return []
|
||||
}
|
||||
|
||||
return ingredients?.data.map((ingredient: any) => ({
|
||||
label: ingredient.name || ingredient.nama || ingredient.ingredient_name,
|
||||
value: ingredient.id || ingredient.code || ingredient.value,
|
||||
id: ingredient.id || ingredient.code || ingredient.value,
|
||||
originalData: ingredient
|
||||
}))
|
||||
}, [ingredients, isLoading])
|
||||
|
||||
const satuanOptions = [
|
||||
{ label: 'KG', value: 'kg' },
|
||||
@ -63,6 +72,40 @@ const PurchaseIngredientsTable: React.FC<PurchaseIngredientsTableProps> = ({
|
||||
{ label: 'Custom', value: 'custom' }
|
||||
]
|
||||
|
||||
// Handle ingredient selection with additional data population
|
||||
const handleIngredientSelection = (index: number, selectedIngredient: any) => {
|
||||
handleIngredientChange(index, 'ingredient', selectedIngredient)
|
||||
|
||||
// Auto-populate related fields if available in the ingredient data
|
||||
if (selectedIngredient) {
|
||||
// Get ingredient data from originalData or directly from selectedIngredient
|
||||
const ingredientData = selectedIngredient.originalData || selectedIngredient
|
||||
|
||||
// Auto-fill unit if available
|
||||
if (ingredientData.unit || ingredientData.satuan) {
|
||||
const unit = ingredientData.unit || ingredientData.satuan
|
||||
// Convert unit to string and make it safe
|
||||
const unitString = String(unit).toLowerCase()
|
||||
const unitOption = satuanOptions.find(
|
||||
option => option.value === unit || option.label.toLowerCase() === unitString
|
||||
)
|
||||
if (unitOption) {
|
||||
handleIngredientChange(index, 'satuan', unitOption)
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-fill price if available
|
||||
if (ingredientData.price || ingredientData.harga) {
|
||||
handleIngredientChange(index, 'harga', ingredientData.price || ingredientData.harga)
|
||||
}
|
||||
|
||||
// Auto-fill description if available
|
||||
if (ingredientData.description || ingredientData.deskripsi) {
|
||||
handleIngredientChange(index, 'deskripsi', ingredientData.description || ingredientData.deskripsi)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Grid size={{ xs: 12 }} sx={{ mt: 4 }}>
|
||||
<Typography variant='h6' sx={{ mb: 2, fontWeight: 600 }}>
|
||||
@ -92,9 +135,36 @@ const PurchaseIngredientsTable: React.FC<PurchaseIngredientsTableProps> = ({
|
||||
<CustomAutocomplete
|
||||
size='small'
|
||||
options={ingredientOptions}
|
||||
value={item.ingredient}
|
||||
onChange={(event, newValue) => handleIngredientChange(index, 'ingredient', newValue)}
|
||||
renderInput={params => <CustomTextField {...params} placeholder='Pilih Bahan Baku' />}
|
||||
value={item.ingredient || null}
|
||||
onChange={(event, newValue) => handleIngredientSelection(index, newValue)}
|
||||
loading={isLoading}
|
||||
getOptionLabel={(option: any) => {
|
||||
if (!option) return ''
|
||||
return option.label || option.name || option.nama || ''
|
||||
}}
|
||||
isOptionEqualToValue={(option: any, value: any) => {
|
||||
if (!option || !value) return false
|
||||
// Handle different value structures
|
||||
const optionId = option.value || option.id
|
||||
const valueId = value.value || value.id
|
||||
return optionId === valueId
|
||||
}}
|
||||
renderInput={params => (
|
||||
<CustomTextField
|
||||
{...params}
|
||||
placeholder={isLoading ? 'Loading ingredients...' : 'Pilih Bahan Baku'}
|
||||
InputProps={{
|
||||
...params.InputProps,
|
||||
endAdornment: (
|
||||
<>
|
||||
{isLoading ? <CircularProgress color='inherit' size={20} /> : null}
|
||||
{params.InputProps.endAdornment}
|
||||
</>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
@ -215,6 +285,7 @@ const PurchaseIngredientsTable: React.FC<PurchaseIngredientsTableProps> = ({
|
||||
variant='outlined'
|
||||
size='small'
|
||||
sx={{ mt: 1 }}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Tambah bahan baku
|
||||
</Button>
|
||||
|
||||
@ -42,6 +42,9 @@ import Loading from '@/components/layout/shared/Loading'
|
||||
import { PurchaseOrderType } from '@/types/apps/purchaseOrderTypes'
|
||||
import { purchaseOrdersData } from '@/data/dummy/purchase-order'
|
||||
import { getLocalizedUrl } from '@/utils/i18n'
|
||||
import { PurchaseOrder } from '@/types/services/purchaseOrder'
|
||||
import { usePurchaseOrders } from '@/services/queries/purchaseOrder'
|
||||
import StatusFilterTabs from '@/components/StatusFilterTab'
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
@ -52,7 +55,7 @@ declare module '@tanstack/table-core' {
|
||||
}
|
||||
}
|
||||
|
||||
type PurchaseOrderTypeWithAction = PurchaseOrderType & {
|
||||
type PurchaseOrderTypeWithAction = PurchaseOrder & {
|
||||
actions?: string
|
||||
}
|
||||
|
||||
@ -104,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'
|
||||
}
|
||||
@ -135,46 +140,24 @@ const PurchaseOrderListTable = () => {
|
||||
// States
|
||||
const [addPOOpen, setAddPOOpen] = useState(false)
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [currentPage, setCurrentPage] = useState(0)
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [openConfirm, setOpenConfirm] = useState(false)
|
||||
const [poId, setPOId] = useState('')
|
||||
const [search, setSearch] = useState('')
|
||||
const [statusFilter, setStatusFilter] = useState<string>('Semua')
|
||||
const [filteredData, setFilteredData] = useState<PurchaseOrderType[]>(purchaseOrdersData)
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
// Filter data based on search and status
|
||||
useEffect(() => {
|
||||
let filtered = purchaseOrdersData
|
||||
const { data, isLoading, error, isFetching } = usePurchaseOrders({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
search,
|
||||
status: statusFilter === 'Semua' ? '' : statusFilter
|
||||
})
|
||||
|
||||
// Filter by search
|
||||
if (search) {
|
||||
filtered = filtered.filter(
|
||||
po =>
|
||||
po.number.toLowerCase().includes(search.toLowerCase()) ||
|
||||
po.vendorName.toLowerCase().includes(search.toLowerCase()) ||
|
||||
po.vendorCompany.toLowerCase().includes(search.toLowerCase()) ||
|
||||
po.status.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
}
|
||||
|
||||
// Filter by status
|
||||
if (statusFilter !== 'Semua') {
|
||||
filtered = filtered.filter(po => po.status === statusFilter)
|
||||
}
|
||||
|
||||
setFilteredData(filtered)
|
||||
setCurrentPage(0)
|
||||
}, [search, statusFilter])
|
||||
|
||||
const totalCount = filteredData.length
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = currentPage * pageSize
|
||||
return filteredData.slice(startIndex, startIndex + pageSize)
|
||||
}, [filteredData, currentPage, pageSize])
|
||||
const purchaseOrders = data?.purchase_orders ?? []
|
||||
const totalCount = data?.total_count ?? 0
|
||||
|
||||
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||
setCurrentPage(newPage)
|
||||
@ -222,14 +205,15 @@ const PurchaseOrderListTable = () => {
|
||||
/>
|
||||
)
|
||||
},
|
||||
columnHelper.accessor('number', {
|
||||
columnHelper.accessor('po_number', {
|
||||
header: 'Nomor PO',
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
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,
|
||||
@ -239,19 +223,19 @@ const PurchaseOrderListTable = () => {
|
||||
}
|
||||
}}
|
||||
>
|
||||
{row.original.number}
|
||||
{row.original.po_number}
|
||||
</Button>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('vendorName', {
|
||||
columnHelper.accessor('vendor.name', {
|
||||
header: 'Vendor',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex flex-col'>
|
||||
<Typography color='text.primary' className='font-medium'>
|
||||
{row.original.vendorName}
|
||||
{row.original.vendor.contact_person}
|
||||
</Typography>
|
||||
<Typography variant='body2' color='text.secondary'>
|
||||
{row.original.vendorCompany}
|
||||
{row.original.vendor.name}
|
||||
</Typography>
|
||||
</div>
|
||||
)
|
||||
@ -260,13 +244,13 @@ const PurchaseOrderListTable = () => {
|
||||
header: 'Referensi',
|
||||
cell: ({ row }) => <Typography color='text.secondary'>{row.original.reference || '-'}</Typography>
|
||||
}),
|
||||
columnHelper.accessor('date', {
|
||||
columnHelper.accessor('transaction_date', {
|
||||
header: 'Tanggal',
|
||||
cell: ({ row }) => <Typography>{row.original.date}</Typography>
|
||||
cell: ({ row }) => <Typography>{row.original.transaction_date}</Typography>
|
||||
}),
|
||||
columnHelper.accessor('dueDate', {
|
||||
columnHelper.accessor('due_date', {
|
||||
header: 'Tanggal Jatuh Tempo',
|
||||
cell: ({ row }) => <Typography>{row.original.dueDate}</Typography>
|
||||
cell: ({ row }) => <Typography>{row.original.due_date}</Typography>
|
||||
}),
|
||||
columnHelper.accessor('status', {
|
||||
header: 'Status',
|
||||
@ -282,16 +266,16 @@ const PurchaseOrderListTable = () => {
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('total', {
|
||||
columnHelper.accessor('total_amount', {
|
||||
header: 'Total',
|
||||
cell: ({ row }) => <Typography className='font-medium'>{formatCurrency(row.original.total)}</Typography>
|
||||
cell: ({ row }) => <Typography className='font-medium'>{formatCurrency(row.original.total_amount)}</Typography>
|
||||
})
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: paginatedData as PurchaseOrderType[],
|
||||
data: purchaseOrders as PurchaseOrder[],
|
||||
columns,
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter
|
||||
@ -316,27 +300,11 @@ const PurchaseOrderListTable = () => {
|
||||
{/* Filter Status Tabs */}
|
||||
<div className='p-6 border-bs'>
|
||||
<div className='flex flex-wrap gap-2'>
|
||||
{['Semua', 'Draft', 'Disetujui', 'Dikirim Sebagian', 'Selesai', 'Lainnya'].map(status => (
|
||||
<Button
|
||||
key={status}
|
||||
variant={statusFilter === status ? 'contained' : 'outlined'}
|
||||
color={statusFilter === status ? 'primary' : 'inherit'}
|
||||
onClick={() => handleStatusFilter(status)}
|
||||
size='small'
|
||||
className='rounded-lg'
|
||||
sx={{
|
||||
textTransform: 'none',
|
||||
fontWeight: statusFilter === status ? 600 : 400,
|
||||
borderRadius: '8px',
|
||||
...(statusFilter !== status && {
|
||||
borderColor: '#e0e0e0',
|
||||
color: '#666'
|
||||
})
|
||||
}}
|
||||
>
|
||||
{status}
|
||||
</Button>
|
||||
))}
|
||||
<StatusFilterTabs
|
||||
statusOptions={['Semua', 'draft', 'sent', 'approved', 'received', 'cancelled']}
|
||||
selectedStatus={statusFilter}
|
||||
onStatusChange={handleStatusFilter}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -378,6 +346,9 @@ const PurchaseOrderListTable = () => {
|
||||
</div>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
{isLoading ? (
|
||||
<Loading />
|
||||
) : (
|
||||
<table className={tableStyles.table}>
|
||||
<thead>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
@ -406,7 +377,7 @@ const PurchaseOrderListTable = () => {
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
{filteredData.length === 0 ? (
|
||||
{purchaseOrders.length === 0 ? (
|
||||
<tbody>
|
||||
<tr>
|
||||
<td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
|
||||
@ -428,6 +399,7 @@ const PurchaseOrderListTable = () => {
|
||||
</tbody>
|
||||
)}
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TablePagination
|
||||
@ -445,6 +417,7 @@ const PurchaseOrderListTable = () => {
|
||||
onPageChange={handlePageChange}
|
||||
onRowsPerPageChange={handlePageSizeChange}
|
||||
rowsPerPageOptions={[10, 25, 50]}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
|
||||
@ -1,20 +1,28 @@
|
||||
'use client'
|
||||
|
||||
// MUI Imports
|
||||
import Card from '@mui/material/Card'
|
||||
import CardContent from '@mui/material/CardContent'
|
||||
import Typography from '@mui/material/Typography'
|
||||
import Chip from '@mui/material/Chip'
|
||||
import Divider from '@mui/material/Divider'
|
||||
import Button from '@mui/material/Button'
|
||||
import type { ButtonProps } from '@mui/material/Button'
|
||||
|
||||
// Type Imports
|
||||
import type { ThemeColor } from '@core/types'
|
||||
|
||||
// Component Imports
|
||||
import EditUserInfo from '@components/dialogs/edit-user-info'
|
||||
import ConfirmationDialog from '@components/dialogs/confirmation-dialog'
|
||||
import OpenDialogOnElementClick from '@components/dialogs/OpenDialogOnElementClick'
|
||||
import CustomAvatar from '@core/components/mui/Avatar'
|
||||
import { useParams } from 'next/navigation'
|
||||
import { useVendorById } from '@/services/queries/vendor'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
import { getInitials } from '@/utils/getInitials'
|
||||
import OpenDialogOnElementClick from '@/components/dialogs/OpenDialogOnElementClick'
|
||||
import { Box, Button, ButtonProps, CircularProgress } from '@mui/material'
|
||||
import ConfirmationDialog from '@/components/dialogs/confirmation-dialog'
|
||||
import EditUserInfo from '@/components/dialogs/edit-user-info'
|
||||
import { ThemeColor } from '@/@core/types'
|
||||
import { useState } from 'react'
|
||||
import AddVendorDrawer from '../../list/AddVendorDrawer'
|
||||
import ConfirmDeleteDialog from '@/components/dialogs/confirm-delete'
|
||||
import { useRouter } from 'next/router'
|
||||
import { useVendorsMutation } from '@/services/mutations/vendor'
|
||||
|
||||
// Vars
|
||||
const userData = {
|
||||
@ -33,7 +41,25 @@ const userData = {
|
||||
}
|
||||
|
||||
const VendorDetails = () => {
|
||||
// Vars
|
||||
const [editVendorOpen, setEditVendorOpen] = useState(false)
|
||||
const [openConfirm, setOpenConfirm] = useState(false)
|
||||
|
||||
const params = useParams()
|
||||
const id = params?.id ?? ''
|
||||
|
||||
const { data: vendor, isLoading, error } = useVendorById(id as string)
|
||||
|
||||
const { deleteVendor } = useVendorsMutation()
|
||||
|
||||
const handleDelete = () => {
|
||||
deleteVendor.mutate(id as string, {
|
||||
onSuccess: () => {
|
||||
setOpenConfirm(false)
|
||||
window.history.back()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const buttonProps = (children: string, color: ThemeColor, variant: ButtonProps['variant']): ButtonProps => ({
|
||||
children,
|
||||
color,
|
||||
@ -42,13 +68,31 @@ const VendorDetails = () => {
|
||||
|
||||
return (
|
||||
<>
|
||||
{isLoading ? (
|
||||
<Box
|
||||
position='absolute'
|
||||
top={0}
|
||||
left={0}
|
||||
right={0}
|
||||
bottom={0}
|
||||
display='flex'
|
||||
alignItems='center'
|
||||
justifyContent='center'
|
||||
bgcolor='rgba(255,255,255,0.7)'
|
||||
zIndex={1}
|
||||
>
|
||||
<CircularProgress size={24} />
|
||||
</Box>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className='flex flex-col pbs-12 gap-6'>
|
||||
<div className='flex flex-col gap-6'>
|
||||
<div className='flex items-center justify-center flex-col gap-4'>
|
||||
<div className='flex flex-col items-center gap-4'>
|
||||
<CustomAvatar alt='user-profile' src='/images/avatars/1.png' variant='rounded' size={120} />
|
||||
<Typography variant='h5'>{`${userData.firstName} ${userData.lastName}`}</Typography>
|
||||
{/* <CustomAvatar alt='vendor-profile' variant='rounded' size={120}>
|
||||
{getInitials(vendor?.name as string)}
|
||||
</CustomAvatar> */}
|
||||
<Typography variant='h5'>{vendor?.name}</Typography>
|
||||
</div>
|
||||
<Chip label='Vendor' color='primary' size='small' variant='tonal' />
|
||||
</div>
|
||||
@ -61,22 +105,22 @@ const VendorDetails = () => {
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='flex items-center flex-wrap gap-x-1.5'>
|
||||
<Typography className='font-medium' color='text.primary'>
|
||||
Nama:
|
||||
Contact Person:
|
||||
</Typography>
|
||||
<Typography>{`${userData.firstName} ${userData.lastName}`}</Typography>
|
||||
<Typography>{vendor?.contact_person}</Typography>
|
||||
</div>
|
||||
<div className='flex items-center flex-wrap gap-x-1.5'>
|
||||
<Typography className='font-medium' color='text.primary'>
|
||||
Perusahaan:
|
||||
</Typography>
|
||||
<Typography>{userData.perusahaan}</Typography>
|
||||
<Typography>{vendor?.name}</Typography>
|
||||
</div>
|
||||
<div className='flex items-center flex-wrap gap-x-1.5'>
|
||||
<Typography className='font-medium' color='text.primary'>
|
||||
Email:
|
||||
</Typography>
|
||||
<Typography color='primary' sx={{ textDecoration: 'none', cursor: 'pointer' }}>
|
||||
{userData.email}
|
||||
{vendor?.email}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className='flex items-center flex-wrap gap-x-1.5'>
|
||||
@ -84,7 +128,7 @@ const VendorDetails = () => {
|
||||
Telepon:
|
||||
</Typography>
|
||||
<Typography color='primary' sx={{ textDecoration: 'none', cursor: 'pointer' }}>
|
||||
{userData.telepon}
|
||||
{vendor?.phone_number}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className='flex items-center flex-wrap gap-x-1.5'>
|
||||
@ -92,7 +136,7 @@ const VendorDetails = () => {
|
||||
Alamat Penagihan:
|
||||
</Typography>
|
||||
<Typography color='primary' sx={{ textDecoration: 'none', cursor: 'pointer' }}>
|
||||
{userData.alamatPenagihan}
|
||||
{vendor?.address ?? '-'}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
@ -125,8 +169,31 @@ const VendorDetails = () => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex gap-4 justify-center'>
|
||||
<Button variant='contained' onClick={() => setEditVendorOpen(!editVendorOpen)} className='max-sm:is-full'>
|
||||
Edit
|
||||
</Button>
|
||||
<Button
|
||||
variant='contained'
|
||||
color='error'
|
||||
onClick={() => setOpenConfirm(!openConfirm)}
|
||||
className='max-sm:is-full'
|
||||
>
|
||||
Hapus
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
<AddVendorDrawer open={editVendorOpen} handleClose={() => setEditVendorOpen(!editVendorOpen)} data={vendor} />
|
||||
<ConfirmDeleteDialog
|
||||
open={openConfirm}
|
||||
onClose={() => setOpenConfirm(false)}
|
||||
onConfirm={handleDelete}
|
||||
isLoading={deleteVendor.isPending}
|
||||
title='Delete Vendor'
|
||||
message='Are you sure you want to delete this Vendor? This action cannot be undone.'
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
757
src/views/apps/vendor/list/AddVendorDrawer.tsx
vendored
757
src/views/apps/vendor/list/AddVendorDrawer.tsx
vendored
@ -1,5 +1,5 @@
|
||||
// React Imports
|
||||
import { useState } from 'react'
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
// MUI Imports
|
||||
import Button from '@mui/material/Button'
|
||||
@ -10,54 +10,60 @@ import Typography from '@mui/material/Typography'
|
||||
import Divider from '@mui/material/Divider'
|
||||
import Grid from '@mui/material/Grid2'
|
||||
import Box from '@mui/material/Box'
|
||||
import Switch from '@mui/material/Switch'
|
||||
import FormControlLabel from '@mui/material/FormControlLabel'
|
||||
|
||||
// Third-party Imports
|
||||
import { useForm, Controller } from 'react-hook-form'
|
||||
|
||||
// Types Imports
|
||||
import type { VendorType } from '@/types/apps/vendorTypes'
|
||||
|
||||
// Component Imports
|
||||
import CustomTextField from '@core/components/mui/TextField'
|
||||
import { Vendor, VendorRequest } from '@/types/services/vendor'
|
||||
import { useVendorsMutation } from '@/services/mutations/vendor'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
handleClose: () => void
|
||||
vendorData?: VendorType[]
|
||||
setData: (data: VendorType[]) => void
|
||||
data?: Vendor // Data vendor untuk edit (jika ada)
|
||||
}
|
||||
|
||||
type FormValidateType = {
|
||||
name: string
|
||||
company: string
|
||||
email: string
|
||||
telephone: string
|
||||
phone_number: string
|
||||
address: string
|
||||
contact_person: string
|
||||
tax_number: string
|
||||
payment_terms: string
|
||||
notes: string
|
||||
is_active: boolean
|
||||
}
|
||||
|
||||
// Vars
|
||||
const initialData = {
|
||||
// Initial form data
|
||||
const initialData: FormValidateType = {
|
||||
name: '',
|
||||
company: '',
|
||||
email: '',
|
||||
telephone: ''
|
||||
phone_number: '',
|
||||
address: '',
|
||||
contact_person: '',
|
||||
tax_number: '',
|
||||
payment_terms: '',
|
||||
notes: '',
|
||||
is_active: true
|
||||
}
|
||||
|
||||
const AddVendorDrawer = (props: Props) => {
|
||||
const AddEditVendorDrawer = (props: Props) => {
|
||||
// Props
|
||||
const { open, handleClose, vendorData, setData } = props
|
||||
const { open, handleClose, data } = props
|
||||
|
||||
// States
|
||||
const [showMore, setShowMore] = useState(false)
|
||||
const [alamatPengiriman, setAlamatPengiriman] = useState([''])
|
||||
const [rekeningBank, setRekeningBank] = useState([
|
||||
{
|
||||
bank: '',
|
||||
cabang: '',
|
||||
namaPemilik: '',
|
||||
nomorRekening: ''
|
||||
}
|
||||
])
|
||||
const [showPemetaanAkun, setShowPemetaanAkun] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
|
||||
const { createVendor, updateVendor } = useVendorsMutation()
|
||||
|
||||
// Determine if this is edit mode
|
||||
const isEditMode = Boolean(data?.id)
|
||||
|
||||
// Hooks
|
||||
const {
|
||||
@ -69,92 +75,85 @@ const AddVendorDrawer = (props: Props) => {
|
||||
defaultValues: initialData
|
||||
})
|
||||
|
||||
// Functions untuk alamat
|
||||
const handleTambahAlamat = () => {
|
||||
setAlamatPengiriman([...alamatPengiriman, ''])
|
||||
// Effect to populate form when editing
|
||||
useEffect(() => {
|
||||
if (isEditMode && data) {
|
||||
// Populate form with existing data
|
||||
const formData: FormValidateType = {
|
||||
name: data.name || '',
|
||||
email: data.email || '',
|
||||
phone_number: data.phone_number || '',
|
||||
address: data.address || '',
|
||||
contact_person: data.contact_person || '',
|
||||
tax_number: data.tax_number || '',
|
||||
payment_terms: data.payment_terms || '',
|
||||
notes: data.notes || '',
|
||||
is_active: data.is_active ?? true
|
||||
}
|
||||
|
||||
const handleHapusAlamat = (index: number) => {
|
||||
if (alamatPengiriman.length > 1) {
|
||||
const newAlamat = alamatPengiriman.filter((_, i) => i !== index)
|
||||
setAlamatPengiriman(newAlamat)
|
||||
}
|
||||
}
|
||||
resetForm(formData)
|
||||
|
||||
const handleChangeAlamat = (index: number, value: string) => {
|
||||
const newAlamat = [...alamatPengiriman]
|
||||
newAlamat[index] = value
|
||||
setAlamatPengiriman(newAlamat)
|
||||
// Show more fields if any optional field has data
|
||||
const hasOptionalData = data.address || data.tax_number || data.payment_terms || data.notes
|
||||
if (hasOptionalData) {
|
||||
setShowMore(true)
|
||||
}
|
||||
|
||||
// Functions untuk rekening bank
|
||||
const handleTambahRekening = () => {
|
||||
setRekeningBank([
|
||||
...rekeningBank,
|
||||
{
|
||||
bank: '',
|
||||
cabang: '',
|
||||
namaPemilik: '',
|
||||
nomorRekening: ''
|
||||
}
|
||||
])
|
||||
}
|
||||
|
||||
const handleHapusRekening = (index: number) => {
|
||||
if (rekeningBank.length > 1) {
|
||||
const newRekening = rekeningBank.filter((_, i) => i !== index)
|
||||
setRekeningBank(newRekening)
|
||||
}
|
||||
}
|
||||
|
||||
const handleChangeRekening = (index: number, field: string, value: string) => {
|
||||
const newRekening = [...rekeningBank]
|
||||
newRekening[index] = { ...newRekening[index], [field]: value }
|
||||
setRekeningBank(newRekening)
|
||||
}
|
||||
|
||||
const onSubmit = (data: FormValidateType) => {
|
||||
const newVendor: VendorType = {
|
||||
id: (vendorData?.length && vendorData?.length + 1) || 1,
|
||||
photo: '',
|
||||
name: data.name,
|
||||
company: data.company,
|
||||
email: data.email,
|
||||
telephone: data.telephone,
|
||||
youPayable: 0,
|
||||
theyPayable: 0
|
||||
}
|
||||
|
||||
setData([...(vendorData ?? []), newVendor])
|
||||
handleClose()
|
||||
} else {
|
||||
// Reset to initial data for add mode
|
||||
resetForm(initialData)
|
||||
setAlamatPengiriman([''])
|
||||
setRekeningBank([
|
||||
{
|
||||
bank: '',
|
||||
cabang: '',
|
||||
namaPemilik: '',
|
||||
nomorRekening: ''
|
||||
}
|
||||
])
|
||||
setShowMore(false)
|
||||
setShowPemetaanAkun(false)
|
||||
}
|
||||
}, [data, isEditMode, resetForm])
|
||||
|
||||
const handleFormSubmit = async (formData: FormValidateType) => {
|
||||
try {
|
||||
setIsSubmitting(true)
|
||||
|
||||
// Create VendorRequest object
|
||||
const vendorRequest: VendorRequest = {
|
||||
name: formData.name,
|
||||
email: formData.email || undefined,
|
||||
phone_number: formData.phone_number || undefined,
|
||||
address: formData.address || undefined,
|
||||
contact_person: formData.contact_person || undefined,
|
||||
tax_number: formData.tax_number || undefined,
|
||||
payment_terms: formData.payment_terms || undefined,
|
||||
notes: formData.notes || undefined,
|
||||
is_active: formData.is_active
|
||||
}
|
||||
|
||||
if (isEditMode && data?.id) {
|
||||
// Update existing vendor
|
||||
updateVendor.mutate(
|
||||
{ id: data.id, payload: vendorRequest },
|
||||
{
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// Create new vendor
|
||||
createVendor.mutate(vendorRequest, {
|
||||
onSuccess: () => {
|
||||
handleReset()
|
||||
handleClose()
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error submitting vendor:', error)
|
||||
// Handle error (show toast, etc.)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
handleClose()
|
||||
resetForm(initialData)
|
||||
setAlamatPengiriman([''])
|
||||
setRekeningBank([
|
||||
{
|
||||
bank: '',
|
||||
cabang: '',
|
||||
namaPemilik: '',
|
||||
nomorRekening: ''
|
||||
}
|
||||
])
|
||||
setShowMore(false)
|
||||
setShowPemetaanAkun(false)
|
||||
}
|
||||
|
||||
return (
|
||||
@ -185,7 +184,7 @@ const AddVendorDrawer = (props: Props) => {
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center justify-between plb-5 pli-6'>
|
||||
<Typography variant='h5'>Tambah Vendor Baru</Typography>
|
||||
<Typography variant='h5'>{isEditMode ? 'Edit Vendor' : 'Tambah Vendor Baru'}</Typography>
|
||||
<IconButton size='small' onClick={handleReset}>
|
||||
<i className='tabler-x text-2xl text-textPrimary' />
|
||||
</IconButton>
|
||||
@ -194,472 +193,200 @@ const AddVendorDrawer = (props: Props) => {
|
||||
|
||||
{/* Scrollable Content */}
|
||||
<Box sx={{ flex: 1, overflowY: 'auto' }}>
|
||||
<form id='vendor-form' onSubmit={handleSubmit(data => onSubmit(data))}>
|
||||
<form id='vendor-form' onSubmit={handleSubmit(handleFormSubmit)}>
|
||||
<div className='flex flex-col gap-6 p-6'>
|
||||
{/* Tampilkan Foto */}
|
||||
<div className='flex items-center gap-3'>
|
||||
<i className='tabler-plus text-blue-500' />
|
||||
<Typography variant='body1' color='primary' className='cursor-pointer'>
|
||||
Tampilkan Foto
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
{/* Nama */}
|
||||
{/* Nama Vendor */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nama <span className='text-red-500'>*</span>
|
||||
Nama Vendor <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Grid container spacing={2}>
|
||||
<Grid size={4}>
|
||||
<CustomTextField select fullWidth defaultValue='Tuan'>
|
||||
<MenuItem value='Tuan'>Tuan</MenuItem>
|
||||
<MenuItem value='Nyonya'>Nyonya</MenuItem>
|
||||
<MenuItem value='Nona'>Nona</MenuItem>
|
||||
<MenuItem value='Bapak'>Bapak</MenuItem>
|
||||
<MenuItem value='Ibu'>Ibu</MenuItem>
|
||||
</CustomTextField>
|
||||
</Grid>
|
||||
<Grid size={8}>
|
||||
<Controller
|
||||
name='name'
|
||||
control={control}
|
||||
rules={{ required: true }}
|
||||
rules={{ required: 'Nama vendor wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Nama'
|
||||
{...(errors.name && { error: true, helperText: 'Field ini wajib diisi.' })}
|
||||
placeholder='Masukkan nama vendor'
|
||||
error={!!errors.name}
|
||||
helperText={errors.name?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</div>
|
||||
|
||||
{/* Perusahaan dan Telepon */}
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={6}>
|
||||
<Controller
|
||||
name='company'
|
||||
control={control}
|
||||
rules={{ required: true }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
label='Perusahaan'
|
||||
placeholder='Perusahaan'
|
||||
{...(errors.company && { error: true, helperText: 'Field ini wajib diisi.' })}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<Controller
|
||||
name='telephone'
|
||||
control={control}
|
||||
rules={{ required: true }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
label='Telepon'
|
||||
placeholder='Telepon'
|
||||
{...(errors.telephone && { error: true, helperText: 'Field ini wajib diisi.' })}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
{/* Email */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Email <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='email'
|
||||
control={control}
|
||||
rules={{ required: true }}
|
||||
rules={{
|
||||
required: 'Email wajib diisi',
|
||||
pattern: {
|
||||
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
|
||||
message: 'Format email tidak valid'
|
||||
}
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
type='email'
|
||||
label='Email'
|
||||
placeholder='Email'
|
||||
{...(errors.email && { error: true, helperText: 'Field ini wajib diisi.' })}
|
||||
placeholder='vendor@example.com'
|
||||
error={!!errors.email}
|
||||
helperText={errors.email?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Nomor Telepon */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nomor Telepon <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='phone_number'
|
||||
control={control}
|
||||
rules={{ required: 'Telepon wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField {...field} fullWidth placeholder='Harus Diawali 62' error={!!errors.phone_number} />
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Contact Person */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Contact Person <span className='text-red-500'>*</span>
|
||||
</Typography>
|
||||
<Controller
|
||||
name='contact_person'
|
||||
control={control}
|
||||
rules={{ required: 'Contact Person wajib diisi' }}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Nama contact person'
|
||||
error={!!errors.contact_person}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Status Aktif */}
|
||||
<div>
|
||||
<Controller
|
||||
name='is_active'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<FormControlLabel
|
||||
control={<Switch checked={field.value} onChange={field.onChange} color='primary' />}
|
||||
label='Vendor Aktif'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tampilkan selengkapnya */}
|
||||
{!showMore && (
|
||||
<div className='flex items-center gap-3' onClick={() => setShowMore(true)}>
|
||||
<i className='tabler-plus text-blue-500' />
|
||||
<Typography variant='body1' color='primary' className='cursor-pointer'>
|
||||
Tampilkan selengkapnya
|
||||
</Typography>
|
||||
</div>
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(true)}
|
||||
>
|
||||
+ Tampilkan selengkapnya
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Konten tambahan yang muncul saat showMore true */}
|
||||
{/* Konten tambahan */}
|
||||
{showMore && (
|
||||
<>
|
||||
{/* Alamat Penagihan */}
|
||||
{/* Alamat */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Alamat Penagihan
|
||||
Alamat
|
||||
</Typography>
|
||||
<CustomTextField fullWidth placeholder='Alamat Penagihan' multiline rows={3} />
|
||||
<Controller
|
||||
name='address'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField {...field} fullWidth placeholder='Alamat lengkap vendor' multiline rows={3} />
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Negara */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Negara
|
||||
</Typography>
|
||||
<CustomTextField select fullWidth defaultValue='Indonesia'>
|
||||
<MenuItem value='Indonesia'>Indonesia</MenuItem>
|
||||
</CustomTextField>
|
||||
</div>
|
||||
|
||||
{/* Provinsi dan Kota */}
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={6}>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Provinsi
|
||||
</Typography>
|
||||
<CustomTextField select fullWidth placeholder='Provinsi'>
|
||||
<MenuItem value=''>Pilih Provinsi</MenuItem>
|
||||
<MenuItem value='DKI Jakarta'>DKI Jakarta</MenuItem>
|
||||
<MenuItem value='Jawa Barat'>Jawa Barat</MenuItem>
|
||||
<MenuItem value='Jawa Tengah'>Jawa Tengah</MenuItem>
|
||||
<MenuItem value='Jawa Timur'>Jawa Timur</MenuItem>
|
||||
</CustomTextField>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Kota
|
||||
</Typography>
|
||||
<CustomTextField select fullWidth placeholder='Kota'>
|
||||
<MenuItem value=''>Pilih Kota</MenuItem>
|
||||
<MenuItem value='Jakarta'>Jakarta</MenuItem>
|
||||
<MenuItem value='Bandung'>Bandung</MenuItem>
|
||||
<MenuItem value='Surabaya'>Surabaya</MenuItem>
|
||||
</CustomTextField>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
{/* Kecamatan dan Kelurahan */}
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={6}>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Kecamatan
|
||||
</Typography>
|
||||
<CustomTextField select fullWidth placeholder='Kecamatan'>
|
||||
<MenuItem value=''>Pilih Kecamatan</MenuItem>
|
||||
</CustomTextField>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Kelurahan
|
||||
</Typography>
|
||||
<CustomTextField select fullWidth placeholder='Kelurahan'>
|
||||
<MenuItem value=''>Pilih Kelurahan</MenuItem>
|
||||
</CustomTextField>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
{/* Tipe Kartu Identitas dan ID */}
|
||||
<Grid container spacing={6}>
|
||||
<Grid size={6}>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Tipe Kartu Identitas
|
||||
</Typography>
|
||||
<CustomTextField select fullWidth placeholder='Silahkan pilih tipe kartu identitas'>
|
||||
<MenuItem value=''>Pilih Tipe Kartu Identitas</MenuItem>
|
||||
<MenuItem value='KTP'>KTP</MenuItem>
|
||||
<MenuItem value='SIM'>SIM</MenuItem>
|
||||
<MenuItem value='Paspor'>Paspor</MenuItem>
|
||||
</CustomTextField>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
ID Kartu Identitas
|
||||
</Typography>
|
||||
<CustomTextField fullWidth placeholder='ID Kartu Identitas' />
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
{/* NPWP */}
|
||||
{/* NPWP/Tax Number */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
NPWP
|
||||
</Typography>
|
||||
<CustomTextField fullWidth placeholder='NPWP' />
|
||||
<Controller
|
||||
name='tax_number'
|
||||
control={control}
|
||||
render={({ field }) => <CustomTextField {...field} fullWidth placeholder='Nomor NPWP' />}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Alamat Pengiriman */}
|
||||
{/* Payment Terms */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2 font-medium'>
|
||||
Alamat Pengiriman
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Syarat Pembayaran
|
||||
</Typography>
|
||||
{alamatPengiriman.map((alamat, index) => (
|
||||
<div key={index} className='flex items-center gap-3 mb-3'>
|
||||
<Controller
|
||||
name='payment_terms'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField {...field} select fullWidth placeholder='Pilih syarat pembayaran'>
|
||||
<MenuItem value=''>Pilih Syarat Pembayaran</MenuItem>
|
||||
<MenuItem value='CASH'>Cash</MenuItem>
|
||||
<MenuItem value='NET_7'>Net 7 Hari</MenuItem>
|
||||
<MenuItem value='NET_14'>Net 14 Hari</MenuItem>
|
||||
<MenuItem value='NET_30'>Net 30 Hari</MenuItem>
|
||||
<MenuItem value='NET_60'>Net 60 Hari</MenuItem>
|
||||
<MenuItem value='NET_90'>Net 90 Hari</MenuItem>
|
||||
</CustomTextField>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Notes */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Catatan
|
||||
</Typography>
|
||||
<Controller
|
||||
name='notes'
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<CustomTextField
|
||||
{...field}
|
||||
fullWidth
|
||||
placeholder='Alamat'
|
||||
placeholder='Catatan tambahan tentang vendor'
|
||||
multiline
|
||||
rows={2}
|
||||
value={alamat}
|
||||
onChange={e => handleChangeAlamat(index, e.target.value)}
|
||||
sx={{
|
||||
'& .MuiOutlinedInput-root': {
|
||||
borderColor: index === 1 ? 'primary.main' : 'default'
|
||||
}
|
||||
}}
|
||||
rows={3}
|
||||
/>
|
||||
{alamatPengiriman.length > 1 && (
|
||||
<IconButton
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sembunyikan */}
|
||||
<Button
|
||||
variant='text'
|
||||
color='primary'
|
||||
size='small'
|
||||
onClick={() => handleHapusAlamat(index)}
|
||||
sx={{
|
||||
color: 'error.main',
|
||||
border: 1,
|
||||
borderColor: 'error.main',
|
||||
'&:hover': {
|
||||
backgroundColor: 'error.light',
|
||||
borderColor: 'error.main'
|
||||
}
|
||||
}}
|
||||
sx={{ textTransform: 'none', fontSize: '14px', p: 0, textAlign: 'left', width: '200px' }}
|
||||
onClick={() => setShowMore(false)}
|
||||
>
|
||||
<i className='tabler-trash' />
|
||||
</IconButton>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Tambah Alamat Pengiriman */}
|
||||
<div className='flex items-center gap-3' onClick={handleTambahAlamat}>
|
||||
<i className='tabler-plus text-blue-500' />
|
||||
<Typography variant='body1' color='primary' className='cursor-pointer'>
|
||||
Tambah Alamat Pengiriman
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
{/* Rekening Bank */}
|
||||
<div>
|
||||
<Typography variant='body2' className='mb-2 font-medium'>
|
||||
Rekening Bank
|
||||
</Typography>
|
||||
{rekeningBank.map((rekening, index) => (
|
||||
<div key={index} className='mb-4'>
|
||||
<div className='flex items-start gap-3'>
|
||||
<div className='flex-1'>
|
||||
{/* Baris pertama: Bank & Cabang */}
|
||||
<Grid container spacing={3} className='mb-3'>
|
||||
<Grid size={6}>
|
||||
<CustomTextField
|
||||
select
|
||||
fullWidth
|
||||
placeholder='Bank'
|
||||
value={rekening.bank}
|
||||
onChange={e => handleChangeRekening(index, 'bank', e.target.value)}
|
||||
>
|
||||
<MenuItem value=''>Pilih Bank</MenuItem>
|
||||
<MenuItem value='BCA'>BCA</MenuItem>
|
||||
<MenuItem value='Mandiri'>Mandiri</MenuItem>
|
||||
<MenuItem value='BNI'>BNI</MenuItem>
|
||||
<MenuItem value='BRI'>BRI</MenuItem>
|
||||
</CustomTextField>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
placeholder='Cabang'
|
||||
value={rekening.cabang}
|
||||
onChange={e => handleChangeRekening(index, 'cabang', e.target.value)}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
{/* Baris kedua: Nama Pemilik & Nomor Rekening */}
|
||||
<Grid container spacing={3}>
|
||||
<Grid size={6}>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
placeholder='Nama Pemilik'
|
||||
value={rekening.namaPemilik}
|
||||
onChange={e => handleChangeRekening(index, 'namaPemilik', e.target.value)}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<CustomTextField
|
||||
fullWidth
|
||||
placeholder='Nomor Rekening'
|
||||
value={rekening.nomorRekening}
|
||||
onChange={e => handleChangeRekening(index, 'nomorRekening', e.target.value)}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</div>
|
||||
|
||||
{/* Tombol hapus di samping, sejajar dengan tengah kedua baris */}
|
||||
{rekeningBank.length > 1 && (
|
||||
<div className='flex items-center' style={{ height: '120px' }}>
|
||||
<IconButton
|
||||
size='small'
|
||||
onClick={() => handleHapusRekening(index)}
|
||||
sx={{
|
||||
color: 'error.main',
|
||||
border: 1,
|
||||
borderColor: 'error.main',
|
||||
'&:hover': {
|
||||
backgroundColor: 'error.light',
|
||||
borderColor: 'error.main'
|
||||
}
|
||||
}}
|
||||
>
|
||||
<i className='tabler-trash' />
|
||||
</IconButton>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<div className='flex items-center gap-3 mt-4' onClick={handleTambahRekening}>
|
||||
<i className='tabler-plus text-blue-500' />
|
||||
<Typography variant='body1' color='primary' className='cursor-pointer'>
|
||||
Tambah Rekening Bank
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className='flex items-center gap-3 mt-2' onClick={() => setShowPemetaanAkun(!showPemetaanAkun)}>
|
||||
<i className={showPemetaanAkun ? 'tabler-minus text-blue-500' : 'tabler-plus text-blue-500'} />
|
||||
<Typography variant='body1' color='primary' className='cursor-pointer'>
|
||||
{showPemetaanAkun ? 'Sembunyikan pemetaan akun' : 'Tampilkan pemetaan akun'}
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
{/* Konten Pemetaan Akun */}
|
||||
{showPemetaanAkun && (
|
||||
<div className='mt-6 p-4 border border-gray-200 rounded-lg'>
|
||||
{/* Akun Hutang */}
|
||||
<Grid container spacing={6} className='mb-4'>
|
||||
<Grid size={6}>
|
||||
<Typography variant='body2' className='mb-2 font-medium'>
|
||||
Akun Hutang
|
||||
</Typography>
|
||||
<CustomTextField select fullWidth defaultValue='2-20100 Hutang Usaha'>
|
||||
<MenuItem value='2-20100 Hutang Usaha'>2-20100 Hutang Usaha</MenuItem>
|
||||
<MenuItem value='2-20200 Hutang Bank'>2-20200 Hutang Bank</MenuItem>
|
||||
<MenuItem value='2-20300 Hutang Lainnya'>2-20300 Hutang Lainnya</MenuItem>
|
||||
</CustomTextField>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<Typography variant='body2' className='mb-2 font-medium'>
|
||||
Maksimal Hutang
|
||||
<i className='tabler-help-circle text-gray-400 ml-1' />
|
||||
</Typography>
|
||||
<CustomTextField fullWidth type='number' defaultValue='0' placeholder='0' />
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
{/* Akun Piutang */}
|
||||
<Grid container spacing={6} className='mb-4'>
|
||||
<Grid size={6}>
|
||||
<Typography variant='body2' className='mb-2 font-medium'>
|
||||
Akun Piutang
|
||||
</Typography>
|
||||
<CustomTextField select fullWidth defaultValue='1-10100 Piutang Usaha'>
|
||||
<MenuItem value='1-10100 Piutang Usaha'>1-10100 Piutang Usaha</MenuItem>
|
||||
<MenuItem value='1-10200 Piutang Karyawan'>1-10200 Piutang Karyawan</MenuItem>
|
||||
<MenuItem value='1-10300 Piutang Lainnya'>1-10300 Piutang Lainnya</MenuItem>
|
||||
</CustomTextField>
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<Typography variant='body2' className='mb-2 font-medium'>
|
||||
Maksimal Piutang
|
||||
<i className='tabler-help-circle text-gray-400 ml-1' />
|
||||
</Typography>
|
||||
<CustomTextField fullWidth type='number' defaultValue='0' placeholder='0' />
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
{/* Kena Pajak */}
|
||||
<div className='mb-4'>
|
||||
<Typography variant='body2' className='mb-3 font-medium'>
|
||||
Kena pajak ?
|
||||
</Typography>
|
||||
<div className='flex items-center'>
|
||||
<input
|
||||
type='checkbox'
|
||||
className='toggle-switch'
|
||||
style={{
|
||||
appearance: 'none',
|
||||
width: '60px',
|
||||
height: '30px',
|
||||
backgroundColor: '#3b82f6',
|
||||
borderRadius: '15px',
|
||||
position: 'relative',
|
||||
cursor: 'pointer',
|
||||
outline: 'none'
|
||||
}}
|
||||
/>
|
||||
<style>
|
||||
{`
|
||||
.toggle-switch::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
left: 3px;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
background-color: white;
|
||||
border-radius: 50%;
|
||||
transition: transform 0.3s ease;
|
||||
transform: translateX(0);
|
||||
}
|
||||
.toggle-switch:checked::before {
|
||||
transform: translateX(30px);
|
||||
}
|
||||
`}
|
||||
</style>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Grid container spacing={6} className='mt-4'>
|
||||
<Grid size={6}>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Nomor
|
||||
</Typography>
|
||||
<CustomTextField fullWidth placeholder='Nomor' />
|
||||
</Grid>
|
||||
<Grid size={6}>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Tanggal Lahir
|
||||
</Typography>
|
||||
<CustomTextField fullWidth type='date' placeholder='Tanggal Lahir' />
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<div className='mt-4'>
|
||||
<Typography variant='body2' className='mb-2'>
|
||||
Deskripsi
|
||||
</Typography>
|
||||
<CustomTextField fullWidth placeholder='Deskripsi' multiline rows={3} />
|
||||
</div>
|
||||
|
||||
{/* Button Sembunyikan di dalam konten */}
|
||||
<div className='flex items-center gap-3 mt-6 mb-6' onClick={() => setShowMore(false)}>
|
||||
<i className='tabler-minus text-blue-500' />
|
||||
<Typography variant='body1' color='primary' className='cursor-pointer'>
|
||||
Sembunyikan
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
- Sembunyikan
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@ -679,10 +406,10 @@ const AddVendorDrawer = (props: Props) => {
|
||||
}}
|
||||
>
|
||||
<div className='flex items-center gap-4'>
|
||||
<Button variant='contained' type='submit' form='vendor-form'>
|
||||
Simpan
|
||||
<Button variant='contained' type='submit' form='vendor-form' disabled={isSubmitting}>
|
||||
{isSubmitting ? (isEditMode ? 'Mengupdate...' : 'Menyimpan...') : isEditMode ? 'Update' : 'Simpan'}
|
||||
</Button>
|
||||
<Button variant='tonal' color='error' onClick={() => handleReset()}>
|
||||
<Button variant='outlined' color='error' onClick={handleReset} disabled={isSubmitting}>
|
||||
Batal
|
||||
</Button>
|
||||
</div>
|
||||
@ -691,4 +418,4 @@ const AddVendorDrawer = (props: Props) => {
|
||||
)
|
||||
}
|
||||
|
||||
export default AddVendorDrawer
|
||||
export default AddEditVendorDrawer
|
||||
|
||||
142
src/views/apps/vendor/list/VendorListTable.tsx
vendored
142
src/views/apps/vendor/list/VendorListTable.tsx
vendored
@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
// React Imports
|
||||
import { useEffect, useState, useMemo } from 'react'
|
||||
import { useEffect, useState, useMemo, useCallback } from 'react'
|
||||
|
||||
// Next Imports
|
||||
import Link from 'next/link'
|
||||
@ -58,6 +58,9 @@ import { getLocalizedUrl } from '@/utils/i18n'
|
||||
// Style Imports
|
||||
import tableStyles from '@core/styles/table.module.css'
|
||||
import { formatCurrency } from '@/utils/transform'
|
||||
import { useVendors } from '@/services/queries/vendor'
|
||||
import { Vendor } from '@/types/services/vendor'
|
||||
import Loading from '@/components/layout/shared/Loading'
|
||||
|
||||
declare module '@tanstack/table-core' {
|
||||
interface FilterFns {
|
||||
@ -68,7 +71,7 @@ declare module '@tanstack/table-core' {
|
||||
}
|
||||
}
|
||||
|
||||
type VendorTypeWithAction = VendorType & {
|
||||
type VendorTypeWithAction = Vendor & {
|
||||
action?: string
|
||||
}
|
||||
|
||||
@ -120,17 +123,37 @@ const DebouncedInput = ({
|
||||
// Column Definitions
|
||||
const columnHelper = createColumnHelper<VendorTypeWithAction>()
|
||||
|
||||
const VendorListTable = ({ tableData }: { tableData?: VendorType[] }) => {
|
||||
const VendorListTable = () => {
|
||||
// States
|
||||
const [addVendorOpen, setAddVendorOpen] = useState(false)
|
||||
const [rowSelection, setRowSelection] = useState({})
|
||||
const [data, setData] = useState(...[tableData])
|
||||
const [filteredData, setFilteredData] = useState(data)
|
||||
const [globalFilter, setGlobalFilter] = useState('')
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(10)
|
||||
const [search, setSearch] = useState('')
|
||||
|
||||
const { data, isLoading, error, isFetching } = useVendors({
|
||||
page: currentPage,
|
||||
limit: pageSize,
|
||||
search
|
||||
})
|
||||
|
||||
const vendors = data?.vendors ?? []
|
||||
const totalCount = data?.total_count ?? 0
|
||||
|
||||
// Hooks
|
||||
const { lang: locale } = useParams()
|
||||
|
||||
const handlePageChange = useCallback((event: unknown, newPage: number) => {
|
||||
setCurrentPage(newPage)
|
||||
}, [])
|
||||
|
||||
const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newPageSize = parseInt(event.target.value, 10)
|
||||
setPageSize(newPageSize)
|
||||
setCurrentPage(1) // Reset to first page
|
||||
}, [])
|
||||
|
||||
const columns = useMemo<ColumnDef<VendorTypeWithAction, any>[]>(
|
||||
() => [
|
||||
{
|
||||
@ -155,103 +178,64 @@ const VendorListTable = ({ tableData }: { tableData?: VendorType[] }) => {
|
||||
/>
|
||||
)
|
||||
},
|
||||
columnHelper.accessor('name', {
|
||||
columnHelper.accessor('contact_person', {
|
||||
header: 'Vendor',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-4'>
|
||||
{getAvatar({ photo: row.original.photo, name: row.original.name })}
|
||||
<div className='flex flex-col'>
|
||||
<Link href={getLocalizedUrl(`/apps/vendor/detail`, locale as Locale)}>
|
||||
<Typography color='primary' className='font-medium cursor-pointer hover:underline'>
|
||||
{row.original.name}
|
||||
<Link href={getLocalizedUrl(`/apps/vendor/${row.original.id}/detail`, locale as Locale)}>
|
||||
<Typography className='font-medium cursor-pointer hover:underline text-primary'>
|
||||
{row.original.contact_person}
|
||||
</Typography>
|
||||
</Link>
|
||||
<Typography variant='body2'>{row.original.email}</Typography>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('company', {
|
||||
columnHelper.accessor('name', {
|
||||
header: 'Perusahaan',
|
||||
cell: ({ row }) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon className='tabler-building' sx={{ color: 'var(--mui-palette-primary-main)' }} />
|
||||
<Typography color='text.primary'>{row.original.company}</Typography>
|
||||
<Typography color='text.primary'>{row.original.name}</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('telephone', {
|
||||
columnHelper.accessor('phone_number', {
|
||||
header: 'Telepon',
|
||||
cell: ({ row }) => <Typography color='text.primary'>{row.original.telephone}</Typography>
|
||||
}),
|
||||
columnHelper.accessor('youPayable', {
|
||||
header: () => <div className='text-right'>Anda Hutang</div>,
|
||||
cell: ({ row }) => (
|
||||
<div className='text-right'>
|
||||
<Typography color='text.primary' className='font-medium'>
|
||||
{formatCurrency(row.original.youPayable)}
|
||||
</Typography>
|
||||
</div>
|
||||
)
|
||||
}),
|
||||
columnHelper.accessor('theyPayable', {
|
||||
header: () => <div className='text-right'>Mereka Hutang</div>,
|
||||
cell: ({ row }) => (
|
||||
<div className='text-right'>
|
||||
<Typography color='text.primary' className='font-medium'>
|
||||
{formatCurrency(row.original.theyPayable)}
|
||||
</Typography>
|
||||
</div>
|
||||
)
|
||||
cell: ({ row }) => <Typography color='text.primary'>{row.original.phone_number}</Typography>
|
||||
})
|
||||
],
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[data, filteredData]
|
||||
[]
|
||||
)
|
||||
|
||||
const table = useReactTable({
|
||||
data: filteredData as VendorType[],
|
||||
data: vendors as Vendor[],
|
||||
columns,
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter
|
||||
},
|
||||
state: {
|
||||
rowSelection,
|
||||
globalFilter
|
||||
},
|
||||
initialState: {
|
||||
globalFilter,
|
||||
pagination: {
|
||||
pageSize: 10
|
||||
pageIndex: currentPage,
|
||||
pageSize
|
||||
}
|
||||
},
|
||||
enableRowSelection: true,
|
||||
globalFilterFn: fuzzyFilter,
|
||||
onRowSelectionChange: setRowSelection,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
onGlobalFilterChange: setGlobalFilter,
|
||||
getFilteredRowModel: getFilteredRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getPaginationRowModel: getPaginationRowModel(),
|
||||
getFacetedRowModel: getFacetedRowModel(),
|
||||
getFacetedUniqueValues: getFacetedUniqueValues(),
|
||||
getFacetedMinMaxValues: getFacetedMinMaxValues()
|
||||
manualPagination: true,
|
||||
pageCount: Math.ceil(totalCount / pageSize)
|
||||
})
|
||||
|
||||
const getAvatar = (params: Pick<VendorType, 'photo' | 'name'>) => {
|
||||
const { photo, name } = params
|
||||
|
||||
if (photo) {
|
||||
return <CustomAvatar src={photo} size={34} />
|
||||
} else {
|
||||
return <CustomAvatar size={34}>{getInitials(name as string)}</CustomAvatar>
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card>
|
||||
<CardHeader title='Filter' className='pbe-4' />
|
||||
<TableFilters setData={setFilteredData} tableData={data} />
|
||||
{/* <TableFilters setData={setFilteredData} tableData={data} /> */}
|
||||
<div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
|
||||
<CustomTextField
|
||||
select
|
||||
@ -265,8 +249,8 @@ const VendorListTable = ({ tableData }: { tableData?: VendorType[] }) => {
|
||||
</CustomTextField>
|
||||
<div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
|
||||
<DebouncedInput
|
||||
value={globalFilter ?? ''}
|
||||
onChange={value => setGlobalFilter(String(value))}
|
||||
value={search ?? ''}
|
||||
onChange={value => setSearch(value as string)}
|
||||
placeholder='Cari Vendor'
|
||||
className='max-sm:is-full'
|
||||
/>
|
||||
@ -289,6 +273,9 @@ const VendorListTable = ({ tableData }: { tableData?: VendorType[] }) => {
|
||||
</div>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
{isLoading ? (
|
||||
<Loading />
|
||||
) : (
|
||||
<table className={tableStyles.table}>
|
||||
<thead>
|
||||
{table.getHeaderGroups().map(headerGroup => (
|
||||
@ -342,22 +329,27 @@ const VendorListTable = ({ tableData }: { tableData?: VendorType[] }) => {
|
||||
</tbody>
|
||||
)}
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
<TablePagination
|
||||
component={() => (
|
||||
<TablePaginationComponent
|
||||
pageIndex={table.getState().pagination.pageIndex}
|
||||
pageSize={table.getState().pagination.pageSize}
|
||||
totalCount={table.getFilteredRowModel().rows.length}
|
||||
onPageChange={(_, page) => {
|
||||
table.setPageIndex(page)
|
||||
}}
|
||||
pageIndex={currentPage}
|
||||
pageSize={pageSize}
|
||||
totalCount={totalCount}
|
||||
onPageChange={handlePageChange}
|
||||
/>
|
||||
)}
|
||||
count={totalCount}
|
||||
rowsPerPage={pageSize}
|
||||
page={currentPage}
|
||||
onPageChange={handlePageChange}
|
||||
onRowsPerPageChange={handlePageSizeChange}
|
||||
rowsPerPageOptions={[10, 25, 50]}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</Card>
|
||||
<AddVendorDrawer
|
||||
open={addVendorOpen}
|
||||
handleClose={() => setAddVendorOpen(!addVendorOpen)}
|
||||
vendorData={data}
|
||||
setData={setData}
|
||||
/>
|
||||
<AddVendorDrawer open={addVendorOpen} handleClose={() => setAddVendorOpen(!addVendorOpen)} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user