Closed Naveenkumar-1411 closed 1 month ago
import React, { useEffect, useState, useMemo, useRef } from "react"; import { SafeAreaView, Text, View, TouchableOpacity, Modal, StyleSheet, TextInput, Pressable, FlatList, Platform, Image, Linking, } from "react-native"; import styles from "../../../../../../css/Styles"; import FontAwesomeIcon from "react-native-vector-icons/FontAwesome"; import Entypo from "react-native-vector-icons/Entypo"; import { useNavigation } from "@react-navigation/native"; import BASE_URL from "../../../../../../utils/Api"; import RecordCollectionStyle from "../../../../../collection/collections/recordcollection/RecordCollectionStyle"; import RecordDepositStyle from "../../../../../collection/deosit/RecordDeposit/RecordDepositStyle"; import UserProfileStyle from "../../../profile/UserProfileStyle"; import axios from "axios"; import tw from "tailwind-react-native-classnames"; import { ScrollView } from "react-native-gesture-handler"; import as ImagePicker from "expo-image-picker"; import { CheckBox } from "react-native-elements"; import Buttons from "../../../../../../components/Buttons"; import FormData from "form-data"; import Header3 from "../../../../../../components/Header3"; import AttendanceStyle from "../AttendanceStyle"; import DealerAddStyle from "../../../../../sales/dealer/dealer_add/DealerAddStyle"; import { Octicons, Ionicons } from "@expo/vector-icons"; import { setBeat } from "../../../../../../redux/beat/BeatSlice"; import { Alert } from "react-native"; import Constants from "expo-constants"; import as Application from "expo-application"; import { setUser } from "../../../../../../redux/user/UserSlice"; import { useDispatch, useSelector } from "react-redux"; // import as Location from "expo-location"; // import as Battery from 'expo-battery'; //import { startLocationTracking } from "../../backgroundtask"; import BackgroundGeolocation from "react-native-background-geolocation"; const AttendanceStart = () => { const dispatch = useDispatch(); const navigation = useNavigation(); const loginUser = useSelector((state) => state.user.user); const [kilometer, setKiloMeter] = useState(""); const [startDt, setStartDt] = useState(""); const userBeat = useSelector((state) => state.beat.beat); const [selectedImage, setSelectedImage] = useState(null); const [areaName, setAreaName] = useState(""); const [beatId, setBeatId] = useState(0); const [beatStatus, setBeatStatus] = useState(""); const userData = useSelector((state) => state.user.user); const [loading, setLoading] = useState(false); const [beatData, setBeatData] = useState(null); const [beatLength, setBeatLength] = useState(0); const [location, setLocation] = useState(null); const [errorMsg, setErrorMsg] = useState(null); const [locationSubscription, setLocationSubscription] = useState(null); const getCurrentDate = () => { const currentDate = new Date();
const date = currentDate.getDate();
const month = currentDate.getMonth() + 1;
const year = currentDate.getFullYear();
let currentHour = currentDate.getHours();
const currentMinutes = currentDate.getMinutes();
const currentSeconds = currentDate.getSeconds();
const ampm = currentHour >= 12 ? "PM" : "AM";
currentHour = currentHour % 12;
currentHour = currentHour ? currentHour : 12; // the hour '0' should be '12'
const paddedHour = currentHour < 10 ? `0${currentHour}` : currentHour;
const paddedMinutes =
currentMinutes < 10 ? `0${currentMinutes}` : currentMinutes;
const paddedSeconds =
currentSeconds < 10 ? `0${currentSeconds}` : currentSeconds;
const submitStartAt = `${year}/${month}/${date} ${paddedHour}:${paddedMinutes}:${paddedSeconds}`;
return {
date,
month,
year,
submitStartAt,
hour: paddedHour,
minutes: paddedMinutes,
seconds: paddedSeconds,
ampm,
};
};
const updateLoginUser = async () => {
try {
const response = await axios.post(${BASE_URL}/user/authorise
, {
auth_key: ${loginUser.auth_key}
,
unique_id: Constants.platform.android
? Application.getAndroidId()
: Application.installationId,
});
dispatch(setUser(response.data));
if (response.data) {
if (beatLength > 0) {
navigation.navigate("MyBeatDealerList", {
areaname: areaName,
beatid: beatId,
});
} else {
navigation.navigate("Dashboard");
}
}
} catch (error) {
console.log("error in updateLoginUser : " + error);
}
};
const fetchData = async () => {
try {
setLoading(true);
const endpoint = ${BASE_URL}/mybeats?action=today-beat&expand=mybeatDealers,areagroup,mybeatDealers.mybeatLists,mybeatDealers.dealer
;
const headers = {
Authorization: Bearer ${userData?.auth_key}
,
Cookie: "_csrf=AEkKVq4-6Virf2Se2PRCsxP0RP2YYTWr",
};
const response = await axios.get(endpoint, { headers });
if (response.data) {
setBeat(response.data);
setLoading(false);
setBeatData(response.data);
const areaName = response.data?.areagroup?.name || "-";
setBeatId(response.data?.id || 0);
setAreaName(areaName);
setBeatStatus(response.data?.status || "");
setBeatLength(response?.data?.mybeatDealers?.length || 0);
} else {
setAreaName("-");
}
// console.log(response.data,"Mybeat");
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
useEffect(() => { const result = getCurrentDate(); setStartDt(result.submitStartAt); }, []);
const startDay = async () => {
if (!selectedImage) {
Alert.alert("Image Required", "Please select or capture an image.");
return false;
}
//await startLocationTracking();
const payload = {
location: "",
start_dt: startDt,
AttendanceValue: [
{
name: "Start Km",
value: kilometer,
},
{
name: "Start Fuel",
value: "",
},
],
AttendanceTime: [
{
event: "DAYSTART",
geo: "",
source: "MOBILE",
},
],
};
console.log(JSON.stringify(payload) + " = payload in attendance ");
try {
const response = await axios.post(${BASE_URL}/attendances
, payload, {
headers: {
Authorization: Bearer ${loginUser.auth_key}
,
},
});
if (response.data) {
uploadMedia(response.data.id);
startLocationTracking();
} else {
alert("Error occurred");
}
} catch (error) {
console.error("Error starting day:", error);
alert("Error occurred while starting the day");
}
};
const startLocationTracking = () => {
BackgroundGeolocation.ready({
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
distanceFilter: 10,
debug: false, // Disable this in production
logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
stopOnTerminate: false,
startOnBoot: true,
locationUpdateInterval: 5000,
url: ${BASE_URL}/location/track
,
batchSync: false,
autoSync: true,
headers: {
Authorization: Bearer ${loginUser.auth_key}
,
},
params: {
device_uuid: Constants.platform.android
? Application.getAndroidId()
: Application.installationId,
employee_id: loginUser.profile.id,
},
})
.then((state) => {
if (!state.enabled) {
BackgroundGeolocation.start();
console.log("BackgroundGeolocation started successfully");
}
})
.catch((error) => {
console.error("BackgroundGeolocation error: ", error);
});
};
const uploadMedia = async (id) => { try { if (!selectedImage) { console.warn("No image selected"); return; }
const formData = new FormData();
const fileName = `StartAttendance_${id}_${Date.now()}.jpeg`;
formData.append("path", {
// uri: selectedImage,
uri:
Platform.OS === "android"
? selectedImage
: selectedImage.replace("file://", ""),
type: "image/jpeg",
name: selectedImage.split("/").pop(),
// name: "selectedImage3.jpeg",
});
// console.log(selectedImage, "Hello");
formData.append("module", "attendance");
formData.append("module_id", id);
formData.append("title", "Start Attendance");
// console.log("formData =", JSON.stringify(formData));
const response = await axios.post(`${BASE_URL}/media`, formData, {
headers: {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${loginUser.auth_key}`,
},
transformRequest: () => {
return formData;
},
});
if (response.data) {
// navigation.navigate("MyBeatDealerList", {
// areaname: userBeat?.areag0roup?.name,
// beatid: userBeat?.id,
// });
updateLoginUser();
// if(beatLength>0){
// navigation.navigate("MyBeatDealerList", {
// areaname: areaName,
// beatid: beatId,
// });
// }else{
// navigation.navigate("Dashboard");
// }
} else {
alert("Error occurred");
}
} catch (error) {
if (axios.isAxiosError(error) && error.response) {
console.error(
"Server responded with status code:",
error.response.status
);
console.log("Error response data:", error.response.data);
alert("An error occurred. Please check server logs for details.");
} else {
console.error("Error in uploadMedia:", error);
alert("An error occurred. Please try again.");
}
}
};
useEffect(() => { // Request permission to access the camera and gallery (async () => { const { status } = await ImagePicker.requestCameraPermissionsAsync(); if (status !== "granted") { Alert.alert( "Permission denied", "Sorry, we need camera and gallery permissions to make this work!" ); } })(); }, []); const pickImage = async (fromCamera) => { let result;
if (fromCamera) {
result = await ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [10, 9],
quality: 0.5,
});
} else {
result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: false,
aspect: [10, 9],
quality: 1,
});
}
if (!result.canceled) {
// Access selected assets through the "assets" array
const selectedAsset = result.assets[0];
// console.log(selectedAsset.uri);
setSelectedImage(selectedAsset.uri);
}
}; return ( <SafeAreaView style={[ Platform.OS === "android" && [AttendanceStyle.androidPlatform], styles.bgPrimary, ]}
<Header3 title="Attendance" onBackPress={() => navigation.navigate("Attendance")} onSubmit={() => startDay()} buttons={["StartDay"]} /> <View style={[styles.itemsCenter, styles.marginVerticalTen]}>
Hi {loginUser.user && loginUser.user.name}, Have a Nice Day! <View style={[ AttendanceStyle.roundedContainer, AttendanceStyle.marginHorizontal, ]}
<Text style={[styles.textSecondary, styles.textXl, styles.fontWeightBold]}
{getCurrentDate().hour}:{getCurrentDate().minutes}{" "} {getCurrentDate().ampm}
Dubai, {getCurrentDate().date}/{getCurrentDate().month}/ {getCurrentDate().year}
<View style={[ styles.bgTertiry, styles.paddingVerticalFour, styles.paddingHorizontal,
DealerAddStyle.mainBox,
]}
>
<View style={[styles.flexColumn]}>
<Text
style={[
styles.h4,
styles.textSecondary,
styles.paddingVertical,
styles.fontWeightSemiBold,
]}
>
Document Information
</Text>
<View style={[styles.flexRow, styles.justifyAround]}>
<TouchableOpacity
style={[
styles.flexRow,
styles.borderColorSecondary,
styles.paddingVerticalFour,
RecordDepositStyle.button,
]}
onPress={() => pickImage(true)}
>
<FontAwesomeIcon
name="camera"
size={30}
color="#7A6CE7"
style={[styles.marginHorizontalAuto]}
/>
<Text
style={[
styles.h4,
styles.textSecondary,
styles.marginHorizontalAuto,
styles.marginVerticalAuto,
styles.paddingLeftTwo,
styles.checkCenter,
]}
>
Camera
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[
styles.flexRow,
styles.borderColorSecondary,
styles.paddingVerticalFour,
RecordDepositStyle.button,
]}
onPress={() => pickImage(false)}
>
<FontAwesomeIcon
name="photo"
size={30}
color="#7A6CE7"
style={[styles.marginHorizontalAuto]}
/>
<Text
style={[
styles.h4,
styles.textSecondary,
styles.marginHorizontalAuto,
styles.marginVerticalAuto,
styles.paddingLeftTwo,
styles.checkCenter,
]}
>
Gallery
</Text>
</TouchableOpacity>
</View>
<Text
style={[styles.textCenter, styles.paddingVertical, styles.textGray]}
>
Upload file size less than 2MB.. ***
</Text>
{selectedImage && (
<Image source={{ uri: selectedImage }} style={sample.image} />
)}
</View>
</View>
</SafeAreaView>
); }; const sample = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center", }, title: { fontSize: 24, marginBottom: 20, }, image: { width: 275, height: 250, resizeMode: "cover", marginBottom: 20, }, button: { backgroundColor: "blue", padding: 10, margin: 10, borderRadius: 5, }, buttonText: { color: "white", fontSize: 16, }, });
export default AttendanceStart; here is my full code
The issue template, that text you see in the textarea when you open an issue, is asking you questions you’re supposed to provide info for.
const startLocationTracking = () => { BackgroundGeolocation.ready({ desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, distanceFilter: 10, debug: false, // Disable this in production logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE, stopOnTerminate: false, startOnBoot: true, locationUpdateInterval: 5000, url:
${BASE_URL}/location/track
, batchSync: false, autoSync: true, headers: { Authorization:Bearer ${loginUser.auth_key}
, }, params: { device_uuid: Constants.platform.android ? Application.getAndroidId() : Application.installationId, employee_id: loginUser.profile.id, }, }) .then((state) => { if (!state.enabled) { BackgroundGeolocation.start(); console.log("BackgroundGeolocation started successfully"); } }) .catch((error) => { console.error("BackgroundGeolocation error: ", error); }); };