import { apiConfig } from '@/config/api.config'; import { useRef, useState, useCallback, useEffect } from 'react'; import { Alert, useDataGrid } from '@/components'; import { useCallApi } from '@/hooks'; import { Dialog, DialogBody, DialogContent, DialogDescription, 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 { Check, ChevronDown } from 'lucide-react'; import { initialStateNotification, selectedNotification, validateFormNotification } from './Types'; const API_URL_CUSTOMER = apiConfig.service_customer; const API_URL_NOTIFICATION = apiConfig.service_notification; const AddDialog = () => { const { handleAddDialog, showAddDialog } = useManageNotificationContext(); const { reload } = useDataGrid(); const { GetData, PostData } = useCallApi(); const [alert, setAlert] = useState({ show: false, message: '' }); const isSubmittingRef = useRef(false); const [errors, setErrors] = useState>({}); const [formField, setFormField] = useState(initialStateNotification); const [open, setOpen] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false); const [customers, setCustomers] = useState([]); const resetForm = () => { setFormField({ ...initialStateNotification }); setIsSubmitting(false); setAlert({ show: false, message: '' }); setErrors({}); }; const handleChange = (e: React.ChangeEvent) => { const { name, value } = e.target; setFormField({ ...formField, [name]: value }); if (name === 'all_customer' && value === 'true') { setFormField((prev) => ({ ...prev, customers: [] })); } if (errors[name]) { setErrors((prevErrors) => { const updatedErrors = { ...prevErrors }; delete updatedErrors[name]; return updatedErrors; }); } }; const doCreateNotification = useCallback( async (e: React.FormEvent) => { if (isSubmittingRef.current) return; isSubmittingRef.current = true; setIsSubmitting(true); try { const response = await PostData(`${API_URL_NOTIFICATION}/send`, formField); // console.log('send 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.' }); } } catch (err) { toast.error('Something went wrong'); console.log(err); } finally { isSubmittingRef.current = false; setIsSubmitting(false); } }, [PostData, formField, handleAddDialog, reload] ); 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) => { e.preventDefault(); if (!validateFormNotification(formField, setErrors)) return; doCreateNotification(e); }; useEffect(() => { getCustomerList([{ id: 'id', desc: false }]); }, []); useEffect(() => { if (showAddDialog === false) { resetForm(); } }, [showAddDialog]); return ( Notification - Create
{alert.show && (

{alert.message}

)}
{errors.all_customer && (
{errors.all_customer}
)}
{ e.currentTarget.scrollTop += e.deltaY; }} > No Customer found. {customers.map((customer) => { const isSelected = formField.customers.includes(customer.id); return ( { const customerId = customer.id; setFormField((prev) => { const isSelected = prev.customers.includes(customerId); return { ...prev, customers: isSelected ? prev.customers.filter((id) => id !== customerId) : [...prev.customers, customerId] }; }); }} className={isSelected ? 'bg-accent font-semibold' : ''} > {isSelected && } {customer.username} ); })}
{['info', 'promo'].map((type) => ( ))}
{errors.type && (
{errors.type}
)}
{errors.via && (
{errors.via}
)}
{ const value = e.target.value; if (/^\d{0,5}$/.test(value)) { handleChange(e); } }} disabled={formField.via !== 'whatsapp'} inputMode="numeric" pattern="\d*" />