Files
imexmobile/components/time-ticket/screen-time-ticket-create.component.jsx
2023-07-26 08:38:19 -04:00

328 lines
11 KiB
JavaScript

import { Formik } from "formik";
import React, { useRef, useState,useCallback } from "react";
import { StyleSheet, Text, View, ScrollView, RefreshControl,FlatList } from "react-native";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { Button, TextInput, Card } from "react-native-paper";
import CostCenterSelect from "../Selects/select-cost-center";
import DateTimePickerModal from "react-native-modal-datetime-picker";
import {
selectCurrentEmployee,
selectRates,
selectEmployeeFullName,
} from "../../redux/employee/employee.selectors";
import {
selectBodyshop,
selectRestrictClaimableHoursFlag,
} from "../../redux/user/user.selectors";
import LaborAllocationsTable from "../labor-allocations-table/labor-allocations-table.component";
import ErrorDisplay from "../error-display/error-display.component";
import { INSERT_NEW_TIME_TICKET } from "../../graphql/timetickets.queries";
import { useMutation } from "@apollo/client";
import moment from "moment";
import { useNavigation } from "@react-navigation/native";
import styles from "../styles";
import JobSearchAndSelectModal from "../Modals/JobSearchAndSelectModal";
const mapStateToProps = createStructuredSelector({
currentEmployee: selectCurrentEmployee,
currentRatesNCostCenters: selectRates,
currentBodyshop: selectBodyshop,
currentEmployeeFullName: selectEmployeeFullName,
currentRestrictClaimableHoursFlag: selectRestrictClaimableHoursFlag,
});
export function TimeTicketCreate({
currentEmployee,
currentRatesNCostCenters,
currentBodyshop,
currentEmployeeFullName,
currentRestrictClaimableHoursFlag,
}) {
const costCenterDiff = useRef(0);
const navigation = useNavigation();
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [loadingCreate, setLoadingCreate] = useState(false);
const [error, setError] = useState(null);
const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
const [date2, setDate2] = useState(new Date());
const [currentSCC, setCurrentSCC] = useState(null);
const [curSelClockIntoJob,setCurSelClockIntoJob] = useState(null);
const showDatePicker = () => {
setDatePickerVisibility(true);
};
const hideDatePicker = () => {
setDatePickerVisibility(false);
};
const handleConfirm = (date) => {
setDate2(date);
hideDatePicker();
};
const [insertTicket] = useMutation(INSERT_NEW_TIME_TICKET);
const handleFinish = async (values) => {
setError(null);
setLoadingCreate(true);
if (
!!currentSCC?.value &&
!!curSelClockIntoJob?.id &&
!!values.productivehours &&
!!currentBodyshop.id &&
!!currentEmployee?.technician?.id &&
!!date2 &&
!!values.actualhours
) {
if (isNaN(values.actualhours) | isNaN(values.productivehours)) {
// console.log("actual hours is NAN!");
setLoadingCreate(false);
setError({ message: t("createtimeticket.errors.nan") });
return;
}
setError(null);
// console.log("have all values");
} else {
// console.log("missing values!");
setLoadingCreate(false);
setError({ message: t("createtimeticket.errors.missingvalues") });
return;
}
if (!!currentRestrictClaimableHoursFlag) {
if (values.productivehours > costCenterDiff.current) {
setLoadingCreate(false);
setError({
message: t("timeticketclockoff.errors.hoursenteredmorethanavailable"),
});
return;
}
}
const tempVariablesObj = {
variables: {
timeTicketInput: [
{
actualhrs: values?.actualhours ? values?.actualhours : null,
bodyshopid: currentBodyshop.id,
ciecacode:
currentBodyshop?.cdk_dealerid || currentBodyshop?.pbs_serialnumber
? currentSCC?.value
: Object.keys(
currentBodyshop.md_responsibility_centers.defaults.costs
).find((key) => {
return (
currentBodyshop.md_responsibility_centers.defaults.costs[
key
] === currentSCC?.value
);
}),
cost_center: currentSCC?.value,
date: moment(date2).format("YYYY-MM-DD"),
employeeid: currentEmployee?.technician?.id,
flat_rate:
currentEmployee &&
currentEmployee.technician &&
currentEmployee.technician?.flat_rate,
jobid: curSelClockIntoJob?.id,
productivehrs: values?.productivehours,
rate:
currentRatesNCostCenters && currentSCC?.value
? currentRatesNCostCenters.filter(
(r) => r.cost_center === currentSCC?.value
)[0].rate
: null,
},
],
},
};
const result = await insertTicket(tempVariablesObj);
setLoadingCreate(false);
if (!!result.errors) {
// console.log("insertTicket, result.error :", result.errors);
setError(JSON.stringify(result.errors));
} else {
// console.log("insertTicket, result. :", result.data);
navigation.goBack();
}
};
const onRefresh = useCallback(() => {
setLoading(true);
// refetch();
setTimeout(() => {
setLoading(false);
}, 500);
}, []);
return (
<View style={styles.cardBackground}>
<FlatList
ListHeaderComponent={
<Card style={localStyles.localCardStyle}>
<Card.Content>
<Formik
initialValues={{
ticketdate: date2.toLocaleDateString(),
employee: { currentEmployeeFullName },
costcenter: { currentSCC },
productivehours: "",
actualhours: "",
}}
onSubmit={handleFinish}
>
{({ handleChange, handleBlur, handleSubmit, values }) => (
<View style={localStyles.topTimeTicketContainer}>
<JobSearchAndSelectModal
currentValue={curSelClockIntoJob}
onSetCurrentValue={setCurSelClockIntoJob}
notExported={!currentBodyshop.tt_allow_post_to_invoiced}
notInvoiced={!currentBodyshop.tt_allow_post_to_invoiced}
convertedOnly={true}
/>
<Button
mode="outlined"
title="TicketDatePickerButton"
onPress={showDatePicker}
style={localStyles.dateButton}
>
<Text style={localStyles.textForButton}>
{t("createtimeticket.actions.ticketdate")}
{date2.toLocaleDateString("en-US", {
day: "2-digit",
month: "2-digit",
year: "numeric",
})}
</Text>
</Button>
<DateTimePickerModal
isVisible={isDatePickerVisible}
mode="date"
date={date2}
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
<TextInput
style={localStyles.inputStyle}
mode="outlined"
disabled={true}
value={currentEmployeeFullName}
label={t("createtimeticket.labels.employeeplaceholder")}
/>
<CostCenterSelect
currentRatesNCostCenters={currentRatesNCostCenters}
currentValue={currentSCC}
onValueSelected={setCurrentSCC}
/>
<TextInput
style={localStyles.inputStyle}
mode="outlined"
onChangeText={handleChange("productivehours")}
onBlur={handleBlur("productivehours")}
value={values.productivehours}
label={t(
"createtimeticket.labels.productivehoursplaceholder"
)}
keyboardType="numeric"
/>
<TextInput
style={localStyles.inputStyle}
mode="outlined"
onChangeText={handleChange("actualhours")}
onBlur={handleBlur("actualhours")}
value={values.actualhours}
label={t(
"createtimeticket.labels.actualhoursplaceholder"
)}
keyboardType="numeric"
/>
{error ? (
<ErrorDisplay errorMessage={error.message} />
) : null}
<View style={{ flexDirection: "row",justifyContent: "center", paddingTop:8 }}>
<Button
mode="outlined"
style={styles.buttonBasicOutlined}
onPress={handleSubmit}
loading={loadingCreate}
title="Submit"
>
<Text style={{ fontSize: 12 }}>
{t("createtimeticket.actions.createticket")}
</Text>
</Button>
</View>
</View>
)}
</Formik>
</Card.Content>
</Card>
}
data={null}
renderItem={null}
ListFooterComponent={
<LaborAllocationsTable
jobId={curSelClockIntoJob?.id}
costCenterDiff={costCenterDiff}
selectedCostCenter={currentSCC}
style={localStyles.localCardStyle}
shouldRefresh={loading}
/>
}
refreshControl={
<RefreshControl refreshing={loading} onRefresh={onRefresh} />
}
/>
</View>
);
}
export default connect(mapStateToProps, null)(TimeTicketCreate);
const localStyles = StyleSheet.create({
content: {
display: "flex",
flex: 1,
},
topContainer: {},
bottomContainer: {},
input: {
marginVertical: 4,
marginHorizontal: 16,
height: 48,
justifyContent: "center",
alignContent: "center",
borderWidth: 0.8,
},
dateButton: {
marginVertical: 4,
marginHorizontal: 16,
height: 48,
justifyContent: "center",
alignContent: "center",
borderColor: "gray",
borderWidth: 0.8,
},
textForButton: {
flex: 1,
justifyContent: "center",
alignContent: "center",
},
inputStyle: {
marginVertical: 4,
marginHorizontal: 16,
height: 48,
fontSize: 16,
},
localCardStyle: {
margin: 4,
},
});