pledge

mail@pastecode.io avatar
unknown
plain_text
a year ago
8.8 kB
2
Indexable
Never
import { Button, Container, Flex, Input, Radio, RadioGroup, Select, Text, VStack, useToast } from '@chakra-ui/react'
import { Table, TableContainer, Tbody, Td, Th, Thead, Tr } from '@chakra-ui/table'
import React, { useEffect, useState } from 'react'
import radioStyles from '../../assets/css/inputRadioStyles.module.css'
import { getSessionStorageLoginID } from '../../Services/sessionStorage'
import { pledgeCDSLFn } from '../../Services/getdatafromapi'
import { useNavigate } from 'react-router-dom'
import { numberFormat } from '../../Services/formatter'

const PledgeTable = ({ data,clientCode='' }) => {
    const toast = useToast()
    const [pledgeType, setpledgeType] = useState('MP')
    const [inputValue, setinputValue] = useState(data.map((item,index)=>{return 0}))
    const [amount, setAmount] = useState(0);
    const [allClientRadio, setAllClientRadio] = useState('CM');
    const [redirectionLink, setredirectionLink] = useState(null)
    const [clientdata, setData] = useState(data);
    const [errorMessage,setErrorMessage]=useState("")
    const handleOnSubmit= async()=>{
        let tempData = []
        clientdata.map((clientdataItem,index)=>{
            if(clientdataItem.new_pledge>0){
                tempData.push({isin:clientdataItem.ISIN,Price:clientdataItem.Price, newPledgeQty: clientdataItem.new_pledge,script_code:clientdataItem.ScripCode})
            }
        })
        if(tempData.length == 0){
            toast({
                title: 'Missing Pledge Quantity',
                description: "Please enter pledge quantity to continue.",
                status: 'error',
                duration: 1500,
                isClosable: true,
                position:'top'
              })
            return
        }
        let payload = {
            client_code: clientCode == ''?getSessionStorageLoginID():clientCode,
            data: tempData,
            segment: pledgeType == 'MP'?allClientRadio:'',
            pledgeType:pledgeType
        }
        let res = await pledgeCDSLFn("CDSLPledge", payload);
        if (res.status == 200) {
            setredirectionLink(res.data)
        }
        else{
            setErrorMessage(res.message)
        }
    }
    data?.map((item)=>{
        item.inputValue = 0
        item.new_pledge = 0
    })
    
   
    const handleInputChange = (id, value,index) => {
        const inputValueData = [...inputValue];
  inputValueData[index] = parseInt(value)
  setinputValue(inputValueData)

        const updatedData = clientdata.map(updateDataItem => {
            if (updateDataItem.ISIN == id) {
                const maxPledgeQty = Math.min(parseInt(value), updateDataItem.Qty);
              return { ...updateDataItem,new_pledge:value != '' ? maxPledgeQty:0, inputValue: value != '' ? (updateDataItem.Price - (updateDataItem.Haircut/100) * updateDataItem.Price) * parseInt(value):0 };
            }
            return updateDataItem;
          });
          setData(updatedData);
    };
    const totalCalculate = () =>{
        const totalQty = clientdata.reduce((accumulator, item) => {
            return accumulator + (item.inputValue);
        }, 0);
        setAmount(totalQty)
    }
    useEffect(()=>{
        totalCalculate()
    },[clientdata])

    useEffect(() => {
        if(redirectionLink != null){
            const openLinkInNewTab = () => {
              const url = redirectionLink;
              const target = '_blank';
              window.open(url, target);
            };
            openLinkInNewTab();
        }
      }, [redirectionLink]);
    return (
        <VStack w={'100%'}>
            <a href={redirectionLink} target="_blank" rel="noopener noreferrer" style={{display:'none'}}></a>
            <Container maxW='100%'>
                <Flex mb={'1rem'} justifyContent={'space-between'} alignItems={'center'}>
                <Flex gap={'1rem'}>
                    <Select defaultValue={'MP'} onChange={(e)=>setpledgeType(e.target.value)}>
                    <option value='MP'>Margin</option>
                    <option value='MF'>MTF</option>
                    </Select>
                    {pledgeType == 'MP' && <RadioGroup onChange={setAllClientRadio} value={allClientRadio}>
                        <Flex gap={'1rem'}>
                            <label htmlFor="allClientsRadio" className={radioStyles.radioBtn}>
                                <Radio id='allClientsRadio' value='CM' >CM</Radio>
                            </label>
                            <label htmlFor="groupRadio" className={radioStyles.radioBtn}>
                                <Radio id='groupRadio' value='FO' >F&O</Radio>
                            </label>
                        </Flex>
                    </RadioGroup>}
                    </Flex>
                    <Text>Amount : ₹ {numberFormat(amount)}</Text>
                    <Button bg={'var(--vz-primary)'} color={'var(--vz-white)'} _hover={{ bg: 'var(--vz-primary-dark)' }} size='md' onClick={handleOnSubmit}>Continue</Button>
                </Flex>
            </Container>
            <Container maxW='100%'>
                <TableContainer overflowY={'scroll'} maxH={'28vw'} w='full'>
                    <Table variant='striped' size='sm'>
                        <Thead>
                            <Tr>
                                <Th p={'1rem'} fontSize={{ base: '0.9rem', '2xl': '0.7vw' }}>ScripCode</Th>
                                <Th p={'1rem'} fontSize={{ base: '0.9rem', '2xl': '0.7vw' }}>ScriptName</Th>
                                <Th p={'1rem'} fontSize={{ base: '0.9rem', '2xl': '0.7vw' }}>ISIN</Th>
                                <Th p={'1rem'} fontSize={{ base: '0.9rem', '2xl': '0.7vw' }}>Total Qty</Th>
                                <Th p={'1rem'} fontSize={{ base: '0.9rem', '2xl': '0.7vw' }}>Pledge Qty</Th>
                                <Th p={'1rem'} fontSize={{ base: '0.9rem', '2xl': '0.7vw' }}>New Pledge</Th>
                                <Th p={'1rem'} fontSize={{ base: '0.9rem', '2xl': '0.7vw' }}>Price</Th>
                                <Th p={'1rem'} fontSize={{ base: '0.9rem', '2xl': '0.7vw' }}>Haircut</Th>
                                <Th p={'1rem'} fontSize={{ base: '0.9rem', '2xl': '0.7vw' }}>Net Value</Th>
                            </Tr>
                        </Thead>
                        <Tbody>
                            {clientdata?.length > 0 && clientdata?.map((item, i) => (
                                <Tr key={i}>
                                    <Td fontSize={{ base: 'md', '2xl': '0.8vw' }}>{item["ScripCode"]}</Td>
                                    <Td fontSize={{ base: 'md', '2xl': '0.8vw' }}>{item["ScripName"]}</Td>
                                    <Td fontSize={{ base: 'md', '2xl': '0.8vw' }}>{item["ISIN"]}</Td>
                                    <Td textAlign={'right'} fontSize={{ base: 'md', '2xl': '0.8vw' }}>{item["Qty"]}</Td>
                                    <Td textAlign={'right'} fontSize={{ base: 'md', '2xl': '0.8vw' }}>{item["AlreadyPledge"]}</Td>
                                    <Td p={'1rem'} fontSize={{ base: '0.9rem', '2xl': '0.7vw' }}>
                                        <Input bg={'white'}
                                         disabled={item.Qty == 0} value={inputValue[i]} type='number' placeholder='Enter Pledge Quantity' 
                                         onChange={(e) => {
                                             if((parseInt(e.target.value)<0) || (parseInt(e.target.value) > parseInt(item.Qty))){
                                               return
                                            }else{

                                            }
                                            handleInputChange(item.ISIN, e.target.value,i)
                                        }}
                                         ></Input>
                                        </Td>
                                    <Td textAlign={'right'} fontSize={{ base: 'md', '2xl': '0.8vw' }}>{numberFormat(item["Price"])}</Td>
                                    <Td textAlign={'right'} fontSize={{ base: 'md', '2xl': '0.8vw' }}>{numberFormat(item["Haircut"])}</Td>
                                    <Td textAlign={'right'} fontSize={{ base: 'md', '2xl': '0.8vw' }}>{numberFormat(item.inputValue)}</Td>
                                </Tr>
                            ))}
                        </Tbody>
                    </Table>
                </TableContainer>
            </Container>
        </VStack>
    )
}

export default PledgeTable