Stashed / app / src / pages / sales / sales.jsx
sales.jsx
Raw
import React, { useState, useEffect } from "react";
import clsx from "clsx";
import { connect } from "react-redux";
import ROUTES from "Constants/routes";
import { history } from "Redux/store/store";
import {
  writeConfigRequest,
  useConfigInMainRequest,
} from "secure-electron-store";
import { makeStyles } from "@material-ui/core/styles";
import {
  Button,
  Divider,
  Grid,
  Typography,
  Menu,
  MenuItem,
} from "@material-ui/core";
import { DataGrid } from "@material-ui/data-grid";

import { openModal } from "Redux/modals/addItemModalSlice";
import { openEditModal } from "Redux/modals/editItemModalSlice";
import { addItem, replaceItems } from "Redux/data/inventorySlice";
import EditItemModal from "Components/modals/editItemModal";

const useStyles = makeStyles((theme) => ({
  divider: { marginBottom: 24 },
  section: { paddingLeft: 4, paddingRight: 4, marginBottom: 18 },
  data: {
    height: 650,
    width: "100%",
    "& .datagrid.negative": { color: "#d50000" },
    "& .datagrid.positive": {
      color: "#00c853",
    },
  },
  root: {
    width: "100%",
    "& > * + *": {
      marginTop: theme.spacing(2),
    },
  },
  paper: {
    padding: theme.spacing(2),
    color: theme.palette.text.secondary,
    display: "flex",
    alignItems: "center",
    marginBottom: theme.spacing(1),
  },
  buttonSpacing: {
    marginRight: 12,
  },
}));

const initialState = {
  mouseX: null,
  mouseY: null,
};

