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

@ -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,134 +10,322 @@ 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>
<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>
<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>
<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">
Name<span className="text-red-500">*</span>
</label>
<Input
className="input"
type="text"
autoComplete="off"
value={formField.name}
onChange={({ target }) =>
setFormField((prev) => ({ ...prev, name: target.value }))
}
/>
</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">
Destination Module<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 }))
}
{/* <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"
/>
</div>
</div>
<div className="flex justify-end pt-2.5 gap-5">
<Button variant={'outline'} type="reset" onClick={handleReset}>
Reset
</Button>
<Button variant={'default'} type="submit">
Save Changes
</Button>
<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>
</form>
</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">
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 col-span-6"
name="subject"
placeholder="Enter Subject"
value={formField.subject}
onChange={handleChange}
disabled={formField.via !== 'email'}
/>
</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">
Content<span className="text-red-500">*</span>
</label>
<Textarea
className="input col-span-6"
name="content"
placeholder="Enter Content Notification"
value={formField.content}
onChange={handleChange}
/>
</div>
</div>
<div className="flex justify-end gap-4">
<Button type="reset" variant="outline" onClick={() => setFormField(initialState)}>
Reset
</Button>
<Button type="submit">Create Notification</Button>
</div>
</form>
</DialogBody>
</DialogContent>
</Dialog>