Stashed / app / src / components / modals / addSaleModal.jsx
addSaleModal.jsx
Raw
import React, { useState, useEffect } from "react";
import clsx from "clsx";
import { makeStyles, withStyles } from "@material-ui/core/styles";
import {
  Typography,
  Button,
  Grid,
  TextField,
  ButtonGroup,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  Paper,
  Divider,
  Card,
  CardContent,
  CardMedia,
  Menu,
  MenuItem,
  FormControl,
  InputLabel,
  FilledInput,
  InputAdornment,
} from "@material-ui/core";
import CloseIcon from "@material-ui/icons/Close";
import AddIcon from "@material-ui/icons/Add";
import AttachMoneyIcon from "@material-ui/icons/AttachMoney";
import RemoveIcon from "@material-ui/icons/Remove";
import Autocomplete from "@material-ui/lab/Autocomplete";
import useAutocomplete from "@material-ui/lab/useAutocomplete";

import {
  writeConfigRequest,
  useConfigInMainRequest,
} from "secure-electron-store";
import { connect } from "react-redux";
import { v4 as uuidv4 } from "uuid";

import algoliasearch from "algoliasearch";

import { closeSaleModal } from "../../redux/modals/addSaleModalSlice";
import { addSale } from "Redux/data/salesSlice";
import { deleteItem } from "Redux/data/inventorySlice";

const useStyles = makeStyles((theme) => ({
  paper: {
    padding: theme.spacing(1),
    color: theme.palette.text.secondary,
    display: "flex",
    alignItems: "center",
  },
  paperTitle: {
    marginBottom: theme.spacing(0.5),
  },
  verticalSpacing: {
    marginBottom: theme.spacing(2),
  },
  root: {
    display: "flex",
    flexWrap: "wrap",
  },
  details: {
    display: "flex",
    flexDirection: "column",
  },
  content: {
    flex: "1 0 auto",
  },
  cover: {
    width: 75,
    minWidth: 75,
    display: "flex",
    alignItems: "center",
    marginLeft: theme.spacing(1.5),
  },
  margin: {
    margin: theme.spacing(1),
  },
}));
const StyledMenu = withStyles({
  paper: {
    border: "1px solid #d3d4d5",
  },
})((props) => (
  <Menu
    elevation={0}
    getContentAnchorEl={null}
    anchorOrigin={{
      vertical: "bottom",
      horizontal: "left",
    }}
    transformOrigin={{
      vertical: "top",
      horizontal: "left",
    }}
    {...props}
  />
));

