Skip to content

Commit

Permalink
Ability to duplicate a recipe #243
Browse files Browse the repository at this point in the history
  • Loading branch information
flauschtrud committed Dec 15, 2024
1 parent 5dedc13 commit 1ad971a
Show file tree
Hide file tree
Showing 11 changed files with 174 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withParent;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static com.flauschcode.broccoli.recipe.crud.CreateAndEditRecipeActivity.DUPLICATE;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
Expand Down Expand Up @@ -202,6 +203,50 @@ public void edit_recipe(){
assertThat(editedRecipe.getServings(), is("1 Portion"));
}

@Test
public void duplicate_recipe(){
when(recipeRepository.insertOrUpdate(recipeCaptor.capture())).thenReturn(CompletableFuture.completedFuture(2L));
when(recipeImageService.getUri("lauchkuchen.jpg")).thenReturn(uri);
when(recipeImageService.copyImage(uri)).thenReturn(CompletableFuture.completedFuture("12345.jpg"));
when(recipeImageService.moveImage("12345.jpg")).thenReturn(CompletableFuture.completedFuture(null));

Intent intent = new Intent(ApplicationProvider.getApplicationContext(), CreateAndEditRecipeActivity.class);
intent.putExtra(Recipe.class.getName(), LAUCHKUCHEN_SAVED);
intent.putExtra(DUPLICATE, true);
scenario = launchActivityForResult(intent);

onView(withId(R.id.new_title)).check(matches(withText(LAUCHKUCHEN_SAVED.getTitle())));
onView(withId(R.id.new_categories)).check(matches(withText(LAUCHKUCHEN_SAVED.getCategories().stream().map(Category::getName).collect(Collectors.joining(", ")))));
onView(withId(R.id.new_description)).check(matches(withText(LAUCHKUCHEN_SAVED.getDescription())));
onView(withId(R.id.new_source)).check(matches(withText(LAUCHKUCHEN_SAVED.getSource())));
onView(withId(R.id.new_servings)).check(matches(withText(LAUCHKUCHEN_SAVED.getServings())));
onView(withId(R.id.new_preparation_time)).check(matches(withText(LAUCHKUCHEN_SAVED.getPreparationTime())));
onView(withId(R.id.new_ingredients)).check(matches(withText(LAUCHKUCHEN_SAVED.getIngredients())));
onView(withId(R.id.new_directions)).check(matches(withText(LAUCHKUCHEN_SAVED.getDirections())));
onView(withId(R.id.new_nutritional_values)).check(matches(withText(LAUCHKUCHEN_SAVED.getNutritionalValues())));
onView(withId(R.id.new_notes)).check(matches(withText(LAUCHKUCHEN_SAVED.getNotes())));

onView(withId(R.id.button_save_recipe)).perform(click());

verify(recipeImageService).moveImage("12345.jpg");

Instrumentation.ActivityResult result = scenario.getResult();
assertThat(result.getResultCode(), is(RESULT_OK));
assertThat(result.getResultData().hasExtra(Recipe.class.getName()), is(true));

Recipe recipe = recipeCaptor.getValue();
assertThat(recipe.getTitle(), is(LAUCHKUCHEN.getTitle()));
assertThat(recipe.getDescription(), is(LAUCHKUCHEN.getDescription()));
assertThat(recipe.getSource(), is(LAUCHKUCHEN.getSource()));
assertThat(recipe.getServings(), is(LAUCHKUCHEN.getServings()));
assertThat(recipe.getPreparationTime(), is(LAUCHKUCHEN.getPreparationTime()));
assertThat(recipe.getIngredients(), is(LAUCHKUCHEN.getIngredients()));
assertThat(recipe.getDirections(), is(LAUCHKUCHEN.getDirections()));
assertThat(recipe.getNutritionalValues(), is(LAUCHKUCHEN.getNutritionalValues()));
assertThat(recipe.getNotes(), is(LAUCHKUCHEN.getNotes()));
assertThat(recipe.getImageName(), startsWith("12345.jpg"));
}

