Add, edit, delete currency

This commit is contained in:
bagusajisaputroo
2025-04-04 16:56:59 +07:00
parent 2f138824ba
commit 28090b726e
8 changed files with 838 additions and 0 deletions

View File

@ -0,0 +1,44 @@
import { Container, DataGridInner } from '@/components';
import { ManageCurrencyContextProvider } from './hooks/ManageCurrencyContext';
import { Breadcrumbs, Link } from '@mui/material';
import { Delete } from 'lucide-react';
import AddDialog from './blocks/AddDialog';
import DeleteDialog from './blocks/DeleteDialog';
import EditDialog from './blocks/EditDialog';
// import EditDialog from './blocks/EditDialog';
const CurrencyMaster = () => {
return (
<ManageCurrencyContextProvider>
<Container>
<h1 className="text-xl font-medium leading-none text-gray-900 mb-5">Currency</h1>
<Breadcrumbs sx={{ mb: 2 }}>
<Link underline="none" color="inherit" href="/">
<span className="text-sm hover:underline">Dashboard</span>
</Link>
<Link underline="none" color="inherit">
<span className="text-sm">Master Data</span>
</Link>
<Link underline="none" color="inherit">
<span className="text-sm">Manage Currency</span>
</Link>
</Breadcrumbs>
<div className="grid gap-5 lg:gap-7.5">
<DataGridInner />
</div>
<AddDialog />
<DeleteDialog />
<EditDialog />
{/* <EditDialog/>
<DeleteDialog/> */}
</Container>
</ManageCurrencyContextProvider>
);
};
export default CurrencyMaster;

View File

@ -0,0 +1,226 @@
import { apiConfig } from '@/config/api.config';
import { Alert, useDataGrid } from '@/components';
import { useCallApi } from '@/hooks';
import { getAuth } from '@/auth';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { NumericFormat } from 'react-number-format';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList
} from '@/components/ui/command';
import { set } from 'date-fns';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import { useManageCurrencyContext } from '../hooks/useManageCurrencyContext';
import { prefix } from 'stylis';
interface CurrencyProps {
ID: string;
name: string;
}
const API_URL = apiConfig.service_wallet;
const AddDialog = () => {
const parentRef = useRef<any | null>(null);
const { showAddDialog, handleAddDialog, selectedCurrency } = useManageCurrencyContext();
const { reload } = useDataGrid();
const { PostData, GetData } = useCallApi();
const parsedUser = getAuth()?.user;
const [currencies, setCurrencies] = useState<CurrencyProps[]>([]);
const [open, setOpen] = useState(false);
const [alert, setAlert] = useState({
show: false,
message: ''
});
const initialState = {
code: '',
name: '',
prefix: '',
status: '',
created_by: '',
created_at: ''
};
const [formField, setFormField] = useState(initialState);
const created_time = new Date();
const formattedTime = created_time.toISOString().slice(0, 19).replace('T', ' ');
const resetForm = () => {
setFormField(initialState);
setAlert({ show: false, message: '' });
};
const doCreateCurrency = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const response = await PostData(`${API_URL}/dashboard/currency/`, formField);
if (response?.status) {
resetForm();
handleAddDialog(false);
toast.success('Success Create Currency');
reload();
} else {
toast.error('Error Create Currency');
setAlert({ show: true, message: 'Failed to create Currency. Please try again.' });
}
},
[formField]
);
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (
formField.code === '' ||
formField.name === '' ||
formField.prefix === '' ||
formField.status === ''
) {
setAlert({ show: true, message: 'Please fill in all required fields.' });
return;
}
doCreateCurrency(e);
// console.log(formField);
setAlert({ show: false, message: '' });
};
useEffect(() => {
if (showAddDialog) {
setFormField({
...formField,
created_by: parsedUser.username,
created_at: formattedTime
});
}
}, [formattedTime]);
useEffect(() => {
if (showAddDialog === false) {
resetForm();
}
}, [showAddDialog]);
return (
<Dialog open={showAddDialog} onOpenChange={(open) => handleAddDialog(open)}>
<DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
<DialogHeader>
<DialogTitle>Cuurency - Create</DialogTitle>
<DialogDescription></DialogDescription>
</DialogHeader>
<DialogBody ref={parentRef}>
<div className="flex flex-col">
{alert.show && (
<Alert variant="danger">
<h3>{alert.message}</h3>
</Alert>
)}
<form onSubmit={handleSubmit}>
<div className="card-body grid gap-5">
<div className="grid grid-cols-8 gap-2 w-full items-center">
<label className="form-label flex items-center gap-1 col-span-2">
Code<span className="text-red-500">*</span>
</label>
<Input
className="input col-span-6"
type="text"
autoComplete="off"
value={formField.code}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, code: target.value }))
}
/>
</div>
<div className="grid grid-cols-8 gap-2 w-full items-center">
<label className="form-label flex items-center gap-1 col-span-2">
Name<span className="text-red-500">*</span>
</label>
<Input
className="input col-span-6"
type="text"
autoComplete="off"
value={formField.name}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, name: target.value }))
}
/>
</div>
<div className="grid grid-cols-8 gap-2 w-full items-center">
<label className="form-label flex items-center gap-1 col-span-2">
Prefix<span className="text-red-500">*</span>
</label>
<Input
className="input col-span-6"
type="text"
autoComplete="off"
value={formField.prefix}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, prefix: target.value }))
}
/>
</div>
<div className="grid grid-cols-8 gap-2 w-full items-center">
<label className="form-label flex items-center gap-1 col-span-2">
Status<span className="text-red-500">*</span>
</label>
<div className="col-span-6">
<Select
value={formField.status}
onValueChange={(value) =>
setFormField((prev) => ({ ...prev, status: value }))
}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="Select" />
</SelectTrigger>
<SelectContent>
<SelectItem value="Y">Active</SelectItem>
<SelectItem value="N">Inactive</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="flex justify-end gap-5">
<Button type="button" variant="outline" onClick={resetForm}>
Reset
</Button>
<Button variant="default">Save Changes</Button>
</div>
</div>
</form>
</div>
</DialogBody>
</DialogContent>
</Dialog>
);
};
export default AddDialog;

