Untitled

 avatar
unknown
plain_text
5 months ago
12 kB
3
Indexable
import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton, Button, Box, Text, FormControl, FormLabel, Switch, Flex, Select, Tab, Tabs, TabList, TabPanels, TabPanel, RadioGroup, Radio, Input, CheckboxGroup, Stack, Checkbox, IconButton, HStack, useDisclosure, Heading, } from '@chakra-ui/react'
import { useForm } from 'react-hook-form'
import { useCallListStore } from '../../store/CallListStore'
import React, { useEffect, useState } from 'react'
import { STATUS } from '../../constants'
import { useCheckStatus } from '../../utils/useCheckStatus'
import { ErrorAlert, SuccessAlert } from '../../utils/Helper'
import { useAuthStore } from '../../store/useAuth'
import { useLeadListStore } from '../../store/LeadListStore'
import { useStaffStore } from '../../store/StaffStore'
import { AddIcon } from '@chakra-ui/icons'
import { useAddCallList } from '../../services/call-list.service'


export const ManageLeadsCall = ({ isOpen, onClose, getOneLeadList }) => {

    const { activeBranch } = useAuthStore((s) => ({ activeBranch: s.activeBranch }));

    const { getAllCallList, allCallList } = useCallListStore()
    const { getAllStaff, allStaffDetails } = useStaffStore()

    useEffect(() => {
        getAllCallList({ notPaginated: true, isPublished: true, branchId: activeBranch })
        getAllStaff({ isCaller: true, branch: activeBranch, isActive: true })

    }, [getAllCallList, getAllStaff, activeBranch])

    return <Modal size={'md'} isOpen={isOpen} onClose={onClose}>
        <ModalOverlay />
        <ModalContent>
            <ModalHeader>Manage Leads Call</ModalHeader>
            <ModalCloseButton />

            <ModalBody minH={370} pb={10}>
                <Tabs size={'sm'} variant='soft-rounded' colorScheme='green'>
                    <TabList>
                        <Tab>Call Center Setting</Tab>
                        <Tab>Sync Existing Leads</Tab>
                    </TabList>

                    <TabPanels>
                        <TabPanel>
                            <LeadCallSetting allCallList={allCallList} getOneLeadList={getOneLeadList} onClose={onClose} allStaffDetails={allStaffDetails} />
                        </TabPanel>
                           <TabPanel>
                            <ExistingSyncButton  getOneLeadList={getOneLeadList} onClose={onClose} />
                        </TabPanel> 
                     </TabPanels> 
                </Tabs>
            </ModalBody>

        </ModalContent>
    </Modal>
}