@Test
public void remove_image(){
when(recipeRepository.insertOrUpdate(recipeCaptor.capture())).thenReturn(CompletableFuture.completedFuture(1L));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import static androidx.test.espresso.matcher.ViewMatchers.withSubstring;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static com.flauschcode.broccoli.recipe.crud.CreateAndEditRecipeActivity.DUPLICATE;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;
Expand All @@ -42,6 +43,7 @@
import com.flauschcode.broccoli.MockApplicationComponent;
import com.flauschcode.broccoli.R;
import com.flauschcode.broccoli.recipe.cooking.CookingAssistantActivity;
import com.flauschcode.broccoli.recipe.crud.CreateAndEditRecipeActivity;
import com.flauschcode.broccoli.recipe.details.RecipeDetailsActivity;
import com.flauschcode.broccoli.recipe.sharing.ShareRecipeAsFileService;
import com.flauschcode.broccoli.recipe.sharing.ShareableRecipe;
Expand Down Expand Up @@ -180,6 +182,18 @@ public void share_as_file() throws IOException {
))));
}

@Test
public void duplicate() {
openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
onView(withText(R.string.duplicate_action)).perform(click());

intended(allOf(
hasComponent(CreateAndEditRecipeActivity.class.getName()),
hasExtra(Recipe.class.getName(), lauchkuchen),
hasExtra(DUPLICATE, true)
));
}