View File

@ -0,0 +1,78 @@
import { Alert, useDataGrid } from '@/components';
import { useManageCurrencyContext } from '../hooks/useManageCurrencyContext';
import { useCallback, useState } from 'react';
import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks';
import { toast } from 'sonner';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { DialogDescription } from '@radix-ui/react-dialog';
const API_URL = apiConfig.service_wallet;
const DeleteDialog = () => {
const { showDeleteDialog, handleDeleteDialog, selectedCurrency } = useManageCurrencyContext();
const { reload } = useDataGrid();
const { DeleteData } = useCallApi();
const [alert, setAlert] = useState({
show: false,
message: ''
});
const doDeleteCurrency = useCallback(async () => {
if (!selectedCurrency) {
toast.error('No Currency selected');
return;
}
// console.log(selectedCurrency);
const response = await DeleteData(`${API_URL}/dashboard/currency/${selectedCurrency}`, {
id: selectedCurrency
});
if (response?.status) {
setAlert({ show: false, message: '' });
handleDeleteDialog(false, null);
toast.success('Success Delete Currency');
reload();
} else {
setAlert({ show: true, message: response?.message });
toast.error('Failed Delete Currency');
}
}, [selectedCurrency, DeleteData, handleDeleteDialog, reload]);
// console.log(selectedCurrency);
return (
<Dialog open={showDeleteDialog} onOpenChange={(open) => handleDeleteDialog(open, null)}>
<DialogContent className="container-fixed max-w-md flex flex-col p-5 overflow-hidden [&>button]:hidden">
<DialogHeader className="p-0 border-0 block">
<DialogTitle></DialogTitle>
<DialogDescription></DialogDescription>
<Alert variant="warning">
<h3 className="text-lg">Are you sure?</h3>
<span className="text-sm">You will delete this data!</span>
</Alert>
{alert.show && (
<Alert variant="danger">
<h3>{alert.message}</h3>
</Alert>
)}
</DialogHeader>
<DialogFooter className="flex justify-end items-center gap-4 mt-3">
<Button variant="outline" onClick={() => handleDeleteDialog(false, null)}>
Cancel
</Button>
<Button variant="destructive" onClick={doDeleteCurrency}>
Delete
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};
export default DeleteDialog;

View File

@ -0,0 +1,220 @@
import { apiConfig } from '@/config/api.config';
import { Alert, useDataGrid } from '@/components';
import { useCallApi } from '@/hooks';
import { getAuth } from '@/auth';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { NumericFormat } from 'react-number-format';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList
} from '@/components/ui/command';
import { set } from 'date-fns';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select';
import { useManageCurrencyContext } from '../hooks/useManageCurrencyContext';
interface CurrencyProps {
ID: string;
name: string;
}
const API_URL = apiConfig.service_wallet;
const EditDialog = () => {
const parentRef = useRef<any | null>(null);
const { showEditDialog, handleEditDialog, selectedCurrency } = useManageCurrencyContext();
const { reload } = useDataGrid();
const { PostData, GetData, PutData } = useCallApi();
const parsedUser = getAuth()?.user;
const [currencies, setCurrencies] = useState<CurrencyProps[]>([]);
const [open, setOpen] = useState(false);
const [alert, setAlert] = useState({
show: false,
message: ''
});
const initialState = {
code: '',
name: '',
prefix: '',
status: '',
created_by: '',
created_at: ''
};
const [formField, setFormField] = useState(initialState);
const updated_time = new Date();
const formattedTime = updated_time.toISOString().slice(0, 19).replace('T', ' ');
const resetForm = () => {
setFormField(initialState);
setAlert({ show: false, message: '' });
};
const doUpdateCurrency = useCallback(
async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!showEditDialog) return;
const response = await PutData(`${API_URL}/dashboard/currency/${selectedCurrency}`, {
...formField
});
if (response?.status) {
resetForm();
handleEditDialog(false, null);
toast.success('Success Update Currency');
reload();
} else {
toast.error('Error Create Currency');
setAlert({ show: true, message: 'Failed to Update Currency. Please try again.' });
}
},
[formField]
);
const doGetCurrencyById = useCallback(async (id: string) => {
const response = await GetData(`${API_URL}/dashboard/currency/${id}`, { id });
// console.log('Transaction Type: ', response?.data);
if (response?.status) {
setFormField((prev) => ({
...prev,
status: response.data.status,
code:response.data.code,
name:response.data.name,
prefix:response.data.prefix,
}));
}
// console.log('form fieldd Transaction Type: ', formField);
}, []);
useEffect(() => {
if (selectedCurrency) {
doGetCurrencyById(selectedCurrency);
}
}, [selectedCurrency]);
useEffect(() => {
if (showEditDialog) {
setFormField({
...formField,
created_by: parsedUser.username,
created_at: formattedTime
});
}
}, [formattedTime]);
useEffect(() => {
if (showEditDialog === false) {
resetForm();
}
}, [showEditDialog]);
return (
<Dialog open={showEditDialog} onOpenChange={(open) => handleEditDialog(open, null)}>
<DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
<DialogHeader>
<DialogTitle>Currency - Update</DialogTitle>
<DialogDescription></DialogDescription>
</DialogHeader>
<DialogBody ref={parentRef}>
<div className="flex flex-col">
{alert.show && (
<Alert variant="danger">
<h3>{alert.message}</h3>
</Alert>
)}
<form onSubmit={doUpdateCurrency}>
<div className="card-body grid gap-5">
<div className="w-full">
<label className="form-label">
Code
<span className="text-red-500">*</span>
</label>
<Input
type="text"
placeholder="Code"
value={formField.code}
onChange={(e) => setFormField((prev) => ({ ...prev, code: e.target.value }))}
/>
</div>
<div className="w-full">
<label className="form-label">
Name
<span className="text-red-500">*</span>
</label>
<Input
type="text"
placeholder="Code"
value={formField.name}
onChange={(e) => setFormField((prev) => ({ ...prev, name: e.target.value }))}
/>
</div>
<div className="w-full">
<label className="form-label">
Prefix
<span className="text-red-500">*</span>
</label>
<Input
type="text"
placeholder="Code"
value={formField.prefix}
onChange={(e) => setFormField((prev) => ({ ...prev, prefix: e.target.value }))}
/>
</div>
<div className="w-full">
<label className="form-label">
Status
<span className="text-red-500">*</span>
</label>
<Select
value={formField.status}
onValueChange={(value) => setFormField((prev) => ({ ...prev, status: value }))}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="Select" defaultValue={formField.status} />
</SelectTrigger>
<SelectContent>
<SelectItem value="Y">Active</SelectItem>
<SelectItem value="N">Inactive</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex justify-end gap-5">
<Button type="button" variant="outline" onClick={resetForm}>
Reset
</Button>
<Button variant="default">Save Changes</Button>
</div>
</div>
</form>
</div>
</DialogBody>
</DialogContent>
</Dialog>
);
};
export default EditDialog;