const LeadCallSetting = ({ allCallList, getOneLeadList, onClose, allStaffDetails }) => {

    const { isOpen:CreateLeadisOpen, onOpen:CreateLeadonOpen, onClose:CreateLeadonClose } = useDisclosure()

    const [autoAssignCallerIds, setAutoAssignCallerIds] = useState([])

    const { updateLeadListAction, updateLeadListStatus, getOneLeadListAction } = useLeadListStore()

    const { register: registerSetting, handleSubmit: handleSubmitSetting, reset: resetSetting, watch, setValue } = useForm()

    const isAutoLeadAssign = watch('isAutoLeadAssign')

    useEffect(() => {
        setValue("callListId", getOneLeadList?.callCenterSetting?.callListId ?? "")
        setValue("isAutoLeadAdd", getOneLeadList?.callCenterSetting?.isAutoLeadAdd ?? false)
        setValue("isAutoLeadAssign", getOneLeadList?.callCenterSetting?.isAutoLeadAssign ?? false)
        setAutoAssignCallerIds(getOneLeadList?.callCenterSetting?.callerIds ?? [])
    }, [getOneLeadList, setValue])

    
    const _submitSetting = (e) => {

        if (isAutoLeadAssign && autoAssignCallerIds?.length === 0) { throw ErrorAlert('Please select at least one caller !') }

        const payload = {
            id: getOneLeadList._id,
            callCenterSetting: {
                isAutoLeadAdd: e?.isAutoLeadAdd ?? null,
                isAutoLeadAssign: e?.isAutoLeadAssign ?? null,
                callListId: e?.callListId ?? null,
                callerIds: autoAssignCallerIds
            }
        }
        updateLeadListAction(payload)
    }

    const closeHandler = () => {
        getOneLeadListAction({ id: getOneLeadList._id })
        setAutoAssignCallerIds([])
        resetSetting()
        onClose()
    }

    useCheckStatus({
        status: updateLeadListStatus,
        onSuccess: closeHandler
    })

    return <Box px={5}  >

        <form onSubmit={handleSubmitSetting(_submitSetting)}>

            <FormControl mt={5} isRequired >

                <Heading size={"xs"}>Step 1:</Heading>
                
                <FormLabel>Select Call List</FormLabel>
                <HStack> 
                <Select {...registerSetting("callListId")} placeholder='select call list'  
                isDisabled={!!getOneLeadList?.callCenterSetting?.callListId}
                >
                    {allCallList?.map(cl => {
                        return <option key={cl._id} value={cl._id} >{cl?.name}</option>
                    })}
                </Select>
                <IconButton 
                isDisabled={!!getOneLeadList?.callCenterSetting?.callListId}
                icon={<AddIcon/>} 
                colorScheme='green'
                variant={"outline"}
                cursor="pointer"
                onClick={CreateLeadonOpen}
                 aria-label='Create lead call'/>
                </HStack>
            </FormControl>
            
            <FormControl mt={5}  >
                <HStack>
               <Heading size={"xs"}>Step 2:</Heading>
                <FormLabel htmlFor='is-Auto-Lead-Assign' mb='0'>
                    Is automatic assign Calls to Callers?
                </FormLabel>
                </HStack>
                <Switch {...registerSetting("isAutoLeadAssign")} defaultChecked={getOneLeadList?.callCenterSetting?.isAutoLeadAssign ?? false} colorScheme='green' id='is-Auto-Lead-Assign' ml={2}/>
            </FormControl>

            {isAutoLeadAssign &&
                <Box maxH={150} p={1} mt={5} overflowY="scroll" >
                    <FormControl>
                        <CheckboxGroup colorScheme='green' defaultValue={autoAssignCallerIds} onChange={e => setAutoAssignCallerIds(e)}>
                            <Stack spacing={1} direction={"column"}>
                                {allStaffDetails?.length > 0 ?
                                    allStaffDetails.map((user, index) => {
                                        return <Checkbox key={user._id} value={user._id} mr={2}>{user?.name ?? "-"}</Checkbox>
                                    })
                                    : <Box>
                                        No Callers Found !
                                    </Box>
                                }
                            </Stack>
                        </CheckboxGroup>
                    </FormControl>
                </Box>
            }

            <FormControl mt={5} >
                <HStack>
                <Heading size={"xs"}>Step 3:</Heading>
                 <FormLabel htmlFor='is-Auto-Lead-Add' mb='0'>
                    Is automatic create Calls for new Leads?
                 </FormLabel>
                </HStack>
                <Switch {...registerSetting("isAutoLeadAdd")} defaultChecked={getOneLeadList?.callCenterSetting?.isAutoLeadAdd ?? false} colorScheme='green' id='is-Auto-Lead-Add' ml={2}/>
            </FormControl>

            <Button isLoading={updateLeadListStatus === STATUS.FETCHING} w={'full'} type='submit' mt={10} size={"sm"} colorScheme='green'  >Save</Button>
        </form>

        <CreateLeadsCall 
            getOneLeadList={getOneLeadList} 
            onClose={CreateLeadonClose}
            isOpen={CreateLeadisOpen}  
        />
    </Box>
}