const AddSaleModal = (props) => {
  // Request so that the main process can use the store
  useEffect(() => {
    window.api.store.send(useConfigInMainRequest);
  }, []);

  const styles = useStyles();

  const [listPrice, setListPrice] = useState(0);
  const [feePlatform, setFeePlatform] = useState(0);
  const [feeShip, setFeeShip] = useState(0);
  const [platform, setPlatform] = useState("");
  const [dateList, setDateList] = useState(new Date());
  const [dateSold, setDateSold] = useState(new Date());
  const [prodDesc, setProdDesc] = useState("");

  const resetModalState = () => {
    setListPrice(0);
    setFeeShip(0);
    setFeePlatform(0);
    setPlatform("");
    setDateList(new Date());
    setDateSold(new Date());
    setProdDesc("");
    setFeeVis(false);
    setFeeType("");
  };

  useEffect(() => {
    if (props.addSaleModal.visibility == false) {
      resetModalState();
    } else {
      if (props.saleItems.length == 1) {
        const item = props.inventory.items.filter((item) => {
          return item.id == props.saleItems[0];
        });
        setProdDesc(item[0].description);
      }
    }
  }, [props.addSaleModal.visibility]);

  const [feeVis, setFeeVis] = useState(false);
  const [feeType, setFeeType] = useState("");
  const [anchorElFees, setAnchorElFees] = useState(null);
  const handleFeesMenuClick = (e) => {
    setAnchorElFees(e.currentTarget);
  };
  const handleFeesMenuClose = () => {
    setAnchorElFees(null);
  };
  const [feePlatformType, setFeePlatformType] = useState("fixed");
  const [feeShipType, setFeeShipType] = useState("fixed");
  const switchFeePlatformType = () => {
    if (feePlatformType == "fixed") {
      setFeePlatformType("percent");
    } else {
      setFeePlatformType("fixed");
    }
  };
  const switchFeeShipType = () => {
    if (feeShipType == "fixed") {
      setFeeShipType("percent");
    } else {
      setFeeShipType("fixed");
    }
  };

  const getSoldPrice = () => {
    let platformFees = 0.0;
    let shipFees = 0.0;
    if (feePlatformType == "percent") {
      platformFees = (parseFloat(feePlatform) / 100) * parseFloat(listPrice);
    } else {
      platformFees = feePlatform;
    }
    if (feeShipType == "percent") {
      shipFees = (parseFloat(feeShip) / 100) * parseFloat(listPrice);
    } else {
      shipFees = feeShip;
    }

    return (
      parseFloat(listPrice) -
      (parseFloat(platformFees) + parseFloat(shipFees))
    ).toFixed(2);
  };

  const addNewSales = () => {
    var prevSales = props.sales.sales;
    var prevItems = props.inventory.items;

    const markedSales = props.inventory.items.filter((item) => {
      return props.saleItems.includes(item.id);
    });

    markedSales.map((sale) => {
      const newSale = {
        ...sale,
        description: prodDesc,
        status: "Sold",
        saleData: {
          payout: getSoldPrice(),
          platform: platform,
          listDate: new Date(dateList).toLocaleDateString("en-US"),
          soldDate: new Date(dateSold).toLocaleDateString("en-US"),
          xtra: {
            listPrice: listPrice,
            feePlatformType: feePlatformType,
            feeShipType: feeShipType,
            feePlatformAmnt: feePlatform,
            feeShipAmnt: feeShip,
          },
        },
      };
      prevSales = [...prevSales, newSale];
      prevItems = prevItems.filter((item) => {
        return item.id !== newSale.id;
      });
      props.addSale(newSale);
      props.deleteItem(newSale.id);
    });
    console.log(prevSales);
    console.log(prevItems);
    window.api.store.send(writeConfigRequest, "inventoryItems", prevItems);
    window.api.store.send(writeConfigRequest, "saleItems", prevSales);
    props.closeSaleModal();
  };

  return (
    <>
      <Dialog
        open={props.addSaleModal.visibility}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">
          Mark as Sold  {props.saleItems.length}{" "}
          {props.saleItems.length > 1 ? "items" : "item"}
        </DialogTitle>
        <DialogContent>
          <Grid container spacing={1}>
            <Grid
              container
              item
              xs={12}
              spacing={1}
              className={styles.verticalSpacing}
            >
              <TextField
                id="listingPrice"
                label="Listing Price"
                variant="filled"
                size="small"
                fullWidth
                value={listPrice}
                onChange={(e) => {
                  setListPrice(e.target.value);
                }}
              />
            </Grid>

            <Grid
              container
              item
              xs={12}
              spacing={1}
              className={styles.verticalSpacing}
            >
              <Button
                variant="contained"
                color="primary"
                fullWidth
                onClick={handleFeesMenuClick}
              >
                Add Fee
              </Button>
              <StyledMenu
                anchorEl={anchorElFees}
                keepMounted
                open={Boolean(anchorElFees)}
                onClose={handleFeesMenuClose}
              >
                <MenuItem
                  onClick={() => {
                    setFeeVis(true);
                    setFeeType("custom");
                    handleFeesMenuClose();
                  }}
                >
                  Custom Fee
                </MenuItem>
                <MenuItem
                  style={{ display: "flex", alignItems: "center" }}
                  onClick={() => {
                    setFeeVis(true);
                    setFeeType("preset");
                    handleFeesMenuClose();
                  }}
                >
                  <Typography>New Preset</Typography>
                  <AddIcon />
                </MenuItem>
              </StyledMenu>
              {feeVis && (
                <Paper className={styles.paper}>
                  <Grid container>
                    <Grid container>
                      <Grid xs item className={styles.paperTitle}>
                        <Typography>
                          {feeType == "custom"
                            ? "Custom Fee"
                            : feeType == "preset"
                            ? "New Preset"
                            : ""}
                        </Typography>
                      </Grid>
                      <Grid item>
                        <CloseIcon
                          fontSize="small"
                          style={{ cursor: "pointer" }}
                          onClick={() => {
                            setFeeVis(false);
                            setFeeType("");
                            setFeeShip(0);
                            setFeePlatform(0);
                          }}
                        />
                      </Grid>
                    </Grid>

                    <Grid container spacing={1}>
                      <Grid xs item>
                        <FormControl variant="filled" size="small" fullWidth>
                          <InputLabel htmlFor="filled-adornment-password">
                            Platform Fees
                          </InputLabel>
                          <FilledInput
                            id="feePlatform"
                            value={feePlatform}
                            size="small"
                            onChange={(e) => {
                              setFeePlatform(e.target.value);
                            }}
                            startAdornment={
                              <InputAdornment position="start">
                                <IconButton
                                  edge="start"
                                  size="small"
                                  onClick={() => {
                                    switchFeePlatformType();
                                  }}
                                >
                                  {feePlatformType == "fixed" ? (
                                    <AttachMoneyIcon />
                                  ) : (
                                    <span
                                      style={{
                                        fontWeight: "bolder",
                                        fontSize: 18,
                                        padding: 4,
                                      }}
                                    >
                                      %
                                    </span>
                                  )}
                                </IconButton>
                              </InputAdornment>
                            }
                          />
                        </FormControl>
                      </Grid>
                      <Grid xs item>
                        <FormControl variant="filled" size="small" fullWidth>
                          <InputLabel htmlFor="filled-adornment-password">
                            Shipping Fees
                          </InputLabel>
                          <FilledInput
                            id="feeShip"
                            value={feeShip}
                            onChange={(e) => {
                              setFeeShip(e.target.value);
                            }}
                            startAdornment={
                              <InputAdornment position="start">
                                <IconButton
                                  edge="start"
                                  size="small"
                                  onClick={() => {
                                    switchFeeShipType();
                                  }}
                                >
                                  {feeShipType == "fixed" ? (
                                    <AttachMoneyIcon />
                                  ) : (
                                    <span
                                      style={{
                                        fontWeight: "bolder",
                                        fontSize: 18,
                                        padding: 4,
                                      }}
                                    >
                                      %
                                    </span>
                                  )}
                                </IconButton>
                              </InputAdornment>
                            }
                          />
                        </FormControl>
                      </Grid>
                      <Grid xs={12} item>
                        <Typography>
                          {listPrice == 0
                            ? "Listing price cannot be empty!"
                            : "Total Payout: $" + getSoldPrice()}
                        </Typography>
                      </Grid>
                    </Grid>
                  </Grid>
                </Paper>
              )}
            </Grid>

            <Grid
              container
              item
              xs={12}
              spacing={1}
              className={styles.verticalSpacing}
            >
              <TextField
                id="platform"
                label="Listing platform"
                variant="filled"
                size="small"
                fullWidth
                value={platform}
                onChange={(e) => {
                  setPlatform(e.target.value);
                }}
              />
            </Grid>

            <Grid
              container
              item
              xs={12}
              spacing={1}
              className={styles.verticalSpacing}
            >
              <Grid item xs={6}>
                <TextField
                  id="dateListed"
                  label="Listing Date"
                  variant="filled"
                  size="small"
                  type="date"
                  value={dateList}
                  onChange={(e) => {
                    setDateList(e.target.value);
                  }}
                  InputLabelProps={{
                    shrink: true,
                  }}
                  fullWidth
                />
              </Grid>
              <Grid item xs={6}>
                <TextField
                  id="dateSold"
                  label="Sale date"
                  variant="filled"
                  size="small"
                  type="date"
                  value={dateSold}
                  onChange={(e) => {
                    setDateSold(e.target.value);
                  }}
                  InputLabelProps={{
                    shrink: true,
                  }}
                  fullWidth
                />
              </Grid>
            </Grid>

            <Grid container xs={12}>
              <TextField
                id="prodDesc"
                label="Description"
                multiline
                rows={3}
                variant="filled"
                size="small"
                type="date"
                value={prodDesc}
                onChange={(e) => {
                  setProdDesc(e.target.value);
                }}
                fullWidth
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button
            color="primary"
            onClick={() => {
              props.closeSaleModal();
            }}
          >
            Cancel
          </Button>
          <Button
            color="primary"
            onClick={(e) => {
              addNewSales();
            }}
          >
            Confirm
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};

const mapStateToProps = (state, props) => ({
  addSaleModal: state.addSaleModal,
  inventory: state.inventory,
  sales: state.sales,
});
const mapDispatch = { closeSaleModal, addSale, deleteItem };

export default connect(mapStateToProps, mapDispatch)(AddSaleModal);