NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

import React, { Fragment, useEffect, useState, useContext } from "react";
import { useNavigate } from "react-router-dom";
import Box from "@mui/material/Box";
import Drawer from "@mui/material/Drawer";
import MuiButton from "@mui/material/Button";
import List from "@mui/material/List";
import Divider from "@mui/material/Divider";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ShortTextIcon from "@mui/icons-material/ShortText";
import ListItemIcon from "@mui/material/ListItemIcon";
import CategoryIcon from "@mui/icons-material/Category";
import DeleteIcon from "@mui/icons-material/Delete";
import LabelImportantIcon from "@mui/icons-material/LabelImportant";
import ListItemText from "@mui/material/ListItemText";
import InputLabel from "@mui/material/InputLabel";
import FormControl from "@mui/material/FormControl";
import Select, { SelectChangeEvent } from "@mui/material/Select";
import MenuItem from "@mui/material/MenuItem";
import { Anchor } from "@mui/icons-material";
import { Dialog } from "primereact/dialog";
import { Button } from "primereact/button";
import CustomerContext from "../../context/customer/CustomerContext";
import states from "../../data/StateLookup.json";
import MultiSelect from "../common/MultiSelect";
import { format } from "date-fns";
import Alert from "@mui/material/Alert";
import useDialog from "../common/UseDialog";
import { confirmDialog } from "primereact/confirmdialog";
import CloseIcon from '@mui/icons-material/Close';
import { IconButton } from "@mui/material";
import _ from "lodash";
import {
Card,
CardActions,
CardContent,
CardMedia,
CardHeader,
Grid,
Stack,
TextField,
Typography,
} from "@mui/material";
import {
Customer,
BusinessCategory,
CustomerCategory,
} from "../../types/customer";
import { resolve } from "path";

type Anchor = "top" | "left" | "bottom" | "right";

