feat: add grouped field dropdown and composite fields to magic shelf (#2750)
This commit is contained in:
@@ -70,6 +70,32 @@ public enum RuleField {
|
||||
@JsonProperty("ageRating")
|
||||
AGE_RATING,
|
||||
@JsonProperty("contentRating")
|
||||
CONTENT_RATING
|
||||
CONTENT_RATING,
|
||||
@JsonProperty("addedOn")
|
||||
ADDED_ON,
|
||||
@JsonProperty("lubimyczytacRating")
|
||||
LUBIMYCZYTAC_RATING,
|
||||
@JsonProperty("description")
|
||||
DESCRIPTION,
|
||||
@JsonProperty("narrator")
|
||||
NARRATOR,
|
||||
@JsonProperty("audibleRating")
|
||||
AUDIBLE_RATING,
|
||||
@JsonProperty("audibleReviewCount")
|
||||
AUDIBLE_REVIEW_COUNT,
|
||||
@JsonProperty("abridged")
|
||||
ABRIDGED,
|
||||
@JsonProperty("audiobookDuration")
|
||||
AUDIOBOOK_DURATION,
|
||||
@JsonProperty("isPhysical")
|
||||
IS_PHYSICAL,
|
||||
@JsonProperty("seriesStatus")
|
||||
SERIES_STATUS,
|
||||
@JsonProperty("seriesGaps")
|
||||
SERIES_GAPS,
|
||||
@JsonProperty("seriesPosition")
|
||||
SERIES_POSITION,
|
||||
@JsonProperty("readingProgress")
|
||||
READING_PROGRESS
|
||||
}
|
||||
|
||||
|
||||
@@ -34,5 +34,11 @@ public enum RuleOperator {
|
||||
@JsonProperty("excludes_all")
|
||||
EXCLUDES_ALL,
|
||||
@JsonProperty("includes_all")
|
||||
INCLUDES_ALL
|
||||
INCLUDES_ALL,
|
||||
@JsonProperty("within_last")
|
||||
WITHIN_LAST,
|
||||
@JsonProperty("older_than")
|
||||
OLDER_THAN,
|
||||
@JsonProperty("this_period")
|
||||
THIS_PERIOD
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.model.dto.GroupRule;
|
||||
import org.booklore.model.dto.Rule;
|
||||
import org.booklore.model.dto.RuleField;
|
||||
import org.booklore.model.dto.RuleOperator;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.UserBookProgressEntity;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
@@ -13,10 +14,9 @@ import org.springframework.stereotype.Service;
|
||||
import tools.jackson.core.type.TypeReference;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.*;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
import java.util.*;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -28,22 +28,26 @@ public class BookRuleEvaluatorService {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private static final Set<RuleField> COMPOSITE_FIELDS = Set.of(
|
||||
RuleField.SERIES_STATUS, RuleField.SERIES_GAPS, RuleField.SERIES_POSITION
|
||||
);
|
||||
|
||||
public Specification<BookEntity> toSpecification(GroupRule groupRule, Long userId) {
|
||||
return (root, query, cb) -> {
|
||||
Join<BookEntity, UserBookProgressEntity> progressJoin = root.join("userBookProgress", JoinType.LEFT);
|
||||
|
||||
Predicate userPredicate = cb.or(
|
||||
cb.isNull(progressJoin.get("user").get("id")),
|
||||
cb.equal(progressJoin.get("user").get("id"), userId)
|
||||
cb.isNull(progressJoin.get("user").get("id")),
|
||||
cb.equal(progressJoin.get("user").get("id"), userId)
|
||||
);
|
||||
|
||||
Predicate rulePredicate = buildPredicate(groupRule, cb, root, progressJoin);
|
||||
Predicate rulePredicate = buildPredicate(groupRule, query, cb, root, progressJoin, userId);
|
||||
|
||||
return cb.and(userPredicate, rulePredicate);
|
||||
};
|
||||
}
|
||||
|
||||
private Predicate buildPredicate(GroupRule group, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
private Predicate buildPredicate(GroupRule group, CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin, Long userId) {
|
||||
if (group.getRules() == null || group.getRules().isEmpty()) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
@@ -59,11 +63,11 @@ public class BookRuleEvaluatorService {
|
||||
|
||||
if ("group".equals(type)) {
|
||||
GroupRule subGroup = objectMapper.convertValue(ruleObj, GroupRule.class);
|
||||
predicates.add(buildPredicate(subGroup, cb, root, progressJoin));
|
||||
predicates.add(buildPredicate(subGroup, query, cb, root, progressJoin, userId));
|
||||
} else {
|
||||
try {
|
||||
Rule rule = objectMapper.convertValue(ruleObj, Rule.class);
|
||||
Predicate rulePredicate = buildRulePredicate(rule, cb, root, progressJoin);
|
||||
Predicate rulePredicate = buildRulePredicate(rule, query, cb, root, progressJoin, userId);
|
||||
if (rulePredicate != null) {
|
||||
predicates.add(rulePredicate);
|
||||
}
|
||||
@@ -82,9 +86,13 @@ public class BookRuleEvaluatorService {
|
||||
: cb.or(predicates.toArray(new Predicate[0]));
|
||||
}
|
||||
|
||||
private Predicate buildRulePredicate(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
private Predicate buildRulePredicate(Rule rule, CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin, Long userId) {
|
||||
if (rule.getField() == null || rule.getOperator() == null) return null;
|
||||
|
||||
if (COMPOSITE_FIELDS.contains(rule.getField())) {
|
||||
return buildCompositeFieldPredicate(rule, query, cb, root, progressJoin, userId);
|
||||
}
|
||||
|
||||
return switch (rule.getOperator()) {
|
||||
case EQUALS -> buildEquals(rule, cb, root, progressJoin);
|
||||
case NOT_EQUALS -> buildNotEquals(rule, cb, root, progressJoin);
|
||||
@@ -97,14 +105,305 @@ public class BookRuleEvaluatorService {
|
||||
case LESS_THAN -> buildLessThan(rule, cb, root, progressJoin);
|
||||
case LESS_THAN_EQUAL_TO -> buildLessThanEqual(rule, cb, root, progressJoin);
|
||||
case IN_BETWEEN -> buildInBetween(rule, cb, root, progressJoin);
|
||||
case IS_EMPTY -> buildIsEmpty(rule, cb, root, progressJoin);
|
||||
case IS_NOT_EMPTY -> cb.not(buildIsEmpty(rule, cb, root, progressJoin));
|
||||
case IS_EMPTY -> buildIsEmpty(rule, query, cb, root, progressJoin);
|
||||
case IS_NOT_EMPTY -> cb.not(buildIsEmpty(rule, query, cb, root, progressJoin));
|
||||
case INCLUDES_ANY -> buildIncludesAny(rule, cb, root, progressJoin);
|
||||
case EXCLUDES_ALL -> buildExcludesAll(rule, cb, root, progressJoin);
|
||||
case INCLUDES_ALL -> buildIncludesAll(rule, cb, root, progressJoin);
|
||||
case WITHIN_LAST -> buildWithinLast(rule, cb, root, progressJoin);
|
||||
case OLDER_THAN -> buildOlderThan(rule, cb, root, progressJoin);
|
||||
case THIS_PERIOD -> buildThisPeriod(rule, cb, root, progressJoin);
|
||||
};
|
||||
}
|
||||
|
||||
private Predicate buildWithinLast(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
|
||||
if (field == null) return cb.conjunction();
|
||||
|
||||
Instant threshold = computeRelativeDateThreshold(rule);
|
||||
if (threshold == null) return cb.conjunction();
|
||||
|
||||
if (rule.getField() == RuleField.PUBLISHED_DATE) {
|
||||
LocalDateTime ldt = threshold.atZone(ZoneId.systemDefault()).toLocalDateTime();
|
||||
return cb.greaterThanOrEqualTo(field.as(LocalDateTime.class), ldt);
|
||||
}
|
||||
return cb.greaterThanOrEqualTo(field.as(Instant.class), threshold);
|
||||
}
|
||||
|
||||
private Predicate buildOlderThan(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
|
||||
if (field == null) return cb.conjunction();
|
||||
|
||||
Instant threshold = computeRelativeDateThreshold(rule);
|
||||
if (threshold == null) return cb.conjunction();
|
||||
|
||||
if (rule.getField() == RuleField.PUBLISHED_DATE) {
|
||||
LocalDateTime ldt = threshold.atZone(ZoneId.systemDefault()).toLocalDateTime();
|
||||
return cb.lessThan(field.as(LocalDateTime.class), ldt);
|
||||
}
|
||||
return cb.lessThan(field.as(Instant.class), threshold);
|
||||
}
|
||||
|
||||
private Predicate buildThisPeriod(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
|
||||
if (field == null) return cb.conjunction();
|
||||
|
||||
String period = rule.getValue() != null ? rule.getValue().toString().toLowerCase() : "year";
|
||||
LocalDate now = LocalDate.now();
|
||||
LocalDate start = switch (period) {
|
||||
case "week" -> now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
|
||||
case "month" -> now.withDayOfMonth(1);
|
||||
default -> now.withDayOfYear(1);
|
||||
};
|
||||
|
||||
Instant startInstant = start.atStartOfDay(ZoneId.systemDefault()).toInstant();
|
||||
|
||||
if (rule.getField() == RuleField.PUBLISHED_DATE) {
|
||||
LocalDateTime ldt = startInstant.atZone(ZoneId.systemDefault()).toLocalDateTime();
|
||||
return cb.greaterThanOrEqualTo(field.as(LocalDateTime.class), ldt);
|
||||
}
|
||||
return cb.greaterThanOrEqualTo(field.as(Instant.class), startInstant);
|
||||
}
|
||||
|
||||
private Instant computeRelativeDateThreshold(Rule rule) {
|
||||
if (rule.getValue() == null) return null;
|
||||
int amount;
|
||||
try {
|
||||
amount = ((Number) rule.getValue()).intValue();
|
||||
} catch (ClassCastException e) {
|
||||
try {
|
||||
amount = Integer.parseInt(rule.getValue().toString());
|
||||
} catch (NumberFormatException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
String unit = rule.getValueEnd() != null ? rule.getValueEnd().toString().toLowerCase() : "days";
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime threshold = switch (unit) {
|
||||
case "weeks" -> now.minusWeeks(amount);
|
||||
case "months" -> now.minusMonths(amount);
|
||||
case "years" -> now.minusYears(amount);
|
||||
default -> now.minusDays(amount);
|
||||
};
|
||||
return threshold.atZone(ZoneId.systemDefault()).toInstant();
|
||||
}
|
||||
|
||||
private Predicate buildCompositeFieldPredicate(Rule rule, CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin, Long userId) {
|
||||
boolean negate = rule.getOperator() == RuleOperator.NOT_EQUALS;
|
||||
String value = rule.getValue() != null ? rule.getValue().toString().toLowerCase() : "";
|
||||
Predicate hasSeries = cb.and(
|
||||
cb.isNotNull(root.get("metadata").get("seriesName")),
|
||||
cb.notEqual(cb.trim(root.get("metadata").get("seriesName").as(String.class)), "")
|
||||
);
|
||||
|
||||
Predicate result = switch (rule.getField()) {
|
||||
case SERIES_STATUS -> buildSeriesStatusPredicate(value, query, cb, root, hasSeries, userId);
|
||||
case SERIES_GAPS -> buildSeriesGapsPredicate(value, query, cb, root, hasSeries);
|
||||
case SERIES_POSITION -> buildSeriesPositionPredicate(value, query, cb, root, progressJoin, hasSeries, userId);
|
||||
default -> cb.conjunction();
|
||||
};
|
||||
|
||||
return negate ? cb.not(result) : result;
|
||||
}
|
||||
|
||||
private Predicate buildSeriesStatusPredicate(String value, CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root, Predicate hasSeries, Long userId) {
|
||||
Predicate condition = switch (value) {
|
||||
case "reading" -> seriesHasReadStatus(query, cb, root, userId, List.of("READING", "RE_READING"));
|
||||
case "not_started" -> cb.not(seriesHasReadStatus(query, cb, root, userId, List.of("READ", "READING", "RE_READING", "PARTIALLY_READ")));
|
||||
case "fully_read" -> seriesAllRead(query, cb, root, userId);
|
||||
case "completed" -> seriesOwnsLastBook(query, cb, root);
|
||||
case "ongoing" -> cb.and(seriesHasTotal(query, cb, root), cb.not(seriesOwnsLastBook(query, cb, root)));
|
||||
default -> cb.conjunction();
|
||||
};
|
||||
return cb.and(hasSeries, condition);
|
||||
}
|
||||
|
||||
private Predicate seriesHasReadStatus(CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root, Long userId, List<String> statuses) {
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookEntity> subRoot = sub.from(BookEntity.class);
|
||||
Join<Object, Object> subProgress = subRoot.join("userBookProgress", JoinType.INNER);
|
||||
|
||||
sub.select(cb.literal(1L)).where(
|
||||
cb.equal(subRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.equal(subProgress.get("user").get("id"), userId),
|
||||
subProgress.get("readStatus").as(String.class).in(statuses)
|
||||
);
|
||||
return cb.exists(sub);
|
||||
}
|
||||
|
||||
private Predicate seriesAllRead(CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root, Long userId) {
|
||||
Subquery<Long> notReadSub = query.subquery(Long.class);
|
||||
Root<BookEntity> nrRoot = notReadSub.from(BookEntity.class);
|
||||
Join<Object, Object> nrProgress = nrRoot.join("userBookProgress", JoinType.INNER);
|
||||
notReadSub.select(cb.literal(1L)).where(
|
||||
cb.equal(nrRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.equal(nrProgress.get("user").get("id"), userId),
|
||||
cb.notEqual(nrProgress.get("readStatus").as(String.class), "READ")
|
||||
);
|
||||
|
||||
return cb.and(
|
||||
seriesHasReadStatus(query, cb, root, userId, List.of("READ")),
|
||||
cb.not(cb.exists(notReadSub))
|
||||
);
|
||||
}
|
||||
|
||||
private Predicate seriesOwnsLastBook(CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root) {
|
||||
Subquery<Integer> totalSub = query.subquery(Integer.class);
|
||||
Root<BookEntity> totalRoot = totalSub.from(BookEntity.class);
|
||||
totalSub.select(cb.max(totalRoot.get("metadata").get("seriesTotal"))).where(
|
||||
cb.equal(totalRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.isNotNull(totalRoot.get("metadata").get("seriesTotal"))
|
||||
);
|
||||
|
||||
Subquery<Long> existsSub = query.subquery(Long.class);
|
||||
Root<BookEntity> subRoot = existsSub.from(BookEntity.class);
|
||||
existsSub.select(cb.literal(1L)).where(
|
||||
cb.equal(subRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.equal(
|
||||
cb.function("FLOOR", Integer.class, subRoot.get("metadata").get("seriesNumber")),
|
||||
totalSub
|
||||
)
|
||||
);
|
||||
return cb.exists(existsSub);
|
||||
}
|
||||
|
||||
private Predicate seriesHasTotal(CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root) {
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookEntity> subRoot = sub.from(BookEntity.class);
|
||||
sub.select(cb.literal(1L)).where(
|
||||
cb.equal(subRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.isNotNull(subRoot.get("metadata").get("seriesTotal"))
|
||||
);
|
||||
return cb.exists(sub);
|
||||
}
|
||||
|
||||
private Predicate buildSeriesGapsPredicate(String value, CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root, Predicate hasSeries) {
|
||||
Predicate condition = switch (value) {
|
||||
case "any_gap" -> seriesHasAnyGap(query, cb, root);
|
||||
case "missing_first" -> seriesMissingFirst(query, cb, root);
|
||||
case "missing_latest" -> cb.and(seriesHasTotal(query, cb, root), cb.not(seriesOwnsLastBook(query, cb, root)));
|
||||
case "duplicate_number" -> seriesHasDuplicateNumber(query, cb, root);
|
||||
default -> cb.conjunction();
|
||||
};
|
||||
return cb.and(hasSeries, condition);
|
||||
}
|
||||
|
||||
private Predicate seriesHasAnyGap(CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root) {
|
||||
Subquery<Long> countSub = query.subquery(Long.class);
|
||||
Root<BookEntity> cRoot = countSub.from(BookEntity.class);
|
||||
countSub.select(cb.countDistinct(cb.function("FLOOR", Integer.class, cRoot.get("metadata").get("seriesNumber")))).where(
|
||||
cb.equal(cRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.isNotNull(cRoot.get("metadata").get("seriesNumber"))
|
||||
);
|
||||
|
||||
Subquery<Integer> maxSub = query.subquery(Integer.class);
|
||||
Root<BookEntity> mRoot = maxSub.from(BookEntity.class);
|
||||
maxSub.select(cb.max(cb.function("FLOOR", Integer.class, mRoot.get("metadata").get("seriesNumber")))).where(
|
||||
cb.equal(mRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.isNotNull(mRoot.get("metadata").get("seriesNumber"))
|
||||
);
|
||||
|
||||
return cb.lt(countSub, maxSub.as(Long.class));
|
||||
}
|
||||
|
||||
private Predicate seriesMissingFirst(CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root) {
|
||||
Subquery<Long> sub = query.subquery(Long.class);
|
||||
Root<BookEntity> subRoot = sub.from(BookEntity.class);
|
||||
sub.select(cb.literal(1L)).where(
|
||||
cb.equal(subRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.equal(cb.function("FLOOR", Integer.class, subRoot.get("metadata").get("seriesNumber")), 1)
|
||||
);
|
||||
return cb.not(cb.exists(sub));
|
||||
}
|
||||
|
||||
private Predicate seriesHasDuplicateNumber(CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root) {
|
||||
Subquery<Long> totalSub = query.subquery(Long.class);
|
||||
Root<BookEntity> tRoot = totalSub.from(BookEntity.class);
|
||||
totalSub.select(cb.count(tRoot)).where(
|
||||
cb.equal(tRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.isNotNull(tRoot.get("metadata").get("seriesNumber"))
|
||||
);
|
||||
|
||||
Subquery<Long> distinctSub = query.subquery(Long.class);
|
||||
Root<BookEntity> dRoot = distinctSub.from(BookEntity.class);
|
||||
distinctSub.select(cb.countDistinct(dRoot.get("metadata").get("seriesNumber"))).where(
|
||||
cb.equal(dRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.isNotNull(dRoot.get("metadata").get("seriesNumber"))
|
||||
);
|
||||
|
||||
return cb.gt(totalSub, distinctSub);
|
||||
}
|
||||
|
||||
private Predicate buildSeriesPositionPredicate(String value, CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin, Predicate hasSeries, Long userId) {
|
||||
Predicate hasNumber = cb.isNotNull(root.get("metadata").get("seriesNumber"));
|
||||
Predicate condition = switch (value) {
|
||||
case "next_unread" -> isNextUnread(query, cb, root, progressJoin, userId);
|
||||
case "first_in_series" -> isFirstInSeries(query, cb, root);
|
||||
case "last_in_series" -> isLastInSeries(query, cb, root);
|
||||
default -> cb.conjunction();
|
||||
};
|
||||
return cb.and(hasSeries, hasNumber, condition);
|
||||
}
|
||||
|
||||
private Predicate isFirstInSeries(CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root) {
|
||||
Subquery<Float> minSub = query.subquery(Float.class);
|
||||
Root<BookEntity> mRoot = minSub.from(BookEntity.class);
|
||||
minSub.select(cb.min(mRoot.get("metadata").get("seriesNumber"))).where(
|
||||
cb.equal(mRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.isNotNull(mRoot.get("metadata").get("seriesNumber"))
|
||||
);
|
||||
return cb.equal(root.get("metadata").get("seriesNumber"), minSub);
|
||||
}
|
||||
|
||||
private Predicate isLastInSeries(CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root) {
|
||||
Subquery<Float> maxSub = query.subquery(Float.class);
|
||||
Root<BookEntity> mRoot = maxSub.from(BookEntity.class);
|
||||
maxSub.select(cb.max(mRoot.get("metadata").get("seriesNumber"))).where(
|
||||
cb.equal(mRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.isNotNull(mRoot.get("metadata").get("seriesNumber"))
|
||||
);
|
||||
return cb.equal(root.get("metadata").get("seriesNumber"), maxSub);
|
||||
}
|
||||
|
||||
private Predicate isNextUnread(CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin, Long userId) {
|
||||
Predicate notRead = cb.or(
|
||||
cb.isNull(progressJoin.get("readStatus")),
|
||||
cb.notEqual(progressJoin.get("readStatus").as(String.class), "READ")
|
||||
);
|
||||
|
||||
Subquery<Long> lowerUnreadSub = query.subquery(Long.class);
|
||||
Root<BookEntity> luRoot = lowerUnreadSub.from(BookEntity.class);
|
||||
Join<Object, Object> luProgress = luRoot.join("userBookProgress", JoinType.LEFT);
|
||||
lowerUnreadSub.select(cb.literal(1L)).where(
|
||||
cb.equal(luRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.isNotNull(luRoot.get("metadata").get("seriesNumber")),
|
||||
cb.lt(luRoot.get("metadata").get("seriesNumber"), root.get("metadata").get("seriesNumber")),
|
||||
cb.or(
|
||||
cb.isNull(luProgress.get("readStatus")),
|
||||
cb.notEqual(luProgress.get("readStatus").as(String.class), "READ")
|
||||
),
|
||||
cb.or(
|
||||
cb.isNull(luProgress.get("user").get("id")),
|
||||
cb.equal(luProgress.get("user").get("id"), userId)
|
||||
)
|
||||
);
|
||||
Predicate noLowerUnread = cb.not(cb.exists(lowerUnreadSub));
|
||||
|
||||
Subquery<Long> priorReadSub = query.subquery(Long.class);
|
||||
Root<BookEntity> prRoot = priorReadSub.from(BookEntity.class);
|
||||
Join<Object, Object> prProgress = prRoot.join("userBookProgress", JoinType.INNER);
|
||||
priorReadSub.select(cb.literal(1L)).where(
|
||||
cb.equal(prRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
|
||||
cb.isNotNull(prRoot.get("metadata").get("seriesNumber")),
|
||||
cb.lt(prRoot.get("metadata").get("seriesNumber"), root.get("metadata").get("seriesNumber")),
|
||||
cb.equal(prProgress.get("user").get("id"), userId),
|
||||
cb.equal(prProgress.get("readStatus").as(String.class), "READ")
|
||||
);
|
||||
Predicate hasPriorRead = cb.exists(priorReadSub);
|
||||
|
||||
return cb.and(notRead, noLowerUnread, hasPriorRead);
|
||||
}
|
||||
|
||||
private Predicate buildEquals(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
List<String> ruleList = toStringList(rule.getValue());
|
||||
|
||||
@@ -117,7 +416,9 @@ public class BookRuleEvaluatorService {
|
||||
|
||||
Object value = normalizeValue(rule.getValue(), rule.getField());
|
||||
|
||||
if (value instanceof LocalDateTime) {
|
||||
if (value instanceof Boolean) {
|
||||
return cb.equal(field, value);
|
||||
} else if (value instanceof LocalDateTime) {
|
||||
return cb.equal(field, value);
|
||||
} else if (rule.getField() == RuleField.READ_STATUS) {
|
||||
if ("UNSET".equals(value.toString())) {
|
||||
@@ -137,25 +438,25 @@ public class BookRuleEvaluatorService {
|
||||
private Predicate buildContains(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
String ruleVal = rule.getValue().toString().toLowerCase();
|
||||
return buildStringPredicate(rule.getField(), root, progressJoin, cb,
|
||||
nameField -> cb.like(cb.lower(nameField), "%" + escapeLike(ruleVal) + "%"));
|
||||
nameField -> cb.like(cb.lower(nameField), "%" + escapeLike(ruleVal) + "%"));
|
||||
}
|
||||
|
||||
private Predicate buildStartsWith(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
String ruleVal = rule.getValue().toString().toLowerCase();
|
||||
return buildStringPredicate(rule.getField(), root, progressJoin, cb,
|
||||
nameField -> cb.like(cb.lower(nameField), escapeLike(ruleVal) + "%"));
|
||||
nameField -> cb.like(cb.lower(nameField), escapeLike(ruleVal) + "%"));
|
||||
}
|
||||
|
||||
private Predicate buildEndsWith(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
String ruleVal = rule.getValue().toString().toLowerCase();
|
||||
return buildStringPredicate(rule.getField(), root, progressJoin, cb,
|
||||
nameField -> cb.like(cb.lower(nameField), "%" + escapeLike(ruleVal)));
|
||||
nameField -> cb.like(cb.lower(nameField), "%" + escapeLike(ruleVal)));
|
||||
}
|
||||
|
||||
private Predicate buildStringPredicate(RuleField field, Root<BookEntity> root,
|
||||
Join<BookEntity, UserBookProgressEntity> progressJoin,
|
||||
CriteriaBuilder cb,
|
||||
java.util.function.Function<Expression<String>, Predicate> predicateBuilder) {
|
||||
Join<BookEntity, UserBookProgressEntity> progressJoin,
|
||||
CriteriaBuilder cb,
|
||||
java.util.function.Function<Expression<String>, Predicate> predicateBuilder) {
|
||||
if (isArrayField(field)) {
|
||||
Join<?, ?> arrayJoin = createArrayFieldJoin(field, root);
|
||||
Expression<String> nameField = getArrayFieldNameExpression(field, arrayJoin);
|
||||
@@ -170,32 +471,32 @@ public class BookRuleEvaluatorService {
|
||||
|
||||
private Predicate buildGreaterThan(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
return buildComparisonPredicate(rule, cb, root, progressJoin,
|
||||
(field, dateValue) -> cb.greaterThan(field.as(LocalDateTime.class), dateValue),
|
||||
(field, numValue) -> cb.gt(field.as(Number.class), numValue));
|
||||
(field, dateValue) -> cb.greaterThan(field.as(LocalDateTime.class), dateValue),
|
||||
(field, numValue) -> cb.gt(field.as(Double.class), numValue));
|
||||
}
|
||||
|
||||
private Predicate buildGreaterThanEqual(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
return buildComparisonPredicate(rule, cb, root, progressJoin,
|
||||
(field, dateValue) -> cb.greaterThanOrEqualTo(field.as(LocalDateTime.class), dateValue),
|
||||
(field, numValue) -> cb.ge(field.as(Number.class), numValue));
|
||||
(field, dateValue) -> cb.greaterThanOrEqualTo(field.as(LocalDateTime.class), dateValue),
|
||||
(field, numValue) -> cb.ge(field.as(Double.class), numValue));
|
||||
}
|
||||
|
||||
private Predicate buildLessThan(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
return buildComparisonPredicate(rule, cb, root, progressJoin,
|
||||
(field, dateValue) -> cb.lessThan(field.as(LocalDateTime.class), dateValue),
|
||||
(field, numValue) -> cb.lt(field.as(Number.class), numValue));
|
||||
(field, dateValue) -> cb.lessThan(field.as(LocalDateTime.class), dateValue),
|
||||
(field, numValue) -> cb.lt(field.as(Double.class), numValue));
|
||||
}
|
||||
|
||||
private Predicate buildLessThanEqual(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
return buildComparisonPredicate(rule, cb, root, progressJoin,
|
||||
(field, dateValue) -> cb.lessThanOrEqualTo(field.as(LocalDateTime.class), dateValue),
|
||||
(field, numValue) -> cb.le(field.as(Number.class), numValue));
|
||||
(field, dateValue) -> cb.lessThanOrEqualTo(field.as(LocalDateTime.class), dateValue),
|
||||
(field, numValue) -> cb.le(field.as(Double.class), numValue));
|
||||
}
|
||||
|
||||
private Predicate buildComparisonPredicate(Rule rule, CriteriaBuilder cb, Root<BookEntity> root,
|
||||
Join<BookEntity, UserBookProgressEntity> progressJoin,
|
||||
BiFunction<Expression<?>, LocalDateTime, Predicate> dateComparator,
|
||||
BiFunction<Expression<?>, Double, Predicate> numberComparator) {
|
||||
Join<BookEntity, UserBookProgressEntity> progressJoin,
|
||||
BiFunction<Expression<?>, LocalDateTime, Predicate> dateComparator,
|
||||
BiFunction<Expression<?>, Double, Predicate> numberComparator) {
|
||||
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
|
||||
if (field == null) return cb.conjunction();
|
||||
|
||||
@@ -227,9 +528,9 @@ public class BookRuleEvaluatorService {
|
||||
return cb.between(field.as(Double.class), ((Number) start).doubleValue(), ((Number) end).doubleValue());
|
||||
}
|
||||
|
||||
private Predicate buildIsEmpty(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
private Predicate buildIsEmpty(Rule rule, CriteriaQuery<?> query, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
if (isArrayField(rule.getField())) {
|
||||
Subquery<Long> subquery = cb.createQuery().subquery(Long.class);
|
||||
Subquery<Long> subquery = query.subquery(Long.class);
|
||||
Root<BookEntity> subRoot = subquery.from(BookEntity.class);
|
||||
|
||||
if (rule.getField() == RuleField.SHELF) {
|
||||
@@ -281,10 +582,10 @@ public class BookRuleEvaluatorService {
|
||||
}
|
||||
|
||||
private Predicate buildFieldInPredicate(RuleField ruleField,
|
||||
java.util.function.Function<Expression<?>, Expression<?>> fieldTransformer,
|
||||
List<String> ruleList,
|
||||
CriteriaBuilder cb,
|
||||
Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
java.util.function.Function<Expression<?>, Expression<?>> fieldTransformer,
|
||||
List<String> ruleList,
|
||||
CriteriaBuilder cb,
|
||||
Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
Expression<?> field = fieldTransformer.apply(getFieldExpression(ruleField, cb, null, progressJoin));
|
||||
if (field == null) return cb.conjunction();
|
||||
|
||||
@@ -296,8 +597,8 @@ public class BookRuleEvaluatorService {
|
||||
|
||||
if (hasUnset && !nonUnsetValues.isEmpty()) {
|
||||
return cb.or(
|
||||
cb.isNull(field),
|
||||
field.as(String.class).in(nonUnsetValues)
|
||||
cb.isNull(field),
|
||||
field.as(String.class).in(nonUnsetValues)
|
||||
);
|
||||
} else if (hasUnset) {
|
||||
return cb.isNull(field);
|
||||
@@ -313,7 +614,7 @@ public class BookRuleEvaluatorService {
|
||||
private Expression<?> getFieldExpression(RuleField field, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||
return switch (field) {
|
||||
case LIBRARY -> root.get("library").get("id");
|
||||
case SHELF -> null; // Shelf is handled specially as a join field
|
||||
case SHELF -> null;
|
||||
case READ_STATUS -> progressJoin.get("readStatus");
|
||||
case DATE_FINISHED -> progressJoin.get("dateFinished");
|
||||
case LAST_READ_TIME -> progressJoin.get("lastReadTime");
|
||||
@@ -340,6 +641,23 @@ public class BookRuleEvaluatorService {
|
||||
case RANOBEDB_RATING -> root.get("metadata").get("ranobedbRating");
|
||||
case AGE_RATING -> root.get("metadata").get("ageRating");
|
||||
case CONTENT_RATING -> root.get("metadata").get("contentRating");
|
||||
case ADDED_ON -> root.get("addedOn");
|
||||
case LUBIMYCZYTAC_RATING -> root.get("metadata").get("lubimyczytacRating");
|
||||
case DESCRIPTION -> root.get("metadata").get("description");
|
||||
case NARRATOR -> root.get("metadata").get("narrator");
|
||||
case AUDIBLE_RATING -> root.get("metadata").get("audibleRating");
|
||||
case AUDIBLE_REVIEW_COUNT -> root.get("metadata").get("audibleReviewCount");
|
||||
case ABRIDGED -> root.get("metadata").get("abridged");
|
||||
case AUDIOBOOK_DURATION -> root.join("bookFiles", JoinType.LEFT).get("durationSeconds");
|
||||
case IS_PHYSICAL -> root.get("isPhysical");
|
||||
case READING_PROGRESS -> {
|
||||
Expression<Float> koreader = cb.coalesce(progressJoin.get("koreaderProgressPercent"), 0f);
|
||||
Expression<Float> kobo = cb.coalesce(progressJoin.get("koboProgressPercent"), 0f);
|
||||
Expression<Float> pdf = cb.coalesce(progressJoin.get("pdfProgressPercent"), 0f);
|
||||
Expression<Float> epub = cb.coalesce(progressJoin.get("epubProgressPercent"), 0f);
|
||||
Expression<Float> cbx = cb.coalesce(progressJoin.get("cbxProgressPercent"), 0f);
|
||||
yield cb.function("GREATEST", Float.class, koreader, kobo, pdf, epub, cbx);
|
||||
}
|
||||
case FILE_TYPE -> cb.function("SUBSTRING_INDEX", String.class,
|
||||
root.get("fileName"), cb.literal("."), cb.literal(-1));
|
||||
default -> null;
|
||||
@@ -348,8 +666,8 @@ public class BookRuleEvaluatorService {
|
||||
|
||||
private boolean isArrayField(RuleField field) {
|
||||
return field == RuleField.AUTHORS || field == RuleField.CATEGORIES ||
|
||||
field == RuleField.MOODS || field == RuleField.TAGS ||
|
||||
field == RuleField.GENRE || field == RuleField.SHELF;
|
||||
field == RuleField.MOODS || field == RuleField.TAGS ||
|
||||
field == RuleField.GENRE || field == RuleField.SHELF;
|
||||
}
|
||||
|
||||
private Join<?, ?> createArrayFieldJoin(RuleField field, Root<BookEntity> root) {
|
||||
@@ -411,7 +729,7 @@ public class BookRuleEvaluatorService {
|
||||
return parseDate(value);
|
||||
}
|
||||
|
||||
if (field == RuleField.DATE_FINISHED || field == RuleField.LAST_READ_TIME) {
|
||||
if (field == RuleField.DATE_FINISHED || field == RuleField.LAST_READ_TIME || field == RuleField.ADDED_ON) {
|
||||
LocalDateTime parsed = parseDate(value);
|
||||
if (parsed != null) {
|
||||
return parsed.atZone(ZoneId.systemDefault()).toInstant();
|
||||
@@ -423,6 +741,10 @@ public class BookRuleEvaluatorService {
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
if (field == RuleField.ABRIDGED || field == RuleField.IS_PHYSICAL) {
|
||||
return Boolean.valueOf(value.toString());
|
||||
}
|
||||
|
||||
if (value instanceof Number) {
|
||||
return value;
|
||||
}
|
||||
@@ -458,7 +780,7 @@ public class BookRuleEvaluatorService {
|
||||
|
||||
private String escapeLike(String value) {
|
||||
return value.replace("\\", "\\\\")
|
||||
.replace("%", "\\%")
|
||||
.replace("_", "\\_");
|
||||
.replace("%", "\\%")
|
||||
.replace("_", "\\_");
|
||||
}
|
||||
}
|
||||
|
||||
+1532
File diff suppressed because it is too large
Load Diff
+3
-2
@@ -165,8 +165,9 @@ export class BookBrowserEntityService {
|
||||
if (!bookState.loaded || bookState.error || !magicShelf?.filterJson) {
|
||||
return bookState;
|
||||
}
|
||||
const filteredBooks: Book[] | undefined = bookState.books?.filter(book =>
|
||||
this.bookRuleEvaluatorService.evaluateGroup(book, JSON.parse(magicShelf.filterJson!) as GroupRule)
|
||||
const allBooks = bookState.books ?? [];
|
||||
const filteredBooks = allBooks.filter(book =>
|
||||
this.bookRuleEvaluatorService.evaluateGroup(book, JSON.parse(magicShelf.filterJson!) as GroupRule, allBooks)
|
||||
);
|
||||
const sortedBooks = this.sortService.applySort(filteredBooks ?? [], sortOption);
|
||||
return {...bookState, books: sortedBooks};
|
||||
|
||||
+1
-1
@@ -204,7 +204,7 @@ export class BookFilterService {
|
||||
if (!magicShelf.filterJson) return [];
|
||||
try {
|
||||
const groupRule = JSON.parse(magicShelf.filterJson) as GroupRule;
|
||||
return books.filter(book => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule));
|
||||
return books.filter(book => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule, books));
|
||||
} catch {
|
||||
console.warn('Invalid filterJson for MagicShelf');
|
||||
return [];
|
||||
|
||||
+3
-2
@@ -166,8 +166,9 @@ export class MainDashboardComponent implements OnInit {
|
||||
|
||||
return this.bookService.bookState$.pipe(
|
||||
map((state: BookState) => {
|
||||
const filteredBooks = (state.books || []).filter((book) =>
|
||||
this.ruleEvaluatorService.evaluateGroup(book, group)
|
||||
const allBooks = state.books || [];
|
||||
const filteredBooks = allBooks.filter((book) =>
|
||||
this.ruleEvaluatorService.evaluateGroup(book, group, allBooks)
|
||||
);
|
||||
|
||||
return maxItems ? filteredBooks.slice(0, maxItems) : filteredBooks;
|
||||
|
||||
@@ -116,15 +116,20 @@
|
||||
<ng-container *ngTemplateOutlet="groupTemplate; context: { group: ruleCtrl }"></ng-container>
|
||||
</ng-container>
|
||||
} @else {
|
||||
<p-select [options]="fieldOptions" formControlName="field" (onChange)="onFieldChange(ruleCtrl)" [placeholder]="t('placeholders.field')" appendTo="body" class="field-select"/>
|
||||
<p-select [options]="fieldOptions" [group]="true" optionGroupLabel="label" optionGroupChildren="items" [filter]="true" filterBy="label" formControlName="field" (onChange)="onFieldChange(ruleCtrl)" [placeholder]="t('placeholders.field')" appendTo="body" class="field-select"/>
|
||||
<p-select [options]="getOperatorOptionsForField(ruleCtrl.get('field')?.value)" appendTo="body" formControlName="operator" [placeholder]="t('placeholders.operator')" class="operator-select" (onChange)="onOperatorChange(ruleCtrl)"/>
|
||||
|
||||
@if (!['is_empty', 'is_not_empty'].includes(ruleCtrl.get('operator')?.value)) {
|
||||
@if (ruleCtrl.get('operator')?.value === 'in_between') {
|
||||
@if (['within_last', 'older_than'].includes(ruleCtrl.get('operator')?.value)) {
|
||||
<p-inputNumber formControlName="value" class="value-input" [min]="1" [placeholder]="t('placeholders.amount')" [showButtons]="true"></p-inputNumber>
|
||||
<p-select [options]="dateUnitOptions" formControlName="valueEnd" [placeholder]="t('placeholders.selectUnit')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('operator')?.value === 'this_period') {
|
||||
<p-select [options]="datePeriodOptions" formControlName="value" [placeholder]="t('placeholders.selectPeriod')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('operator')?.value === 'in_between') {
|
||||
@if (ruleCtrl.get('field')?.value === 'publishedDate') {
|
||||
<p-datepicker [formControl]="ruleCtrl.get('valueStart')" dateFormat="dd-M-yy" [placeholder]="t('placeholders.startYear')" appendTo="body" fluid class="value-input"></p-datepicker>
|
||||
<p-datepicker [formControl]="ruleCtrl.get('valueEnd')" dateFormat="dd-M-yy" [placeholder]="t('placeholders.endYear')" appendTo="body" fluid class="value-input"></p-datepicker>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'dateFinished') {
|
||||
} @else if (['dateFinished', 'addedOn', 'lastReadTime'].includes(ruleCtrl.get('field')?.value)) {
|
||||
<p-datepicker [formControl]="ruleCtrl.get('valueStart')" dateFormat="dd-M-yy" [placeholder]="t('placeholders.startDate')" appendTo="body" fluid class="value-input"></p-datepicker>
|
||||
<p-datepicker [formControl]="ruleCtrl.get('valueEnd')" dateFormat="dd-M-yy" [placeholder]="t('placeholders.endDate')" appendTo="body" fluid class="value-input"></p-datepicker>
|
||||
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'number') {
|
||||
@@ -140,12 +145,20 @@
|
||||
} @else {
|
||||
@if (ruleCtrl.get('field')?.value === 'publishedDate') {
|
||||
<p-datepicker formControlName="value" dateFormat="dd-M-yy" appendTo="body" fluid class="value-input"></p-datepicker>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'dateFinished') {
|
||||
} @else if (['dateFinished', 'addedOn', 'lastReadTime'].includes(ruleCtrl.get('field')?.value)) {
|
||||
<p-datepicker formControlName="value" dateFormat="dd-M-yy" appendTo="body" fluid class="value-input"></p-datepicker>
|
||||
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'boolean') {
|
||||
<p-select [options]="booleanOptions" formControlName="value" [placeholder]="t('placeholders.selectValue')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'number') {
|
||||
<p-inputNumber formControlName="value" class="value-input" mode="decimal" [placeholder]="t('placeholders.value')" [showButtons]="true"></p-inputNumber>
|
||||
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'decimal') {
|
||||
<p-inputNumber formControlName="value" mode="decimal" [minFractionDigits]="1" [maxFractionDigits]="1" [min]="0" [max]="numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.max || 10" class="value-input" [placeholder]="t('placeholders.value')"></p-inputNumber>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'seriesStatus') {
|
||||
<p-select [options]="seriesStatusOptions" formControlName="value" [placeholder]="t('placeholders.selectSeriesStatus')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'seriesGaps') {
|
||||
<p-select [options]="seriesGapsOptions" formControlName="value" [placeholder]="t('placeholders.selectSeriesGap')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'seriesPosition') {
|
||||
<p-select [options]="seriesPositionOptions" formControlName="value" [placeholder]="t('placeholders.selectSeriesPosition')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (['includes_any', 'includes_all', 'excludes_all'].includes(ruleCtrl.get('operator')?.value)) {
|
||||
@if (ruleCtrl.get('field')?.value === 'readStatus') {
|
||||
<p-multiSelect [options]="readStatusOptions" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectStatuses')"></p-multiSelect>
|
||||
@@ -157,6 +170,8 @@
|
||||
<p-multiSelect [options]="shelfOptions" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectShelves')"></p-multiSelect>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'categories') {
|
||||
<p-multiSelect [options]="categoryOptions" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectGenres')"></p-multiSelect>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'contentRating') {
|
||||
<p-multiSelect [options]="contentRatingOptions" formControlName="value" display="chip" class="value-input" appendTo="body" [placeholder]="t('placeholders.selectContentRatings')"></p-multiSelect>
|
||||
} @else {
|
||||
<div class="autocomplete-wrapper">
|
||||
<p-autoComplete [formControl]="ruleCtrl.get('value')" [multiple]="true" [typeahead]="false" [dropdown]="false" [forceSelection]="false" [placeholder]="t('placeholders.enterValues')" (onBlur)="onAutoCompleteBlur(ruleCtrl.get('value'), $event)"></p-autoComplete>
|
||||
@@ -172,6 +187,8 @@
|
||||
<p-select [options]="shelfOptions" formControlName="value" [placeholder]="t('placeholders.selectShelf')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'categories') {
|
||||
<p-select [options]="categoryOptions" formControlName="value" [placeholder]="t('placeholders.selectGenre')" appendTo="body" class="value-input"></p-select>
|
||||
} @else if (ruleCtrl.get('field')?.value === 'contentRating') {
|
||||
<p-select [options]="contentRatingOptions" formControlName="value" [placeholder]="t('placeholders.selectContentRating')" appendTo="body" class="value-input"></p-select>
|
||||
} @else {
|
||||
<input pInputText formControlName="value" class="value-input" [placeholder]="t('placeholders.value')"/>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,603 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {MagicShelfComponent, Rule} from './magic-shelf-component';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {LibraryService} from '../../book/service/library.service';
|
||||
import {ShelfService} from '../../book/service/shelf.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {MagicShelfService} from '../service/magic-shelf.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
import {IconPickerService} from '../../../shared/service/icon-picker.service';
|
||||
import {of} from 'rxjs';
|
||||
|
||||
describe('MagicShelfComponent (Part 3)', () => {
|
||||
let component: MagicShelfComponent;
|
||||
|
||||
const mockTransloco = {
|
||||
translate: vi.fn((key: string) => key),
|
||||
selectTranslation: vi.fn(() => of({})),
|
||||
langChanges$: of('en'),
|
||||
getActiveLang: vi.fn(() => 'en'),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{provide: TranslocoService, useValue: mockTransloco},
|
||||
{provide: LibraryService, useValue: {getLibrariesFromState: vi.fn(() => [])}},
|
||||
{provide: ShelfService, useValue: {getShelvesFromState: vi.fn(() => [])}},
|
||||
{provide: BookService, useValue: {bookState$: of({loaded: false, books: []})}},
|
||||
{provide: MagicShelfService, useValue: {}},
|
||||
{provide: MessageService, useValue: {add: vi.fn()}},
|
||||
{provide: DynamicDialogRef, useValue: {close: vi.fn()}},
|
||||
{provide: DynamicDialogConfig, useValue: {data: null}},
|
||||
{provide: UserService, useValue: {getCurrentUser: vi.fn(() => ({permissions: {admin: false}}))}},
|
||||
{provide: IconPickerService, useValue: {open: vi.fn(() => of(null))}},
|
||||
]
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(MagicShelfComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
describe('getOperatorOptionsForField', () => {
|
||||
it('should return is/isNot operators for seriesStatus', () => {
|
||||
const operators = component.getOperatorOptionsForField('seriesStatus');
|
||||
expect(operators).toHaveLength(2);
|
||||
expect(operators.map(o => o.value)).toEqual(['equals', 'not_equals']);
|
||||
expect(operators[0].label).toContain('is');
|
||||
});
|
||||
|
||||
it('should return is/isNot operators for seriesPosition', () => {
|
||||
const operators = component.getOperatorOptionsForField('seriesPosition');
|
||||
expect(operators).toHaveLength(2);
|
||||
expect(operators.map(o => o.value)).toEqual(['equals', 'not_equals']);
|
||||
});
|
||||
|
||||
it('should return has/hasNot operators for seriesGaps', () => {
|
||||
const operators = component.getOperatorOptionsForField('seriesGaps');
|
||||
expect(operators).toHaveLength(2);
|
||||
expect(operators.map(o => o.value)).toEqual(['equals', 'not_equals']);
|
||||
expect(operators[0].label).toContain('has');
|
||||
});
|
||||
|
||||
it('should include relative date operators for date fields', () => {
|
||||
const operators = component.getOperatorOptionsForField('dateFinished');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('within_last');
|
||||
expect(values).toContain('older_than');
|
||||
expect(values).toContain('this_period');
|
||||
});
|
||||
|
||||
it('should include relative date operators for addedOn', () => {
|
||||
const operators = component.getOperatorOptionsForField('addedOn');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('within_last');
|
||||
expect(values).toContain('older_than');
|
||||
expect(values).toContain('this_period');
|
||||
});
|
||||
|
||||
it('should include relative date operators for publishedDate', () => {
|
||||
const operators = component.getOperatorOptionsForField('publishedDate');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('within_last');
|
||||
expect(values).toContain('older_than');
|
||||
expect(values).toContain('this_period');
|
||||
});
|
||||
|
||||
it('should NOT include relative date operators for number fields', () => {
|
||||
const operators = component.getOperatorOptionsForField('pageCount');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).not.toContain('within_last');
|
||||
expect(values).not.toContain('older_than');
|
||||
expect(values).not.toContain('this_period');
|
||||
});
|
||||
|
||||
it('should include comparison operators for readingProgress', () => {
|
||||
const operators = component.getOperatorOptionsForField('readingProgress');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('greater_than');
|
||||
expect(values).toContain('less_than');
|
||||
expect(values).toContain('in_between');
|
||||
});
|
||||
|
||||
it('should NOT include relative date operators for readingProgress', () => {
|
||||
const operators = component.getOperatorOptionsForField('readingProgress');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).not.toContain('within_last');
|
||||
});
|
||||
|
||||
it('should return only base operators for boolean fields', () => {
|
||||
const operators = component.getOperatorOptionsForField('abridged');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('equals');
|
||||
expect(values).toContain('not_equals');
|
||||
expect(values).toContain('is_empty');
|
||||
expect(values).toContain('is_not_empty');
|
||||
expect(values).not.toContain('contains');
|
||||
expect(values).not.toContain('greater_than');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildRuleFromData', () => {
|
||||
it('should parse within_last value as number, not date', () => {
|
||||
const rule: Rule = {field: 'dateFinished', operator: 'within_last', value: 30, valueEnd: 'days'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe(30);
|
||||
expect(formGroup.get('valueEnd')?.value).toBe('days');
|
||||
});
|
||||
|
||||
it('should preserve this_period value as string', () => {
|
||||
const rule: Rule = {field: 'addedOn', operator: 'this_period', value: 'month'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe('month');
|
||||
expect(formGroup.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should parse older_than value as number', () => {
|
||||
const rule: Rule = {field: 'lastReadTime', operator: 'older_than', value: 6, valueEnd: 'months'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe(6);
|
||||
expect(formGroup.get('valueEnd')?.value).toBe('months');
|
||||
});
|
||||
|
||||
it('should still parse regular date values as Date objects', () => {
|
||||
const rule: Rule = {field: 'dateFinished', operator: 'equals', value: '2024-06-15'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('should parse composite field values as strings', () => {
|
||||
const rule: Rule = {field: 'seriesStatus', operator: 'equals', value: 'reading'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe('reading');
|
||||
});
|
||||
|
||||
it('should parse readingProgress values as numbers', () => {
|
||||
const rule: Rule = {field: 'readingProgress', operator: 'greater_than', value: 50};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe(50);
|
||||
});
|
||||
});
|
||||
|
||||
describe('onOperatorChange', () => {
|
||||
it('should set valueEnd to days for within_last operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('within_last');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBe('days');
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should set valueEnd to days for older_than operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('older_than');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBe('days');
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should set valueEnd to null for this_period operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('this_period');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should set value to empty array for includes_any operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('includes_any');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toEqual([]);
|
||||
});
|
||||
|
||||
it('should clear all values for is_empty operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('value')?.setValue('something');
|
||||
ruleCtrl.get('operator')?.setValue('is_empty');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueStart')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('option getters', () => {
|
||||
it('should return 5 series status options', () => {
|
||||
const options = component.seriesStatusOptions;
|
||||
expect(options).toHaveLength(5);
|
||||
expect(options.map(o => o.value)).toEqual(['reading', 'completed', 'ongoing', 'not_started', 'fully_read']);
|
||||
});
|
||||
|
||||
it('should return 4 series gaps options', () => {
|
||||
const options = component.seriesGapsOptions;
|
||||
expect(options).toHaveLength(4);
|
||||
expect(options.map(o => o.value)).toEqual(['any_gap', 'missing_first', 'missing_latest', 'duplicate_number']);
|
||||
});
|
||||
|
||||
it('should return 3 series position options', () => {
|
||||
const options = component.seriesPositionOptions;
|
||||
expect(options).toHaveLength(3);
|
||||
expect(options.map(o => o.value)).toEqual(['next_unread', 'first_in_series', 'last_in_series']);
|
||||
});
|
||||
|
||||
it('should return 4 date unit options', () => {
|
||||
const options = component.dateUnitOptions;
|
||||
expect(options).toHaveLength(4);
|
||||
expect(options.map(o => o.value)).toEqual(['days', 'weeks', 'months', 'years']);
|
||||
});
|
||||
|
||||
it('should return 3 date period options', () => {
|
||||
const options = component.datePeriodOptions;
|
||||
expect(options).toHaveLength(3);
|
||||
expect(options.map(o => o.value)).toEqual(['week', 'month', 'year']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fieldOptions grouping', () => {
|
||||
it('should include readingProgress in organization group', () => {
|
||||
const groups = component.fieldOptions;
|
||||
const orgGroup = groups.find(g => g.label.includes('organization'));
|
||||
const fieldValues = orgGroup?.items.map(i => i.value) ?? [];
|
||||
expect(fieldValues).toContain('readingProgress');
|
||||
});
|
||||
|
||||
it('should include seriesStatus, seriesGaps, seriesPosition in series group', () => {
|
||||
const groups = component.fieldOptions;
|
||||
const seriesGroup = groups.find(g => g.label.includes('series'));
|
||||
const fieldValues = seriesGroup?.items.map(i => i.value) ?? [];
|
||||
expect(fieldValues).toContain('seriesStatus');
|
||||
expect(fieldValues).toContain('seriesGaps');
|
||||
expect(fieldValues).toContain('seriesPosition');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getOperatorOptionsForField edge cases', () => {
|
||||
it('should return baseOperators + multiValueOperators for null field', () => {
|
||||
const operators = component.getOperatorOptionsForField(null);
|
||||
const values = operators.map(o => o.value);
|
||||
expect(operators).toHaveLength(7);
|
||||
expect(values).toContain('equals');
|
||||
expect(values).toContain('not_equals');
|
||||
expect(values).toContain('is_empty');
|
||||
expect(values).toContain('is_not_empty');
|
||||
expect(values).toContain('includes_any');
|
||||
expect(values).toContain('excludes_all');
|
||||
expect(values).toContain('includes_all');
|
||||
});
|
||||
|
||||
it('should return baseOperators + multiValueOperators for undefined field', () => {
|
||||
const operators = component.getOperatorOptionsForField(undefined);
|
||||
const values = operators.map(o => o.value);
|
||||
expect(operators).toHaveLength(7);
|
||||
expect(values).toContain('equals');
|
||||
expect(values).toContain('not_equals');
|
||||
expect(values).toContain('is_empty');
|
||||
expect(values).toContain('is_not_empty');
|
||||
expect(values).toContain('includes_any');
|
||||
expect(values).toContain('excludes_all');
|
||||
expect(values).toContain('includes_all');
|
||||
});
|
||||
|
||||
it('should include text operators for title field', () => {
|
||||
const operators = component.getOperatorOptionsForField('title');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('contains');
|
||||
expect(values).toContain('does_not_contain');
|
||||
expect(values).toContain('starts_with');
|
||||
expect(values).toContain('ends_with');
|
||||
expect(values).toContain('includes_any');
|
||||
expect(values).toContain('excludes_all');
|
||||
expect(values).toContain('includes_all');
|
||||
});
|
||||
|
||||
it('should NOT include text operators for library field', () => {
|
||||
const operators = component.getOperatorOptionsForField('library');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('includes_any');
|
||||
expect(values).not.toContain('contains');
|
||||
expect(values).not.toContain('does_not_contain');
|
||||
expect(values).not.toContain('starts_with');
|
||||
expect(values).not.toContain('ends_with');
|
||||
});
|
||||
|
||||
it('should NOT include text operators for readStatus field', () => {
|
||||
const operators = component.getOperatorOptionsForField('readStatus');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('includes_any');
|
||||
expect(values).not.toContain('contains');
|
||||
expect(values).not.toContain('does_not_contain');
|
||||
expect(values).not.toContain('starts_with');
|
||||
expect(values).not.toContain('ends_with');
|
||||
});
|
||||
|
||||
it('should include comparison operators for metadataScore', () => {
|
||||
const operators = component.getOperatorOptionsForField('metadataScore');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('greater_than');
|
||||
expect(values).toContain('greater_than_equal_to');
|
||||
expect(values).toContain('less_than');
|
||||
expect(values).toContain('less_than_equal_to');
|
||||
expect(values).toContain('in_between');
|
||||
});
|
||||
|
||||
it('should include relative date operators for lastReadTime', () => {
|
||||
const operators = component.getOperatorOptionsForField('lastReadTime');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('within_last');
|
||||
expect(values).toContain('older_than');
|
||||
expect(values).toContain('this_period');
|
||||
});
|
||||
|
||||
it('should NOT include comparison operators for string fields', () => {
|
||||
const operators = component.getOperatorOptionsForField('title');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).not.toContain('greater_than');
|
||||
expect(values).not.toContain('greater_than_equal_to');
|
||||
expect(values).not.toContain('less_than');
|
||||
expect(values).not.toContain('less_than_equal_to');
|
||||
expect(values).not.toContain('in_between');
|
||||
});
|
||||
|
||||
it('should include both text and multi-value operators for authors', () => {
|
||||
const operators = component.getOperatorOptionsForField('authors');
|
||||
const values = operators.map(o => o.value);
|
||||
expect(values).toContain('contains');
|
||||
expect(values).toContain('does_not_contain');
|
||||
expect(values).toContain('starts_with');
|
||||
expect(values).toContain('ends_with');
|
||||
expect(values).toContain('includes_any');
|
||||
expect(values).toContain('excludes_all');
|
||||
expect(values).toContain('includes_all');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildRuleFromData edge cases', () => {
|
||||
it('should handle in_between for date fields', () => {
|
||||
const rule: Rule = {field: 'publishedDate', operator: 'in_between' as any, value: null, valueStart: '2024-01-01', valueEnd: '2024-12-31'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('valueStart')?.value).toBeInstanceOf(Date);
|
||||
expect(formGroup.get('valueEnd')?.value).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('should handle in_between for number fields', () => {
|
||||
const rule: Rule = {field: 'pageCount', operator: 'in_between' as any, value: null, valueStart: 100, valueEnd: 500};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('valueStart')?.value).toBe(100);
|
||||
expect(formGroup.get('valueEnd')?.value).toBe(500);
|
||||
});
|
||||
|
||||
it('should preserve array values for includes_any', () => {
|
||||
const rule: Rule = {field: 'readStatus', operator: 'includes_any' as any, value: ['READ', 'READING']};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toEqual(['READ', 'READING']);
|
||||
});
|
||||
|
||||
it('should handle is_empty operator with no value', () => {
|
||||
const rule: Rule = {field: 'title', operator: 'is_empty' as any, value: null};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should handle boolean field values', () => {
|
||||
const rule: Rule = {field: 'abridged', operator: 'equals', value: 'true'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe('true');
|
||||
});
|
||||
|
||||
it('should handle string values for text fields', () => {
|
||||
const rule: Rule = {field: 'title', operator: 'contains' as any, value: 'Harry Potter'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe('Harry Potter');
|
||||
});
|
||||
|
||||
it('should handle within_last with string number value', () => {
|
||||
const rule: Rule = {field: 'dateFinished', operator: 'within_last', value: '30', valueEnd: 'days'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('value')?.value).toBe(30);
|
||||
});
|
||||
|
||||
it('should handle this_period with null valueEnd', () => {
|
||||
const rule: Rule = {field: 'addedOn', operator: 'this_period', value: 'week', valueEnd: 'something'};
|
||||
const formGroup = component.buildRuleFromData(rule);
|
||||
expect(formGroup.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('onOperatorChange edge cases', () => {
|
||||
it('should set value to empty array for excludes_all operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('excludes_all');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toEqual([]);
|
||||
});
|
||||
|
||||
it('should set value to empty array for includes_all operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('includes_all');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toEqual([]);
|
||||
});
|
||||
|
||||
it('should clear all values for is_not_empty operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('value')?.setValue('something');
|
||||
ruleCtrl.get('valueStart')?.setValue('start');
|
||||
ruleCtrl.get('valueEnd')?.setValue('end');
|
||||
ruleCtrl.get('operator')?.setValue('is_not_empty');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueStart')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should set value to empty string for regular operators', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('equals');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toBe('');
|
||||
expect(ruleCtrl.get('valueStart')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should set value to empty string for in_between operator', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('in_between');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toBe('');
|
||||
});
|
||||
|
||||
it('should not affect form when called with already-set within_last', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('operator')?.setValue('within_last');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
ruleCtrl.get('value')?.setValue('15');
|
||||
ruleCtrl.get('operator')?.setValue('within_last');
|
||||
component.onOperatorChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('onFieldChange', () => {
|
||||
it('should reset operator and all values', () => {
|
||||
const ruleCtrl = component.createRule();
|
||||
ruleCtrl.get('field')?.setValue('title');
|
||||
ruleCtrl.get('operator')?.setValue('contains');
|
||||
ruleCtrl.get('value')?.setValue('some value');
|
||||
ruleCtrl.get('valueStart')?.setValue('start');
|
||||
ruleCtrl.get('valueEnd')?.setValue('end');
|
||||
component.onFieldChange(ruleCtrl);
|
||||
expect(ruleCtrl.get('operator')?.value).toBe('');
|
||||
expect(ruleCtrl.get('value')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueStart')?.value).toBeNull();
|
||||
expect(ruleCtrl.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('createRule and createGroup', () => {
|
||||
it('should create rule with empty defaults', () => {
|
||||
const rule = component.createRule();
|
||||
expect(rule.get('field')?.value).toBe('');
|
||||
expect(rule.get('operator')?.value).toBe('');
|
||||
expect(rule.get('value')?.value).toBeNull();
|
||||
expect(rule.get('valueStart')?.value).toBeNull();
|
||||
expect(rule.get('valueEnd')?.value).toBeNull();
|
||||
});
|
||||
|
||||
it('should create group with and join and empty rules', () => {
|
||||
const group = component.createGroup();
|
||||
expect(group.get('type')?.value).toBe('group');
|
||||
expect(group.get('join')?.value).toBe('and');
|
||||
expect((group.get('rules') as any).length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fieldOptions completeness', () => {
|
||||
it('should have 8 groups total', () => {
|
||||
expect(component.fieldOptions.length).toBe(8);
|
||||
});
|
||||
|
||||
it('should map categories field to genre translation key', () => {
|
||||
const groups = component.fieldOptions;
|
||||
const bookInfoGroup = groups.find(g => g.label.includes('bookInfo'));
|
||||
const categoriesItem = bookInfoGroup?.items.find(i => i.value === 'categories');
|
||||
expect(categoriesItem).toBeDefined();
|
||||
expect(categoriesItem!.label).toContain('genre');
|
||||
});
|
||||
|
||||
it('should include all audiobook fields in audiobook group', () => {
|
||||
const groups = component.fieldOptions;
|
||||
const audiobookGroup = groups.find(g => g.label.includes('audiobook'));
|
||||
const fieldValues = audiobookGroup?.items.map(i => i.value) ?? [];
|
||||
expect(fieldValues).toContain('narrator');
|
||||
expect(fieldValues).toContain('abridged');
|
||||
expect(fieldValues).toContain('audiobookDuration');
|
||||
});
|
||||
|
||||
it('should include all date fields in dates group', () => {
|
||||
const groups = component.fieldOptions;
|
||||
const datesGroup = groups.find(g => g.label.includes('dates'));
|
||||
const fieldValues = datesGroup?.items.map(i => i.value) ?? [];
|
||||
expect(fieldValues).toContain('publishedDate');
|
||||
expect(fieldValues).toContain('dateFinished');
|
||||
expect(fieldValues).toContain('lastReadTime');
|
||||
expect(fieldValues).toContain('addedOn');
|
||||
});
|
||||
});
|
||||
|
||||
describe('numericFieldConfigMap', () => {
|
||||
it('should contain readingProgress with max 100', () => {
|
||||
const config = component.numericFieldConfigMap.get('readingProgress');
|
||||
expect(config).toBeDefined();
|
||||
expect(config!.type).toBe('decimal');
|
||||
expect(config!.max).toBe(100);
|
||||
});
|
||||
|
||||
it('should contain personalRating with max 10', () => {
|
||||
const config = component.numericFieldConfigMap.get('personalRating');
|
||||
expect(config).toBeDefined();
|
||||
expect(config!.type).toBe('decimal');
|
||||
expect(config!.max).toBe(10);
|
||||
});
|
||||
|
||||
it('should contain pageCount with type number and no max', () => {
|
||||
const config = component.numericFieldConfigMap.get('pageCount');
|
||||
expect(config).toBeDefined();
|
||||
expect(config!.type).toBe('number');
|
||||
expect(config!.max).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should not contain title', () => {
|
||||
const config = component.numericFieldConfigMap.get('title' as any);
|
||||
expect(config).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should contain abridged with type boolean', () => {
|
||||
const config = component.numericFieldConfigMap.get('abridged');
|
||||
expect(config).toBeDefined();
|
||||
expect(config!.type).toBe('boolean');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildGroupFromData', () => {
|
||||
it('should build group with mixed rules and nested groups', () => {
|
||||
const groupData = {
|
||||
name: '',
|
||||
type: 'group' as const,
|
||||
join: 'or' as const,
|
||||
rules: [
|
||||
{field: 'title', operator: 'contains', value: 'test'} as Rule,
|
||||
{
|
||||
type: 'group' as const,
|
||||
join: 'and' as const,
|
||||
rules: [
|
||||
{field: 'pageCount', operator: 'greater_than', value: 100} as Rule
|
||||
],
|
||||
name: ''
|
||||
}
|
||||
]
|
||||
};
|
||||
const result = component.buildGroupFromData(groupData);
|
||||
expect(result.get('join')?.value).toBe('or');
|
||||
const rulesArray = result.get('rules') as any;
|
||||
expect(rulesArray.length).toBe(2);
|
||||
const nestedGroup = rulesArray.at(1);
|
||||
expect(nestedGroup.get('rules')).toBeDefined();
|
||||
expect(nestedGroup.get('rules').length).toBe(1);
|
||||
});
|
||||
|
||||
it('should preserve join type', () => {
|
||||
const groupData = {
|
||||
name: '',
|
||||
type: 'group' as const,
|
||||
join: 'or' as const,
|
||||
rules: []
|
||||
};
|
||||
const result = component.buildGroupFromData(groupData);
|
||||
expect(result.get('join')?.value).toBe('or');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,7 @@ import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {MultiSelect} from 'primeng/multiselect';
|
||||
import {AutoComplete} from 'primeng/autocomplete';
|
||||
import {EMPTY_CHECK_OPERATORS, MULTI_VALUE_OPERATORS, parseValue, removeNulls, serializeDateRules} from '../service/magic-shelf-utils';
|
||||
import {EMPTY_CHECK_OPERATORS, MULTI_VALUE_OPERATORS, RELATIVE_DATE_OPERATORS, parseValue, removeNulls, serializeDateRules} from '../service/magic-shelf-utils';
|
||||
import {IconPickerService, IconSelection} from '../../../shared/service/icon-picker.service';
|
||||
import {CheckboxChangeEvent, CheckboxModule} from "primeng/checkbox";
|
||||
import {UserService} from "../../settings/user-management/user.service";
|
||||
@@ -42,6 +42,9 @@ export type RuleOperator =
|
||||
| 'includes_any'
|
||||
| 'excludes_all'
|
||||
| 'includes_all'
|
||||
| 'within_last'
|
||||
| 'older_than'
|
||||
| 'this_period'
|
||||
|
||||
export type RuleField =
|
||||
| 'library'
|
||||
@@ -74,7 +77,22 @@ export type RuleField =
|
||||
| 'lastReadTime'
|
||||
| 'metadataScore'
|
||||
| 'moods'
|
||||
| 'tags';
|
||||
| 'tags'
|
||||
| 'addedOn'
|
||||
| 'lubimyczytacRating'
|
||||
| 'description'
|
||||
| 'narrator'
|
||||
| 'ageRating'
|
||||
| 'contentRating'
|
||||
| 'audibleRating'
|
||||
| 'audibleReviewCount'
|
||||
| 'abridged'
|
||||
| 'audiobookDuration'
|
||||
| 'isPhysical'
|
||||
| 'seriesStatus'
|
||||
| 'seriesGaps'
|
||||
| 'seriesPosition'
|
||||
| 'readingProgress';
|
||||
|
||||
|
||||
interface FullFieldConfig {
|
||||
@@ -83,7 +101,7 @@ interface FullFieldConfig {
|
||||
max?: number;
|
||||
}
|
||||
|
||||
type FieldType = 'number' | 'decimal' | 'date' | undefined;
|
||||
type FieldType = 'number' | 'decimal' | 'date' | 'boolean' | undefined;
|
||||
|
||||
export interface Rule {
|
||||
field: RuleField;
|
||||
@@ -150,9 +168,40 @@ const FIELD_CONFIGS: Record<RuleField, FullFieldConfig> = {
|
||||
goodreadsReviewCount: {label: 'goodreadsReviewCount', type: 'number'},
|
||||
hardcoverRating: {label: 'hardcoverRating', type: 'decimal', max: 5},
|
||||
hardcoverReviewCount: {label: 'hardcoverReviewCount', type: 'number'},
|
||||
ranobedbRating: {label: 'ranobedbRating', type: 'decimal', max: 5}
|
||||
ranobedbRating: {label: 'ranobedbRating', type: 'decimal', max: 5},
|
||||
addedOn: {label: 'addedOn', type: 'date'},
|
||||
lubimyczytacRating: {label: 'lubimyczytacRating', type: 'decimal', max: 5},
|
||||
description: {label: 'description'},
|
||||
narrator: {label: 'narrator'},
|
||||
ageRating: {label: 'ageRating', type: 'number'},
|
||||
contentRating: {label: 'contentRating'},
|
||||
audibleRating: {label: 'audibleRating', type: 'decimal', max: 5},
|
||||
audibleReviewCount: {label: 'audibleReviewCount', type: 'number'},
|
||||
abridged: {label: 'abridged', type: 'boolean'},
|
||||
audiobookDuration: {label: 'audiobookDuration', type: 'number'},
|
||||
isPhysical: {label: 'isPhysical', type: 'boolean'},
|
||||
seriesStatus: {label: 'seriesStatus'},
|
||||
seriesGaps: {label: 'seriesGaps'},
|
||||
seriesPosition: {label: 'seriesPosition'},
|
||||
readingProgress: {label: 'readingProgress', type: 'decimal', max: 100}
|
||||
};
|
||||
|
||||
interface FieldGroup {
|
||||
translationKey: string;
|
||||
fields: RuleField[];
|
||||
}
|
||||
|
||||
const FIELD_GROUPS: FieldGroup[] = [
|
||||
{ translationKey: 'organization', fields: ['library', 'shelf', 'readStatus', 'readingProgress'] },
|
||||
{ translationKey: 'bookInfo', fields: ['title', 'subtitle', 'description', 'authors', 'categories', 'publisher', 'language', 'pageCount', 'ageRating', 'contentRating'] },
|
||||
{ translationKey: 'series', fields: ['seriesName', 'seriesNumber', 'seriesTotal', 'seriesStatus', 'seriesGaps', 'seriesPosition'] },
|
||||
{ translationKey: 'dates', fields: ['publishedDate', 'dateFinished', 'lastReadTime', 'addedOn'] },
|
||||
{ translationKey: 'ratingsReviews', fields: ['personalRating', 'metadataScore', 'amazonRating', 'amazonReviewCount', 'goodreadsRating', 'goodreadsReviewCount', 'hardcoverRating', 'hardcoverReviewCount', 'ranobedbRating', 'lubimyczytacRating', 'audibleRating', 'audibleReviewCount'] },
|
||||
{ translationKey: 'tagsMoods', fields: ['moods', 'tags'] },
|
||||
{ translationKey: 'audiobook', fields: ['narrator', 'abridged', 'audiobookDuration'] },
|
||||
{ translationKey: 'fileIdentifiers', fields: ['fileType', 'fileSize', 'isbn13', 'isbn10', 'isPhysical'] }
|
||||
];
|
||||
|
||||
const READ_STATUS_KEYS: Record<string, string> = {
|
||||
UNREAD: 'unread',
|
||||
READING: 'reading',
|
||||
@@ -204,13 +253,19 @@ export class MagicShelfComponent implements OnInit {
|
||||
}
|
||||
|
||||
get fieldOptions() {
|
||||
return Object.entries(FIELD_CONFIGS).map(([key, config]) => {
|
||||
const translationKey = key === 'categories' ? 'genre' : config.label;
|
||||
return {
|
||||
label: this.t.translate(`magicShelf.fields.${translationKey}`),
|
||||
value: key as RuleField
|
||||
};
|
||||
});
|
||||
return FIELD_GROUPS
|
||||
.map(group => ({
|
||||
label: this.t.translate(`magicShelf.fieldGroups.${group.translationKey}`),
|
||||
items: group.fields.map(field => {
|
||||
const config = FIELD_CONFIGS[field];
|
||||
const translationKey = field === 'categories' ? 'genre' : config.label;
|
||||
return {
|
||||
label: this.t.translate(`magicShelf.fields.${translationKey}`),
|
||||
value: field
|
||||
};
|
||||
})
|
||||
}))
|
||||
.filter(group => group.items.length > 0);
|
||||
}
|
||||
|
||||
fileType: { label: string; value: string }[] = [
|
||||
@@ -231,6 +286,67 @@ export class MagicShelfComponent implements OnInit {
|
||||
}));
|
||||
}
|
||||
|
||||
get booleanOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.booleanValues.yes'), value: 'true'},
|
||||
{label: this.t.translate('magicShelf.booleanValues.no'), value: 'false'},
|
||||
];
|
||||
}
|
||||
|
||||
get contentRatingOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.contentRatings.everyone'), value: 'EVERYONE'},
|
||||
{label: this.t.translate('magicShelf.contentRatings.teen'), value: 'TEEN'},
|
||||
{label: this.t.translate('magicShelf.contentRatings.mature'), value: 'MATURE'},
|
||||
{label: this.t.translate('magicShelf.contentRatings.adult'), value: 'ADULT'},
|
||||
{label: this.t.translate('magicShelf.contentRatings.explicit'), value: 'EXPLICIT'},
|
||||
];
|
||||
}
|
||||
|
||||
get seriesStatusOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.seriesStatuses.reading'), value: 'reading'},
|
||||
{label: this.t.translate('magicShelf.seriesStatuses.completed'), value: 'completed'},
|
||||
{label: this.t.translate('magicShelf.seriesStatuses.ongoing'), value: 'ongoing'},
|
||||
{label: this.t.translate('magicShelf.seriesStatuses.notStarted'), value: 'not_started'},
|
||||
{label: this.t.translate('magicShelf.seriesStatuses.fullyRead'), value: 'fully_read'},
|
||||
];
|
||||
}
|
||||
|
||||
get seriesGapsOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.seriesGaps.anyGap'), value: 'any_gap'},
|
||||
{label: this.t.translate('magicShelf.seriesGaps.missingFirst'), value: 'missing_first'},
|
||||
{label: this.t.translate('magicShelf.seriesGaps.missingLatest'), value: 'missing_latest'},
|
||||
{label: this.t.translate('magicShelf.seriesGaps.duplicateNumber'), value: 'duplicate_number'},
|
||||
];
|
||||
}
|
||||
|
||||
get seriesPositionOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.seriesPositions.nextUnread'), value: 'next_unread'},
|
||||
{label: this.t.translate('magicShelf.seriesPositions.firstInSeries'), value: 'first_in_series'},
|
||||
{label: this.t.translate('magicShelf.seriesPositions.lastInSeries'), value: 'last_in_series'},
|
||||
];
|
||||
}
|
||||
|
||||
get dateUnitOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.dateUnits.days'), value: 'days'},
|
||||
{label: this.t.translate('magicShelf.dateUnits.weeks'), value: 'weeks'},
|
||||
{label: this.t.translate('magicShelf.dateUnits.months'), value: 'months'},
|
||||
{label: this.t.translate('magicShelf.dateUnits.years'), value: 'years'},
|
||||
];
|
||||
}
|
||||
|
||||
get datePeriodOptions() {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.datePeriods.week'), value: 'week'},
|
||||
{label: this.t.translate('magicShelf.datePeriods.month'), value: 'month'},
|
||||
{label: this.t.translate('magicShelf.datePeriods.year'), value: 'year'},
|
||||
];
|
||||
}
|
||||
|
||||
libraries: Library[] = [];
|
||||
libraryOptions: { label: string; value: number }[] = [];
|
||||
shelves: Shelf[] = [];
|
||||
@@ -348,13 +464,25 @@ export class MagicShelfComponent implements OnInit {
|
||||
buildRuleFromData(data: Rule): RuleFormGroup {
|
||||
const config = FIELD_CONFIGS[data.field];
|
||||
const type = config?.type;
|
||||
const isRelativeDate = RELATIVE_DATE_OPERATORS.includes(data.operator);
|
||||
|
||||
let value, valueStart, valueEnd;
|
||||
if (isRelativeDate) {
|
||||
value = data.operator === 'this_period' ? data.value : parseValue(data.value, 'number');
|
||||
valueStart = null;
|
||||
valueEnd = data.operator !== 'this_period' ? data.valueEnd : null;
|
||||
} else {
|
||||
value = parseValue(data.value, type);
|
||||
valueStart = parseValue(data.valueStart, type);
|
||||
valueEnd = parseValue(data.valueEnd, type);
|
||||
}
|
||||
|
||||
return new FormGroup({
|
||||
field: new FormControl<RuleField>(data.field),
|
||||
operator: new FormControl<RuleOperator>(data.operator),
|
||||
value: new FormControl(parseValue(data.value, type)),
|
||||
valueStart: new FormControl(parseValue(data.valueStart, type)),
|
||||
valueEnd: new FormControl(parseValue(data.valueEnd, type)),
|
||||
value: new FormControl(value),
|
||||
valueStart: new FormControl(valueStart),
|
||||
valueEnd: new FormControl(valueEnd),
|
||||
}) as RuleFormGroup;
|
||||
}
|
||||
|
||||
@@ -391,19 +519,46 @@ export class MagicShelfComponent implements OnInit {
|
||||
{label: this.t.translate('magicShelf.operators.between'), value: 'in_between'},
|
||||
];
|
||||
|
||||
const relativeDateOperators = [
|
||||
{label: this.t.translate('magicShelf.operators.withinLast'), value: 'within_last'},
|
||||
{label: this.t.translate('magicShelf.operators.olderThan'), value: 'older_than'},
|
||||
{label: this.t.translate('magicShelf.operators.thisPeriod'), value: 'this_period'},
|
||||
];
|
||||
|
||||
if (!field) return [...baseOperators, ...multiValueOperators];
|
||||
|
||||
const config = FIELD_CONFIGS[field];
|
||||
const isMultiValueField = ['library', 'shelf', 'authors', 'categories', 'moods', 'tags', 'readStatus', 'fileType', 'language', 'title', 'subtitle', 'publisher', 'seriesName', 'isbn13', 'isbn10'].includes(field);
|
||||
|
||||
if (config.type === 'boolean') {
|
||||
return baseOperators;
|
||||
}
|
||||
|
||||
// Composite fields: only is/isNot or has/hasNot
|
||||
if (field === 'seriesStatus' || field === 'seriesPosition') {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.operators.is'), value: 'equals'},
|
||||
{label: this.t.translate('magicShelf.operators.isNot'), value: 'not_equals'},
|
||||
];
|
||||
}
|
||||
if (field === 'seriesGaps') {
|
||||
return [
|
||||
{label: this.t.translate('magicShelf.operators.has'), value: 'equals'},
|
||||
{label: this.t.translate('magicShelf.operators.hasNot'), value: 'not_equals'},
|
||||
];
|
||||
}
|
||||
|
||||
const isMultiValueField = ['library', 'shelf', 'authors', 'categories', 'moods', 'tags', 'readStatus', 'fileType', 'language', 'title', 'subtitle', 'publisher', 'seriesName', 'isbn13', 'isbn10', 'contentRating', 'narrator', 'description'].includes(field);
|
||||
const operators = [...baseOperators];
|
||||
|
||||
if (isMultiValueField) {
|
||||
operators.push(...multiValueOperators);
|
||||
}
|
||||
|
||||
const isTextEligible = !['library', 'shelf', 'readStatus', 'fileType'].includes(field);
|
||||
const isTextEligible = !['library', 'shelf', 'readStatus', 'fileType', 'contentRating'].includes(field);
|
||||
|
||||
if (config.type === 'number' || config.type === 'decimal' || config.type === 'date') {
|
||||
if (config.type === 'date') {
|
||||
operators.push(...comparisonOperators, ...relativeDateOperators);
|
||||
} else if (config.type === 'number' || config.type === 'decimal') {
|
||||
operators.push(...comparisonOperators);
|
||||
} else if (isTextEligible) {
|
||||
operators.push(...textOperators);
|
||||
@@ -466,7 +621,15 @@ export class MagicShelfComponent implements OnInit {
|
||||
const valueStartCtrl = ruleCtrl.get('valueStart');
|
||||
const valueEndCtrl = ruleCtrl.get('valueEnd');
|
||||
|
||||
if (MULTI_VALUE_OPERATORS.includes(operator)) {
|
||||
if (operator === 'within_last' || operator === 'older_than') {
|
||||
valueCtrl?.setValue(null);
|
||||
valueStartCtrl?.setValue(null);
|
||||
valueEndCtrl?.setValue('days');
|
||||
} else if (operator === 'this_period') {
|
||||
valueCtrl?.setValue(null);
|
||||
valueStartCtrl?.setValue(null);
|
||||
valueEndCtrl?.setValue(null);
|
||||
} else if (MULTI_VALUE_OPERATORS.includes(operator)) {
|
||||
valueCtrl?.setValue([]);
|
||||
valueStartCtrl?.setValue(null);
|
||||
valueEndCtrl?.setValue(null);
|
||||
|
||||
+1270
-18
File diff suppressed because it is too large
Load Diff
@@ -2,21 +2,25 @@ import {Injectable} from '@angular/core';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {GroupRule, Rule, RuleField} from '../component/magic-shelf-component';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookRuleEvaluatorService {
|
||||
|
||||
evaluateGroup(book: Book, group: GroupRule): boolean {
|
||||
evaluateGroup(book: Book, group: GroupRule, allBooks: Book[] = []): boolean {
|
||||
const results = group.rules.map(rule => {
|
||||
if ('type' in rule && rule.type === 'group') {
|
||||
return this.evaluateGroup(book, rule as GroupRule);
|
||||
return this.evaluateGroup(book, rule as GroupRule, allBooks);
|
||||
} else {
|
||||
return this.evaluateRule(book, rule as Rule);
|
||||
return this.evaluateRule(book, rule as Rule, allBooks);
|
||||
}
|
||||
});
|
||||
return group.join === 'and' ? results.every(Boolean) : results.some(Boolean);
|
||||
}
|
||||
|
||||
private evaluateRule(book: Book, rule: Rule): boolean {
|
||||
private evaluateRule(book: Book, rule: Rule, allBooks: Book[]): boolean {
|
||||
if (rule.field === 'seriesStatus' || rule.field === 'seriesGaps' || rule.field === 'seriesPosition') {
|
||||
return this.evaluateCompositeField(book, rule, allBooks);
|
||||
}
|
||||
|
||||
const rawValue = this.extractBookValue(book, rule.field);
|
||||
|
||||
const normalize = (val: unknown): unknown => {
|
||||
@@ -81,6 +85,12 @@ export class BookRuleEvaluatorService {
|
||||
return [String(book.metadata?.isbn13 ?? '').toLowerCase()];
|
||||
case 'isbn10':
|
||||
return [String(book.metadata?.isbn10 ?? '').toLowerCase()];
|
||||
case 'narrator':
|
||||
return [String(book.metadata?.narrator ?? '').toLowerCase()];
|
||||
case 'description':
|
||||
return [String(book.metadata?.description ?? '').toLowerCase()];
|
||||
case 'contentRating':
|
||||
return [String(book.metadata?.contentRating ?? '').toLowerCase()];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
@@ -91,17 +101,17 @@ export class BookRuleEvaluatorService {
|
||||
|
||||
const ruleList = Array.isArray(rule.value)
|
||||
? rule.value.map(v => {
|
||||
if (isNumericIdField) return String(v);
|
||||
const lowerValue = String(v).toLowerCase();
|
||||
return isFileTypeField ? mapFileTypeValue(lowerValue) : lowerValue;
|
||||
})
|
||||
if (isNumericIdField) return String(v);
|
||||
const lowerValue = String(v).toLowerCase();
|
||||
return isFileTypeField ? mapFileTypeValue(lowerValue) : lowerValue;
|
||||
})
|
||||
: (rule.value ? [
|
||||
isNumericIdField
|
||||
? String(rule.value)
|
||||
: isFileTypeField
|
||||
? mapFileTypeValue(String(rule.value).toLowerCase())
|
||||
: String(rule.value).toLowerCase()
|
||||
] : []);
|
||||
isNumericIdField
|
||||
? String(rule.value)
|
||||
: isFileTypeField
|
||||
? mapFileTypeValue(String(rule.value).toLowerCase())
|
||||
: String(rule.value).toLowerCase()
|
||||
] : []);
|
||||
|
||||
switch (rule.operator) {
|
||||
case 'equals':
|
||||
@@ -224,6 +234,24 @@ export class BookRuleEvaluatorService {
|
||||
return ruleList.some(v => bookList.includes(v));
|
||||
}
|
||||
|
||||
case 'within_last': {
|
||||
if (!(value instanceof Date)) return false;
|
||||
const threshold = this.computeDateThreshold(Number(rule.value), String(rule.valueEnd ?? 'days'));
|
||||
return value >= threshold;
|
||||
}
|
||||
|
||||
case 'older_than': {
|
||||
if (!(value instanceof Date)) return false;
|
||||
const threshold = this.computeDateThreshold(Number(rule.value), String(rule.valueEnd ?? 'days'));
|
||||
return value < threshold;
|
||||
}
|
||||
|
||||
case 'this_period': {
|
||||
if (!(value instanceof Date)) return false;
|
||||
const start = this.getStartOfPeriod(String(rule.value ?? 'year'));
|
||||
return value >= start;
|
||||
}
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
@@ -293,8 +321,183 @@ export class BookRuleEvaluatorService {
|
||||
return book.metadata?.hardcoverReviewCount;
|
||||
case 'ranobedbRating':
|
||||
return book.metadata?.ranobedbRating;
|
||||
case 'addedOn':
|
||||
return book.addedOn ? new Date(book.addedOn) : null;
|
||||
case 'description':
|
||||
return book.metadata?.description?.toLowerCase() ?? null;
|
||||
case 'narrator':
|
||||
return book.metadata?.narrator?.toLowerCase() ?? null;
|
||||
case 'ageRating':
|
||||
return book.metadata?.ageRating;
|
||||
case 'contentRating':
|
||||
return book.metadata?.contentRating?.toLowerCase() ?? null;
|
||||
case 'audibleRating':
|
||||
return book.metadata?.audibleRating;
|
||||
case 'audibleReviewCount':
|
||||
return book.metadata?.audibleReviewCount;
|
||||
case 'abridged':
|
||||
return book.metadata?.abridged;
|
||||
case 'audiobookDuration':
|
||||
return book.metadata?.audiobookMetadata?.durationSeconds ?? null;
|
||||
case 'isPhysical':
|
||||
return book.isPhysical;
|
||||
case 'lubimyczytacRating':
|
||||
return book.metadata?.lubimyczytacRating;
|
||||
case 'readingProgress': {
|
||||
const prg = [
|
||||
book.koreaderProgress?.percentage ?? 0,
|
||||
book.koboProgress?.percentage ?? 0,
|
||||
book.pdfProgress?.percentage ?? 0,
|
||||
book.epubProgress?.percentage ?? 0,
|
||||
book.cbxProgress?.percentage ?? 0,
|
||||
book.audiobookProgress?.percentage ?? 0,
|
||||
];
|
||||
return Math.max(...prg);
|
||||
}
|
||||
default:
|
||||
return (book as Record<string, unknown>)[field];
|
||||
}
|
||||
}
|
||||
|
||||
private evaluateCompositeField(book: Book, rule: Rule, allBooks: Book[]): boolean {
|
||||
const seriesName = book.metadata?.seriesName;
|
||||
if (!seriesName) return false;
|
||||
|
||||
const seriesBooks = allBooks.filter(b => b.metadata?.seriesName === seriesName);
|
||||
const value = typeof rule.value === 'string' ? rule.value.toLowerCase() : '';
|
||||
const negate = rule.operator === 'not_equals';
|
||||
|
||||
let result: boolean;
|
||||
switch (rule.field) {
|
||||
case 'seriesStatus':
|
||||
result = this.evaluateSeriesStatus(seriesBooks, value);
|
||||
break;
|
||||
case 'seriesGaps':
|
||||
result = this.evaluateSeriesGaps(seriesBooks, value);
|
||||
break;
|
||||
case 'seriesPosition':
|
||||
result = this.evaluateSeriesPosition(book, seriesBooks, value);
|
||||
break;
|
||||
default:
|
||||
result = false;
|
||||
}
|
||||
|
||||
return negate ? !result : result;
|
||||
}
|
||||
|
||||
private evaluateSeriesStatus(seriesBooks: Book[], value: string): boolean {
|
||||
switch (value) {
|
||||
case 'reading':
|
||||
return seriesBooks.some(b => b.readStatus === 'READING' || b.readStatus === 'RE_READING');
|
||||
case 'not_started':
|
||||
return !seriesBooks.some(b =>
|
||||
b.readStatus === 'READ' || b.readStatus === 'READING' ||
|
||||
b.readStatus === 'RE_READING' || b.readStatus === 'PARTIALLY_READ'
|
||||
);
|
||||
case 'fully_read':
|
||||
return seriesBooks.length > 0 && seriesBooks.every(b => b.readStatus === 'READ');
|
||||
case 'completed': {
|
||||
const totals = seriesBooks.map(b => b.metadata?.seriesTotal).filter((t): t is number => t != null);
|
||||
if (totals.length === 0) return false;
|
||||
const maxTotal = Math.max(...totals);
|
||||
return seriesBooks.some(b => b.metadata?.seriesNumber != null && Math.floor(b.metadata.seriesNumber) === maxTotal);
|
||||
}
|
||||
case 'ongoing': {
|
||||
const totals = seriesBooks.map(b => b.metadata?.seriesTotal).filter((t): t is number => t != null);
|
||||
if (totals.length === 0) return false;
|
||||
const maxTotal = Math.max(...totals);
|
||||
return !seriesBooks.some(b => b.metadata?.seriesNumber != null && Math.floor(b.metadata.seriesNumber) === maxTotal);
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private evaluateSeriesGaps(seriesBooks: Book[], value: string): boolean {
|
||||
const numberedBooks = seriesBooks
|
||||
.filter(b => b.metadata?.seriesNumber != null)
|
||||
.map(b => b.metadata!.seriesNumber!);
|
||||
|
||||
if (numberedBooks.length === 0) return false;
|
||||
|
||||
switch (value) {
|
||||
case 'any_gap': {
|
||||
const uniqueFloors = new Set(numberedBooks.map(n => Math.floor(n)));
|
||||
const maxFloor = Math.max(...numberedBooks.map(n => Math.floor(n)));
|
||||
return uniqueFloors.size < maxFloor;
|
||||
}
|
||||
case 'missing_first':
|
||||
return !numberedBooks.some(n => Math.floor(n) === 1);
|
||||
case 'missing_latest': {
|
||||
const totals = seriesBooks.map(b => b.metadata?.seriesTotal).filter((t): t is number => t != null);
|
||||
if (totals.length === 0) return false;
|
||||
const maxTotal = Math.max(...totals);
|
||||
return !numberedBooks.some(n => Math.floor(n) === maxTotal);
|
||||
}
|
||||
case 'duplicate_number':
|
||||
return numberedBooks.length > new Set(numberedBooks).size;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private evaluateSeriesPosition(book: Book, seriesBooks: Book[], value: string): boolean {
|
||||
if (book.metadata?.seriesNumber == null) return false;
|
||||
|
||||
const numberedBooks = seriesBooks.filter(b => b.metadata?.seriesNumber != null);
|
||||
|
||||
switch (value) {
|
||||
case 'first_in_series': {
|
||||
const minNumber = Math.min(...numberedBooks.map(b => b.metadata!.seriesNumber!));
|
||||
return book.metadata.seriesNumber === minNumber;
|
||||
}
|
||||
case 'last_in_series': {
|
||||
const maxNumber = Math.max(...numberedBooks.map(b => b.metadata!.seriesNumber!));
|
||||
return book.metadata.seriesNumber === maxNumber;
|
||||
}
|
||||
case 'next_unread': {
|
||||
if (book.readStatus === 'READ') return false;
|
||||
const hasLowerUnread = numberedBooks.some(b =>
|
||||
b.metadata!.seriesNumber! < book.metadata!.seriesNumber! &&
|
||||
b.readStatus !== 'READ'
|
||||
);
|
||||
if (hasLowerUnread) return false;
|
||||
return numberedBooks.some(b =>
|
||||
b.metadata!.seriesNumber! < book.metadata!.seriesNumber! &&
|
||||
b.readStatus === 'READ'
|
||||
);
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private computeDateThreshold(amount: number, unit: string): Date {
|
||||
const now = new Date();
|
||||
switch (unit.toLowerCase()) {
|
||||
case 'weeks':
|
||||
return new Date(now.getTime() - amount * 7 * 24 * 60 * 60 * 1000);
|
||||
case 'months':
|
||||
return new Date(now.getFullYear(), now.getMonth() - amount, now.getDate());
|
||||
case 'years':
|
||||
return new Date(now.getFullYear() - amount, now.getMonth(), now.getDate());
|
||||
default:
|
||||
return new Date(now.getTime() - amount * 24 * 60 * 60 * 1000);
|
||||
}
|
||||
}
|
||||
|
||||
private getStartOfPeriod(period: string): Date {
|
||||
const now = new Date();
|
||||
switch (period.toLowerCase()) {
|
||||
case 'week': {
|
||||
const day = now.getDay();
|
||||
const diff = day === 0 ? 6 : day - 1;
|
||||
return new Date(now.getFullYear(), now.getMonth(), now.getDate() - diff);
|
||||
}
|
||||
case 'month':
|
||||
return new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
default:
|
||||
return new Date(now.getFullYear(), 0, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
import {RELATIVE_DATE_OPERATORS, MULTI_VALUE_OPERATORS, EMPTY_CHECK_OPERATORS, parseValue, serializeDateRules, removeNulls} from './magic-shelf-utils';
|
||||
|
||||
describe('magic-shelf-utils', () => {
|
||||
|
||||
describe('RELATIVE_DATE_OPERATORS', () => {
|
||||
it('should contain within_last, older_than, this_period', () => {
|
||||
expect(RELATIVE_DATE_OPERATORS).toEqual(['within_last', 'older_than', 'this_period']);
|
||||
});
|
||||
|
||||
it('should not overlap with MULTI_VALUE_OPERATORS', () => {
|
||||
RELATIVE_DATE_OPERATORS.forEach(op => {
|
||||
expect(MULTI_VALUE_OPERATORS).not.toContain(op);
|
||||
});
|
||||
});
|
||||
|
||||
it('should not overlap with EMPTY_CHECK_OPERATORS', () => {
|
||||
RELATIVE_DATE_OPERATORS.forEach(op => {
|
||||
expect(EMPTY_CHECK_OPERATORS).not.toContain(op);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('serializeDateRules', () => {
|
||||
it('should serialize Date values for regular date operators', () => {
|
||||
const rule = {
|
||||
field: 'dateFinished',
|
||||
operator: 'equals',
|
||||
value: new Date('2024-06-15T00:00:00Z'),
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe('2024-06-15');
|
||||
});
|
||||
|
||||
it('should serialize Date values for in_between operator on date fields', () => {
|
||||
const rule = {
|
||||
field: 'addedOn',
|
||||
operator: 'in_between',
|
||||
value: null,
|
||||
valueStart: new Date('2024-01-01T00:00:00Z'),
|
||||
valueEnd: new Date('2024-12-31T00:00:00Z')
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['valueStart']).toBe('2024-01-01');
|
||||
expect(result['valueEnd']).toBe('2024-12-31');
|
||||
});
|
||||
|
||||
it('should NOT serialize values for within_last operator on date fields', () => {
|
||||
const rule = {
|
||||
field: 'dateFinished',
|
||||
operator: 'within_last',
|
||||
value: 30,
|
||||
valueStart: null,
|
||||
valueEnd: 'days'
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe(30);
|
||||
expect(result['valueEnd']).toBe('days');
|
||||
});
|
||||
|
||||
it('should NOT serialize values for older_than operator on date fields', () => {
|
||||
const rule = {
|
||||
field: 'lastReadTime',
|
||||
operator: 'older_than',
|
||||
value: 6,
|
||||
valueStart: null,
|
||||
valueEnd: 'months'
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe(6);
|
||||
expect(result['valueEnd']).toBe('months');
|
||||
});
|
||||
|
||||
it('should NOT serialize values for this_period operator on date fields', () => {
|
||||
const rule = {
|
||||
field: 'addedOn',
|
||||
operator: 'this_period',
|
||||
value: 'year',
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe('year');
|
||||
});
|
||||
|
||||
it('should NOT serialize values for publishedDate with within_last', () => {
|
||||
const rule = {
|
||||
field: 'publishedDate',
|
||||
operator: 'within_last',
|
||||
value: 2,
|
||||
valueStart: null,
|
||||
valueEnd: 'years'
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe(2);
|
||||
expect(result['valueEnd']).toBe('years');
|
||||
});
|
||||
|
||||
it('should recurse through group rules', () => {
|
||||
const group = {
|
||||
type: 'group',
|
||||
join: 'and',
|
||||
rules: [
|
||||
{
|
||||
field: 'dateFinished',
|
||||
operator: 'within_last',
|
||||
value: 7,
|
||||
valueStart: null,
|
||||
valueEnd: 'days'
|
||||
},
|
||||
{
|
||||
field: 'addedOn',
|
||||
operator: 'equals',
|
||||
value: new Date('2024-03-15T00:00:00Z'),
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const result = serializeDateRules(group) as { rules: Record<string, unknown>[] };
|
||||
expect(result.rules[0]['value']).toBe(7);
|
||||
expect(result.rules[0]['valueEnd']).toBe('days');
|
||||
expect(result.rules[1]['value']).toBe('2024-03-15');
|
||||
});
|
||||
|
||||
it('should not affect non-date fields', () => {
|
||||
const rule = {
|
||||
field: 'title',
|
||||
operator: 'contains',
|
||||
value: 'Harry Potter',
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe('Harry Potter');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseValue', () => {
|
||||
it('should parse number values correctly', () => {
|
||||
expect(parseValue(42, 'number')).toBe(42);
|
||||
expect(parseValue('42', 'number')).toBe(42);
|
||||
expect(parseValue(3.5, 'decimal')).toBe(3.5);
|
||||
});
|
||||
|
||||
it('should return null for NaN number values', () => {
|
||||
expect(parseValue('not a number', 'number')).toBeNull();
|
||||
});
|
||||
|
||||
it('should parse date values correctly', () => {
|
||||
const result = parseValue('2024-06-15', 'date');
|
||||
expect(result).toBeInstanceOf(Date);
|
||||
expect((result as Date).getFullYear()).toBe(2024);
|
||||
});
|
||||
|
||||
it('should return null for invalid date values', () => {
|
||||
expect(parseValue('not a date', 'date')).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null for null input', () => {
|
||||
expect(parseValue(null, 'number')).toBeNull();
|
||||
expect(parseValue(null, 'date')).toBeNull();
|
||||
expect(parseValue(null, undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it('should return value as-is for undefined type', () => {
|
||||
expect(parseValue('hello', undefined)).toBe('hello');
|
||||
expect(parseValue('true', 'boolean' as any)).toBe('true');
|
||||
});
|
||||
|
||||
it('should return arrays as-is for undefined type', () => {
|
||||
const arr = ['a', 'b'];
|
||||
expect(parseValue(arr, undefined)).toBe(arr);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeNulls', () => {
|
||||
it('should remove null values from flat object', () => {
|
||||
expect(removeNulls({a: 1, b: null, c: 'hello'})).toEqual({a: 1, c: 'hello'});
|
||||
});
|
||||
|
||||
it('should remove undefined values from flat object', () => {
|
||||
expect(removeNulls({a: 1, b: undefined})).toEqual({a: 1});
|
||||
});
|
||||
|
||||
it('should keep falsy non-null values', () => {
|
||||
expect(removeNulls({a: 0, b: '', c: false})).toEqual({a: 0, b: '', c: false});
|
||||
});
|
||||
|
||||
it('should recurse into nested objects', () => {
|
||||
expect(removeNulls({a: {b: null, c: 1}, d: 2})).toEqual({a: {c: 1}, d: 2});
|
||||
});
|
||||
|
||||
it('should recurse into arrays', () => {
|
||||
expect(removeNulls([{a: null, b: 1}, {c: null}])).toEqual([{b: 1}, {}]);
|
||||
});
|
||||
|
||||
it('should handle empty objects', () => {
|
||||
expect(removeNulls({})).toEqual({});
|
||||
});
|
||||
|
||||
it('should handle empty arrays', () => {
|
||||
expect(removeNulls([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('should pass through primitive values', () => {
|
||||
expect(removeNulls('hello')).toBe('hello');
|
||||
expect(removeNulls(42)).toBe(42);
|
||||
});
|
||||
|
||||
it('should handle deeply nested structures', () => {
|
||||
expect(removeNulls({a: {b: {c: null, d: {e: null, f: 1}}}})).toEqual({a: {b: {d: {f: 1}}}});
|
||||
});
|
||||
});
|
||||
|
||||
describe('serializeDateRules edge cases', () => {
|
||||
it('should handle lastReadTime date field serialization', () => {
|
||||
const rule = {
|
||||
field: 'lastReadTime',
|
||||
operator: 'equals',
|
||||
value: new Date('2024-08-20T00:00:00Z'),
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe('2024-08-20');
|
||||
});
|
||||
|
||||
it('should preserve string values on date fields', () => {
|
||||
const rule = {
|
||||
field: 'dateFinished',
|
||||
operator: 'equals',
|
||||
value: '2024-06-15',
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe('2024-06-15');
|
||||
});
|
||||
|
||||
it('should handle null value on date field', () => {
|
||||
const rule = {
|
||||
field: 'dateFinished',
|
||||
operator: 'is_empty',
|
||||
value: null,
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBeNull();
|
||||
});
|
||||
|
||||
it('should handle undefined value on date field', () => {
|
||||
const rule = {
|
||||
field: 'addedOn',
|
||||
operator: 'is_empty',
|
||||
value: undefined,
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle deeply nested groups', () => {
|
||||
const nested = {
|
||||
type: 'group',
|
||||
join: 'and',
|
||||
rules: [
|
||||
{
|
||||
type: 'group',
|
||||
join: 'or',
|
||||
rules: [
|
||||
{
|
||||
field: 'addedOn',
|
||||
operator: 'equals',
|
||||
value: new Date('2024-11-01T00:00:00Z'),
|
||||
valueStart: null,
|
||||
valueEnd: null
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const result = serializeDateRules(nested) as { rules: { rules: Record<string, unknown>[] }[] };
|
||||
expect(result.rules[0].rules[0]['value']).toBe('2024-11-01');
|
||||
});
|
||||
|
||||
it('should handle rule with no field property', () => {
|
||||
const rule = {
|
||||
operator: 'equals',
|
||||
value: 'test'
|
||||
};
|
||||
|
||||
const result = serializeDateRules(rule) as Record<string, unknown>;
|
||||
expect(result['value']).toBe('test');
|
||||
});
|
||||
|
||||
it('should handle empty rules array in group', () => {
|
||||
const group = {
|
||||
type: 'group',
|
||||
rules: []
|
||||
};
|
||||
|
||||
const result = serializeDateRules(group) as { rules: unknown[] };
|
||||
expect(result.rules).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseValue edge cases', () => {
|
||||
it('should parse 0 as valid number', () => {
|
||||
expect(parseValue(0, 'number')).toBe(0);
|
||||
});
|
||||
|
||||
it('should parse empty string as 0 for number', () => {
|
||||
expect(parseValue('', 'number')).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle undefined input', () => {
|
||||
expect(parseValue(undefined, 'number')).toBeNull();
|
||||
});
|
||||
|
||||
it('should handle Date object input for date type', () => {
|
||||
const result = parseValue(new Date('2024-01-01'), 'date');
|
||||
expect(result).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('should handle numeric timestamp for date type', () => {
|
||||
const result = parseValue(1718409600000, 'date');
|
||||
expect(result).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('should parse negative numbers', () => {
|
||||
expect(parseValue(-5, 'number')).toBe(-5);
|
||||
});
|
||||
|
||||
it('should parse decimal string as number', () => {
|
||||
expect(parseValue('3.14', 'decimal')).toBe(3.14);
|
||||
});
|
||||
|
||||
it('should return string type value as-is', () => {
|
||||
expect(parseValue('hello', 'string')).toBe('hello');
|
||||
});
|
||||
});
|
||||
|
||||
describe('MULTI_VALUE_OPERATORS', () => {
|
||||
it('should contain exactly includes_any, includes_all, excludes_all', () => {
|
||||
expect(MULTI_VALUE_OPERATORS).toEqual(['includes_any', 'includes_all', 'excludes_all']);
|
||||
});
|
||||
|
||||
it('should have length 3', () => {
|
||||
expect(MULTI_VALUE_OPERATORS.length).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('EMPTY_CHECK_OPERATORS', () => {
|
||||
it('should contain exactly is_empty, is_not_empty', () => {
|
||||
expect(EMPTY_CHECK_OPERATORS).toEqual(['is_empty', 'is_not_empty']);
|
||||
});
|
||||
|
||||
it('should have length 2', () => {
|
||||
expect(EMPTY_CHECK_OPERATORS.length).toBe(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,13 @@ export const EMPTY_CHECK_OPERATORS: RuleOperator[] = [
|
||||
'is_not_empty'
|
||||
];
|
||||
|
||||
export function parseValue(val: unknown, type: 'string' | 'number' | 'decimal' | 'date' | undefined): unknown {
|
||||
export const RELATIVE_DATE_OPERATORS: RuleOperator[] = [
|
||||
'within_last',
|
||||
'older_than',
|
||||
'this_period'
|
||||
];
|
||||
|
||||
export function parseValue(val: unknown, type: 'string' | 'number' | 'decimal' | 'date' | 'boolean' | undefined): unknown {
|
||||
if (val == null) return null;
|
||||
if (type === 'number' || type === 'decimal') {
|
||||
const num = Number(val);
|
||||
@@ -48,8 +54,9 @@ export function serializeDateRules(ruleOrGroup: unknown): unknown {
|
||||
};
|
||||
}
|
||||
|
||||
const rule = ruleOrGroup as { field?: string; value?: unknown; valueStart?: unknown; valueEnd?: unknown; [key: string]: unknown };
|
||||
const isDateField = rule.field === 'publishedDate' || rule.field === 'dateFinished';
|
||||
const rule = ruleOrGroup as { field?: string; operator?: string; value?: unknown; valueStart?: unknown; valueEnd?: unknown; [key: string]: unknown };
|
||||
const isRelativeDateOp = RELATIVE_DATE_OPERATORS.includes(rule.operator as RuleOperator);
|
||||
const isDateField = !isRelativeDateOp && (rule.field === 'publishedDate' || rule.field === 'dateFinished' || rule.field === 'addedOn' || rule.field === 'lastReadTime');
|
||||
const serialize = (val: unknown) => (val instanceof Date ? val.toISOString().split('T')[0] : val);
|
||||
|
||||
return {
|
||||
|
||||
@@ -162,11 +162,12 @@ export class MagicShelfService {
|
||||
}
|
||||
|
||||
return this.bookService.bookState$.pipe(
|
||||
map((state) =>
|
||||
(state.books ?? []).filter((book) =>
|
||||
this.ruleEvaluatorService.evaluateGroup(book, group)
|
||||
).length
|
||||
)
|
||||
map((state) => {
|
||||
const allBooks = state.books ?? [];
|
||||
return allBooks.filter((book) =>
|
||||
this.ruleEvaluatorService.evaluateGroup(book, group, allBooks)
|
||||
).length;
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
@@ -42,7 +42,16 @@
|
||||
"selectFileType": "Select File Type",
|
||||
"selectLibrary": "Select Library",
|
||||
"selectShelf": "Select Shelf",
|
||||
"selectGenre": "Select Genre"
|
||||
"selectGenre": "Select Genre",
|
||||
"selectValue": "Select Value",
|
||||
"selectContentRating": "Select Content Rating",
|
||||
"selectContentRatings": "Select Content Ratings",
|
||||
"amount": "Amount",
|
||||
"selectUnit": "Select Unit",
|
||||
"selectPeriod": "Select Period",
|
||||
"selectSeriesStatus": "Select Status",
|
||||
"selectSeriesGap": "Select Gap Type",
|
||||
"selectSeriesPosition": "Select Position"
|
||||
},
|
||||
"conditions": {
|
||||
"and": "AND",
|
||||
@@ -80,7 +89,32 @@
|
||||
"hardcoverRating": "Hardcover Rating",
|
||||
"hardcoverReviewCount": "Hardcover Review Count",
|
||||
"ranobedbRating": "Ranobedb Rating",
|
||||
"genre": "Genre"
|
||||
"genre": "Genre",
|
||||
"addedOn": "Date Added",
|
||||
"lubimyczytacRating": "Lubimyczytac Rating",
|
||||
"description": "Description",
|
||||
"narrator": "Narrator",
|
||||
"ageRating": "Age Rating",
|
||||
"contentRating": "Content Rating",
|
||||
"audibleRating": "Audible Rating",
|
||||
"audibleReviewCount": "Audible Review Count",
|
||||
"abridged": "Abridged",
|
||||
"audiobookDuration": "Audiobook Duration (s)",
|
||||
"isPhysical": "Physical Book",
|
||||
"seriesStatus": "Series Status",
|
||||
"seriesGaps": "Series Gaps",
|
||||
"seriesPosition": "Series Position",
|
||||
"readingProgress": "Reading Progress (%)"
|
||||
},
|
||||
"fieldGroups": {
|
||||
"organization": "Organization",
|
||||
"bookInfo": "Book Info",
|
||||
"series": "Series",
|
||||
"dates": "Dates",
|
||||
"ratingsReviews": "Ratings & Reviews",
|
||||
"tagsMoods": "Tags & Moods",
|
||||
"audiobook": "Audiobook",
|
||||
"fileIdentifiers": "File & Identifiers"
|
||||
},
|
||||
"operators": {
|
||||
"equals": "Equals",
|
||||
@@ -98,7 +132,25 @@
|
||||
"greaterOrEqual": "\u2265 Greater or Equal",
|
||||
"lessThan": "< Less Than",
|
||||
"lessOrEqual": "\u2264 Less or Equal",
|
||||
"between": "Between"
|
||||
"between": "Between",
|
||||
"withinLast": "Within Last",
|
||||
"olderThan": "Older Than",
|
||||
"thisPeriod": "This Period",
|
||||
"is": "Is",
|
||||
"isNot": "Is Not",
|
||||
"has": "Has",
|
||||
"hasNot": "Has Not"
|
||||
},
|
||||
"booleanValues": {
|
||||
"yes": "Yes",
|
||||
"no": "No"
|
||||
},
|
||||
"contentRatings": {
|
||||
"everyone": "Everyone",
|
||||
"teen": "Teen",
|
||||
"mature": "Mature",
|
||||
"adult": "Adult",
|
||||
"explicit": "Explicit"
|
||||
},
|
||||
"readStatuses": {
|
||||
"unread": "Unread",
|
||||
@@ -111,6 +163,35 @@
|
||||
"abandoned": "Abandoned",
|
||||
"unset": "Unset"
|
||||
},
|
||||
"seriesStatuses": {
|
||||
"reading": "Currently Reading",
|
||||
"completed": "Completed",
|
||||
"ongoing": "Ongoing",
|
||||
"notStarted": "Not Started",
|
||||
"fullyRead": "Fully Read"
|
||||
},
|
||||
"seriesGaps": {
|
||||
"anyGap": "Any Gap",
|
||||
"missingFirst": "Missing First",
|
||||
"missingLatest": "Missing Latest",
|
||||
"duplicateNumber": "Duplicate Number"
|
||||
},
|
||||
"seriesPositions": {
|
||||
"nextUnread": "Next Unread",
|
||||
"firstInSeries": "First in Series",
|
||||
"lastInSeries": "Last in Series"
|
||||
},
|
||||
"dateUnits": {
|
||||
"days": "Days",
|
||||
"weeks": "Weeks",
|
||||
"months": "Months",
|
||||
"years": "Years"
|
||||
},
|
||||
"datePeriods": {
|
||||
"week": "This Week",
|
||||
"month": "This Month",
|
||||
"year": "This Year"
|
||||
},
|
||||
"toast": {
|
||||
"validationErrorSummary": "Validation Error",
|
||||
"validationErrorDetail": "You must add at least one valid rule before saving.",
|
||||
|
||||
@@ -42,7 +42,16 @@
|
||||
"selectFileType": "Seleccionar Tipo de Archivo",
|
||||
"selectLibrary": "Seleccionar Biblioteca",
|
||||
"selectShelf": "Seleccionar Estante",
|
||||
"selectGenre": "Seleccionar G\u00e9nero"
|
||||
"selectGenre": "Seleccionar G\u00e9nero",
|
||||
"selectValue": "Seleccionar Valor",
|
||||
"selectContentRating": "Seleccionar Clasificaci\u00f3n de Contenido",
|
||||
"selectContentRatings": "Seleccionar Clasificaciones de Contenido",
|
||||
"amount": "Cantidad",
|
||||
"selectUnit": "Seleccionar Unidad",
|
||||
"selectPeriod": "Seleccionar Per\u00edodo",
|
||||
"selectSeriesStatus": "Seleccionar Estado",
|
||||
"selectSeriesGap": "Seleccionar Tipo de Hueco",
|
||||
"selectSeriesPosition": "Seleccionar Posici\u00f3n"
|
||||
},
|
||||
"conditions": {
|
||||
"and": "Y",
|
||||
@@ -80,7 +89,32 @@
|
||||
"hardcoverRating": "Calificaci\u00f3n de Hardcover",
|
||||
"hardcoverReviewCount": "Cantidad de Rese\u00f1as de Hardcover",
|
||||
"ranobedbRating": "Calificaci\u00f3n de Ranobedb",
|
||||
"genre": "G\u00e9nero"
|
||||
"genre": "G\u00e9nero",
|
||||
"addedOn": "Fecha de Agregado",
|
||||
"lubimyczytacRating": "Calificaci\u00f3n de Lubimyczytac",
|
||||
"description": "Descripci\u00f3n",
|
||||
"narrator": "Narrador",
|
||||
"ageRating": "Clasificaci\u00f3n por Edad",
|
||||
"contentRating": "Clasificaci\u00f3n de Contenido",
|
||||
"audibleRating": "Calificaci\u00f3n de Audible",
|
||||
"audibleReviewCount": "Cantidad de Rese\u00f1as de Audible",
|
||||
"abridged": "Abreviado",
|
||||
"audiobookDuration": "Duraci\u00f3n del Audiolibro (s)",
|
||||
"isPhysical": "Libro F\u00edsico",
|
||||
"seriesStatus": "Estado de la Serie",
|
||||
"seriesGaps": "Huecos en la Serie",
|
||||
"seriesPosition": "Posici\u00f3n en la Serie",
|
||||
"readingProgress": "Progreso de Lectura (%)"
|
||||
},
|
||||
"fieldGroups": {
|
||||
"organization": "Organizaci\u00f3n",
|
||||
"bookInfo": "Info del Libro",
|
||||
"series": "Serie",
|
||||
"dates": "Fechas",
|
||||
"ratingsReviews": "Calificaciones y Rese\u00f1as",
|
||||
"tagsMoods": "Etiquetas y Estados de \u00c1nimo",
|
||||
"audiobook": "Audiolibro",
|
||||
"fileIdentifiers": "Archivo e Identificadores"
|
||||
},
|
||||
"operators": {
|
||||
"equals": "Igual",
|
||||
@@ -98,7 +132,25 @@
|
||||
"greaterOrEqual": "\u2265 Mayor o Igual",
|
||||
"lessThan": "< Menor Que",
|
||||
"lessOrEqual": "\u2264 Menor o Igual",
|
||||
"between": "Entre"
|
||||
"between": "Entre",
|
||||
"withinLast": "En los \u00daltimos",
|
||||
"olderThan": "Anterior a",
|
||||
"thisPeriod": "Este Per\u00edodo",
|
||||
"is": "Es",
|
||||
"isNot": "No Es",
|
||||
"has": "Tiene",
|
||||
"hasNot": "No Tiene"
|
||||
},
|
||||
"booleanValues": {
|
||||
"yes": "S\u00ed",
|
||||
"no": "No"
|
||||
},
|
||||
"contentRatings": {
|
||||
"everyone": "Todos",
|
||||
"teen": "Adolescentes",
|
||||
"mature": "Maduro",
|
||||
"adult": "Adulto",
|
||||
"explicit": "Expl\u00edcito"
|
||||
},
|
||||
"readStatuses": {
|
||||
"unread": "No Le\u00eddo",
|
||||
@@ -111,6 +163,35 @@
|
||||
"abandoned": "Abandonado",
|
||||
"unset": "Sin Establecer"
|
||||
},
|
||||
"seriesStatuses": {
|
||||
"reading": "Leyendo Actualmente",
|
||||
"completed": "Completada",
|
||||
"ongoing": "En Curso",
|
||||
"notStarted": "No Iniciada",
|
||||
"fullyRead": "Totalmente Le\u00edda"
|
||||
},
|
||||
"seriesGaps": {
|
||||
"anyGap": "Cualquier Hueco",
|
||||
"missingFirst": "Falta el Primero",
|
||||
"missingLatest": "Falta el \u00daltimo",
|
||||
"duplicateNumber": "N\u00famero Duplicado"
|
||||
},
|
||||
"seriesPositions": {
|
||||
"nextUnread": "Siguiente Sin Leer",
|
||||
"firstInSeries": "Primero de la Serie",
|
||||
"lastInSeries": "\u00daltimo de la Serie"
|
||||
},
|
||||
"dateUnits": {
|
||||
"days": "D\u00edas",
|
||||
"weeks": "Semanas",
|
||||
"months": "Meses",
|
||||
"years": "A\u00f1os"
|
||||
},
|
||||
"datePeriods": {
|
||||
"week": "Esta Semana",
|
||||
"month": "Este Mes",
|
||||
"year": "Este A\u00f1o"
|
||||
},
|
||||
"toast": {
|
||||
"validationErrorSummary": "Error de Validaci\u00f3n",
|
||||
"validationErrorDetail": "Debe agregar al menos una regla v\u00e1lida antes de guardar.",
|
||||
|
||||
Reference in New Issue
Block a user