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

dynamic units #3

Merged
merged 2 commits into from
Sep 13, 2024
Merged
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
33 changes: 0 additions & 33 deletions src/main/java/de/flavormate/ac_scripts/S01_InitDatabaseScript.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
import de.flavormate.ba_entities.categoryGroup.repository.CategoryGroupRepository;
import de.flavormate.ba_entities.role.model.Role;
import de.flavormate.ba_entities.role.repository.RoleRepository;
import de.flavormate.ba_entities.unit.model.Unit;
import de.flavormate.ba_entities.unit.repository.UnitRepository;
import de.flavormate.utils.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
Expand Down Expand Up @@ -43,9 +41,6 @@ public class S01_InitDatabaseScript extends AScript {
@Value("classpath*:initialization/l10n/categoryGroups/*.json")
private Resource[] categoryGroupsLocalizationsFiles;

@Value("classpath:initialization/units.json")
private Resource unitsFile;

@Autowired
private RoleRepository roleRepository;

Expand All @@ -61,9 +56,6 @@ public class S01_InitDatabaseScript extends AScript {
@Autowired
private CategoryGroupLocalizationRepository categoryGroupLocalizationRepository;

@Autowired
private UnitRepository unitRepository;

public S01_InitDatabaseScript() {
super("Initialize Database");
}
Expand All @@ -72,7 +64,6 @@ public void run() {
log("Starting database initialization");

initializeRoles();
initializeUnits();

initializeCategoryGroups();
initializeCategoryGroupLocalizations();
Expand Down Expand Up @@ -230,28 +221,4 @@ private Boolean initializeCategoryGroupLocalizations() {
return false;
}
}

private Boolean initializeUnits() {
try {
if (unitRepository.count() > 0) {
log("Skipping unit initialization");
return true;
}

log("Reading units from JSON file");
var unitsArr = JSONUtils.mapper.readValue(unitsFile.getInputStream(), Unit[].class);
var units = Arrays.asList(unitsArr);

log("Found {} units", units.size());

log("Saving units into the database");
unitRepository.saveAll(units);

log("Saved {} units", units.size());
return true;
} catch (Exception e) {
warning("Units could not be initialized");
return false;
}
}
}
29 changes: 29 additions & 0 deletions src/main/java/de/flavormate/ac_scripts/S99_CleanScript.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import de.flavormate.ba_entities.tag.repository.TagRepository;
import de.flavormate.ba_entities.token.model.Token;
import de.flavormate.ba_entities.token.repository.TokenRepository;
import de.flavormate.ba_entities.unit.repository.UnitRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
Expand All @@ -26,6 +27,9 @@ public class S99_CleanScript extends AScript {
@Autowired
private TagRepository tagRepository;

@Autowired
private UnitRepository unitRepository;

@Autowired
private TokenRepository tokenRepository;

Expand All @@ -38,11 +42,13 @@ public void run() {

cleanHighlights();
cleanTags();
cleanUnits();
cleanTokens();

log("Finished database cleaning");
}


private Boolean cleanHighlights() {
try {
if (highlightRepository.count() == 0) {
Expand Down Expand Up @@ -95,6 +101,29 @@ private Boolean cleanTags() {
}
}

private boolean cleanUnits() {
try {
var units = unitRepository.findEmpty();

if (units.isEmpty()) {
log("Skipping unit cleaning");
return true;
}

log("Found {} invalid units", units.size());

log("Deleting invalid units");

unitRepository.deleteAll(units);

log("Deleted {} units", units.size());
return true;
} catch (Exception e) {
warning("Units could not be cleaned");
return false;
}
}

private Boolean cleanTokens() {
try {
if (tokenRepository.count() == 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class Ingredient extends BaseEntity {
@Column(nullable = false)
private Double amount;

@ManyToOne
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "unit_id", referencedColumnName = "id")
private Unit unit;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
import de.flavormate.ba_entities.story.repository.StoryRepository;
import de.flavormate.ba_entities.tag.model.Tag;
import de.flavormate.ba_entities.tag.repository.TagRepository;
import de.flavormate.ba_entities.unit.model.Unit;
import de.flavormate.ba_entities.unit.repository.UnitRepository;
import de.flavormate.utils.JSONUtils;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -65,11 +67,12 @@ public class RecipeService extends BaseService implements ICRUDService<Recipe, R
private final StoryRepository storyRepository;
private final TagRepository tagRepository;
private final TemplateEngine templateEngine;
private final UnitRepository unitRepository;

@Value("${flavorMate.files}")
private URL ROOT;

protected RecipeService(RecipeRepository repository, AuthorRepository authorRepository, BookRepository bookRepository, CategoryRepository categoryRepository, FileRepository fileRepository, HighlightRepository highlightRepository, StoryRepository storyRepository, TagRepository tagRepository, TemplateEngine templateEngine) {
protected RecipeService(RecipeRepository repository, AuthorRepository authorRepository, BookRepository bookRepository, CategoryRepository categoryRepository, FileRepository fileRepository, HighlightRepository highlightRepository, StoryRepository storyRepository, TagRepository tagRepository, TemplateEngine templateEngine, UnitRepository unitRepository) {
this.repository = repository;
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
Expand All @@ -79,6 +82,7 @@ protected RecipeService(RecipeRepository repository, AuthorRepository authorRepo
this.storyRepository = storyRepository;
this.tagRepository = tagRepository;
this.templateEngine = templateEngine;
this.unitRepository = unitRepository;
}


Expand All @@ -94,8 +98,18 @@ public Recipe create(RecipeDraft form) throws CustomException {
.filter(Objects::nonNull).toList();

var ingredientGroups = form.ingredientGroups().stream().map(iG -> {
var ingredients = iG.ingredients().stream().map(i -> (Ingredient) Ingredient.builder()
.amount(i.amount()).label(i.label()).unit(i.unit()).build()).toList();
var ingredients = iG.ingredients().stream().map(i -> {
Unit unit = null;
if (i.unit() != null) {
unit = unitRepository.findByLabel(i.unit().getLabel()).orElse(null);
if (unit == null) {
i.unit().setId(null);
unit = unitRepository.save(i.unit());
}
}
return (Ingredient) Ingredient.builder()
.amount(i.amount()).label(i.label()).unit(unit).build();
}).toList();
return (IngredientGroup) IngredientGroup.builder().ingredients(ingredients)
.label(iG.label()).build();
}).toList();
Expand Down Expand Up @@ -198,8 +212,19 @@ public Recipe update(Long id, JsonNode json) throws CustomException {

var ingredientGroups = data.ingredientGroups().stream().map(iG -> {
var ingredients = iG
.ingredients().stream().map(i -> (Ingredient) Ingredient.builder()
.amount(i.amount()).label(i.label()).unit(i.unit()).build())
.ingredients().stream().map(i -> {
Unit unit = null;
if (i.unit() != null) {
unit = unitRepository.findByLabel(i.unit().getLabel()).orElse(null);
if (unit == null) {
i.unit().setId(null);
unit = unitRepository.save(i.unit());
}
}

return (Ingredient) Ingredient.builder()
.amount(i.amount()).label(i.label()).unit(unit).build();
})
.toList();
return (IngredientGroup) IngredientGroup.builder().ingredients(ingredients)
.label(iG.label()).build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,34 +138,28 @@ private IngredientGroupDraft getIngredientGroup(JsonNode json) {
.collect(Collectors.toCollection(ArrayList::new));

var ttt = ingredients.stream().map(i -> {
var list = new ArrayList<String>(Arrays.asList(i.split(" ")));// List.of(i.split("
// "));//
// .removeAll();
var list = new ArrayList<String>(Arrays.asList(i.split(" ")));
list.removeAll(Arrays.asList("", null));

String[] parts = list.toArray(new String[0]);

double amount = NumberUtils.tryParseDouble(parts[0], -1);
String label;
Optional<Unit> unit;
Unit unit;

int startIndex = 0;

if (amount < 0) {
var unitList = unitRepository.findByLabelOrShortLabel(parts[0], parts[0]);
unit = unitList.isEmpty() ? Optional.empty() : Optional.of(unitList.get(0));
if (unit.isEmpty()) {
unit = unitRepository.findByLabel("");
unit = unitRepository.findByLabel(parts[0]).orElse(null);
if (unit == null) {
startIndex = 0;
} else {
startIndex = 1;
}
} else {
var unitList = unitRepository.findByLabelOrShortLabel(parts[1], parts[1]);
unit = unitList.isEmpty() ? Optional.empty() : Optional.of(unitList.get(0));
unit = unitRepository.findByLabel(parts[1]).orElse(null);

if (unit.isEmpty()) {
unit = unitRepository.findByLabel("");
if (unit == null) {
startIndex = 1;
} else {
startIndex = 2;
Expand All @@ -174,7 +168,7 @@ private IngredientGroupDraft getIngredientGroup(JsonNode json) {

label = String.join(" ", List.of(parts).subList(startIndex, parts.length));

return new IngredientDraft(amount, unit.get(), label);
return new IngredientDraft(amount, unit, label);
}).toList();

return new IngredientGroupDraft("", ttt);
Expand Down
9 changes: 2 additions & 7 deletions src/main/java/de/flavormate/ba_entities/unit/model/Unit.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package de.flavormate.ba_entities.unit.model;

import de.flavormate.aa_interfaces.models.ManualBaseEntity;
import de.flavormate.aa_interfaces.models.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
Expand Down Expand Up @@ -49,17 +49,12 @@
@SuperBuilder
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = true)
@ToString(onlyExplicitlyIncluded = true, callSuper = true)
public class Unit extends ManualBaseEntity {
public class Unit extends BaseEntity {

/**
* The label of the unit. This field is marked as non-nullable in the database.
*/
@NotNull
@Column(nullable = false)
private String label;

/**
* The short label of the unit.
*/
private String shortLabel;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import de.flavormate.ba_entities.unit.model.Unit;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;
import java.util.Optional;
Expand All @@ -10,6 +11,6 @@ public interface UnitRepository extends JpaRepository<Unit, Long> {

Optional<Unit> findByLabel(String label);

List<Unit> findByLabelOrShortLabel(String label, String shortLabel);

@Query(nativeQuery = true, value = "SELECT u.* FROM units u LEFT JOIN ingredients i ON u.id = i.unit_id WHERE i.unit_id IS NULL")
List<Unit> findEmpty();
}
Loading