Browse Source

update draft

master
Choirul Fajri 1 year ago
parent
commit
d2083ffb2e
  1. 16
      App.tsx
  2. 7
      src/component/collectLinescreen.tsx
  3. 6
      src/component/collectPolygonscreen.tsx
  4. 6
      src/component/collectscreen.tsx
  5. 5
      src/component/draftPDAM.tsx
  6. 2
      src/component/draftPJU.tsx
  7. 4
      src/component/draftPermit.tsx
  8. 33
      src/component/editLinescreen.tsx
  9. 141
      src/component/resendPDAM.tsx
  10. 20
      src/component/resendPJU.tsx
  11. 806
      src/component/resendPermit.tsx

16
App.tsx

@ -48,6 +48,7 @@ import MyAccount from './src/component/myAccount';
import ChangePass from './src/component/changePassword'; import ChangePass from './src/component/changePassword';
import ResendPJU from './src/component/resendPJU'; import ResendPJU from './src/component/resendPJU';
import ResendPDAM from './src/component/resendPDAM'; import ResendPDAM from './src/component/resendPDAM';
import ResendLandPermit from './src/component/resendPermit';
import { USER_API_URL } from "../SurveyApp/urlConfig"; import { USER_API_URL } from "../SurveyApp/urlConfig";
import { PermissionsAndroid } from 'react-native'; import { PermissionsAndroid } from 'react-native';
@ -551,7 +552,7 @@ export const Nav = () => {
fontSize:20 fontSize:20
} }
}}/> }}/>
<Stack.Screen name="Resend PJU" component={ResendPJU} <Stack.Screen name="Resend Survey PJU" component={ResendPJU}
options={{ options={{
headerStyle: { headerStyle: {
backgroundColor: '#34A6F8', backgroundColor: '#34A6F8',
@ -562,7 +563,18 @@ export const Nav = () => {
fontSize:20 fontSize:20
} }
}}/> }}/>
<Stack.Screen name="Resend PDAM" component={ResendPDAM} <Stack.Screen name="Resend Survey Pipa PDAM" component={ResendPDAM}
options={{
headerStyle: {
backgroundColor: '#34A6F8',
},
headerTintColor: '#FFFFFF',
headerShadowVisible: false,
headerTitleStyle: {
fontSize:20
}
}}/>
<Stack.Screen name="Resend Survey Land Permit" component={ResendLandPermit}
options={{ options={{
headerStyle: { headerStyle: {
backgroundColor: '#34A6F8', backgroundColor: '#34A6F8',

7
src/component/collectLinescreen.tsx

@ -252,6 +252,9 @@ export default function CollectLineScreen({route,navigation}:collectLineScreenPr
} }
}; };
storeData() storeData()
setAlertOnline(false);
Alert.alert("Success")
navigation.navigate('Survey Pipa PDAM', { screen: 'Survey Pipa PDAM'})
} }
}) })
} catch (error) { } catch (error) {
@ -283,9 +286,7 @@ export default function CollectLineScreen({route,navigation}:collectLineScreenPr
}, },
JSON.stringify({pdam_id:json[0].id, file:file.file, mimetype:file.file_type, size:file.fileSize}) JSON.stringify({pdam_id:json[0].id, file:file.file, mimetype:file.file_type, size:file.fileSize})
).then(async (resp) => { ).then(async (resp) => {
Alert.alert("Success")
navigation.navigate('Survey Pipa PDAM', { screen: 'Survey Pipa PDAM'})
setAlertOnline(false);
} }
) )
}); });

6
src/component/collectPolygonscreen.tsx

@ -242,6 +242,9 @@ export default function CollectPolygonScreen({route,navigation}:collectPolygonSc
} }
}; };
storeData() storeData()
setAlertOnline(false);
Alert.alert("Success")
navigation.navigate('Survey Land Permit', { screen: 'Survey Land Permit'})
} }
}) })
} catch (error) { } catch (error) {
@ -273,9 +276,6 @@ export default function CollectPolygonScreen({route,navigation}:collectPolygonSc
}, },
JSON.stringify({permit_id:json[0].id, file:file.file, mimetype:file.file_type, size:file.fileSize}) JSON.stringify({permit_id:json[0].id, file:file.file, mimetype:file.file_type, size:file.fileSize})
).then(async (resp) => { ).then(async (resp) => {
Alert.alert("Success")
navigation.navigate('Survey Land Permit', { screen: 'Survey Land Permit'})
setAlertOnline(false);
} }
) )
}); });

6
src/component/collectscreen.tsx

@ -265,6 +265,9 @@ function CollectScreen({route,navigation}: collectScreenProps) {
} }
}; };
storeData() storeData()
setAlertOnline(false);
Alert.alert("Success")
navigation.navigate('Survey Penerangan Jalan Umum', { screen: 'Survey Penerangan Jalan Umum'})
} }
}) })
} catch (error) { } catch (error) {
@ -327,9 +330,6 @@ function CollectScreen({route,navigation}: collectScreenProps) {
mimetype:file.file_type, mimetype:file.file_type,
size:file.fileSize}) size:file.fileSize})
).then(async (resp) => { ).then(async (resp) => {
Alert.alert("Success")
setAlertOnline(false);
navigation.navigate('Survey Penerangan Jalan Umum', { screen: 'Survey Penerangan Jalan Umum'})
} }
) )
}); });

5
src/component/draftPDAM.tsx

