manage notification

This commit is contained in:
Raja Oktafrianto
2025-04-15 15:15:56 +07:00
parent 8a3d842819
commit a6e341c54a
4 changed files with 399 additions and 160 deletions

View File

@ -7,6 +7,7 @@ interface apiConfigProps {
transaction: string;
nationality: string;
service_disbursement: string;
service_notification: string;
}
const API_URL = import.meta.env.VITE_APP_API_URL;
@ -20,6 +21,7 @@ const apiConfig: apiConfigProps = {
service_wallet: `${API_URL}/w`,
transaction: `${API_URL}/x`,
service_disbursement: `${API_URL}/s`,
service_notification: `${API_URL}/n`,
nationality: `https://tpay.shiblysolution.id/cms/api/mobile/list-country/
`
};

View File

@ -1,6 +1,6 @@
import { apiConfig } from '@/config/api.config';
import { useRef, useState } from 'react';
import { Alert, KeenIcon, useDataGrid } from '@/components';
import { useRef, useState, useCallback, useEffect } from 'react';
import { Alert, useDataGrid } from '@/components';
import { useCallApi } from '@/hooks';
import {
Dialog,
@ -10,102 +10,296 @@ import {
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList
} from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { toast } from 'sonner';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { useManageNotificationContext } from '../hooks/useManageNotificationContext';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { CustomerProps } from '@/pages/master/provider/blocks/AddDialog';
import { ChevronDown } from 'lucide-react';
const API_URL = apiConfig.service_dashboard;
const API_URL_CUSTOMER = apiConfig.service_customer;
const API_URL_NOTIFICATION = apiConfig.service_notification;
const AddDialog = () => {
const parentRef = useRef<any | null>(null);
const {
handleAddDialog,
handleEditDialog,
showAddDialog,
showEditDialog,
selectedNotification,
notifications
} = useManageNotificationContext();
const { handleAddDialog, showAddDialog } = useManageNotificationContext();
const { reload } = useDataGrid();
const { PostData, PutData } = useCallApi();
const [alert, setAlert] = useState({
show: false,
message: ''
});
const { GetData, PostData } = useCallApi();
const [alert, setAlert] = useState({ show: false, message: '' });
const initialState = {
name: '',
destination_module: ''
customers: [],
type: '',
via: '',
subject: '',
content: ''
};
const [formField, setFormField] = useState(initialState);
const [open, setOpen] = useState(false);
const [customers, setCustomers] = useState<CustomerProps[]>([]);
const resetForm = () => {
setFormField(initialState);
setAlert({ show: false, message: '' });
};
const [isSubmitting, setIsSubmitting] = useState(false);
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
setFormField({ ...formField, [e.target.name]: e.target.value });
};
const doCreateNotification = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const response = await PostData(`${API_URL_NOTIFICATION}/send`, formField);
console.log('API Response :', response);
if (response?.status) {
handleAddDialog(false);
resetForm();
reload();
toast.success('Notification Send Successfully!');
const createActivity = {
module: 'Manage Notification',
description: `Send New Notification => ${formField.via}`,
action: 'C'
};
doSaveLogActivity(createActivity);
} else {
toast.error('Failed to create notification');
setAlert({ show: true, message: 'Failed to create notification. Please Try Again.' });
}
};
// const getCustomerList = async (sorting: any) => {
// try {
// sorting = sorting.length == 0 ? [{ id: 'name', desc: false }] : sorting;
// const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, {
// limit: 100,
// page: 1,
// with_deleted: false,
// order_field: sorting[0].id,
// order_direction: sorting[0].desc == false ? 'ASC' : 'DESC'
// });
// setCustomers(response?.data.list);
// } catch (error) {
// console.error('Error fetching customer', error);
// }
// };
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (formField.name === '' || formField.destination_module === '') {
setAlert({ show: true, message: 'Please fill in all required fields.' });
if (
formField.type.trim() === '' ||
formField.via.trim() === '' ||
formField.subject.trim() === '' ||
formField.content.trim() === ''
) {
setAlert({ show: true, message: 'Please fill all required fields.' });
return;
}
console.log(formField);
doCreateNotification(e);
// console.log(formField);
setAlert({ show: false, message: '' });
};
const handleReset = () => {
setFormField(initialState);
};
// useEffect(() => {
// getCustomerList([{ id: 'id', desc: false }]);
// }, []);
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 [&>button]:hidden">
<DialogTitle></DialogTitle>
<Dialog open={showAddDialog} onOpenChange={handleAddDialog}>
<DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden">
<DialogHeader>
<DialogTitle>Notification - Create</DialogTitle>
<DialogDescription></DialogDescription>
<DialogHeader className="p-5 border-0">
<div className="flex items-center justify-between flex-wrap grow">
<div className="flex flex-col justify-center">
<h1 className="text-xl font-semibold leading-none text-gray-900">
Create Notification
</h1>
<div className="flex items-center gap-2 text-sm font-normal text-gray-700"></div>
</div>
<div
className="cursor-pointer hover:opacity-100 opacity-50"
onClick={() => {
handleAddDialog(false);
resetForm();
}}
>
<KeenIcon icon="cross" className="text-1.5xl" />
</div>
</div>
</DialogHeader>
<DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
<div className="flex flex-col px-0">
<DialogBody className="scrollable">
<form onSubmit={handleSubmit} className="space-y-6">
{alert.show && (
<Alert variant="danger" className="mb-5">
{alert.message}
<Alert variant="danger">
<h3>{alert.message}</h3>
</Alert>
)}
<form action="" onSubmit={handleSubmit}>
<div className="card-body grid gap-5 p-0">
{/* <div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">
Send To<span className="text-red-500">*</span>
</label>
<div className="flex gap-6 items-center">
<label className="flex items-center space-x-2">
<input
type="radio"
name="sendTo"
value="all"
checked={formField.sendTo === 'all'}
onChange={handleChange}
className="accent-blue-600"
/>
<span>All Users</span>
</label>
<label className="flex items-center space-x-2">
<input
type="radio"
name="sendTo"
value="selected"
checked={formField.sendTo === 'selected'}
onChange={handleChange}
className="accent-blue-600"
/>
<span>Selected Customers</span>
</label>
</div>
</div>
</div> */}
{/* <div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">Customer</label>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button
type="button"
className="input col-span-5 text-left flex justify-between"
style={{ color: 'inherit' }}
>
<span>
{customers.find((customer) => customer.id === formField.customers)
?.username || 'Select Customer'}
</span>
<ChevronDown className="w-4 h-4 opacity-70" />
</button>
</PopoverTrigger>
<PopoverContent className="w-[400px] p-0">
<Command>
<CommandInput placeholder="Search Customer..." />
<CommandList
className="max-h-[300px] overflow-y-auto"
style={{ touchAction: 'pan-y' }}
onWheel={(e) => {
e.currentTarget.scrollTop += e.deltaY;
}}
>
<CommandEmpty>No Customer found.</CommandEmpty>
<CommandGroup>
{customers.map((customer) => (
<CommandItem
key={customer.id}
value={customer.username}
onSelect={() => {
setFormField({
...formField,
customers: customer.id
});
setOpen(false);
}}
>
{customer.username}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
</div> */}
<div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">
Name<span className="text-red-500">*</span>
Type<span className="text-red-500">*</span>
</label>
<div className="flex gap-6 items-center">
{['info', 'promo'].map((type) => (
<label key={type} className="flex items-center space-x-2">
<input
type="radio"
name="type"
value={type}
checked={formField.type === type}
onChange={handleChange}
className="accent-blue-600"
/>
<span>{type.charAt(0).toUpperCase() + type.slice(1)}</span>
</label>
))}
</div>
</div>
</div>
<div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">
Send Via<span className="text-red-500">*</span>
</label>
<div className="flex gap-6 items-center">
<label className="flex items-center space-x-2">
<input
type="radio"
name="via"
value="fcm"
checked={formField.via === 'fcm'}
onChange={handleChange}
className="accent-blue-600"
/>
<span>FCM</span>
</label>
<label className="flex items-center space-x-2">
<input
type="radio"
name="via"
value="sms"
checked={formField.via === 'sms'}
onChange={handleChange}
className="accent-blue-600"
/>
<span>SMS</span>
</label>
<label className="flex items-center space-x-2">
<input
type="radio"
name="via"
value="email"
checked={formField.via === 'email'}
onChange={handleChange}
className="accent-blue-600"
/>
<span>E-Mail</span>
</label>
</div>
</div>
</div>
<div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">Subject</label>
<Input
className="input"
type="text"
autoComplete="off"
value={formField.name}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, name: target.value }))
}
className="input col-span-6"
name="subject"
placeholder="Enter Subject"
value={formField.subject}
onChange={handleChange}
disabled={formField.via !== 'email'}
/>
</div>
</div>
@ -113,31 +307,25 @@ const AddDialog = () => {
<div className="w-full">
<div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
<label className="form-label flex items-center gap-1 max-w-56">
Destination Module<span className="text-red-500">*</span>
Content<span className="text-red-500">*</span>
</label>
<Input
className="input"
type="text"
autoComplete="off"
value={formField.destination_module}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, destination_module: target.value }))
}
<Textarea
className="input col-span-6"
name="content"
placeholder="Enter Content Notification"
value={formField.content}
onChange={handleChange}
/>
</div>
</div>
<div className="flex justify-end pt-2.5 gap-5">
<Button variant={'outline'} type="reset" onClick={handleReset}>
<div className="flex justify-end gap-4">
<Button type="reset" variant="outline" onClick={() => setFormField(initialState)}>
Reset
</Button>
<Button variant={'default'} type="submit">
Save Changes
</Button>
</div>
<Button type="submit">Create Notification</Button>
</div>
</form>
</div>
</DialogBody>
</DialogContent>
</Dialog>