export default function CustomerBusinessCategory(props: {
dockAt?: "top" | "left" | "bottom" | "right";
show?: boolean;
handleClose: () => void;
cust?: Customer;
categories?: CustomerCategory[];
categoriesLookup?: BusinessCategory[];
}) {
const customerContext = useContext(CustomerContext);

const fontStyle = {
fontWeight: "regular",
fontSize: "1rem",

color: "#424242",
};

const {
createCustomerBusinessCategories,
getCustomerBusinessCategories,
deleteCustomerBusinessCategories,
customerLoading,
} = customerContext;
const [data, setData] = React.useState<CustomerCategory[]>([]);
const [sourceData, setSourceData] = React.useState<CustomerCategory[]>([]);
const [state, setState] = React.useState({
top: false,
left: false,
bottom: false,
right: false,
});
const [alertMessage, setAlertMessage] = useState("");
const [selectedState, setSelectedState] = useState("");
const [dataChanged, setDataChanged] = useState(false);
const [showAlert, setShowAlert] = useState(false);
const [showError, setShowError] = useState(false);
const [showSuccess, setShowSuccess] = useState(false);
const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
const [initCategories, setInitCategories] = useState<string[]>([]);
const [selectedIdForDelete, setSelectedIdForDelete] = useState<string>("");
const navigate = useNavigate();

const closeAlert = () => {
setSelectedState(() => "");
setSelectedCategories(() => []);
setInitCategories(() => []);
setShowAlert(false);
props.handleClose();
// navigate("/");
};

const footerContent = (
<div>
<Button
label='OK'
icon='pi pi-check'
onClick={() => closeAlert()}
autoFocus
/>
</div>
);

const toggleDrawer =
(anchor: Anchor, open: boolean) =>
(event: React.KeyboardEvent | React.MouseEvent) => {
console.log(`Drawer Mouse Key Event...`);
// if (
// event.type === "keydown" &&
// ((event as React.KeyboardEvent).key === "Tab" ||
// (event as React.KeyboardEvent).key === "Shift")
// ) {
// return;
// }
// console.log(`Toogle Drawer: DockAt:${anchor}, Show: ${open}`);
// setState({ ...state, [anchor]: open });
// if (!open) props.handleClose();
};

const handleDeleteSubmit = async () => {
console.log("Submitting Delete....", selectedIdForDelete);
if (deleteCustomerBusinessCategories) {
const _res = await deleteCustomerBusinessCategories(selectedIdForDelete);
if (_res) {
if (getCustomerBusinessCategories) {
const _catData = await getCustomerBusinessCategories(
props.cust?.customerId
);
setSourceData(() => _catData);
}
setAlertMessage("Sucessfully deleted Client Business Category");
setShowSuccess(true);
setShowError(false);
closeDialog();
setState({ ...state, [props.dockAt ? props.dockAt : "right"]: true });
} else {
setAlertMessage("Error while deleting Client Business Category");
setShowSuccess(false);
setShowError(true);
closeDialog();
setState({ ...state, [props.dockAt ? props.dockAt : "right"]: true });
}
}
};

const closeDeleteConfirm = () => {
console.log("Cancelling....");
setSelectedIdForDelete("");
setState({ ...state, [props.dockAt ? props.dockAt : "right"]: true });
// navigate("/");
};

const { AlertDialog, showDialog, closeDialog } = useDialog({
onSubmit: handleDeleteSubmit,
onClose: closeDeleteConfirm,
});

const handleCategoryChanges = (
values: string[],
keys: any,
action: string
) => {
console.log("@@Changed BusinessCategories:", values);
setSelectedCategories((old) => values);
setDataChanged(() => hasDataChanged(values));
// formik.setFieldValue("businessCategoryId", selectedCategories, false);
};

const hasDataChanged = (values: string[]): boolean => {
const _delCats = _.difference(initCategories, values);
let _addCats = _.difference(values, initCategories);
return _delCats.length > 0 || _addCats.length > 0;
};

useEffect(() => {
if (
typeof props.dockAt !== "undefined" &&
typeof props.show !== "undefined"
) {
console.log(
`Toogle Drawer UEF: DockAt:${props.dockAt}, Show: ${props.show}`
);
// toggleDrawer(props.dockAt, props.show);
if (props.show) setState({ ...state, [props.dockAt]: props.show });
}
// setApprovalComment((old) => "");
if (!props.show) {
setInitCategories(() => []);
}
// if (getCustomerComments && props.cust && props.cust.customerId) {
// console.log(`Fetching Commnet for :${props.cust.customerId}`);
// fetchCustomerComments(props.cust.customerId);
// }
//eslint-disable-next-line
}, [props.show]);

useEffect(() => {
let _data: CustomerCategory[] = props.categories!;
if (props.categories) {
setSourceData(() => _data);
}
//eslint-disable-next-line
}, [props.categories]);

useEffect(() => {
if (sourceData) {
const _data2 = sourceData.filter((item) => item.state !== null);
const _data3 = _.sortBy(_data2, [
(item) => item.state,
(item) => item.businessCategoryName,
]);
console.log("@@Ggroup Cust Bus Cats:", _data3);

setData(() => _data3);
}

//eslint-disable-next-line
}, [sourceData]);

useEffect(() => {
// if(props.cust && props.cust.createDate!==null)
//eslint-disable-next-line
}, [props.cust]);

useEffect(() => {
if (selectedState) {
const _initCat = data
.filter((cat) => cat.state === selectedState)
.map((item) => item.businessCategoryId + "");
setInitCategories(() => _initCat);
setDataChanged(() => false);
}
//eslint-disable-next-line
}, [selectedState]);

// useEffect(() => {
// if (getCustomerComments && props.cust && props.cust.customerId) {
// console.log(`Fetching Comment for :${props.cust.customerId}`);
// fetchCustomerComments(props.cust.customerId);
// }
// //eslint-disable-next-line
// }, []);

const list = (anchor: Anchor) => (
<Fragment>
<Dialog
header='Info'
visible={showAlert}
style={{ width: "30vw" }}
onHide={() => closeAlert()}
footer={footerContent}
>
<p className='m-0'>{alertMessage}</p>
</Dialog>
<Grid container>
<Stack
sx={{
width: anchor === "top" || anchor === "bottom" ? "auto" : "20vw",
minWidth: "35vw",
display: "flex",
alignContent: "center",
}}
role='presentation'
onClick={toggleDrawer(anchor, false)}
onKeyDown={toggleDrawer(anchor, false)}
>
<Card>
<CardHeader>
<Stack direction="row" justifyContent="space-between" >
<Typography gutterBottom variant='h5' component='div'>
Client Business Categories
</Typography>
<IconButton >
<CloseIcon onClick={() => handleCancel(anchor)} />
</IconButton>
</Stack>
</CardHeader>
<CardContent>
<Typography
variant='h6'
color='text.secondary'
sx={{ mt: "1rem" }}
>
BUSINESS CATEGORY
</Typography>
</CardContent>
<CardContent>
<FormControl fullWidth variant='filled'>
<Typography sx={fontStyle}>State</Typography>
<Select
id='state'
name='state'
value={selectedState}
onChange={handleStateChange}
label='State'
>
{states.map((item) => (
<MenuItem key={item.code} value={item.code}>
{item.state}
</MenuItem>
))}
</Select>
</FormControl>
<FormControl fullWidth variant='filled' sx={{ mt: "2rem" }}>
{/* <InputLabel id='customer-category-label'>
Customer Category
</InputLabel> */}
<Typography sx={fontStyle}>Business Category</Typography>
<MultiSelect
inputs={
props.categoriesLookup &&
props.categoriesLookup.map((item) => ({
name: item.businessCategoryName
? item.businessCategoryName
: "",
value: item.businessCategoryId
? item.businessCategoryId + ""
: "",
}))
}
values={selectedCategories}
initValues={initCategories}
updateSelection={handleCategoryChanges}
/>
</FormControl>
</CardContent>
<CardActions
sx={{
mt: "1.5rem",
display: "flex",
flexDirection: "row",
justifyContent: "flex-end",
}}
>
<MuiButton
variant='contained'
color='secondary'
sx={{ margin: 1, padding: 1 }}
onClick={() => handleCancel(anchor)}
>
Cancel
</MuiButton>
<MuiButton
variant='contained'
type='submit'
sx={{ margin: 1, padding: 1 }}
disabled={!dataChanged}
onClick={() => handleOk(anchor)}
>
SAVE
</MuiButton>
</CardActions>
<CardContent>
{showError && <Alert severity='error'>{alertMessage}</Alert>}
{showSuccess && <Alert severity='success'>{alertMessage}</Alert>}
</CardContent>
<CardContent>
<ListItem disablePadding>
<ListItemIcon>{/* <CategoryIcon /> */}</ListItemIcon>
<ListItemText primary={"State"} />
<ListItemText primary={"CategoryName"} />
<ListItemIcon>{/* <CategoryIcon /> */}</ListItemIcon>
</ListItem>
<Divider />
<List>
{data &&
data.map((item, index: number) => (
<Fragment>
<ListItem key={index} disablePadding>
<ListItemIcon>
<LabelImportantIcon />
</ListItemIcon>
<ListItemText
primary={
item && item.state && item.state !== null
? item.state
: ""
}
/>
<ListItemText
primary={
item &&
item.businessCategoryName &&
item.businessCategoryName !== null
? item.businessCategoryName
: ""
}
/>

<ListItemIcon>
<ListItemButton
sx={{ display: "flex", justifyContent: "flex-end" }}
onClick={() => handleDelete(item)}
>
<DeleteIcon />
</ListItemButton>
</ListItemIcon>
</ListItem>
</Fragment>
))}
</List>
</CardContent>
</Card>
</Stack>
</Grid>
</Fragment>
);

// const onCommentChange = async (e: React.ChangeEvent<any>) => {
// setApprovalComment((old) => e.target.value);
// };

const handleStateChange = (event: SelectChangeEvent) => {
const {
target: { value },
} = event;
setSelectedState((old) => value);
};

const addCategoriers = async (cats: string[]): Promise<boolean> => {
console.log(`Add Business Category changes for`, cats);
return new Promise(async (resolve, reject) => {
try {
if (createCustomerBusinessCategories && cats.length > 0) {
const payloadList = cats.map((item) => ({
customerId: props.cust?.customerId,
state: selectedState,
businessCategoryId: item,
}));

const res = await createCustomerBusinessCategories(payloadList);
if (res) {
resolve(true);
}
}
} catch (error) {
console.log(
`Error while saving Client Business Category changes`,
error
);
reject(false);
}
});
};
const getRecordIdForDelete = (catId: string): number => {
const _id = data.filter(
(item) =>
item.state === selectedState &&
item.businessCategoryId === parseInt(catId)
)[0].id;
return _id ? _id : 0;
};

const deleteCategoriers = (cats: string[]): Promise<boolean> => {
console.log(`Delete Business Category changes for`, cats);
return new Promise(async (resolve, reject) => {
if (deleteCustomerBusinessCategories && cats.length > 0) {
let promises: Promise<boolean>[] = [];
cats.forEach((item) => {
promises.push(
new Promise(async (resolve, reject) => {
try {
const _id = getRecordIdForDelete(item);
const res = await deleteCustomerBusinessCategories(_id);
if (res) {
console.log(`Delete Business Category sucess1`);
resolve(true);
}
} catch (error) {
reject(false);
}
})
);
});
return Promise.all(promises)
.then((result) => {
console.log(`Delete Business Category sucess2`);
resolve(true);
})
.catch((err) => reject(false));
} else {
resolve(true);
}
});
};

const handleOk = async (anchor: Anchor) => {
setShowSuccess(false);
// navigate("/filing-master-list");
// console.log(`Add Comment:${approvalComment}`);
const _delCats = _.difference(initCategories, selectedCategories);
const _addCats = _.difference(selectedCategories, initCategories);
// deleteCategoriers(_delCats).then((result) => {
// console.log(`Delete Business Category sucessf0`);
// });
Promise.all([addCategoriers(_addCats), deleteCategoriers(_delCats)])
.then(async (result) => {
console.log(`Delete Business Category sucessf`);
if (getCustomerBusinessCategories) {
const _catData = await getCustomerBusinessCategories(
props.cust?.customerId
);
setSourceData(() => _catData);
}
setAlertMessage("Client Business Category changes were saved");
setShowSuccess(true);
setShowError(false);
setSelectedState(() => "");
setSelectedCategories(() => []);
setInitCategories(() => []);
return;
})
.catch((error) => {
console.log(
`Error while saving Client Business Category changes`,
error
);
setAlertMessage("Error while saving Client Business Category changes");
setShowSuccess(false);
setShowError(true);
});
// try {
// if (createCustomerBusinessCategories && _addCats.length > 0) {
// const addRes = await addCategoriers(_addCats);
// const payloadList = _addCats.map((item) => ({
// customerId: props.cust?.customerId,
// state: selectedState,
// businessCategoryId: item,
// }));

// const res = await createCustomerBusinessCategories(payloadList);
// if (res) {
// console.log(`Client Business Category has been added`);
// // setSelectedState(() => "");
// // setSelectedCategories(() => []);
// // setState({ ...state, [anchor]: false });
// // props.handleClose();
// if (getCustomerBusinessCategories) {
// const _catData = await getCustomerBusinessCategories(
// props.cust?.customerId
// );
// setSourceData(() => _catData);
// }
// setAlertMessage("Client Business Category changes were saved");
// setShowSuccess(true);
// setShowError(false);
// setSelectedState(() => "");
// setSelectedCategories(() => []);
// setInitCategories(() => []);
// return;
// }
// }
// } catch (error) {
// console.log(`Error while saving Client Business Category changes`, error);
// setAlertMessage("Error while saving Client Business Category changes");
// setShowSuccess(false);
// setShowError(true);
// // props.handleClose();
// }
};

const handleCancel = async (anchor: Anchor) => {
setSelectedState(() => "");
setSelectedCategories(() => []);
setState({ ...state, [anchor]: false });
// setShowSuccess(false);
// setShowError(false);
props.handleClose();
};

const handleDelete = async (item: any) => {
setSelectedIdForDelete(item.id);
// props.handleClose();
setState({ ...state, [props.dockAt ? props.dockAt : "right"]: false });
showDialog(
"Confirmation",
"Are you sure to delete the Business Category?",
"confirm"
);
console.log(`Delete Client Business Category`, item);
};

return (
<div>
{/* {(["left", "right", "top", "bottom"] as const).map((anchor) => (
// <React.Fragment key={anchor}>
<Button onClick={toggleDrawer(anchor, true)}>{anchor}</Button> */}
{typeof props.dockAt !== "undefined" && (
<React.Fragment>
<Drawer
anchor={props.dockAt}
open={state[props.dockAt]}
onClose={toggleDrawer(props.dockAt, false)}
>
{list(props.dockAt)}
</Drawer>
<AlertDialog />
</React.Fragment>
)}
</div>
);
}
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.