Skip to content
New issue

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

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

Already on GitHub? # to your account

[#898] upload photos to images #902

Merged
merged 3 commits into from
Jan 12, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
10 changes: 9 additions & 1 deletion app/src/form/FormContainer.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,14 @@ const style = {
flex: 1,
};

const FormContainer = ({ forms, initialValues = {}, onSubmit, onSave, setShowDialogMenu }) => {
const FormContainer = ({
forms,
initialValues = {},
onSubmit,
onSave,
setShowDialogMenu,
submitting,
}) => {
const formRef = useRef();
const [activeGroup, setActiveGroup] = useState(0);
const [showQuestionGroupList, setShowQuestionGroupList] = useState(false);
Expand Down Expand Up @@ -140,6 +147,7 @@ const FormContainer = ({ forms, initialValues = {}, onSubmit, onSave, setShowDia
showQuestionGroupList={showQuestionGroupList}
setShowQuestionGroupList={setShowQuestionGroupList}
setShowDialogMenu={setShowDialogMenu}
submitting={submitting}
/>
</View>
</>
Expand Down
7 changes: 6 additions & 1 deletion app/src/form/support/FormNavigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const FormNavigation = ({
showQuestionGroupList,
setShowQuestionGroupList,
setShowDialogMenu,
submitting,
}) => {
const visitedQuestionGroup = FormState.useState((s) => s.visitedQuestionGroup);
const activeLang = UIState.useState((s) => s.lang);
Expand Down Expand Up @@ -74,6 +75,9 @@ const FormNavigation = ({
.catch((err) => console.error(err));
};

const submitText = submitting?.text || trans.buttonSubmit;
const submitDisabled = submitting?.status || false;

return (
<Tab
buttonStyle={styles.formNavigationButton}
Expand Down Expand Up @@ -109,12 +113,13 @@ const FormNavigation = ({
/>
) : (
<Tab.Item
title={trans.buttonSubmit}
title={submitText}
icon={{ name: 'paper-plane-outline', type: 'ionicon', color: 'grey', size: 20 }}
iconPosition="right"
iconContainerStyle={styles.formNavigationIcon}
titleStyle={styles.formNavigationTitle}
testID="form-btn-submit"
disabled={submitDisabled}
/>
)}
</Tab>
Expand Down
100 changes: 79 additions & 21 deletions app/src/pages/FormPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@ import {
} from 'react-native';
import { Button, Dialog, Text } from '@rneui/themed';
import Icon from 'react-native-vector-icons/Ionicons';
import axios from 'axios';
import { FormContainer } from '../form';
import { SaveDialogMenu, SaveDropdownMenu } from '../form/support';
import { BaseLayout } from '../components';
import { crudDataPoints } from '../database/crud';
import { UserState, UIState, FormState } from '../store';
import { getDurationInMinutes } from '../form/lib';
import { i18n } from '../lib';
import { i18n, api } from '../lib';

const FormPage = ({ navigation, route }) => {
const selectedForm = FormState.useState((s) => s.form);
Expand All @@ -27,6 +28,7 @@ const FormPage = ({ navigation, route }) => {
const [showDialogMenu, setShowDialogMenu] = useState(false);
const [showDropdownMenu, setShowDropdownMenu] = useState(false);
const [showExitConfirmationDialog, setShowExitConfirmationDialog] = useState(false);
const [loading, setLoading] = useState(false);
const activeLang = UIState.useState((s) => s.lang);
const trans = i18n.text(activeLang);

Expand All @@ -35,7 +37,10 @@ const FormPage = ({ navigation, route }) => {
const savedDataPointId = route?.params?.dataPointId;
const isNewSubmission = route?.params?.newSubmission;
const [currentDataPoint, setCurrentDataPoint] = useState({});
const [loading, setLoading] = useState(false);
const [submitting, setSubmitting] = useState({
text: null,
status: false,
});

const refreshForm = () => {
FormState.update((s) => {
Expand Down Expand Up @@ -145,25 +150,8 @@ const FormPage = ({ navigation, route }) => {
return navigation.navigate('Home');
};

const handleOnSubmitForm = async (values) => {
const handleOnStoreSubmission = async (values, answers) => {
try {
const answers = {};
formJSON.question_group
.flatMap((qg) => qg.question)
.forEach((q) => {
let val = values.answers?.[q.id];
if (!val && val !== 0) {
return;
}
if (q.type === 'cascade') {
val = val.slice(-1)[0];
}
if (q.type === 'number') {
val = parseFloat(val);
}
answers[q.id] = val;
});
// TODO:: submittedAt still null
const submitData = {
form: currentFormId,
user: userId,
Expand All @@ -190,11 +178,79 @@ const FormPage = ({ navigation, route }) => {
} catch (err) {
console.error(err);
if (Platform.OS === 'android') {
ToastAndroid.show(trans.errorSubmitted, ToastAndroid.LONG);
ToastAndroid.show(trans.errorSaveDatapoint, ToastAndroid.LONG);
}
}
};

const handleOnSubmitForm = async (values) => {
setSubmitting({
text: trans.loadingText,
status: true,
});
const answers = {};
const photos = [];
formJSON.question_group
.flatMap((qg) => qg.question)
.forEach((q) => {
let val = values.answers?.[q.id];
if (!val && val !== 0) {
return;
}
if (q.type === 'cascade') {
val = val.slice(-1)[0];
}
if (q.type === 'number') {
val = parseFloat(val);
}
if (q.type === 'photo' && val) {
photos.push({ id: q.id, value: val });
}
answers[q.id] = val;
});
if (photos.length) {
const uploads = photos.map((p) => {
const fileType = p.value.split('.').slice(-1)[0];
const formData = new FormData();
formData.append('file', {
uri: p.value,
name: `photo_${currentFormId}_${p.id}.${fileType}`,
type: `image/${fileType}`,
});
return api.post('/images', formData, {
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
});
});

axios
.all(uploads)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How this is working? the image uploads requires a token.
Please check: http://localhost:3000/api/doc/#/Mobile%20Device%20Form/v1_device_images_create

.then(async (responses) => {
const files = responses.forEach(({ data: dataFile }) => {
const findPhoto = photos.find((p) => dataFile?.file?.includes(`${p.id}`));
if (findPhoto) {
answers[findPhoto.id] = dataFile.file;
}
});
await handleOnStoreSubmission(values, answers);
})
.catch(() => {
setSubmitting({
text: null,
status: false,
});

if (Platform.OS === 'android') {
ToastAndroid.show(trans.errorSubmitted, ToastAndroid.LONG);
}
});
} else {
await handleOnStoreSubmission(values, answers);
}
};

return (
<BaseLayout
title={route?.params?.name}
Expand Down Expand Up @@ -222,13 +278,15 @@ const FormPage = ({ navigation, route }) => {
/>
}
>
{submitting.status && <Text>{submitting.text}</Text>}
{!loading ? (
<FormContainer
forms={formJSON}
initialValues={currentValues}
onSubmit={handleOnSubmitForm}
onSave={onSaveCallback}
setShowDialogMenu={setShowDialogMenu}
submitting={submitting}
/>
) : (
<View style={styles.loadingContainer}>
Expand Down