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

[#1153] Add sync button to manage form #1154

Merged
merged 42 commits into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
e9c921a
[#1153] Add sync button to manage form
navins94 Feb 7, 2024
b454185
Merge branch 'develop' into feature/1153-download-the-JSON-file-with-…
ifirmawan Feb 7, 2024
ad23682
[#1153] Modify jobs table to handle sync datapoints job
ifirmawan Feb 7, 2024
4f7b2f5
[#1153] Update getActiveJob query to include form
ifirmawan Feb 7, 2024
eae82b7
[#1153] Add formID when creating sync form submission job
ifirmawan Feb 7, 2024
6801f5c
[#1153] Add new lib: sync datapoints process
ifirmawan Feb 7, 2024
e2f0c8a
[#1153] Add syncForm query to insert & update monitoring
ifirmawan Feb 7, 2024
8cb1c8d
[#1153] Add new global UserState: syncDatapointsAdded & syncDatapoint…
ifirmawan Feb 7, 2024
4b39bd7
[#1153] Add on sync click
navins94 Feb 9, 2024
31f62d7
[#1153] Update sync service
navins94 Feb 11, 2024
e714eaf
[#1153] Fix error
navins94 Feb 12, 2024
72a031b
Merge branch 'develop' into feature/1153-download-the-JSON-file-with-…
ifirmawan Feb 12, 2024
f58b8b3
[#1153] Refactor sync service
navins94 Feb 12, 2024
07cbfe0
Merge branch 'develop' into feature/1153-download-the-JSON-file-with-…
ifirmawan Feb 12, 2024
78ce5bb
Merge branch 'develop' into feature/1153-download-the-JSON-file-with-…
ifirmawan Feb 12, 2024
9006675
[#1153] Fix fetchDataPoints recursion logic
ifirmawan Feb 12, 2024
24b367a
[#1153] Add dataSyncActiveForms in UserState
ifirmawan Feb 12, 2024
294444d
[#1153] Implement dataSyncActiveForms in SyncService
ifirmawan Feb 12, 2024
43abdba
[#1153] Subscribe dataSyncActiveForms to handle loading state in sync…
ifirmawan Feb 12, 2024
0718a15
[#1153] Add update function
navins94 Feb 12, 2024
a6b097a
Merge branch 'develop' into feature/1153-download-the-JSON-file-with-…
ifirmawan Feb 13, 2024
aadec23
[#1153] Add `id` in form details response endpoint
ifirmawan Feb 13, 2024
9f0ba8a
[#1153] Create new global state: DatapointSyncState
ifirmawan Feb 13, 2024
fb9e8ef
[#1153] Update fetchDatapoint to remove query params: form
ifirmawan Feb 13, 2024
0b4ac6b
[#1153] Add update param to replace existing cascade file
ifirmawan Feb 13, 2024
cf8dd3f
[#1153] Remove form in jobs table
ifirmawan Feb 13, 2024
09c3cb6
[#1153] Remove spread data & return reject promise in addJob query
ifirmawan Feb 13, 2024
953bf11
[#1153] Replace raw syntax with existing query in crudForms
ifirmawan Feb 13, 2024
9fb07af
[#1153] Remove log.info "downloading" in AuthForm
ifirmawan Feb 13, 2024
b3c4a71
[#1153] Revert ManageForm changes
ifirmawan Feb 13, 2024
4a824e8
[#1153] Add sync datapoint button in Homepage
ifirmawan Feb 13, 2024
ac55edb
[#1153] Implement download JSON and insert monitoring with queue
ifirmawan Feb 13, 2024
357b765
Merge branch 'develop' into feature/1153-download-the-JSON-file-with-…
ifirmawan Feb 13, 2024
6d7ee3e
[#1153] Remove form in getActiveJob query
ifirmawan Feb 13, 2024
d74e4ef
[#1153] Implement last synced at after redownloading forms
ifirmawan Feb 13, 2024
bad47b4
[#1153] Execute save_to_file in fake_data_seeder
ifirmawan Feb 14, 2024
72b0968
[#1153] Fix download cascades by closing & re-creating database
ifirmawan Feb 14, 2024
bdd851d
[#1153] Change to async await for all `cascades.download` uses
ifirmawan Feb 14, 2024
66698c1
[#1153] Close all cascade database connection when exit Form
ifirmawan Feb 14, 2024
0b9a40e
[#1153] Fix removeDB connection by adding db name
ifirmawan Feb 14, 2024
74f9c9c
[#1153] Remove set form in addJob FormPage
ifirmawan Feb 14, 2024
c89ab26
[#1153] Add optional chaining on cascadeFiles
ifirmawan Feb 14, 2024
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
63 changes: 62 additions & 1 deletion app/src/components/SyncService.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { useCallback, useEffect } from 'react';
import { BuildParamsState, UIState } from '../store';
import { backgroundTask } from '../lib';
import crudJobs, { jobStatus, MAX_ATTEMPT } from '../database/crud/crud-jobs';
import crudJobs, {
jobStatus,
MAX_ATTEMPT,
SYNC_DATAPOINT_JOB_NAME,
} from '../database/crud/crud-jobs';
import { SYNC_FORM_SUBMISSION_TASK_NAME, syncStatus } from '../lib/background-task';
import { crudDataPoints } from '../database/crud';
import { downloadDatapointsJson, fetchDatapoints } from '../lib/sync-datapoints';
/**
* This sync only works in the foreground service
*/
Expand Down Expand Up @@ -94,6 +99,62 @@ const SyncService = () => {
};
}, [syncInSecond, isOnline, onSync]);

const onSyncDataPoint = useCallback(async () => {
const activeJob = await crudJobs.getActiveJob(SYNC_DATAPOINT_JOB_NAME);

if (activeJob.status === PENDING && activeJob.attempt < 3) {
ifirmawan marked this conversation as resolved.
Show resolved Hide resolved
UIState.update((s) => {
s.statusBar = {
type: syncStatus.ON_PROGRESS,
bgColor: '#2563eb',
icon: 'sync',
};
});
await crudJobs.updateJob(activeJob.id, {
status: jobStatus.ON_PROGRESS,
});
try {
const allData = await fetchDatapoints(activeJob.form);
const urls = allData.map((item) => item.url);
await Promise.all(urls.map(downloadDatapointsJson));
UIState.update((s) => {
s.statusBar = {
type: syncStatus.SUCCESS,
bgColor: '#16a34a',
icon: 'checkmark-done',
};
});
await crudJobs.deleteJob(activeJob.id);
} catch (error) {
await crudJobs.updateJob(activeJob.id, {
status: jobStatus.PENDING,
attempt: activeJob.attempt + 1,
});
}
}

if (activeJob.status === PENDING && activeJob.attempt === 3) {
await crudJobs.deleteJob(activeJob.id);
}

console.log(activeJob, 'activeJob');
}, [statusBar]);

useEffect(() => {
if (!syncInSecond || !isOnline) {
return;
}
const syncTimer = setInterval(() => {
// Perform sync operation
onSyncDataPoint();
}, syncInSecond);

return () => {
// Clear the interval when the component unmounts
clearInterval(syncTimer);
};
}, [syncInSecond, isOnline, onSync]);
ifirmawan marked this conversation as resolved.
Show resolved Hide resolved

return null; // This is a service component, no rendering is needed
};

Expand Down
15 changes: 11 additions & 4 deletions app/src/database/crud/crud-jobs.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,29 @@ export const jobStatus = {

export const MAX_ATTEMPT = 3;

export const SYNC_DATAPOINT_JOB_NAME = 'sync-form-datapoints';

const tableName = 'jobs';
const jobsQuery = () => {
return {
getActiveJob: async (type) => {
getActiveJob: async (type, form = null) => {
try {
const session = await crudUsers.getActiveUser();
if (session?.id) {
/**
* Make sure the app only gets active jobs from current user
*/
const where = { active: 1, type, user: session.id };
const where = { type, user: session.id };
const params = [type, session.id];
if (form) {
where.form = form;
params.push(form);
}

const nocase = false;
const order_by = 'createdAt';
const readQuery = query.read(tableName, where, nocase, order_by);
const { rows } = await conn.tx(db, readQuery, [1, type, session.id]);
const { rows } = await conn.tx(db, readQuery, params);
if (!rows.length) {
return null;
}
Expand All @@ -44,7 +52,6 @@ const jobsQuery = () => {
const insertQuery = query.insert(tableName, {
...data,
createdAt,
uuid: Crypto.randomUUID(), // TODO: Remove if not needed
});
return await conn.tx(db, insertQuery, []);
} catch (error) {
Expand Down
26 changes: 25 additions & 1 deletion app/src/database/crud/crud-monitoring.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,37 @@ const monitoringQuery = () => {
const insertQuery = query.insert('monitoring', {
formId: formId,
uuid: formJSON.uuid,
administration: formJSON?.administration,
name: formJSON?.datapoint_name || null,
json: formJSON ? JSON.stringify(formJSON.answers).replace(/'/g, "''") : null,
syncedAt: new Date().toISOString(),
});
return await conn.tx(db, insertQuery, []);
},
syncForm: async ({ formId, formJSON }) => {
const findQuery = query.read('monitoring', { uuid: formJSON.uuid });
const { rows } = await conn.tx(db, findQuery, [formJSON.uuid]);
if (rows.length) {
const monitoringID = rows._array[0].id;
const updateQuery = query.update(
'monitoring',
{ id: monitoringID },
{
json: formJSON ? JSON.stringify(formJSON.answers).replace(/'/g, "''") : null,
syncedAt: new Date().toISOString(),
},
);
return await conn.tx(db, updateQuery, [monitoringID]);
} else {
const insertQuery = query.insert('monitoring', {
formId: formId,
uuid: formJSON.uuid,
name: formJSON?.datapoint_name || null,
json: formJSON ? JSON.stringify(formJSON.answers).replace(/'/g, "''") : null,
syncedAt: new Date().toISOString(),
});
return await conn.tx(db, insertQuery, []);
}
},
getAllForms: async () => {
const sqlQuery = 'SELECT formId FROM monitoring';
const { rows } = await conn.tx(db, sqlQuery);
Expand Down
6 changes: 2 additions & 4 deletions app/src/database/tables.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ export const tables = [
formId: 'INTEGER NOT NULL',
uuid: 'TEXT type UNIQUE',
name: 'VARCHAR(255)',
administration: 'VARCHAR(255)', // TODO: Remove
syncedAt: 'DATETIME',
json: 'TEXT',
},
Expand All @@ -78,13 +77,12 @@ export const tables = [
name: 'jobs',
fields: {
id: 'INTEGER PRIMARY KEY NOT NULL',
uuid: 'TEXT type UNIQUE', // TODO: Remove if not used
form: 'INTEGER NOT NULL',
user: 'INTEGER NOT NULL',
type: 'VARCHAR(191)',
status: 'INTEGER NOT NULL',
attempt: 'INTEGER DEFAULT "0" NOT NULL',
active: 'TINYINT',
info: 'TEXT',
info: 'VARCHAR(255)',
createdAt: 'DATETIME',
},
},
Expand Down
1 change: 1 addition & 0 deletions app/src/lib/i18n/ui-text.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ const uiText = {
settingAddNewFormPageTitle: 'Add New Form',
errorFormsNotLoaded: 'Unable to load forms',
downloadingData: 'Downloading data',
syncDataPointBtn: 'Sync Datapoint',
syncingText: 'Syncing...',
syncingFailedText: 'Syncing failed...',
syncingSuccessText: 'Syncing successful...',
Expand Down
35 changes: 35 additions & 0 deletions app/src/lib/sync-datapoints.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { crudMonitoring } from '../database/crud';
import api from './api';

export const fetchDatapoints = async (form, pageNumber = 1, allData = []) => {
try {
const response = await api.get(`/datapoint-list?page=${pageNumber}&form=${form}`);
const data = response.data.data;

const updatedData = [...allData, ...data];

if (data.hasMorePages) {
return fetchDatapoints(form, pageNumber + 1, updatedData);
} else {
return updatedData;
}
} catch (error) {
return Promise.reject(error);
}
};

export const downloadDatapointsJson = async (formId, url) => {
try {
const response = await api.get(url);
if (response.status === 200) {
const jsonData = response.data;
const res = await crudMonitoring.syncForm({
formId,
formJSON: jsonData,
});
console.info('[SYNCED MONITORING]', res);
}
} catch (error) {
return Promise.reject(error);
}
};
2 changes: 1 addition & 1 deletion app/src/pages/FormPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,9 @@ const FormPage = ({ navigation, route }) => {
* Create a new job for syncing form submissions.
*/
await crudJobs.addJob({
form: currentFormId,
user: userId,
type: SYNC_FORM_SUBMISSION_TASK_NAME,
active: 1,
status: jobStatus.PENDING,
info: `${currentFormId} | ${datapoitName}`,
});
Expand Down
96 changes: 92 additions & 4 deletions app/src/pages/ManageForm.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import React from 'react';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { View } from 'react-native';
import { ListItem } from '@rneui/themed';
import { View, ToastAndroid } from 'react-native';
import { Button, ListItem } from '@rneui/themed';
import { BaseLayout } from '../components';
import { UIState, FormState } from '../store';
import { i18n } from '../lib';
import { UIState, FormState, UserState } from '../store';
import { i18n, api } from '../lib';
import { getCurrentTimestamp } from '../form/lib';
import { crudForms, crudMonitoring } from '../database/crud';
import crudJobs, { SYNC_DATAPOINT_JOB_NAME, jobStatus } from '../database/crud/crud-jobs';

const ManageForm = ({ navigation, route }) => {
const draftCount = FormState.useState((s) => s.form?.draft);
const submittedCount = FormState.useState((s) => s.form?.submitted);
const activeLang = UIState.useState((s) => s.lang);
const trans = i18n.text(activeLang);
const userId = UserState.useState((s) => s.id);

const goToNewForm = () => {
FormState.update((s) => {
Expand Down Expand Up @@ -57,6 +60,88 @@ const ManageForm = ({ navigation, route }) => {
goTo: () => navigation.navigate('FormData', { ...route?.params, showSubmitted: true }),
},
];

async function fetchData(form, pageNumber = 1, allData = []) {
try {
const response = await api.get(`/datapoint-list?page=${pageNumber}&form=${form}`);
const data = response.data.data;

const updatedData = [...allData, ...data];

if (data.hasMorePages) {
return fetchData(form, pageNumber + 1, updatedData);
} else {
return updatedData;
}
} catch (error) {
ToastAndroid.show(`${error?.errorCode}: ${error?.message}`, ToastAndroid.LONG);
}
}

const handleDataPoint = async () => {
ToastAndroid.show(trans.syncingText, ToastAndroid.CENTER);
setSyncLoading(true);
try {
const allData = await fetchData(route.params.formId);
const urls = allData.map((item) => item.url);
await Promise.all(urls.map(downloadJson));
} catch (error) {
setSyncLoading(false);
}
};

const downloadJson = async (url) => {
try {
const response = await api.get(url);
if (response.status === 200) {
const jsonData = response.data;
await crudMonitoring.addForm({
formId: params.id,
formJSON: jsonData,
});
setSyncLoading(false);
ToastAndroid.show(trans.syncingSuccessText, ToastAndroid.LONG);
}
} catch (error) {
ToastAndroid.show(`${error?.errorCode}: ${error?.message}`, ToastAndroid.LONG);
}
};

const handleGetForm = async (userID) => {
try {
const formRes = await api.get(`/form/${route.params.formId}`);
const apiData = formRes.data;

if (apiData.cascades) {
apiData.cascades.forEach((cascadeFile) => {
const downloadUrl = api.getConfig().baseURL + cascadeFile;
cascades.download(downloadUrl, cascadeFile);
});
}

const savedForm = await crudForms.addForm({
formId: route.params.formId,
version: apiData.version,
userId: userID,
formJSON: apiData,
});

console.info('Saved Form...', savedForm);
} catch (error) {
console.error('Error handling form:', error);
}
};

const handleOnSyncClick = async () => {
await handleGetForm();
await crudJobs.addJob({
form: route.params.formId,
user: userId,
type: SYNC_DATAPOINT_JOB_NAME,
status: jobStatus.PENDING,
});
};

return (
<BaseLayout title={route?.params?.name} rightComponent={false}>
<BaseLayout.Content>
Expand All @@ -78,6 +163,9 @@ const ManageForm = ({ navigation, route }) => {
))}
</View>
</BaseLayout.Content>
<View style={{ paddingHorizontal: 16, paddingBottom: 16 }}>
<Button title={trans.syncDataPointBtn} type="outline" onPress={handleOnSyncClick} />
ifirmawan marked this conversation as resolved.
Show resolved Hide resolved
</View>
</BaseLayout>
);
};
Expand Down
2 changes: 2 additions & 0 deletions app/src/store/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const UserState = new Store({
forms: [],
currentLocation: null,
locationIsGranted: false,
syncDatapointsAdded: false,
syncDatapointsForm: null,
});

export default UserState;