Files
imexmobile/components/time-ticket/screen-time-ticket-create.component.jsx
2023-05-16 00:33:55 -04:00

301 lines
10 KiB
JavaScript

import { Formik } from "formik";
import React, { useEffect, useState } from "react";
import { StyleSheet, Text, View, ScrollView } from "react-native";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { Button, Dialog, TextInput } from "react-native-paper";
import { CostCenterSelect } from "../Selects/select-cost-center";
import { JobIdSearchSelect } from "../Selects/select-job-id";
import DateTimePickerModal from "react-native-modal-datetime-picker";
import {
selectCurrentEmployee,
selectRates,
} from "../../redux/employee/employee.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { useCallback } from "react";
// import LaborAllocationsTable from "../labor-allocations-table/labor-allocations-table.component";
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 axios from "axios";
import { logImEXEvent } from "../../firebase/firebase.analytics";
import moment from "moment";
import { useNavigation } from "@react-navigation/native";
//TODO add props needed for call
const mapStateToProps = createStructuredSelector({
currentEmployee: selectCurrentEmployee,
currentRatesNCostCenters: selectRates,
currentBodyshop: selectBodyshop,
});
// const mapDispatchToProps = (dispatch) => ({});
export function TimeTicketCreate({
currentEmployee,
currentRatesNCostCenters,
currentBodyshop,
}) {
const navigation = useNavigation();
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
const [date2, setDate2] = useState(new Date());
const [currentSCC, setCurrentSCC] = useState(null);
// const [currentSJob, setCurrentSJob] = useState(null);
const [currentSJobId, setCurrentSJobId] = useState(null);
// const wrapperSetCurrentSJobState = useCallback(
// (val) => {
// setCurrentSJob(val);
// },
// [setCurrentSJob]
// );
const showDatePicker = () => {
setDatePickerVisibility(true);
};
const hideDatePicker = () => {
setDatePickerVisibility(false);
};
const handleConfirm = (date) => {
setDate2(date);
//console.war1n("A date has been picked: ", date);
hideDatePicker();
};
const [insertTimeTicket] = useMutation(INSERT_NEW_TIME_TICKET);
const handleFinish = async (values) => {
const theTime = (await axios.post("/utils/time")).data;
setLoading(true);
logImEXEvent("insertTimeTicket_handleFinish");
// console.log("insertTimeTicket, currentSCC :", currentSCC);
// console.log("insertTimeTicket, currentSCC :", currentSJobId);
// console.log("insertTimeTicket, values :", values);
if (
!!currentSCC?.value &&
!!currentSJobId?.value &&
!!values.productivehours &&
!!values.actualhours &&
!!values.productivehours
) {
setError(null);
console.log("all have values:");
} else {
console.log("missing values!");
setError({ message: "Please make sure all fields have a value." });
return;
}
if (currentSJobId)
console.log("jobid or currentSJobId", currentSJobId?.value);
const tempVariablesObj = {
variables: {
timeTicketInput: [
{
bodyshopid: currentBodyshop.id,
employeeid: currentEmployee?.technician?.id,
date: moment(theTime).format("YYYY-MM-DD"),
clockon: moment(theTime),
jobid: currentSJobId?.value,
cost_center: currentSCC?.value,
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);
}),
}
],
},
};
// const tempcallobj = {
// variables: {
// timeticketId: timeTicketId,
// timeticket: {
// actualhrs: values?.actualhours,
// 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
// );
// }),
// clockoff: (await axios.post("/utils/time")).data,
// cost_center: currentSCC?.value,
// flat_rate:
// currentEmployee &&
// currentEmployee.technician &&
// currentEmployee.technician?.flat_rate,
// productivehrs: values?.productivehours,
// rate:
// currentRatesNCostCenters &&
// currentSCC?.value &&
// currentRatesNCostCenters.filter(
// (r) => r.cost_center === currentSCC?.value
// )[0]?.rate,
// },
// },
// };
console.log("insertTimeTicket, tempVariablesObj :", tempVariablesObj?.variables?.timeTicketInput[0]);
//after obj is good add below to make call
const result = await insertTimeTicket(tempVariablesObj);
//after call results are retuning add handling below for cases
console.log("insertTimeTicket, result :", result);
setLoading(false);
if (!!result.errors) {
console.log("insertTimeTicket, result.error :", result.errors);
setError(SON.stringify(result.errors));
} else {
console.log("insertTimeTicket, result. :", result.data);
navigation.goBack();
}
// if (completedCallback) completedCallback();
};
return (
<View style={localStyles.content}>
<ScrollView contentContainerStyle={{ flexGrow: 1 }}>
<Formik
initialValues={{
jobid: { currentSJobId },
ticketdate: date2.toLocaleDateString(),
employee: currentEmployee.technician.first_name,
costcenter: { currentSCC },
productivehours: "",
actualhours: "",
}}
onSubmit={handleFinish}
>
{({ handleChange, handleBlur, handleSubmit, values }) => (
<View style={localStyles.topTimeTicketContainer}>
<JobIdSearchSelect
currentValue={currentSJobId}
onJobSelected={setCurrentSJobId}
convertedOnly={!currentBodyshop.tt_allow_post_to_invoiced}
notExported={!currentBodyshop.tt_allow_post_to_invoiced}
/>
{/* Below will be replaced with a Date Picker*/}
{/* <TextInput style={localStyles.input} mode="flat" onChangeText={handleChange("ticketdate")} onBlur={handleBlur("ticketdate")} value={values.ticketdate} label={"Ticket Date"} /> */}
<Button
mode="outlined"
title="TicketDatePickerButton"
onPress={showDatePicker}
style={localStyles.dateButton}
>
<Text style={localStyles.textForButton}>
Ticket Date: {date2.toLocaleDateString()}
</Text>
</Button>
<DateTimePickerModal
isVisible={isDatePickerVisible}
mode="date"
date={date2}
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
{/* Below will set to auto fill with current employee */}
<TextInput
style={localStyles.inputStyle}
mode="outlined"
disabled={true}
onChangeText={handleChange("employee")}
onBlur={handleBlur("employee")}
value={values.employee}
label={"Employee"}
/>
<CostCenterSelect
currentRatesNCostCenters={currentRatesNCostCenters}
currentValue={currentSCC}
onValueSelected={setCurrentSCC}
/>
<TextInput
style={localStyles.inputStyle}
mode="outlined"
onChangeText={handleChange("productivehours")}
onBlur={handleBlur("productivehours")}
value={values.productivehours}
label={"Productive Hours"}
/>
<TextInput
style={localStyles.inputStyle}
mode="outlined"
onChangeText={handleChange("actualhours")}
onBlur={handleBlur("actualhours")}
value={values.actualhours}
label={"Actual Hours"}
/>
<Button
style={localStyles.input}
onPress={handleSubmit}
title="Submit"
>
<Text style={{ fontSize: 12 }}>Create Ticket</Text>
</Button>
{error ? <ErrorDisplay errorMessage={error.message} /> : null}
</View>
)}
</Formik>
{/* Below is for list of jobs/tickets */}
</ScrollView>
<View style={{ flexGrow: 1 }}>
<LaborAllocationsTable jobId={currentSJobId?.value} />
</View>
</View>
);
}
export default connect(mapStateToProps, null)(TimeTicketCreate);
const localStyles = StyleSheet.create({
content: {
display: "flex",
flex: 1,
},
topContainer: {},
bottomContainer: {},
input: {},
dateButton: {
marginVertical: 4,
marginHorizontal: 16,
height: 48,
justifyContent: "center",
alignContent: "center",
borderColor: "blue",
borderWidth: 0.8,
flex: 1,
},
textForButton: {
flex: 1,
justifyContent: "center",
alignContent: "center",
},
inputStyle: {
marginVertical: 4,
marginHorizontal: 16,
height: 48,
fontSize: 16,
},
});