View File

@ -0,0 +1,55 @@
import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
import { Button } from '@/components/ui/button';
import { useManageCurrencyContext } from '../hooks/useManageCurrencyContext';
const ListToolbar = () => {
const { table, reload } = useDataGrid();
const { handleAddDialog } = useManageCurrencyContext();
return (
<div className="card-header flex-wrap gap-2 border-b-0 px-5">
<div className="flex flex-wrap gap-2 lg:gap-5 w-full">
<div className="flex justify-between w-full items-center">
<div className="flex w-[50%] gap-3 items-center">
{/* <label className="input input-sm w-1/3">
<KeenIcon icon="magnifier" />
<input
type="text"
placeholder="Search Conversion"
value={(table.getColumn('name')?.getFilterValue() as string) ?? ''}
onChange={(event) => table.getColumn('name')?.setFilterValue(event.target.value)}
/>
</label> */}
{/* <DefaultTooltip title={'Filter'} placement={'top'}>
<Button
variant="outline"
className="h-7.5 disabled:bg-gray-400"
disabled={isLoading}
onClick={handleFilterData}
>
{loadingButton === 'filter' ? <ContentLoader /> : <KeenIcon icon="filter" />}
<KeenIcon icon="filter" />
</Button>
</DefaultTooltip> */}
</div>
<div className="flex gap-3 items-center">
<Button
variant="outline"
className="h-7.5 text-[0.8rem]"
onClick={() => handleAddDialog(true)}
>
Add Data
</Button>
<DefaultTooltip title={'Refresh'} placement={'top'}>
<Button variant="outline" className="h-7.5" onClick={() => reload()}>
<KeenIcon icon="arrows-circle" />
</Button>
</DefaultTooltip>
</div>
</div>
</div>
</div>
);
};
export default ListToolbar;