const Sales = (props) => {
  useEffect(() => {
    window.api.store.send(useConfigInMainRequest);
  }, []);

  const Navigate = (url, item) => {
    history.push({ pathname: url, search: selectedItems[0], state: "sales" });
  };

  const styles = useStyles();

  const columns = [
    { field: "name", headerName: "Product Name", width: 300 },
    { field: "size", headerName: "Size", filterable: false, width: 120 },
    {
      field: "sku",
      headerName: "SKU",
      width: 130,
      sortable: false,
      filterable: false,
      description: "Style ID",
    },
    {
      field: "Profit",
      headerName: "Profit",
      filterable: false,
      width: 150,
      valueGetter: (params) =>
        `${getProfit(params) < 0 ? "-" : ""}` +
        `$` +
        `${Math.abs(getProfit(params)).toFixed(2)}`,
      cellClassName: (params) =>
        clsx("datagrid", {
          negative: getProfit(params) < 0,
          positive: getProfit(params) > 0,
        }),
    },
    {
      field: "payout",
      headerName: "Payout",
      description: "Payout - Fees",
      filterable: false,
      width: 150,
      valueGetter: (params) => `$${params.row.saleData.payout}`,
    },
    {
      field: "totalCost",
      headerName: "Cost",
      description: "Cost + Tax + Shipping",
      filterable: false,
      width: 150,
      valueGetter: (params) => `$${getTotalCost(params).toFixed(2)}`,
    },
    {
      field: "platform",
      headerName: "Platform",
      sortable: false,
      filterable: false,
      width: 200,
      valueGetter: (params) => params.row.saleData.platform,
    },
    {
      field: "colorway",
      headerName: "Colorway",
      filterable: false,
      sortable: false,
      width: 160,
    },
    {
      field: "store",
      headerName: "Purchase Location",
      sortable: false,
      filterable: false,
      width: 200,
    },
    {
      field: "dateObtained",
      headerName: "Date Obtained",
      filterable: false,
      width: 170,
    },
    {
      field: "dateAdded",
      headerName: "Date Added",
      filterable: false,
      width: 170,
    },
  ];
  const getTotalCost = (params) => {
    return (
      parseFloat(params.row.cost) +
      parseFloat(params.row.costShipping) +
      parseFloat(params.row.costTax)
    );
  };
  const getProfit = (params) => {
    return (
      parseFloat(params.row.saleData.payout) - parseFloat(getTotalCost(params))
    );
  };

  const [selectedItems, setSelectedItems] = useState([]);
  const [selectedItemsTotalCost, setSelectedItemsTotalCost] = useState(0);
  useEffect(() => {
    if (selectedItems.length > 0) {
      selectedItems.map((itemId) => {
        props.inventory.items.map((item) => {
          if (itemId == item.id) {
            setSelectedItemsTotalCost(
              parseInt(selectedItemsTotalCost) + parseInt(item.cost)
            );
          }
        });
      });
    } else {
      setSelectedItemsTotalCost(0);
    }
  }, [selectedItems]);

  const deleteSelected = () => {
    const newItems = props.inventory.items.filter(
      (item) => !selectedItems.includes(item.id)
    );
    props.replaceItems(newItems);
    window.api.store.send(writeConfigRequest, "inventoryItems", newItems);
    setSelectedItems([]);
    closeContextMenu();
  };

  const [contextMenuVis, setContextMenuVis] = useState(initialState);
  const openContextMenu = (e) => {
    e.preventDefault();
    setContextMenuVis({
      mouseX: e.clientX - 2,
      mouseY: e.clientY - 4,
    });
  };
  const closeContextMenu = () => {
    setContextMenuVis(initialState);
  };

  useEffect(() => {
    console.log("SalesPAGE Props:", props);
  }, []);

  return (
    <React.Fragment>
      <div className={styles.root}>
        <Grid container alignItems="center" direction="row">
          <Grid item xs={6}>
            <Typography variant="h5">Sales</Typography>
            <Typography variant="subtitle1">
              Keep track of all your sold sneakers, apparel, and collectibles.
            </Typography>
          </Grid>
          <Grid
            item
            container
            xs
            direction="row"
            justify="flex-end"
            alignItems="center"
          >
            <Button
              variant="contained"
              size="small"
              className={styles.buttonSpacing}
              onClick={() => {
                console.log("Exporting Items");
              }}
            >
              Export
            </Button>
            <Button
              variant="contained"
              color="primary"
              onClick={() => {
                console.log(props);
              }}
            >
              Mark Unsold
            </Button>
          </Grid>
        </Grid>

        <Divider className={styles.divider} />

        <div
          className={styles.data}
          onContextMenu={openContextMenu}
          style={{ cursor: "context-menu" }}
        >
          <DataGrid
            rows={props.sales.sales}
            columns={columns}
            pageSize={10}
            checkboxSelection
            disableColumnMenu
            onSelectionModelChange={(newSelection) => {
              setSelectedItems(newSelection.selectionModel);
            }}
            selectionModel={selectedItems}
          />

          <Menu
            keepMounted
            open={contextMenuVis.mouseY !== null}
            onClose={closeContextMenu}
            anchorReference="anchorPosition"
            anchorPosition={
              contextMenuVis.mouseY !== null && contextMenuVis.mouseX !== null
                ? { top: contextMenuVis.mouseY, left: contextMenuVis.mouseX }
                : undefined
            }
          >
            <MenuItem
              onClick={() => {
                Navigate(ROUTES.INFO);
                closeContextMenu();
              }}
              disabled={selectedItems.length == 0}
            >
              Info
            </MenuItem>
            <MenuItem
              onClick={() => {
                console.log("swag");
              }}
              disabled={selectedItems.length == 0}
            >
              Mark as Sold
            </MenuItem>
            <MenuItem
              onClick={() => {
                props.openEditModal();
              }}
              disabled={selectedItems.length == 0}
            >
              Edit
            </MenuItem>
            <MenuItem
              onClick={closeContextMenu}
              disabled={selectedItems.length == 0}
            >
              Duplicate
            </MenuItem>
            <MenuItem
              onClick={() => {
                deleteSelected();
              }}
              disabled={selectedItems.length == 0}
            >
              Delete Selected
            </MenuItem>
          </Menu>
        </div>
      </div>
    </React.Fragment>
  );
};

const mapStateToProps = (state, props) => ({
  addItemModal: state.addItemModal,
  editItemModal: state.editItemModal,
  inventory: state.inventory,
  sales: state.sales,
});
const mapDispatch = { openModal, addItem, replaceItems, openEditModal };

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