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

Feature/orangefalcon3/set images #134

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
11 changes: 11 additions & 0 deletions LAKMobile/src/context/ImageUploadContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* images uploaded by the user to our backend.
*/
import React, { createContext, Reducer, useReducer, useState } from 'react';
import { imageIdToSource } from '../api';
import * as ImagePicker from 'expo-image-picker';

const MAX_IMAGES = 3;
Expand Down Expand Up @@ -57,6 +58,12 @@ interface Props {
children: React.ReactNode;
}

export const convertURIsToIds = (uris) => {
uris = uris.filter((value) => value !== '').map((uri) => uri.split('/').slice(-1)[0]);
uris = uris.filter((value) => value.split('.').length < 2).map((uri) => uri);
return uris;
};

export const ImageUploadProvider: React.FC<Props> = ({ children }) => {
const reducer: ImagesReducer = (state, action): ImagesReducerState => {
let newState = state.slice();
Expand All @@ -82,6 +89,10 @@ export const ImageUploadProvider: React.FC<Props> = ({ children }) => {
// This should take a list of preexisting images on the backend and add them to the state.
// Note: We might be able to store the imageIDs under the imageURIs.
// Then, under the backend, we need to check if the imageIDs already exist and not delete them if so.
newState = action.payload.map((imageId) => imageIdToSource(imageId).uri);
while (newState.length < 3) {
newState.push('');
}
break;
case 'CLEAR_IMAGES':
newState = new Array(MAX_IMAGES).fill('');
Expand Down
12 changes: 5 additions & 7 deletions LAKMobile/src/screens/AddJob.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { COLORS } from '../../constants';
import { JobOwnerView, postJob, updateJob, deleteJob, getUser } from '../api';
import { AddJobProps } from '../types/navigation';
import { AuthContext } from '../context/AuthContext';
import { ImageUploadContext } from '../context/ImageUploadContext';
import { ImageUploadContext, convertURIsToIds } from '../context/ImageUploadContext';
import { ImageUploadArea } from '../components/ImageUploadArea';

const PICKER_DEFAULT = '-- Select a district --';
Expand Down Expand Up @@ -224,7 +224,7 @@ export function AddJob({ navigation, route }: AddJobProps) {
body: { [key: string]: any }
) => {
const data = new FormData();
if (images !== null && images[0] !== null) {
if (images !== null) {
images.map((image) => {
if (image !== null) {
const uriArray = image.uri.split('.');
Expand All @@ -242,7 +242,6 @@ export function AddJob({ navigation, route }: AddJobProps) {
Object.keys(body).forEach((key) => {
data.append(key, body[key]);
});

return data;
};

Expand All @@ -265,18 +264,17 @@ export function AddJob({ navigation, route }: AddJobProps) {
pickupDistrict: pickupDistrict.trim(),
dropoffLocation: dropoffLocation.trim(),
dropoffDistrict: dropoffDistrict.trim(),
imageIds: imageURIs.filter((value) => value !== ''),
imageIds: convertURIsToIds(imageURIs),
};
const formedJob: FormData = createFormData(imageInfo, newJob);
dispatch({ type: 'CLEAR_IMAGES' });
if (formType === 'add' || formType == 'repost') {
setLoading(true);
postJob(userId, formedJob).then((response) => {
setLoading(false);
console.log(response);
if (response == null) {
return;
}
dispatch({ type: 'CLEAR_IMAGES' });
const { jobId } = response;
const updatedJob: JobOwnerView = createUpdateFromId(jobId, newJob);
route.params.setJobData((prevJobs) => [...prevJobs, updatedJob]);
Expand All @@ -291,11 +289,11 @@ export function AddJob({ navigation, route }: AddJobProps) {
if (!route.params.jobData) {
return;
}

updateJob(userId, route.params.jobData._id, formedJob).then((response) => {
if (response === null) {
return;
}
dispatch({ type: 'CLEAR_IMAGES' });
console.log(response);
const { jobId } = response;
const updatedJob: JobOwnerView = createUpdateFromId(jobId, newJob);
Expand Down
4 changes: 2 additions & 2 deletions LAKMobile/src/screens/DriverRegistration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { COLORS } from '../../constants';
import { AppButton, AppText, ScreenHeader, LabelWrapper, ModalAlert } from '../components';
import { getUser, updateUser, UserData, VehicleData } from '../api';
import { AuthContext } from '../context/AuthContext';
import { ImageUploadContext } from '../context/ImageUploadContext';
import { ImageUploadContext, convertURIsToIds } from '../context/ImageUploadContext';
import { ImageUploadArea } from '../components/ImageUploadArea';

export function DriverRegistration({ navigation }: DriverRegistrationProps) {
Expand Down Expand Up @@ -99,7 +99,7 @@ export function DriverRegistration({ navigation }: DriverRegistrationProps) {
vehicleModel: vehicleModel.trim(),
vehicleMake: vehicleMake.trim(),
vehicleColor: vehicleColor.trim(),
imageIds: imageURIs.filter((value) => value !== ''),
imageIds: convertURIsToIds(imageURIs),
};

const updatedUser: UserData = {
Expand Down
8 changes: 4 additions & 4 deletions LAKMobile/src/screens/EditProfileScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { AuthContext } from '../context/AuthContext';
import { AppButton, AppText, ScreenHeader, LabelWrapper } from '../components';
import { PublicProfilePicDefault } from '../icons';
import { EditProfileScreenProps } from '../types/navigation';
import { ImageUploadContext } from '../context/ImageUploadContext';
import { ImageUploadContext, convertURIsToIds } from '../context/ImageUploadContext';
import { ImageUploadArea } from '../components/ImageUploadArea';

export function EditProfileScreen({ navigation, route }: EditProfileScreenProps) {
Expand Down Expand Up @@ -88,7 +88,7 @@ export function EditProfileScreen({ navigation, route }: EditProfileScreenProps)
body: { [key: string]: string }
) => {
const data = new FormData();
if (images !== null && images[0] !== null) {
if (images !== null) {
images.map((image) => {
if (image !== null) {
const uriArray = image.uri.split('.');
Expand Down Expand Up @@ -116,7 +116,7 @@ export function EditProfileScreen({ navigation, route }: EditProfileScreenProps)
vehicleModel: vehicleModel.trim(),
vehicleMake: vehicleMake.trim(),
vehicleColor: vehicleColor.trim(),
imageIds: imageURIs.filter((value) => value !== ''),
imageIds: convertURIsToIds(imageURIs),
};
let formattedLocation = location;
if (district !== PICKER_LOCATION_DEFAULT) {
Expand Down Expand Up @@ -246,7 +246,7 @@ export function EditProfileScreen({ navigation, route }: EditProfileScreenProps)
</LabelWrapper>

<LabelWrapper label="Vehicle Photo">
<ImageUploadArea disabled={true} />
<ImageUploadArea disabled={false} />
</LabelWrapper>
</View>
)}
Expand Down
24 changes: 16 additions & 8 deletions backend/services/job.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,9 @@ export async function createJob(userId, jobData, jobImages) {
* @param {list} jobImages
*/
export async function updateJob(userId, jobId, jobData, jobImages) {
console.debug(
`SERVICE: updateJob service runnning: jobId - ${jobId}, userId - ${userId}, jobData - ${JSON.stringify(
jobData
)}, jobImages - files`
);
// console.debug(
// `SERVICE: updateJob service runnning: jobId - ${jobId}, userId - ${userId}, jobData - ${jobData}, jobImages - files`
// );
// Retrieve original job
const originalJob = await JobModel.findById(jobId);
if (!originalJob) {
Expand All @@ -139,20 +137,30 @@ export async function updateJob(userId, jobId, jobData, jobImages) {
throw ServiceError.JOB_EDIT_PERMISSION_DENIED;
}

const incomingImageIds = jobData.imageIds.split(',');
// Ensure updated fields are only getting updated
jobData = filterObject(jobData, FIELDS_OWNER_PERMITTED_TO_UPDATE);

// TODO Find a better way of updating images

// Delete existing images
const existingImageIds = originalJob.imageIds;

const existingImageIds =
originalJob.imageIds.length > 0 ? originalJob.imageIds[0].split(',') : [];

await Promise.all(
existingImageIds.map(async (imageId) => {
await deleteImage(imageId);
if (!incomingImageIds.includes(imageId)) {
console.log('Delete Image');
await deleteImage(imageId);
} else {
console.log('Existing Image');
}
})
);
// Add new images
const newImageIds = [];

const newImageIds = incomingImageIds.filter((value) => value !== '') || [];
await Promise.all(
jobImages.map(async (image) => {
const imageId = await saveImage(image);
Expand Down
16 changes: 12 additions & 4 deletions backend/services/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,23 +109,31 @@ export async function updateUser(userId, userData, userImages) {

// Ensure updated fields are only getting updated
userData = filterObject(userData, FIELDS_USER_PERMITTED_TO_UPDATE);
const incomingImageIds = JSON.parse(userData.vehicleData).imageIds;
if (userData.vehicleData) {
const vehicleData = JSON.parse(userData.vehicleData);
userData.vehicleData = vehicleData;
console.log(userData);
if (userImages) {
// Delete existing images
const existingImageIds = originalUser.imageIds;
const existingImageIds =
originalUser.vehicleData.imageIds.length > 0
? originalUser.vehicleData.imageIds[0].split(',')
: [];
if (existingImageIds) {
await Promise.all(
existingImageIds.map(async (imageId) => {
await deleteImage(imageId);
if (!vehicleData.imageIds.includes(imageId)) {
console.log('Deleting Image');
await deleteImage(imageId);
} else {
console.log('Existing Image');
}
})
);
}

// Add new images
const newImageIds = [];
const newImageIds = incomingImageIds || [];
await Promise.all(
userImages.map(async (image) => {
const imageId = await saveImage(image);
Expand Down
Loading