View File

@ -0,0 +1,199 @@
import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
import { Toaster } from '@/components/ui/sonner';
import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks';
import { ColumnDef } from '@tanstack/react-table';
import { createContext, useCallback, useEffect, useMemo, useState } from 'react';
import ListToolbar from '../blocks/ListToolbar';
import DeleteDialog from '../blocks/DeleteDialog';
interface Currency {
id: string;
code: string;
name: string;
prefix: string;
status: string;
}
interface ContextProps {
showEditDialog: boolean;
handleEditDialog: (show: boolean, selected_currency: string | null) => void;
showAddDialog: boolean;
handleAddDialog: (show: boolean) => void;
showDeleteDialog: boolean;
handleDeleteDialog: (show: boolean, selected_currency: string | null) => void;
selectedCurrency: string | null;
currency: string | null;
}
const initialProps: ContextProps = {
showEditDialog: false,
handleEditDialog: () => {},
showAddDialog: false,
handleAddDialog: () => {},
showDeleteDialog: false,
handleDeleteDialog: () => {},
selectedCurrency: null,
currency: null
};
const ManageCurrencyContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_wallet;
const ManageCurrencyContextProvider = ({ children }: { children: React.ReactNode }) => {
const [showEditDialog, setShowEditDialog] = useState(false);
const [showAddDialog, setShowAddDialog] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const { GetData } = useCallApi();
const [selectedCurrency, setSelectedCurrency] = useState<string | null>(null);
const [currency, setCurrency] = useState<string | null>(null);
const handleEditDialog = useCallback((show: boolean, selected_currency: string | null) => {
setSelectedCurrency(show ? selected_currency : null);
setShowEditDialog(show);
}, []);
const handleAddDialog = useCallback((show: boolean) => {
setShowAddDialog(show);
}, []);
const handleDeleteDialog = useCallback((show: boolean, selected_currency: string | null) => {
setShowDeleteDialog(show);
setSelectedCurrency(show ? selected_currency : null);
}, []);
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
accessorFn: (row) => row.name,
id: 'name',
header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[150px]' }
},
{
accessorFn: (row) => row.code,
id: 'code',
header: ({ column }) => <DataGridColumnHeader title="Code" column={column} />,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[150px]' }
},
{
accessorFn: (row) => row.prefix,
id: 'prefix',
header: ({ column }) => <DataGridColumnHeader title="Prefix" column={column} />,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[150px]' }
},
{
accessorFn: (row) => row.status,
id: 'status',
header: ({ column }) => <DataGridColumnHeader title="Status" column={column} />,
enableSorting: true,
enableHiding: false,
meta: { headerClassName: 'w-[150px]' },
cell: ({ row }) => {
const isActive = row.original.status === 'Y';
return (
<span
className={`px-2 py-1 text-xs font-semibold rounded-full ${
isActive ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'
}`}
>
{isActive ? 'Active' : 'Inactive'}
</span>
);
}
},
{
id: 'actions',
header: ({ column }) => <DataGridColumnHeader title="Actions" column={column} />,
enableSorting: false,
enableHiding: false,
cell: (data) => {
const row = data.row.original;
return (
<>
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => handleEditDialog(true, row.ID)}
>
<KeenIcon icon="notepad-edit" />
</button>
<button
className="btn btn-sm btn-icon btn-clear btn-light"
onClick={() => handleDeleteDialog(true, row.ID)}
>
<KeenIcon icon="trash" />
</button>
</>
);
},
meta: { headerClassName: 'w-[100px]', cellClassName: 'text-center' }
}
],
[handleEditDialog, handleDeleteDialog]
);
const doGetCurrency = async (
page: number,
limit: number,
sorting: any
// filter: any
) => {
// sorting = sorting.length == 0 ? [{ id: 'name', desc: true }] : sorting;
// filter = filter.length == 0 ? {} : { any: filter[0].value?.toLowerCase() };
// console.log(sorting);
const response = await GetData(`${API_URL}/dashboard/currency/`, {
limit,
page: page + 1,
with_deleted: false,
order_field: sorting[0].id,
order_direction: sorting[0].desc ? 'ASC' : 'DESC'
// filter: JSON.stringify(filter)
});
// console.log(response?.data);
return { data: response?.data.list, totalCount: response?.data.total_count };
};
return (
<div className="min-h-screen">
<ManageCurrencyContext.Provider
value={{
showEditDialog,
handleEditDialog,
showAddDialog,
handleAddDialog,
showDeleteDialog,
handleDeleteDialog,
selectedCurrency,
currency
}}
>
<Toaster expand visibleToasts={9} duration={3000} />
<div className="px-4">
<DataGridProvider
columns={columns}
pagination={{ size: 10 }}
layout={{ card: true }}
toolbar={<ListToolbar />}
sorting={[{ id: 'ID', desc: true }]}
serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting }) =>
doGetCurrency(pageIndex, pageSize, sorting)
}
>
{children}
</DataGridProvider>
</div>
</ManageCurrencyContext.Provider>
</div>
);
};
export { ManageCurrencyContext, ManageCurrencyContextProvider };
export type { Currency };