const CreateLeadsCall = ({ getOneLeadList, onClose, isOpen}) => {
    const activeBranch = useAuthStore((s) => s.activeBranch);
    const getallCallList= useCallListStore((s)=>s.getAllCallList)
    const { register, handleSubmit,reset} = useForm();
    const { mutate, isPending} = useAddCallList({
        onSuccess: () => {
            SuccessAlert('Call list created successfully!');
            reset()
            getallCallList({ notPaginated: true, isPublished: true }); 
            onClose(); 
        },
        onError: (error) => {
            ErrorAlert(error?.message || 'Failed to create call list');
        },
    });

    const handleFormSubmit = (data) => {
        const payload = {
            leadListId: getOneLeadList._id,
            branchId: activeBranch,
            name: data.callListName,
            purpose: data.purpose,
        };

        if (payload.leadListId && payload.name && payload.purpose) {
            mutate(payload);
        } else {
            console.error('Lead list ID, name, or purpose is missing.');
        }
    };

    return (
        <Modal isOpen={isOpen} onClose={onClose} size={"md"}>
            <ModalOverlay />
              <ModalContent>
                <ModalHeader>Create Leads Call</ModalHeader>
                  <ModalCloseButton />
        <Box px={10}>
            <form onSubmit={handleSubmit(handleFormSubmit)}>
                <FormControl  isRequired>
                    <FormLabel>Call List Name</FormLabel>
                    <Input
                        placeholder="Call List Name"
                        {...register('callListName', { required: true })}
                        
                    />
                </FormControl>
                <FormControl mt={5} isRequired>
                    <FormLabel>Purpose</FormLabel>
                    <Input
                        placeholder="Purpose"
                        {...register('purpose', { required: true })} 
                       
                    />
                </FormControl>
                <Button
                    isLoading={isPending} 
                    w="full"
                    type="submit"
                    mt={5}
                    size="sm"
                    colorScheme="green"
                >
                    Create Now
                </Button>
            </form>
        </Box>
        <ModalFooter></ModalFooter>
            </ModalContent>
       </Modal>
    );
};

export default CreateLeadsCall;


const ExistingSyncButton = ({ getOneLeadList, onClose }) => {

    const activeBranch = useAuthStore((s) => s.activeBranch);
    const { addLeadToCallListAction, addLeadToCallListStatus, getAllLeadListAction } = useLeadListStore()
    const { getAllCallList } = useCallListStore()

    const { handleSubmit, reset } = useForm()

    const _submit = (e) => {
        
        const radioValue="old"

        let payload = {}
         
        payload.radioValue = radioValue;
        payload.leadListId = getOneLeadList._id;
        payload.branchId = activeBranch;
        payload.isAutoLeadAssign = getOneLeadList.callCenterSetting?.isAutoLeadAssign;
        payload.callerIds = getOneLeadList.callCenterSetting?.callerIds;

        if(getOneLeadList.callCenterSetting?.callListId ){
            payload.callListId = getOneLeadList.callCenterSetting?.callListId;
        }else{
            return ErrorAlert("select call list !")
        }

        if (payload?.leadListId && payload.callListId) {
            addLeadToCallListAction(payload)
        }
    }

    const closeHandler = () => {
        getAllLeadListAction({ leadListId: getOneLeadList._id })
        getAllCallList({ notPaginated: true, isPublished: true, branchId: activeBranch })
        reset()
        onClose()
    }

    useCheckStatus({
        status: addLeadToCallListStatus,
        onSuccess: closeHandler
    })

    return <Box mt={20} px={5} >
        <form onSubmit={handleSubmit(_submit)}>
              <HStack>
                <Heading>Note:</Heading>
                 <Text>
                   Synchronize existing Leads with new Leads. 
                 </Text>
              </HStack>
            <Button isLoading={addLeadToCallListStatus === STATUS.FETCHING} w={'full'} type='submit' mt={10} size={"sm"} colorScheme='green' isDisabled={!getOneLeadList?.callCenterSetting?.callListId } >Sync Existing Leads</Button>
        </form> 
    </Box>
}
Editor is loading...
Leave a Comment