@Test
public void cook() {
onView(withId(R.id.fab_cooking_assistant)).perform(click());
Expand Down
12 changes: 10 additions & 2 deletions app/src/main/java/com/flauschcode/broccoli/recipe/Recipe.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.flauschcode.broccoli.category.Category;

import com.flauschcode.broccoli.BR;
import com.flauschcode.broccoli.category.Category;

import java.io.Serializable;
import java.util.ArrayList;
Expand All @@ -34,6 +33,14 @@ public class Recipe extends BaseObservable implements Serializable {
@Ignore
private boolean isDirty = false;

public Recipe() {}

public Recipe(Recipe other) {
this.coreRecipe = other.getCoreRecipe();
this.categories.addAll(other.getCategories());
this.setRecipeId(0);
}

@JsonIgnore
public CoreRecipe getCoreRecipe() {
return coreRecipe;
Expand Down Expand Up @@ -183,4 +190,5 @@ public boolean equals(Object o) {
public int hashCode() {
return Objects.hash(coreRecipe, categories);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@

public class CreateAndEditRecipeActivity extends AppCompatActivity {

public static final String DUPLICATE = "duplicate";

@Inject
ViewModelProvider.Factory viewModelFactory;

Expand All @@ -67,43 +69,15 @@ protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();

if (intent.hasExtra(Recipe.class.getName())) {
Recipe recipe = (Recipe) intent.getSerializableExtra(Recipe.class.getName());
viewModel.setRecipe(recipe);
getRecipeFrom(intent);
}

if (Intent.ACTION_SEND.equals(intent.getAction())) {
try {
String url = parseUrlFrom(intent);

recipeImportService.importFrom(url)
.thenAccept(optionalRecipe -> {
if (optionalRecipe.isPresent()) {
applyRecipeToViewModel(optionalRecipe.get());
binding.setViewModel(viewModel);
} else {
runOnUiThread(() -> Toast.makeText(this, getString(R.string.recipe_could_not_be_read_message), Toast.LENGTH_LONG).show());
}
})
.exceptionally(e -> {
Log.e(getClass().getName(), e.getMessage());
runOnUiThread(() -> Toast.makeText(this, getString(R.string.recipe_could_not_be_imported_message), Toast.LENGTH_SHORT).show());
return null;
});
} catch (MalformedURLException e) {
Log.e(getClass().getName(), Objects.requireNonNull(e.getMessage()));
runOnUiThread(() -> Toast.makeText(this, getString(R.string.recipe_could_not_be_imported_message), Toast.LENGTH_SHORT).show());
}
getImportedRecipeFrom(intent, binding);
}

if (Intent.ACTION_DEFAULT.equals(intent.getAction())) {
Uri uri = getIntent().getData();
Optional<Recipe> optionalRecipe = shareRecipeAsFileService.loadFromFile(uri);
if (optionalRecipe.isPresent()) {
applyRecipeToViewModel(optionalRecipe.get());
} else {
runOnUiThread(() -> Toast.makeText(this, getString(R.string.recipe_could_not_be_imported_message), Toast.LENGTH_SHORT).show());
}

getSharedRecipeFrom(intent);
}

if (savedInstanceState != null) {
Expand All @@ -119,6 +93,55 @@ protected void onCreate(Bundle savedInstanceState) {
binding.toolbar.setNavigationOnClickListener(v -> showDiscardDialog(this::finish));
}

private void getRecipeFrom(Intent intent) {
Recipe recipe = (Recipe) intent.getSerializableExtra(Recipe.class.getName());

if (intent.getBooleanExtra(DUPLICATE, false)) {
Recipe copy = new Recipe(recipe);
viewModel.setRecipe(copy);

if (!recipe.getImageName().isEmpty()) {
viewModel.duplicateImage(recipe.getImageName());
}
} else {
viewModel.setRecipe(recipe);
}
}

private void getImportedRecipeFrom(Intent intent, ActivityNewRecipeBinding binding) {
try {
String url = parseUrlFrom(intent);

recipeImportService.importFrom(url)
.thenAccept(optionalRecipe -> {
if (optionalRecipe.isPresent()) {
applyRecipeToViewModel(optionalRecipe.get());
binding.setViewModel(viewModel);
} else {
runOnUiThread(() -> Toast.makeText(this, getString(R.string.recipe_could_not_be_read_message), Toast.LENGTH_LONG).show());
}
})
.exceptionally(e -> {
Log.e(getClass().getName(), e.getMessage());
runOnUiThread(() -> Toast.makeText(this, getString(R.string.recipe_could_not_be_imported_message), Toast.LENGTH_SHORT).show());
return null;
});
} catch (MalformedURLException e) {
Log.e(getClass().getName(), Objects.requireNonNull(e.getMessage()));
runOnUiThread(() -> Toast.makeText(this, getString(R.string.recipe_could_not_be_imported_message), Toast.LENGTH_SHORT).show());
}
}

private void getSharedRecipeFrom(Intent intent) {
Uri uri = intent.getData();
Optional<Recipe> optionalRecipe = shareRecipeAsFileService.loadFromFile(uri);
if (optionalRecipe.isPresent()) {
applyRecipeToViewModel(optionalRecipe.get());
} else {
runOnUiThread(() -> Toast.makeText(this, getString(R.string.recipe_could_not_be_imported_message), Toast.LENGTH_SHORT).show());
}
}

@Override
public void onBackPressed() {
showDiscardDialog(super::onBackPressed);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@

public class CreateAndEditRecipeViewModel extends ViewModel {

private RecipeRepository recipeRepository;
private RecipeImageService recipeImageService;
private CategoryRepository categoryRepository;
private final RecipeRepository recipeRepository;
private final RecipeImageService recipeImageService;
private final CategoryRepository categoryRepository;

private Recipe recipe = new Recipe();
private boolean isFinishedBySaving = false;
Expand Down Expand Up @@ -75,6 +75,14 @@ void confirmImageHasBeenTaken() {
setImageNameAndMarkDirty(newImageName);
}

void duplicateImage(String sourceImageName) {
Uri sourceUri = recipeImageService.getUri(sourceImageName);
recipeImageService.copyImage(sourceUri).thenAccept(imageName -> {
newImageName = imageName;
setImageNameAndMarkDirty(imageName);
});
}

void confirmImageHasBeenPicked(Uri uri) {
removeOldImageAndCleanUpAnyTemporaryImages();
recipeImageService.copyImage(uri).thenAccept(imageName -> {
Expand All @@ -90,7 +98,7 @@ void confirmImageHasBeenRemoved() {
}

boolean imageHasBeenSet() {
return recipe.getImageName().length() > 0;
return !recipe.getImageName().isEmpty();
}

private void removeOldImageAndCleanUpAnyTemporaryImages() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.flauschcode.broccoli.recipe.details;

import static com.flauschcode.broccoli.recipe.crud.CreateAndEditRecipeActivity.DUPLICATE;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
Expand Down Expand Up @@ -153,6 +155,13 @@ public void edit(MenuItem menuItem) {
editRecipeResultLauncher.launch(intent);
}

public void duplicate(MenuItem menuItem) {
Intent intent = new Intent(this, CreateAndEditRecipeActivity.class);
intent.putExtra(Recipe.class.getName(), binding.getRecipe());
intent.putExtra(DUPLICATE, true);
editRecipeResultLauncher.launch(intent);
}

public void delete(MenuItem menuItem) {
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setMessage(R.string.delete_recipe_question)
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/res/menu/details.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@
android:title="@string/edit_action"
android:onClick="edit"
app:showAsAction="never" />
<item
android:id="@+id/action_details_duplicate"
android:title="@string/duplicate_action"
android:onClick="duplicate"
app:showAsAction="never" />
<item
android:id="@+id/action_details_delete"
android:icon="@drawable/ic_menu_delete_24dp"
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<string name="title_should_not_be_empty_message">Bitte füge einen Titel hinzu.</string>
<string name="recipe_saved_message">Das Rezept wurde gespeichert.</string>
<string name="recipe_could_not_be_saved_message">Das Rezept konnte nicht gespeichert werden.</string>
<string name="duplicate_action">Duplizieren</string>
<string name="delete_action">Löschen</string>
<string name="delete_recipe_question">Dieses Rezept löschen?</string>
<string name="recipe_deleted_message">Das Rezept wurde gelöscht.</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-es/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<string name="title_should_not_be_empty_message">Por favor, añade un título.</string>
<string name="recipe_saved_message">La receta se ha guardado.</string>
<string name="recipe_could_not_be_saved_message">La receta no se ha podido guardar.</string>
<string name="duplicate_action">Duplicar</string>
<string name="delete_action">Eliminar</string>
<string name="delete_recipe_question">¿Eliminar esta receta?</string>
<string name="recipe_deleted_message">La receta ha sido eliminada.</string>
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
<string name="recipe_saved_message">The recipe has been saved.</string>
<string name="recipe_could_not_be_saved_message">The recipe could not be saved.</string>

<string name="duplicate_action">Duplicate</string>

<string name="delete_action">Delete</string>
<string name="delete_recipe_question">Delete this recipe?</string>
<string name="recipe_deleted_message">The recipe has been deleted.</string>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
package com.flauschcode.broccoli.recipe.crud;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.IsNull.nullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.net.Uri;

import androidx.lifecycle.LiveData;

import com.flauschcode.broccoli.category.Category;
import com.flauschcode.broccoli.category.CategoryRepository;
import com.flauschcode.broccoli.recipe.RecipeRepository;
import com.flauschcode.broccoli.recipe.crud.CreateAndEditRecipeViewModel;
import com.flauschcode.broccoli.recipe.images.RecipeImageService;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
Expand All @@ -20,15 +29,6 @@
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.IsNull.nullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class CreateAndEditRecipeViewModelTest {

Expand Down Expand Up @@ -116,6 +116,17 @@ public void pick_image_file_and_save() throws ExecutionException, InterruptedExc
verify(recipeImageService, never()).deleteTemporaryImage(any());
}

@Test
public void duplicate_image() {
when(recipeImageService.getUri("blupp.jpg")).thenReturn(imageUri);
when(recipeImageService.copyImage(imageUri)).thenReturn(CompletableFuture.completedFuture("lala.jpg"));

createAndEditRecipeViewModel.duplicateImage("blupp.jpg");

assertThat(createAndEditRecipeViewModel.getRecipe().getImageName(), is("lala.jpg"));
assertThat(createAndEditRecipeViewModel.getRecipe().isDirty(), is(true));
}

@Test
public void clean_up_file_on_cancel() throws IOException {
when(recipeImageService.createTemporaryImage()).thenReturn(imageUri);
Expand Down

0 comments on commit 1ad971a

Please sign in to comment.