View File

@ -0,0 +1,13 @@
import { useContext } from 'react';
import {ManageCurrencyContextProvider } from './ManageCurrencyContext';
import { ManageCurrencyContext } from '../hooks/ManageCurrencyContext';
const useManageCurrencyContext = () => {
const context = useContext(ManageCurrencyContext);
if (!context) throw new Error('useManageCurrencyContext must be used within AuthProvider');
return context;
};
export { useManageCurrencyContext };

View File

@ -36,6 +36,7 @@ import ConversionMaster from '@/pages/master/conversion/ConversionMaster';
import WalletRuleMaster from '@/pages/master/walletRule/WalletRuleMaster'; import WalletRuleMaster from '@/pages/master/walletRule/WalletRuleMaster';
import WalletHistory from '@/pages/wallet/wallet-history/WalletHistory'; import WalletHistory from '@/pages/wallet/wallet-history/WalletHistory';
import WalletMaster from '@/pages/master/wallet/WalletMaster'; import WalletMaster from '@/pages/master/wallet/WalletMaster';
import CurrencyMaster from '@/pages/master/currency/CurrencyMaster';
const AppRoutingSetup = (): ReactElement => { const AppRoutingSetup = (): ReactElement => {
return ( return (
@ -58,6 +59,8 @@ const AppRoutingSetup = (): ReactElement => {
/> />
<Route path="/master-data/conversion" element={<ConversionMaster />} /> <Route path="/master-data/conversion" element={<ConversionMaster />} />
<Route path="/master-data/currency/" element={<CurrencyMaster />} />
<Route path="/master-data/wallet" element={<WalletMaster />} /> <Route path="/master-data/wallet" element={<WalletMaster />} />
<Route path="/master-data/wallet-rule" element={<WalletRuleMaster />} /> <Route path="/master-data/wallet-rule" element={<WalletRuleMaster />} />