Files
bodyshop/client/src/components/shop-employees/shop-employees.container.jsx
2021-02-26 14:55:16 -08:00

120 lines
3.4 KiB
JavaScript

import { useMutation, useQuery } from "@apollo/client";
import { Form, notification } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import {
DELETE_EMPLOYEE,
INSERT_EMPLOYEES,
QUERY_EMPLOYEES,
UPDATE_EMPLOYEE,
} from "../../graphql/employees.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import ShopEmployeeComponent from "./shop-employees.component";
const mapStateToProps = createStructuredSelector({
bodyshop: selectBodyshop,
});
function ShopEmployeesContainer({ bodyshop }) {
const [form] = Form.useForm();
const { t } = useTranslation();
const employeeState = useState(null);
const { loading, error, data, refetch } = useQuery(QUERY_EMPLOYEES, {
fetchPolicy: "network-only",
});
const [updateEmployee] = useMutation(UPDATE_EMPLOYEE);
const [insertEmployees] = useMutation(INSERT_EMPLOYEES);
const [deleteEmployee] = useMutation(DELETE_EMPLOYEE);
const handleDelete = (id) => {
logImEXEvent("shop_employee_delete");
deleteEmployee({ variables: { id: id } })
.then((r) => {
notification["success"]({
message: t("employees.successes.delete"),
});
employeeState[1](null);
refetch().then((r) => form.resetFields());
})
.catch((error) => {
notification["error"]({
message: t("employees.errors.delete", {
message: JSON.stringify(error),
}),
});
});
};
const handleFinish = (values) => {
if (employeeState[0].id) {
//Update a record.
logImEXEvent("shop_employee_update");
updateEmployee({
variables: {
id: employeeState[0].id,
employee: {
...values,
user_email: values.user_email === "" ? null : values.user_email,
},
},
})
.then((r) => {
notification["success"]({
message: t("employees.successes.save"),
});
employeeState[1](null);
refetch().then((r) => form.resetFields());
})
.catch((error) => {
notification["error"]({
message: t("employees.errors.save", {
message: JSON.stringify(error),
}),
});
});
} else {
//New record, insert it.
logImEXEvent("shop_employee_insert");
insertEmployees({
variables: { employees: [{ ...values, shopid: bodyshop.id }] },
}).then((r) => {
notification["success"]({
message: t("employees.successes.save"),
});
employeeState[1](null);
refetch().catch((error) => {
notification["error"]({
message: t("employees.errors.save", {
message: JSON.stringify(error),
}),
});
});
});
}
};
if (error) return <AlertComponent message={error.message} type="error" />;
return (
<ShopEmployeeComponent
handleFinish={handleFinish}
handleDelete={handleDelete}
form={form}
loading={loading}
employeeState={employeeState}
employees={data ? data.employees : []}
/>
);
}
export default connect(mapStateToProps, null)(ShopEmployeesContainer);