Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixed request queue values #45

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 33 additions & 56 deletions App.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Order } from '@fleetbase/sdk';
import { Order, lookup } from '@fleetbase/sdk';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { useFleetbase } from 'hooks';
Expand All @@ -12,7 +12,7 @@ import { EventRegister } from 'react-native-event-listeners';
import tailwind from 'tailwind';
import { useDriver } from 'utils/Auth';
import { getString, setString } from 'utils/Storage';
import { config } from './src/utils';
import { config, isArray, capitalize, logError } from './src/utils';
import { useNetInfo } from '@react-native-community/netinfo';
import CoreStack from './src/features/Core/CoreStack';

Expand All @@ -34,77 +34,54 @@ const App: () => Node = () => {
const navigationRef = useRef();
const [isLoading, setLoading] = useState(true);
const fleetbase = useFleetbase();
const { isConnected } = useNetInfo();
const { type, isConnected, isInternetReachable } = useNetInfo();

useEffect(() => {
const orders = JSON.parse(getString('apiRequestQueue'));

if (!isConnected || orders?.length == 0) {
const apiRequestQueue = JSON.parse(getString('apiRequestQueue'));
console.log('#apiRequestQueue', JSON.stringify(apiRequestQueue));
if (!isConnected || !isArray(apiRequestQueue) || apiRequestQueue.length === 0) {
return;
}
if (orders?.length > 0) {

if (apiRequestQueue.length > 0) {
Toast.show({
type: 'success',
text1: `Activity syncing...`,
});
}

orders?.forEach((item, index) => {
console.log('Order: ', item?.order.attributes.tracking_number.status, item?.order.attributes.id, item.action);
const orderService = new Order(item?.order.attributes, fleetbase.getAdapter());
const adapter = fleetbase.getAdapter();
const adapterMethods = ['get', 'put', 'patch', 'post', 'delete'];

if (item.action == 'start') {
startOrder(orderService, index);
} else if (item.action == 'updated') {
updateOrder(orderService, index);
const trackSuccess = response => {
if (response instanceof Order) {
emit('order.synced', response);
}
});
};

if (success) {
emit('order');
for (let i = 0; i < apiRequestQueue.length; i++) {
const apiRequest = apiRequestQueue[i];
const { method, resource, resourceType, endpoint, params } = apiRequest;
if (adapterMethods.includes(method)) {
adapter[method](endpoint, params).then(trackSuccess);
continue;
}
console.log('#queuedApiRequest', JSON.stringify({ method, resourceType, endpoint, params }));
const resourceInstance = lookup('resource', capitalize(resourceType), resource, fleetbase.getAdapter());
console.log('#resourceInstance', JSON.stringify(resourceInstance));
if (resourceInstance) {
console.log('#resourceInstance ID', resourceInstance.id);
console.log('#resourceInstance method', method, typeof resourceInstance[method]);
if (typeof resourceInstance[method] === 'function') {
resourceInstance[method](params).then(trackSuccess).catch(logError);
}
continue;
}
}

success.forEach(item => {
orders.splice(item);
});
setString('apiRequestQueue', JSON.stringify(orders));
setString('apiRequestQueue', JSON.stringify([]));
}, [isConnected]);

const updateOrder = (order, index) => {
order
.updateActivity({ skipDispatch: true })
.then(res => {
Toast.show({
type: 'success',
text1: `Activity synced.`,
});
success.push(index);
console.log('Order updated------->', res);
})
.catch(err => {
console.error('Order update error------->', err);
});
};

const startOrder = (order, index) => {
order
.start({ skipDispatch: true })
.then(res => {
Toast.show({
type: 'success',
text1: `Activity synced.`,
});
success.push(index);
console.log('Sync sucess: ', res);
})
.catch(error => {
console.log('attributes error----->', error);
if (error.message.includes('already started')) {
success.push(index);
}
});
};

const parseDeepLinkUrl = useCallback(url => {
const urlParts = url.split('?');
if (urlParts.length > 1) {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
},
"dependencies": {
"@babel/plugin-proposal-async-generator-functions": "^7.17.12",
"@fleetbase/sdk": "1.2.8",
"@fleetbase/sdk": "1.2.9",
"@fortawesome/fontawesome-svg-core": "^1.2.35",
"@fortawesome/free-brands-svg-icons": "^5.15.4",
"@fortawesome/free-solid-svg-icons": "^5.15.3",
Expand Down
2 changes: 1 addition & 1 deletion src/features/Core/screens/OrdersScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ const OrdersScreen = ({ navigation }) => {
}, [isMounted]);

useEffect(() => {
const orders = addEventListener('order', () => loadOrders({ isQuerying: true }));
const orders = addEventListener('order.synced', () => loadOrders({ isQuerying: true }));

return () => {
removeEventListener(orders);
Expand Down
25 changes: 10 additions & 15 deletions src/features/Shared/OrderScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import RNFS from 'react-native-fs';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import tailwind from 'tailwind';
import { calculatePercentage, formatCurrency, formatMetaValue, getColorCode, getStatusColors, isArray, isEmpty, logError, titleize, translate } from 'utils';
import { getString, setString } from 'utils/Storage';
import { getString, setString, remove } from 'utils/Storage';
import OrderMapPicker from '../../components/OrderMapPicker';

const { addEventListener, removeEventListener } = EventRegister;
Expand Down Expand Up @@ -213,19 +213,14 @@ const OrderScreen = ({ navigation, route }) => {
});
};

const addToRequestQueue = (type, params, order, action) => {
const addToRequestQueue = ({ method, params, resource, resourceType, endpoint }) => {
let apiRequestQueue = JSON.parse(getString('apiRequestQueue'));
const queueItem = {
type: type,
params,
order,
action: action,
time: new Date(),
};
if (isArray(apiRequestQueue)) {
apiRequestQueue.push({ method, params, resource, resourceType, endpoint });
} else {
apiRequestQueue = [{ method, params, resource, resourceType, endpoint }];
}

if (apiRequestQueue?.length > 0) {
apiRequestQueue.push(queueItem);
} else apiRequestQueue = [queueItem];
setString('apiRequestQueue', JSON.stringify(apiRequestQueue));
};

Expand All @@ -250,7 +245,7 @@ const OrderScreen = ({ navigation, route }) => {
setIsLoadingAction(true);

if (!isConnected) {
addToRequestQueue('startOrder', params, order, 'start');
addToRequestQueue({ method: 'start', params: { skipDispatch: true }, resource: order.serialize(), resourceType: 'Order' });
setIsLoadingAction(false);
return;
}
Expand Down Expand Up @@ -291,7 +286,7 @@ const OrderScreen = ({ navigation, route }) => {
setActionSheetAction('update_activity');

if (!isConnected) {
addToRequestQueue('updateOrder', '', order, 'updated');
addToRequestQueue({ method: 'updateActivity', params: { skipDispatch: true }, resource: order.serialize(), resourceType: 'Order' });
setIsLoadingAction(false);
return;
}
Expand Down Expand Up @@ -946,7 +941,7 @@ const OrderScreen = ({ navigation, route }) => {
</View>
</View>
</ScrollView>

<ActionSheet
ref={actionSheetRef}
containerStyle={{ height: actionSheetHeight, backgroundColor: getColorCode('bg-gray-800') }}
Expand Down
Loading