@ -133,7 +133,7 @@ function DraftPDAM({route,navigation}: sendListDataProps) {
setLocalStorage([]) setLocalStorage([])
try { try {
const jsonValue = await AsyncStorage.getAllKeys() const jsonValue = await AsyncStorage.getAllKeys()
// console.log("All Key",jsonValue.length) // console.log("All Key",jsonValue)
if(jsonValue.length != 0) { if(jsonValue.length != 0) {
jsonValue.map((item) => { jsonValue.map((item) => {
if(item != "USER_DATA" && item != "my-jwt"){ if(item != "USER_DATA" && item != "my-jwt"){
@ -402,11 +402,12 @@ function DraftPDAM({route,navigation}: sendListDataProps) {
<MenuOptions customStyles={optionsStyles}> <MenuOptions customStyles={optionsStyles}>
<MenuOption <MenuOption
onSelect={()=>{ onSelect={()=>{
navigation.navigate('Resend PDAM',{ screen: 'Resend PDAM',data: { navigation.navigate('Resend Survey Pipa PDAM',{ screen: 'Resend Survey Pipa PDAM',data: {
nama:item.pipe_name, nama:item.pipe_name,
jenis:item.pipe_type, jenis:item.pipe_type,
tanggal_installasi:item.installation_date, tanggal_installasi:item.installation_date,
status:item.status, status:item.status,
keterangan:item.keterangan,
geom:item.geom geom:item.geom
}}); }});
}} }}

2
src/component/draftPJU.tsx

@ -405,7 +405,7 @@ function DraftPJU({route,navigation}: sendListDataProps) {
<MenuOptions customStyles={optionsStyles}> <MenuOptions customStyles={optionsStyles}>
<MenuOption <MenuOption
onSelect={()=>{ onSelect={()=>{
navigation.navigate('Resend PJU',{ screen: 'Resend PJU',data: { navigation.navigate('Resend Survey PJU',{ screen: 'Resend Survey PJU',data: {
nama:item.pju_name, nama:item.pju_name,
jenis:item.pju_type, jenis:item.pju_type,
tanggal_installasi:item.installation_date, tanggal_installasi:item.installation_date,

4
src/component/draftPermit.tsx

@ -409,11 +409,11 @@ function DraftPermit({route,navigation}: sendListDataProps) {
<MenuOptions customStyles={optionsStyles}> <MenuOptions customStyles={optionsStyles}>
<MenuOption <MenuOption
onSelect={()=>{ onSelect={()=>{
navigation.navigate('Permit Editing',{ screen: 'Edit',data: { navigation.navigate('Resend Survey Land Permit',{ screen: 'Resend Survey Land Permit',data: {
id:item.id,
company_name:item.company_name, company_name:item.company_name,
permit_status:item.permit_status, permit_status:item.permit_status,
location:item.location, location:item.location,
geom:item.geom
}}); }});
}} }}
children={ children={

33
src/component/editLinescreen.tsx

@ -121,6 +121,8 @@ export default function EditLineScreen({route,navigation}:collectLineScreenProps
return [Number(item.long),Number(item.lat)] return [Number(item.long),Number(item.lat)]
}) })
let centCord = turfcenter(points(arr)); let centCord = turfcenter(points(arr));
console.log(coordinates);
console.log("center pertama",centCord.geometry.coordinates); console.log("center pertama",centCord.geometry.coordinates);
setCenterCoords(centCord.geometry.coordinates); setCenterCoords(centCord.geometry.coordinates);
setLoadGeom(false); setLoadGeom(false);
@ -334,38 +336,7 @@ export default function EditLineScreen({route,navigation}:collectLineScreenProps
} catch (error) { } catch (error) {
} }
// const geom = coordinates.map((item:any)=>{
// return String(item).replace(',',' ')
// })
// // console.log("geom",geom);
// const obj = {
// nama: pipeName,
// jenis: selectedPipeType,
// tanggal_installasi: momentDate,
// status: checkedStatus,
// keterangan: Information,
// geom: `MULTILINESTRING((${geom}))`,
// id:data.id
// }
// console.log(obj);
// let result = await fetch(`${PDAM_API_URL}/updateData`, {
// method: "POST",
// headers: {
// "Content-Type": "application/json"
// },
// body: JSON.stringify(obj)
// })
// // const json = await result.json();
// const status = result.status
// if (status == 201) {
// insertAttachment(files)
// }
// else {
// Alert.alert("Internal Server Error")
// }
}; };
const collectDataOffline = () => { const collectDataOffline = () => {
setAlertOnline(false); setAlertOnline(false);

141
src/component/resendPDAM.tsx

@ -15,6 +15,7 @@ import turfcenter from '@turf/center';
const {points,polygon,lineString} = require('@turf/helpers'); const {points,polygon,lineString} = require('@turf/helpers');
import RNFetchBlob from 'rn-fetch-blob'; import RNFetchBlob from 'rn-fetch-blob';
import Modal from "react-native-modal"; import Modal from "react-native-modal";
import AsyncStorage from '@react-native-async-storage/async-storage';
@ -27,6 +28,8 @@ type collectLineScreenProps = {route: any,navigation: any};
export default function ResendPDAM({route,navigation}:collectLineScreenProps) { export default function ResendPDAM({route,navigation}:collectLineScreenProps) {
// console.log("route",route.params); // console.log("route",route.params);
const {data,coors} = route.params; const {data,coors} = route.params;
console.log(data);
const apiKey = "JoJs2pcDv5o0yQlQLMfI"; const apiKey = "JoJs2pcDv5o0yQlQLMfI";
const [basemap, setBasemap] = useState("streets-v2"); const [basemap, setBasemap] = useState("streets-v2");
const styleURL = `https://api.maptiler.com/maps/${basemap}/style.json?key=${apiKey}`; const styleURL = `https://api.maptiler.com/maps/${basemap}/style.json?key=${apiKey}`;
@ -60,17 +63,25 @@ export default function ResendPDAM({route,navigation}:collectLineScreenProps) {
const isFocused = useIsFocused(); const isFocused = useIsFocused();
const [centerCoords,setCenterCoords] = useState<number[]>([]); const [centerCoords,setCenterCoords] = useState<number[]>([]);
const [ModalAttachment, setModalAttachment] = useState(false); const [ModalAttachment, setModalAttachment] = useState(false);
const [userID,setUserID] = useState();
useEffect(()=>{ useEffect(()=>{
if (isFocused) { if (isFocused) {
console.log(data); const getKey = async () =>{
const jsonValue = await AsyncStorage.getItem('USER_DATA')
console.log(JSON.parse(jsonValue!));
const data = JSON.parse(jsonValue!);
console.log("user_data",data.id);
setUserID(data.id)
};
getKey();
if (coors === undefined) { if (coors === undefined) {
getData() getData()
fetchData() // fetchData()
} }
else{ else{
console.log("kedua",coors); // console.log("kedua",coors);
let centCord = turfcenter(points(coors)); let centCord = turfcenter(points(coors));
console.log("center kedua",centCord); // console.log("center kedua",centCord);
setCenterCoords(centCord.geometry.coordinates); setCenterCoords(centCord.geometry.coordinates);
setLoadGeom(false); setLoadGeom(false);
setCoordinates(coors) setCoordinates(coors)
@ -108,24 +119,36 @@ export default function ResendPDAM({route,navigation}:collectLineScreenProps) {
},[isFocused]) },[isFocused])
const getData = async () => { const getData = async () => {
try { try {
const url = `${PDAM_API_URL}/${route.params.data.id}`; const arr = data.geom.map((item:any)=> {
await RNFetchBlob.config({ // console.log("item",item);
trusty : true const str = item.split(" ");
}).fetch('GET', url setCoordinates(oldArray => [...oldArray,[Number(str[0]),Number(str[1])]])
).then(async (resp) => { // console.log("a",typeof(item));
const json = resp.json(); // console.log("b",str[0]);
const arr = json.map((item:any)=>{ return [Number(str[0]),Number(str[1])]
// console.log(item.long); });
let centCord = turfcenter(points(arr));
// console.log("center pertama",centCord.geometry.coordinates);
setCenterCoords(centCord.geometry.coordinates);
setLoadGeom(false);
// const url = `${PDAM_API_URL}/${route.params.data.id}`;
// await RNFetchBlob.config({
// trusty : true
// }).fetch('GET', url
// ).then(async (resp) => {
// const json = resp.json();
// const arr = json.map((item:any)=>{
// // console.log(item.long);
setCoordinates(oldArray => [...oldArray,[Number(item.long),Number(item.lat)]]) // setCoordinates(oldArray => [...oldArray,[Number(item.long),Number(item.lat)]])
return [Number(item.long),Number(item.lat)] // return [Number(item.long),Number(item.lat)]
}) // })
let centCord = turfcenter(points(arr)); // let centCord = turfcenter(points(arr));
console.log("center pertama",centCord.geometry.coordinates); // console.log("center pertama",centCord.geometry.coordinates);
setCenterCoords(centCord.geometry.coordinates); // setCenterCoords(centCord.geometry.coordinates);
setLoadGeom(false); // setLoadGeom(false);
} // }
) // )
} catch (e) { } catch (e) {
console.log("error",e); console.log("error",e);
@ -276,7 +299,7 @@ export default function ResendPDAM({route,navigation}:collectLineScreenProps) {
const handleCancelAlertOffline = () => { const handleCancelAlertOffline = () => {
setAlertOffline(false); setAlertOffline(false);
}; };
const insertAttachment = (files: any) => { const insertAttachment = (json:any,files: any) => {
try { try {
files.forEach(async function(file:any) { files.forEach(async function(file:any) {
const url = `${PDAM_API_URL}/addAttachment`; const url = `${PDAM_API_URL}/addAttachment`;
@ -285,7 +308,7 @@ export default function ResendPDAM({route,navigation}:collectLineScreenProps) {
}).fetch('POST', url,{ }).fetch('POST', url,{
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
JSON.stringify({pdam_id:data.id, file:file.file, mimetype:file.file_type, size:file.fileSize}) JSON.stringify({pdam_id:json[0].id, file:file.file, mimetype:file.file_type, size:file.fileSize})
).then(async (resp) => { ).then(async (resp) => {
} }
@ -297,6 +320,16 @@ export default function ResendPDAM({route,navigation}:collectLineScreenProps) {
}; };
const collectDataOnline = async () => { const collectDataOnline = async () => {
try { try {
let date = new Date();
const milliseconds = Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
);
const localTime = new Date(milliseconds);
const geom = coordinates.map((item:any)=>{ const geom = coordinates.map((item:any)=>{
return String(item).replace(',',' ') return String(item).replace(',',' ')
}); });
@ -307,9 +340,10 @@ export default function ResendPDAM({route,navigation}:collectLineScreenProps) {
status: checkedStatus, status: checkedStatus,
keterangan: Information, keterangan: Information,
geom: `MULTILINESTRING((${geom}))`, geom: `MULTILINESTRING((${geom}))`,
id:data.id created_by: userID,
created_at:localTime
}; };
const url = `${PDAM_API_URL}/updateData`; const url = `${PDAM_API_URL}/addData`;
await RNFetchBlob.config({ await RNFetchBlob.config({
trusty : true trusty : true
}).fetch('POST', url,{ }).fetch('POST', url,{
@ -317,12 +351,14 @@ export default function ResendPDAM({route,navigation}:collectLineScreenProps) {
}, },
JSON.stringify(obj) JSON.stringify(obj)
).then(async (resp) => { ).then(async (resp) => {
const json = resp.json()
const status = resp.respInfo.status const status = resp.respInfo.status
if (status == 201) { if (status == 201) {
insertAttachment(files) insertAttachment(json,files)
Alert.alert("Success") Alert.alert("Success")
setAlertOnline(false); setAlertOnline(false);
navigation.navigate('Inbox Pipa PDAM', { screen: 'Inbox Pipa PDAM'}) removeValue(data.nama+" / "+data.jenis+" / "+data.tanggal_installasi+" / "+data.status+" / "+data.keterangan+" / "+data.geom+" / draftPDAM");
navigation.navigate('Draft Pipa PDAM', { screen: 'Draft Pipa PDAM'})
} }
else { else {
Alert.alert("Internal Server Error") Alert.alert("Internal Server Error")
@ -330,42 +366,17 @@ export default function ResendPDAM({route,navigation}:collectLineScreenProps) {
} }
) )
} catch (error) { } catch (error) {
} }
// const geom = coordinates.map((item:any)=>{ };
// return String(item).replace(',',' ') const removeValue = async (key:string) => {
// }) try {
// // console.log("geom",geom); // console.log("keyDelete",key);
await AsyncStorage.removeItem(key)
// const obj = { // await getCount();
// nama: pipeName, } catch(e) {
// jenis: selectedPipeType, }
// tanggal_installasi: momentDate,
// status: checkedStatus,
// keterangan: Information,
// geom: `MULTILINESTRING((${geom}))`,
// id:data.id
// }
// console.log(obj);
// let result = await fetch(`${PDAM_API_URL}/updateData`, {
// method: "POST",
// headers: {
// "Content-Type": "application/json"
// },
// body: JSON.stringify(obj)
// })
// // const json = await result.json();
// const status = result.status
// if (status == 201) {
// insertAttachment(files)
// }
// else {
// Alert.alert("Internal Server Error")
// }
}; };
const collectDataOffline = () => { const collectDataOffline = () => {
setAlertOnline(false); setAlertOnline(false);
@ -412,7 +423,7 @@ export default function ResendPDAM({route,navigation}:collectLineScreenProps) {
"properties": {}, "properties": {},
"geometry": { "geometry": {
"type": "LineString", "type": "LineString",
"coordinates": [data.geom] "coordinates": coordinates
} }
} }
] ]
@ -633,21 +644,21 @@ export default function ResendPDAM({route,navigation}:collectLineScreenProps) {
/> />
</ScrollView> </ScrollView>
<TouchableOpacity style={{width:'100%',height:50,backgroundColor:'#34A6F8',alignItems:'center',justifyContent:'center'}} onPress={showDialog}> <TouchableOpacity style={{width:'100%',height:50,backgroundColor:'#34A6F8',alignItems:'center',justifyContent:'center'}} onPress={showDialog}>
<Text style={{fontSize:18,fontWeight:'bold',color:'#FFFFFF'}}>UPDATE</Text> <Text style={{fontSize:18,fontWeight:'bold',color:'#FFFFFF'}}>RESEND</Text>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
{/* Online Mode Alert */} {/* Online Mode Alert */}
<AwesomeAlert <AwesomeAlert
show={alertOnline} show={alertOnline}
showProgress={false} showProgress={false}
title="Updating Data" title="Resend Data"
message="Are you sure for Updating PDAM data?" message="Are you sure for Add New PDAM data?"
closeOnTouchOutside={false} closeOnTouchOutside={false}
closeOnHardwareBackPress={false} closeOnHardwareBackPress={false}
showCancelButton={true} showCancelButton={true}
showConfirmButton={true} showConfirmButton={true}
cancelText="No, cancel" cancelText="No, cancel"
confirmText="Yes, Update it" confirmText="Yes, Add it"
confirmButtonColor="#137997" confirmButtonColor="#137997"
onCancelPressed={() => { onCancelPressed={() => {
handleCancelAlertOnline(); handleCancelAlertOnline();

20
src/component/resendPJU.tsx

@ -207,6 +207,7 @@ function ResendPJU({route,navigation}: editScreenProps) {
} }
},[isFocused]); },[isFocused]);
const fetchData = async () => { const fetchData = async () => {
try { try {
await RNFetchBlob.config({ await RNFetchBlob.config({
@ -256,9 +257,11 @@ function ResendPJU({route,navigation}: editScreenProps) {
created_at: localTime created_at: localTime
}) })
).then(async (resp) => { ).then(async (resp) => {
const json = resp.json()
const status = resp.respInfo.status const status = resp.respInfo.status
if (status == 201) { if (status == 201) {
insertAttachment(files) insertAttachment(json,files)
removeValue(data.nama+" / "+data.jenis+" / "+data.tanggal_installasi+" / "+data.status+" / "+data.keterangan+" / "+data.long+" / "+data.lat+" / draftPJU");
Alert.alert("Success") Alert.alert("Success")
setAlertOnline(false); setAlertOnline(false);
navigation.navigate('Draft Penerangan Jalan Umum', { screen: 'Draft Penerangan Jalan Umum'}) navigation.navigate('Draft Penerangan Jalan Umum', { screen: 'Draft Penerangan Jalan Umum'})
@ -281,13 +284,14 @@ function ResendPJU({route,navigation}: editScreenProps) {
// read error // read error
} }
} }
const removeValue = async () => { const removeValue = async (key:string) => {
try { try {
await AsyncStorage.removeItem('Test by mobile / Lampu 20 W / 2024-11-14 / Baik / draftJPU') // console.log("keyDelete",key);
await AsyncStorage.removeItem(key)
// await getCount();
} catch(e) { } catch(e) {
// remove error
} }
} };
const getAllKeys = async () => { const getAllKeys = async () => {
// let keys = [] // let keys = []
try { try {
@ -300,7 +304,7 @@ function ResendPJU({route,navigation}: editScreenProps) {
// example console.log result: // example console.log result:
// ['@MyApp_user', '@MyApp_key'] // ['@MyApp_user', '@MyApp_key']
} }
const insertAttachment = (files: any) => { const insertAttachment = (json:any,files: any) => {
try { try {
files.forEach(async function(file:any) { files.forEach(async function(file:any) {
const url = `${PJU_API_URL}/addAttachment`; const url = `${PJU_API_URL}/addAttachment`;
@ -309,7 +313,7 @@ function ResendPJU({route,navigation}: editScreenProps) {
}).fetch('POST', url,{ }).fetch('POST', url,{
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
JSON.stringify({pju_id:data.id, file:file.file, mimetype:file.file_type, size:file.fileSize}) JSON.stringify({pju_id:json[0].id, file:file.file, mimetype:file.file_type, size:file.fileSize})
).then(async (resp) => { ).then(async (resp) => {
const status = resp.respInfo.status const status = resp.respInfo.status
} }
@ -643,7 +647,7 @@ function ResendPJU({route,navigation}: editScreenProps) {
<AwesomeAlert <AwesomeAlert
show={alertOnline} show={alertOnline}
showProgress={false} showProgress={false}
title="Collecting Data" title="Resend Data"
message="Are you sure for Add New PJU data?" message="Are you sure for Add New PJU data?"
closeOnTouchOutside={false} closeOnTouchOutside={false}
closeOnHardwareBackPress={false} closeOnHardwareBackPress={false}

806
src/component/resendPermit.tsx

@ -0,0 +1,806 @@
import { useEffect, useRef, useState } from 'react';
import {View,Text, StyleSheet, ScrollView, TouchableOpacity, Image, Animated, TextInput, Button, Alert, Pressable, StatusBar, FlatList} from 'react-native';
import {useNavigation,NavigationContainer,useIsFocused} from '@react-navigation/native';
import MapLibreGL from '@maplibre/maplibre-react-native';
import { MapView,ShapeSource,Camera,UserLocation,PointAnnotation,FillLayer,LineLayer,VectorSource } from "@maplibre/maplibre-react-native";
import { SelectList } from 'react-native-dropdown-select-list';
import { RadioButton } from 'react-native-paper';
import DatePicker from 'react-native-date-picker';
import Moment from 'moment';
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
import NetInfo from "@react-native-community/netinfo";
import AwesomeAlert from 'react-native-awesome-alerts';
import AsyncStorage from '@react-native-async-storage/async-storage';
import turfcenter from '@turf/center';
const {points,polygon,lineString} = require('@turf/helpers');
import DocumentPicker from "react-native-document-picker";
import RNFS from 'react-native-fs';
import RNFetchBlob from 'rn-fetch-blob';
import { PERMIT_API_URL } from "../../urlConfig";
import React from 'react';
type EditPolygonScreenProps = {route: any,navigation: any};
export default function ResendLandPermit({route,navigation}:EditPolygonScreenProps) {
// console.log("route",route.params);
const {data,coors} = route.params;
// console.log("params",route.params);
const apiKey = "JoJs2pcDv5o0yQlQLMfI";
const [basemap, setBasemap] = useState("streets-v2");
const styleURL = `https://api.maptiler.com/maps/${basemap}/style.json?key=${apiKey}`;
const [centerCoords,setCenterCoords] = useState<number[]>([]);
const ref = useRef();
const [connected, setConnected] = useState(true);
const [currentIndex, setCurrentIndex] = useState(0);
const [imgUrl, setImgUrl] = useState([]);
const [files, setFiles] = useState([]);
const [fileDocument, setFileDocument] = useState([]);
const [companyName, setCompanyName] = useState(data.company_name);
const [checkedStatus, setCheckedStatus] = useState(data.permit_status);
const [approvedBy,setApprovedBy] = useState('');
const [location, setLocation] = useState(data.location);
const [open, setOpen] = useState(false);
const [install_date, setInstallDate] = useState(new Date());
const momentDate = Moment(install_date).format('YYYY-MM-DD');
const [alertOnline, setAlertOnline] = useState(false);
const [alertOffline, setAlertOffline] = useState(false);
const [companyNameError, setCompanyNameError] = useState(false);
const [permitStatusError, setPermitStatusError] = useState(false);
const [locationError, setLocationError] = useState(false);
const [coordinates,setCoordinates] = useState([]);
const [loadGeom,setLoadGeom] = useState(true);
const [delay,setDelay] = useState(false);
const [secondPress,setSecondPress] = useState(false);
const isFocused = useIsFocused();
const [userID,setUserID] = useState();
useEffect(()=>{
if (isFocused) {
const getKey = async () =>{
const jsonValue = await AsyncStorage.getItem('USER_DATA')
console.log(JSON.parse(jsonValue!));
const data = JSON.parse(jsonValue!);
console.log("user_data",data.id);
setUserID(data.id)
};
getKey();
if (coors === undefined) {
console.log("awal");
getData()
}
else{
console.log("kedua",coors);
let centCord = turfcenter(points(coors));
console.log("center kedua",centCord);
setCenterCoords(centCord.geometry.coordinates);
setLoadGeom(false);
setCoordinates(coors)
setSecondPress(true)
}
}
const unmount = navigation.addListener('beforeRemove', (e:any)=> {
console.log("Event",e);
if (e.data.action.type !== "NAVIGATE"){
e.preventDefault();
Alert.alert(
'Unsave Case',
'There are unsave case. Please chose what you want.',
[
{
text: 'Ok',
onPress: () => navigation.dispatch(e.data.action)
},
{
text: 'Continue',
style: 'cancel'
}
]
)
}
})
const unsubscribe = NetInfo.addEventListener((state) => {
setConnected(state.isConnected!)
});
return () => {
unmount();
unsubscribe();
};
},[isFocused])
const openCameraLib = async () => {
const result = await launchCamera({
mediaType: 'photo',
quality: 1,
includeBase64: true,
saveToPhotos: true
});
const newObj = {
file_type: result?.assets![0]?.type,
file: result?.assets![0]?.base64,
fileSize: result?.assets![0]?.fileSize,
}
setFiles([...files,newObj]);
setImgUrl([...imgUrl,result?.assets![0]?.base64]);
};
const openLib = async () => {
const result = await launchImageLibrary({
quality: 1,
mediaType: 'photo',
selectionLimit: 0,
includeExtra: true,
includeBase64: true
});
result?.assets?.forEach(asset => {
const newObj = {
file_type: asset.type,
file: asset.base64,
fileSize: asset.fileSize
}
setFiles(oldArray => [...oldArray,newObj]);
setImgUrl(oldArray => [...oldArray,asset.base64]);
});
};
const PrevImg = ({isIndex}) => {
if(isIndex===0){
return (
<TouchableOpacity disabled style={{width:'10%',alignSelf:'center'}}>
<Image source={require('../../assets/icon/left-arrow.png')} />
</TouchableOpacity>
)
}
return (
<TouchableOpacity style={{width:'10%',alignSelf:'center'}} onPress={()=> {
setCurrentIndex(currentIndex-1)
ref.current.scrollToIndex({
animated: true,
index: currentIndex-1
});
}}>
<Image source={require('../../assets/icon/left-arrow.png')} />
</TouchableOpacity>
)
};
const NextImg = ({isIndex}) => {
if(imgUrl.length<=1){
return (
<TouchableOpacity disabled style={{width:'10%',alignSelf:'center'}}>
<Image style={{alignSelf:'flex-end'}} source={require('../../assets/icon/right-arrow.png')} />
</TouchableOpacity>
)
}
else{
if (isIndex === (imgUrl.length-1)) {
return (
<TouchableOpacity disabled style={{width:'10%',alignSelf:'center'}}>
<Image style={{alignSelf:'flex-end'}} source={require('../../assets/icon/right-arrow.png')} />
</TouchableOpacity>
)
}
else{
return (
<TouchableOpacity style={{width:'10%',alignSelf:'center'}} onPress={()=> {
setCurrentIndex(currentIndex+1)
ref.current.scrollToIndex({
animated: true,
index: currentIndex+1
});
}}>
<Image style={{alignSelf:'flex-end'}} source={require('../../assets/icon/right-arrow.png')} />
</TouchableOpacity>
)
}
}
};
const showDialog = () => {
if(!companyName){
setCompanyNameError(true)
}else{
setCompanyNameError(false)
}
if(!checkedStatus){
setPermitStatusError(true)
}else{
setPermitStatusError(false)
}
if(!location){
setLocationError(true)
}else{
setLocationError(false)
}
if(!companyName || !checkedStatus || !location) {
return false
}
if(connected){
setAlertOnline(true);
}
else{
setAlertOffline(true)
}
};
const handleCancelAlertOnline = () => {
setAlertOnline(false);
};
const handleCancelAlertOffline = () => {
setAlertOffline(false);
};
const removeValue = async (key:string) => {
try {
// console.log("keyDelete",key);
await AsyncStorage.removeItem(key)
// await getCount();
} catch(e) {
}
};
const collectDataOnline = async () => {
try {
let date = new Date();
const milliseconds = Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
);
const localTime = new Date(milliseconds);
const geom = coordinates.map((item:any)=>{
return String(item).replace(',',' ')
})
const obj = {
company_name: companyName,
location: location,
permit_status: checkedStatus,
geom: "",
created_by:userID,
created_at:localTime
}
if(!secondPress){
obj.geom = `MULTIPOLYGON (((${geom},${String(geom[0]).replace(","," ")})))`
}
else{
obj.geom = `MULTIPOLYGON (((${geom},${String(coordinates[0]).replace(","," ")})))`
}
await RNFetchBlob.config({
trusty : true
}).fetch('POST',`${PERMIT_API_URL}/addData`,
{
"Content-Type": "application/json",
},
JSON.stringify(obj)
).then(async (resp) => {
const json = resp.json()
const status = resp.respInfo.status
if (status == 201) {
insertAttachment(json,files)
removeValue(data.company_name+" / "+data.permit_status+" / "+data.location+" / "+data.geom+" / draftPermit");
Alert.alert("Success")
setAlertOnline(false);
navigation.navigate('Draft Land Permit', { screen: 'Draft Land Permit'})
}
else {
Alert.alert("Internal Server Error")
}
})
} catch (error) {
Alert.alert('Internal Server Error')
}
};
const collectDataOffline = () => {
const geom = route.params.coordinates.map((item:any)=>{
return String(item).replace(',',' ')
})
const storeData = async () => {
try {
await AsyncStorage.setItem(companyName+" / "+checkedStatus+" / "+location+" / "+geom+" / draftPermit","Value");
} catch (e) {
}
};
storeData()
setAlertOffline(false);
navigation.navigate('Property Survey', { screen: 'Property Survey'})
};
const insertAttachment = async (json:any,files: any) => {
try {
files.forEach(async function(file:any){
const url = `${PERMIT_API_URL}/addAttachment`;
await RNFetchBlob.config({
trusty : true
}).fetch('POST',url,{
"Content-Type": "application/json",
},
JSON.stringify({permit_id:json[0].id, file:file.file, mimetype:file.file_type, size:file.fileSize})
).then(async(resp) => {
const status = resp.respInfo.status
})
});
} catch (error) {
}
}
const deleteByIndex = (index:number) => {
setFileDocument(oldValues => {
return oldValues.filter((_: any, i: number) => i !== index)
})
}
const uploadFileOnHandler = async () => {
try {
const pickedFile = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.pdf,DocumentPicker.types.doc,DocumentPicker.types.docx],
// allowMultiSelection:true
})
await RNFS.readFile(pickedFile.uri, 'base64').then(data => {
const newObj = {
file_type: pickedFile.type,
file: data,
fileSize: pickedFile.size
}
setFiles([...files,newObj]);
setFileDocument([...fileDocument,pickedFile]);
});
} catch (error) {
console.error(error)
}
};
const cek = () => {
console.log(coordinates);
};
const getData = async () => {
try {
const arr = data.geom.map((item:any)=> {
const str = item.split(" ");
setCoordinates(oldArray => [...oldArray,[Number(str[0]),Number(str[1])]])
return [Number(str[0]),Number(str[1])]
})
let centCord = turfcenter(points(arr));
console.log("center pertama",centCord.geometry.coordinates);
setCenterCoords(centCord.geometry.coordinates);
setLoadGeom(false);
} catch (e) {
console.log("error",e);
// error reading value
}
};
const renderItem = ({item,index}:any) => {
return (
<View style={{width:352,height:70,borderRadius:10,borderStyle:'dashed',borderWidth:2,borderCurve:'continuous',borderColor:'#434343',alignItems:'center',justifyContent:'center',flexDirection:'row',columnGap:5}}>
<Text style={{fontSize:20,color:'blue',fontWeight:'bold'}}>{item.name}</Text>
</View>
);
};
return (
<View style={styles.mainContainer}>
<StatusBar backgroundColor="#34A6F8" barStyle={'light-content'} />
<View key={"mainBackground"} style={{backgroundColor:'#34A6F8',width:'100%',height:'93%'}} />
<View key={"background"} style={{backgroundColor:'#FFFFFF',width:'100%',height:'100%',position:'absolute',borderTopRightRadius:50,borderTopLeftRadius:35,paddingTop:25}}>
<ScrollView
horizontal={false}
showsHorizontalScrollIndicator={false}
nestedScrollEnabled={true}
style={styles.container}>
<View style={{flexDirection:'column'}}>
<MapView
style={{width:352,height:200,borderWidth:1,borderColor:'#A6A6A6',overflow:'hidden',alignSelf:'center',borderTopRightRadius:10,borderTopLeftRadius:10}}
mapStyle={styleURL}
rotateEnabled={false}
zoomEnabled={false}
pitchEnabled={false}
scrollEnabled={false}
>
<Camera
centerCoordinate={centerCoords.length === 0 ? coordinates[0] : centerCoords}
zoomLevel={17}
minZoomLevel={5}
maxZoomLevel={20}
/>
{
!loadGeom ?
<>
<ShapeSource
id="polygon2"
shape={{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
coordinates
]
}
}
]
}}
>
<LineLayer
id="linelayer2"
style={{lineColor:'red',lineWidth:3}}
/>
<FillLayer
id="some-fill-feature2"
style={{
fillColor: ['interpolate', ['linear'], ['zoom'], 0, '#eeddbb', 2, '#0daa00', 3, '#bbbbee'],
fillOpacity:0.5
}}
/>
</ShapeSource>
</>
:
null
}
{
coordinates.map((item:any,index:number)=>(
<PointAnnotation
key={index}
id={String(index)}
coordinate={item}
draggable={false}
>
<View style={{ height: 75, width: 75 }}>
<View style={{width:15,height:15,backgroundColor:'red',borderColor:'black',borderRadius:50}} />
</View>
</PointAnnotation>
))
}
</MapView>
{!secondPress ?
<TouchableOpacity style={{alignSelf:'center',backgroundColor:'#F9F9F9',width:352,height:50,borderBottomLeftRadius:10,borderBottomRightRadius:10,justifyContent:'center',borderWidth:1,borderColor:'#A6A6A6'}}
onPress={()=>{
navigation.navigate('Map View Polygon', {
screen: 'Map View Polygon',
data: {
id:data.id,
company_name:companyName,
permit_status:checkedStatus,
location:location,
geom:coordinates
}
});
}}
>
<Text style={{alignSelf:'center',fontWeight:'semibold',fontSize:16,color:'#434343'}}>Change Location</Text>
</TouchableOpacity>
:
<TouchableOpacity style={{alignSelf:'center',backgroundColor:'#F9F9F9',width:352,height:50,borderBottomLeftRadius:10,borderBottomRightRadius:10,justifyContent:'center',borderWidth:1,borderColor:'#A6A6A6'}}
onPress={()=>{
navigation.navigate('Map View Polygon', {
screen: 'Map View Polygon',
data: {
id:data.id,
company_name:companyName,
permit_status:checkedStatus,
location:location,
geom:[...coordinates,coordinates[0]]
}
});
}}
>
<Text style={{alignSelf:'center',fontWeight:'semibold',fontSize:16,color:'#434343'}}>Change Location</Text>
</TouchableOpacity>
}
</View>
<View
style={{
marginTop: 15
}}
/>
<View style={{alignSelf:'center'}}>
{/* <Text style={styles.label}>Name<Text style={{color:'red',fontWeight:'bold'}}>*</Text></Text> */}
<Text style={styles.label}>Company Name</Text>
<TextInput
style={styles.input}
onChangeText={(text) => {
setCompanyName(text)
}}
onChange={()=> {
setCompanyNameError(false)
}}
defaultValue={companyName}
/>
{companyNameError ? <Text style={styles.errorInput}>Company Name is Required!</Text>:null}
</View>
<View
style={{
marginTop: 15
}}
/>
<View style={{alignSelf:'center',width:352,height:45}}>
{/* <Text style={styles.label}>Status<Text style={{color:'red',fontWeight:'bold'}}>*</Text></Text> */}
<Text style={styles.label}>Permit Status</Text>
<View style={{flexDirection:'row',alignItems:'center'}}>
<RadioButton
color='#434343'
value="Approved"
status={ checkedStatus === 'Approved' ? 'checked' : 'unchecked' }
onPress={() => {setCheckedStatus('Approved'); setPermitStatusError(false)}}
/>
<Text style={{color:"#434343",fontWeight:'semibold',fontSize:16}}>Approved</Text>
</View>
<View style={{flexDirection:'row',alignItems:'center'}}>
<RadioButton
color='#434343'
value="Under Review"
status={ checkedStatus === 'Under Review' ? 'checked' : 'unchecked' }
onPress={() => {setCheckedStatus('Under Review'); setPermitStatusError(false); }}
/>
<Text style={{color:"#434343",fontWeight:'semibold',fontSize:16}}>Under Review</Text>
</View>
{permitStatusError ? <Text style={styles.errorInput}>Status is Required!</Text>:null}
</View>
<View
style={{
marginTop: 60
}}
/>
{
checkedStatus === 'Approved' ?
<Animated.View>
<View style={{alignSelf:'center'}}>
<Text style={styles.label}>Approved By<Text style={{ color: 'red', fontWeight: 'bold' }}>*</Text></Text>
<TextInput
style={styles.input}
onChangeText={(text) => {
setApprovedBy(text);
} }
/>
</View>
<View
style={{
marginTop: 15
}} />
</Animated.View>
:
null
}
<View style={{alignSelf:'center'}}>
<Text style={styles.label}>Location Detail</Text>
<TextInput style={{borderWidth:1,borderRadius:20,padding: 10,color:'#6B5E5E',borderColor:'#A6A6A6',textAlignVertical:'top',width:352,height:135}}
multiline
numberOfLines={5}
maxLength={255}
onChangeText={(text) => {
setLocation(text)
}}
onChange={()=> {
setLocationError(false)
}}
defaultValue={location}
/>
{locationError ? <Text style={styles.errorInput}>Information is Required!</Text>:null}
</View>
<View
style={{
marginTop: 15
}}
/>
<View style={{alignSelf:'center'}}>
<Text style={styles.label}>Survey Date</Text>
<TextInput
style={styles.input}
onPress={() => setOpen(true)}
value={String(momentDate)}
/>
<DatePicker
locale='en'
theme='light'
mode='date'
modal
open={open}
date={install_date}
onConfirm={(survey_date) => {
setOpen(false)
setInstallDate(survey_date)
}}
onCancel={() => {
setOpen(false)
}}
/>
</View>
<View
style={{
marginTop: 15
}}
/>
<View style={{alignSelf:'center',width:352}}>
<Text style={styles.label}>Attachment</Text>
<Text style={{fontStyle:'italic',color:'#434343',fontSize:14}}>Lampirkan dokumen</Text>
{
fileDocument.length === 0 ?
<Pressable onPress={uploadFileOnHandler}>
<View style={{width:352,height:70,borderRadius:10,borderStyle:'dashed',borderWidth:2,borderCurve:'continuous',borderColor:'#434343',alignItems:'center',justifyContent:'center',flexDirection:'row',columnGap:5}}>
<Image
source={require('../../assets/icon/folder.png')}
/>
<Text style={{fontStyle:'italic',color:'#434343'}}>Klik untuk menambahkan dokumen</Text>
</View>
</Pressable>
:
<FlatList
horizontal={true}
showsHorizontalScrollIndicator={false}
scrollEnabled={false}
ListFooterComponent={()=>
<Pressable onPress={uploadFileOnHandler}>
<View style={{width:352,height:70,borderRadius:10,borderStyle:'dashed',borderWidth:2,borderCurve:'continuous',borderColor:'#434343',alignItems:'center',justifyContent:'center'}}>
<Image
source={require('../../assets/icon/folder.png')}
/>
<Text style={{fontStyle:'italic',color:'#434343'}}>Klik untuk menambahkan dokumen</Text>
</View>
</Pressable>
}
contentContainerStyle={{flexDirection:'column',columnGap:25,rowGap:10}}
data={fileDocument}
renderItem={({item,index})=>renderItem({item,index})}
/>
}
</View>
<View
style={{
marginTop: 30
}}
/>
</ScrollView>
<TouchableOpacity style={{width:'100%',height:50,backgroundColor:'#34A6F8',alignItems:'center',justifyContent:'center'}} onPress={showDialog}>
<Text style={{fontSize:18,fontWeight:'bold',color:'#FFFFFF'}}>RESEND</Text>
</TouchableOpacity>
</View>
<AwesomeAlert
show={alertOnline}
showProgress={false}
title="Resend Data"
message="Are you sure for Add New Permit data?"
closeOnTouchOutside={false}
closeOnHardwareBackPress={false}
showCancelButton={true}
showConfirmButton={true}
cancelText="No, cancel"
confirmText="Yes, Add it"
confirmButtonColor="#137997"
onCancelPressed={() => {
handleCancelAlertOnline();
}}
onConfirmPressed={() => {
collectDataOnline();
// cek()
}}
overlayStyle={{width:'100%'}}
contentContainerStyle={{width:'70%',borderRadius:10}}
titleStyle={{fontSize:20}}
messageStyle={{fontSize:16}}
/>
{/* Offline Mode Alert */}
<AwesomeAlert
show={alertOffline}
showProgress={false}
title="You are offline"
message="You want to add data to the draft?"
closeOnTouchOutside={false}
closeOnHardwareBackPress={false}
showCancelButton={true}
showConfirmButton={true}
cancelText="No, cancel"
confirmText="Yes, Add it"
confirmButtonColor="#DD6B55"
onCancelPressed={() => {
handleCancelAlertOffline();
}}
onConfirmPressed={() => {
collectDataOffline();
}}
overlayStyle={{width:'100%'}}
contentContainerStyle={{width:'70%',borderRadius:10}}
titleStyle={{fontSize:20}}
messageStyle={{fontSize:16}}
/>
</View>
)
};
const styles = StyleSheet.create({
errorInput: {
color: 'red',
marginLeft: 20
},
inputLong: {
height: 40,
borderWidth: 1,
padding: 10,
width: 180,
marginRight: 20
},
inputLat: {
height: 40,
borderWidth: 1,
padding: 10,
borderRadius: 50,
width: 180,
color: 'black'
},
input: {
width:352,
height: 45,
borderWidth: 1,
padding: 10,
borderRadius: 10,
color: '#6B5E5E',
borderColor:'#A6A6A6'
},
container: {
padding: 10,
flexGrow: 1
},
mainContainer: {
flex: 1,
},
label: {
fontSize: 16,
fontWeight:'semibold',
color: '#434343',
// marginBottom: 20
},
title: {
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'center',
fontWeight: 'bold',
fontSize: 22,
color: 'black',
marginBottom: 10
},
borderImg: {
borderColor: 'black',
borderWidth: 1,
borderRadius: 20,
},
img: {
width: 295,
height: 500,
borderRadius: 6,
},
btnCameraContainer: {
flexDirection: 'row',
justifyContent: 'space-around',
top:10,
},
btnCamera: {
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'center',
width: 100,
height: 40,
bottom:20,
borderRadius: 6,
backgroundColor: '#80CBD3'
},
textBtn: {
color: '#fff'
},
buttonImageIconStyle: {
padding: 10,
margin: 5,
height: 25,
width: 25,
resizeMode: 'stretch',
},
});
Loading…
Cancel
Save