Files
bodyshop/client/src/components/jobs-close-allocation-button/jobs-close-allocation-button.component.jsx

108 lines
3.1 KiB
JavaScript

import { PlusCircleFilled, CloseCircleFilled } from "@ant-design/icons";
import { Button, InputNumber, Select } from "antd";
import Dinero from "dinero.js";
import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { useTranslation } from "react-i18next";
const mapStateToProps = createStructuredSelector({
bodyshop: selectBodyshop,
});
const { Option } = Select;
export function JobsCloseLabmatAllocationButton({
remainingAmount,
allocationKey,
allocation,
setAllocations,
bodyshop,
invoiced
}) {
const [visible, setVisible] = useState(false);
const [state, setState] = useState({ center: "", amount: 0 });
const { t } = useTranslation();
const handleAllocate = () => {
const existingIndex = allocation.allocations.findIndex(
(e) => e.center === state.center
);
const newAllocations = allocation.allocations.slice(0);
if (existingIndex > -1) {
newAllocations[existingIndex] = {
center: state.center,
amount: newAllocations[existingIndex].amount.add(
Dinero({ amount: (state.amount || 0) * 100 })
),
};
} else {
newAllocations.push({
center: state.center,
amount: Dinero({ amount: (state.amount || 0) * 100 }),
});
}
setAllocations((labMatState) => {
return {
...labMatState,
[allocationKey]: {
...allocation,
allocations: newAllocations,
},
};
});
setState({ center: "", amount: 0 });
};
const showAllocation = allocation.total.getAmount() > 0;
useEffect(() => {
if (remainingAmount === 0) setVisible(false);
}, [remainingAmount, setVisible]);
if (!showAllocation) return null;
return (
<div style={{ display: "flex", alignItems: "center" }}>
<div style={{ display: visible ? "" : "none" }}>
<Select
style={{ width: "200px" }}
value={state.center}
onSelect={(val) => setState({ ...state, center: val })}
>
{bodyshop.md_responsibility_centers.profits.map((r, idx) => (
<Option key={idx} value={r.name}>
{r.name}
</Option>
))}
</Select>
<InputNumber
precision={2}
min={0}
value={state.amount}
onChange={(val) => setState({ ...state, amount: val })}
max={remainingAmount / 100}
/>
<Button
onClick={handleAllocate}
disabled={
state.amount === 0 || state.center === "" || remainingAmount === 0 || invoiced
}
>
{t("jobs.actions.allocate")}
</Button>
</div>
<div>
{visible ? (
<CloseCircleFilled onClick={() => setVisible(false)} disabled={invoiced} />
) : (
<PlusCircleFilled onClick={() => setVisible(true)} disabled={invoiced}/>
)}
</div>
</div>
);
}
export default connect(mapStateToProps, null)(JobsCloseLabmatAllocationButton);