View File

@ -16,13 +16,11 @@ const ListToolBar = () => {
<input
type="text"
placeholder="Search users"
value={(table.getColumn('name')?.getFilterValue() as string) ?? ''}
onChange={(event) =>
table.getColumn('name')?.setFilterValue(event.target.value)
}
value={(table.getColumn('content')?.getFilterValue() as string) ?? ''}
onChange={(event) => table.getColumn('content')?.setFilterValue(event.target.value)}
/>
</label>
<DefaultTooltip title={'Filter'} placement={'top'}>
{/* <DefaultTooltip title={'Filter'} placement={'top'}>
<Button
variant="outline"
className="h-7.5 disabled:bg-gray-400"
@ -30,9 +28,9 @@ const ListToolBar = () => {
// onClick={handleFilterData}
>
{/* {loadingButton === 'filter' ? <ContentLoader /> : <KeenIcon icon="filter" />} */}
<KeenIcon icon="filter" />
</Button>
</DefaultTooltip>
{/* <KeenIcon icon="filter" /> */}
{/* </Button>
</DefaultTooltip> */}
</div>
<div className="flex gap-3 items-center">
<Button

View File

@ -1,48 +1,50 @@
import { DataGridColumnHeader, DataGridProvider } from '@/components';
import { DataGridColumnHeader, DataGridProvider, KeenIcon } from '@/components';
import { Toaster } from '@/components/ui/sonner';
import { apiConfig } from '@/config/api.config';
import { ColumnDef } from '@tanstack/react-table';
import React, { createContext, useCallback, useMemo, useState } from 'react';
import { ListToolBar } from '../blocks/ListToolbar';
interface ContextProps {
showEditDialog: boolean;
handleEditDialog: (show: boolean, selected_user: string | null) => void;
showAddDialog: boolean;
handleAddDialog: (show: boolean) => void;
selectedNotification: string | null;
notifications: NotificationProps[];
}
import { useCallApi } from '@/hooks';
import moment from 'moment';
interface SelectedNotification {
id: string;
name: string;
destination_module: string;
content: string;
subject: string;
type: string;
via: string;
created_at: string;
}
interface NotificationProps {
id: string;
name: string;
destination_module: string;
interface ContextProps {
showAddDialog: boolean;
handleAddDialog: (show: boolean) => void;
showEditDialog: boolean;
handleEditDialog: (show: boolean, selected_notification: string | null) => void;
showDeleteDialog: boolean;
handleDeleteDialog: (show: boolean, selected_notification: string | null) => void;
selectedNotification: string | null;
}
const initialProps: ContextProps = {
showEditDialog: false,
showAddDialog: false,
handleAddDialog: (show: boolean) => {},
showEditDialog: false,
handleEditDialog: () => {},
handleAddDialog: () => {},
selectedNotification: null,
notifications: []
showDeleteDialog: false,
handleDeleteDialog: () => {},
selectedNotification: null
};
const ManageNotifContext = createContext<ContextProps>(initialProps);
const API_URL = apiConfig.service_dashboard;
const API_URL_NOTIFICATION = apiConfig.service_notification;
const ManageNotifContextProvider = ({ children }: { children: React.ReactNode }) => {
const [showEditDialog, setShowEditDialog] = useState(false);
const [showAddDialog, setShowAddDialog] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [selectedNotification, setSelectedNotification] = useState<string | null>(null);
const [notifications, setNotifications] = useState<NotificationProps[]>([]);
const { GetData } = useCallApi();
const handleAddDialog = useCallback((show: boolean) => {
setShowAddDialog(show);
@ -53,59 +55,104 @@ const ManageNotifContextProvider = ({ children }: { children: React.ReactNode })
setShowEditDialog(show);
}, []);
const handleDeleteDialog = useCallback((show: boolean, selected_notification: string | null) => {
setSelectedNotification(show ? selected_notification : null);
setShowDeleteDialog(show);
}, []);
const columns = useMemo<ColumnDef<any>[]>(
() => [
{
accessorFn: (row) => row.id,
id: 'id',
header: ({ column }) => <DataGridColumnHeader title="ID" column={column} />,
accessorFn: (row) => row.content,
id: 'content',
header: ({ column }) => <DataGridColumnHeader title="Content" column={column} />,
enableSorting: true,
enableHiding: false,
meta: {
headerClassName: 'w-[100px]'
headerClassName: 'w-[300px]'
}
},
{
accessorFn: (row) => row.name,
id: 'name',
header: ({ column }) => <DataGridColumnHeader title="Name" column={column} />,
accessorFn: (row) => row.subject,
id: 'subject',
header: ({ column }) => <DataGridColumnHeader title="Subject" column={column} />,
enableSorting: true,
enableHiding: false
},
{
accessorFn: (row) => row.destination_module,
id: 'destination_module',
header: ({ column }) => <DataGridColumnHeader title="Destination Module" column={column} />,
accessorFn: (row) => row.type,
id: 'type',
header: ({ column }) => <DataGridColumnHeader title="Type" column={column} />,
enableSorting: true,
enableHiding: false
},
{
id: 'actions',
header: ({ column }) => <DataGridColumnHeader title="Actions" column={column} />,
meta: {
headerClassName: 'w-[100px]',
cellClassName: 'text-center'
accessorFn: (row) => row.via,
id: 'via',
header: ({ column }) => <DataGridColumnHeader title="Via" column={column} />,
enableSorting: true,
enableHiding: false
},
cell: (data: any) => {
const row = data.row.original;
{
accessorFn: (row) => row.created_at,
id: 'created_at',
header: ({ column }) => <DataGridColumnHeader title="Date Create" column={column} />,
enableSorting: true,
enableHiding: false,
cell: ({ row }) => moment(row.original.created_at).format('YYYY-MM-DD HH:mm:ss')
}
// {
// id: 'actions',
// header: ({ column }) => <DataGridColumnHeader title="Actions" column={column} />,
// meta: {
// headerClassName: 'w-[100px]',
// cellClassName: 'text-center'
// },
// cell: (data: any) => {
// const row = data.row.original;
return (
<div className="flex justify-center gap-2">
<button
type="button"
className="flex items-center justify-center gap-2 text-sm font-medium leading-6 text-primary"
onClick={() => handleEditDialog(true, row.id)}
>
<span>Edit</span>
</button>
</div>
);
}
}
// 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>
// </>
// );
// }
// }
],
[handleEditDialog, handleAddDialog]
[handleEditDialog, handleDeleteDialog]
);
const getNotificationList = async (page: number, limit: number, sorting: any, filter: any) => {
try {
sorting = sorting.length == 0 ? [{ id: 'content', desc: false }] : sorting;
filter =
filter.length == 0 ? {} : { content: { like: `%${filter[0].value?.toLowerCase()}%` } };
const response = await GetData(`${API_URL_NOTIFICATION}/list`, {
limit: limit,
page: page + 1,
with_deleted: false,
order_field: sorting[0].id,
order_direction: sorting[0].desc == false ? 'ASC' : 'DESC',
filter: JSON.stringify(filter)
});
console.log('API Response notif: ', response);
return { data: response?.data.list, totalCount: response?.data.total_count };
} catch (error) {
console.error('Error fetching notification', error);
}
};
return (
<div>
<ManageNotifContext.Provider
@ -114,8 +161,9 @@ const ManageNotifContextProvider = ({ children }: { children: React.ReactNode })
showAddDialog,
handleEditDialog,
showEditDialog,
selectedNotification,
notifications
handleDeleteDialog,
showDeleteDialog,
selectedNotification
}}
>
<Toaster expand visibleToasts={9} duration={3000} />
@ -125,8 +173,11 @@ const ManageNotifContextProvider = ({ children }: { children: React.ReactNode })
pagination={{ size: 10 }}
toolbar={<ListToolBar />}
layout={{ card: true }}
sorting={[{ id: 'username', desc: false }]}
sorting={[{ id: 'content', desc: false }]}
serverSide={true}
onFetchData={({ pageIndex, pageSize, sorting, columnFilters }) =>
getNotificationList(pageIndex, pageSize, sorting, columnFilters)
}
>
{children}
</DataGridProvider>