add sorting
This commit is contained in:
@@ -22,7 +22,7 @@
|
|||||||
| 0.15 | Удаление неактивного набора: `DELETE /api/admin/sets/{id}` (DRAFT/ARCHIVED, каскадно с составом; ACTIVE → 409 `SET_STATE_CONFLICT`) — исключение из I5. Админское чтение состава набора: `GET /api/admin/sets/{id}/items` (id, name, iconUrl — presigned), сортировка по названию |
|
| 0.15 | Удаление неактивного набора: `DELETE /api/admin/sets/{id}` (DRAFT/ARCHIVED, каскадно с составом; ACTIVE → 409 `SET_STATE_CONFLICT`) — исключение из I5. Админское чтение состава набора: `GET /api/admin/sets/{id}/items` (id, name, iconUrl — presigned), сортировка по названию |
|
||||||
| 0.16 | Каскадное удаление зоны (FR-M1): `DELETE /api/admin/areas/{id}` — всё поддерево зон; достопримечательности (строки БД + файлы S3: эталонные фото с `.npz`, иконки, медиа ачивок), наборы с составами, посещения пользователей; файлы S3 — best-effort после строк БД |
|
| 0.16 | Каскадное удаление зоны (FR-M1): `DELETE /api/admin/areas/{id}` — всё поддерево зон; достопримечательности (строки БД + файлы S3: эталонные фото с `.npz`, иконки, медиа ачивок), наборы с составами, посещения пользователей; файлы S3 — best-effort после строк БД |
|
||||||
| 0.17 | Распознавание переведено на сервис dinoV2: эталонные фото больше не предобрабатываются (`.npz`-блобы, `/features`, FR-M7 и `cv_profile` удалены), `/verify` получает probe + все эталонные фото как images (1…32); админская проверка — по всей коллекции фото: `POST /api/admin/attractions/{id}/photos/verify` |
|
| 0.17 | Распознавание переведено на сервис dinoV2: эталонные фото больше не предобрабатываются (`.npz`-блобы, `/features`, FR-M7 и `cv_profile` удалены), `/verify` получает probe + все эталонные фото как images (1…32); админская проверка — по всей коллекции фото: `POST /api/admin/attractions/{id}/photos/verify` |
|
||||||
| 0.18 | Вердикт вычисляется нашим сервисом по confidence dino против границ `gorodar.dinov2.match-threshold`/`no-match-threshold` (0.75/0.55, переопределяются на достопримечательность — `PUT /api/admin/attractions/{id}/match-thresholds`, FR-M11); лимит эталонных фото — 15 (16-я загрузка → 409 `REFERENCE_PHOTO_LIMIT_EXCEEDED`); админская проверка итеративна — по одному эталону за вызов dino с процентами по каждому (`references[]`) |
|
| 0.18 | Вердикт вычисляется нашим сервисом по confidence dino против границ `gorodar.dinov2.match-threshold`/`no-match-threshold` (0.75/0.55, переопределяются на достопримечательность — `PUT /api/admin/attractions/{id}/match-thresholds`, FR-M11, любые значения 0…1); лимит эталонных фото — 15 (16-я загрузка → 409 `REFERENCE_PHOTO_LIMIT_EXCEEDED`); админская проверка итеративна — по одному эталону за вызов dino с процентами по каждому (`references[]`); сортировка зон публичного каталога — сначала с достопримечательностями, затем по алфавиту (FR-U1) |
|
||||||
|
|
||||||
## 1. Назначение документа
|
## 1. Назначение документа
|
||||||
|
|
||||||
@@ -108,6 +108,8 @@
|
|||||||
### 4.2 Пользовательская часть
|
### 4.2 Пользовательская часть
|
||||||
|
|
||||||
- **FR-U1.** Просмотр дерева зон — публично. Зона = название + вложенность (типа зоны нет).
|
- **FR-U1.** Просмотр дерева зон — публично. Зона = название + вложенность (типа зоны нет).
|
||||||
|
Порядок выдачи: сначала зоны, у которых есть достопримечательности (привязанные
|
||||||
|
напрямую), затем — по алфавиту.
|
||||||
- **FR-U2.** Просмотр активного набора зоны: список достопримечательностей с признаком
|
- **FR-U2.** Просмотр активного набора зоны: список достопримечательностей с признаком
|
||||||
«посещено текущим пользователем» (для анонима признак опускается/`false`).
|
«посещено текущим пользователем» (для анонима признак опускается/`false`).
|
||||||
- **FR-U3.** Просмотр карточки достопримечательности — публично. Состав карточки:
|
- **FR-U3.** Просмотр карточки достопримечательности — публично. Состав карточки:
|
||||||
@@ -452,8 +454,8 @@ AWS SDK v2 (`software.amazon.awssdk:s3`), совместимые реализа
|
|||||||
|
|
||||||
| Метод и путь | Доступ | Назначение |
|
| Метод и путь | Доступ | Назначение |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `GET /api/areas` | публично | Список корневых зон; `?parent-id={id}` — дети. Каждая зона — с `attractions` (активный набор: id, name, iconUrl, visited) и `progress {visited, total}`; анониму — visited=false везде, прогресс 0 |
|
| `GET /api/areas` | публично | Список корневых зон; `?parent-id={id}` — дети. Каждая зона — с `attractions` (активный набор: id, name, iconUrl, visited) и `progress {visited, total}`; анониму — visited=false везде, прогресс 0. Порядок: сначала зоны с достопримечательностями, затем по алфавиту (параметр sort игнорируется) |
|
||||||
| `GET /api/areas/{id}` | публично | Зона + дочерние зоны (дети — с тем же обогащением) + собственные `attractions`/`progress` |
|
| `GET /api/areas/{id}` | публично | Зона + дочерние зоны (дети — с тем же обогащением и порядком: сначала с достопримечательностями, затем по алфавиту) + собственные `attractions`/`progress` |
|
||||||
| `GET /api/areas/{id}/active-set` | публично | Активный набор зоны с достопримечательностями; с токеном — флаги `visited` (404 `NO_ACTIVE_SET`, если нет) |
|
| `GET /api/areas/{id}/active-set` | публично | Активный набор зоны с достопримечательностями; с токеном — флаги `visited` (404 `NO_ACTIVE_SET`, если нет) |
|
||||||
| `GET /api/attractions/{id}` | публично | Карточка достопримечательности |
|
| `GET /api/attractions/{id}` | публично | Карточка достопримечательности |
|
||||||
| `POST /api/attractions/{id}/visits` | user | **Ключевой эндпоинт**: multipart `photo` → `/verify` → отметка посещения |
|
| `POST /api/attractions/{id}/visits` | user | **Ключевой эндпоинт**: multipart `photo` → `/verify` → отметка посещения |
|
||||||
|
|||||||
@@ -29,8 +29,8 @@ public class PublicAreaController {
|
|||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public Page<AreaResponse> list(@RequestParam(name = "parent-id", required = false) UUID parentId,
|
public Page<AreaResponse> list(@RequestParam(name = "parent-id", required = false) UUID parentId,
|
||||||
@PageableDefault(size = 20, sort = "name") Pageable pageable) {
|
@PageableDefault(size = 20) Pageable pageable) {
|
||||||
return areaService.list(parentId, pageable);
|
return areaService.listPublic(parentId, pageable);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{id}")
|
@GetMapping("/{id}")
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import ru.gorodar.dao.entity.Area;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
public interface AreaRepository extends JpaRepository<Area, UUID> {
|
public interface AreaRepository extends JpaRepository<Area, UUID>, AreaRepositoryCustom {
|
||||||
|
|
||||||
Page<Area> findByParentIsNull(Pageable pageable);
|
Page<Area> findByParentIsNull(Pageable pageable);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package ru.gorodar.dao;
|
||||||
|
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import ru.gorodar.dao.entity.Area;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface AreaRepositoryCustom {
|
||||||
|
|
||||||
|
/** Публичный каталог: сначала зоны с достопримечательностями, затем по алфавиту. */
|
||||||
|
Page<Area> findPageByAttractionsFirstThenName(UUID parentId, Pageable pageable);
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package ru.gorodar.dao;
|
||||||
|
|
||||||
|
import jakarta.persistence.EntityManager;
|
||||||
|
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||||
|
import jakarta.persistence.criteria.CriteriaQuery;
|
||||||
|
import jakarta.persistence.criteria.Expression;
|
||||||
|
import jakarta.persistence.criteria.Predicate;
|
||||||
|
import jakarta.persistence.criteria.Root;
|
||||||
|
import jakarta.persistence.criteria.Subquery;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageImpl;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import ru.gorodar.dao.entity.Area;
|
||||||
|
import ru.gorodar.dao.entity.Area_;
|
||||||
|
import ru.gorodar.dao.entity.Attraction;
|
||||||
|
import ru.gorodar.dao.entity.Attraction_;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Фрагмент AreaRepository для порядка публичного каталога: ORDER BY с коррелированным
|
||||||
|
* подзапросом невыразим через Specification (Sort принимает только пути атрибутов),
|
||||||
|
* поэтому Criteria-запрос руками — с метамоделью, без @Query. Порядок считает БД:
|
||||||
|
* сначала зоны с достопримечательностями, затем по алфавиту.
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public class AreaRepositoryCustomImpl implements AreaRepositoryCustom {
|
||||||
|
|
||||||
|
private final EntityManager entityManager;
|
||||||
|
|
||||||
|
public AreaRepositoryCustomImpl(EntityManager entityManager) {
|
||||||
|
this.entityManager = entityManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Page<Area> findPageByAttractionsFirstThenName(UUID parentId, Pageable pageable) {
|
||||||
|
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||||
|
|
||||||
|
CriteriaQuery<Area> query = cb.createQuery(Area.class);
|
||||||
|
Root<Area> root = query.from(Area.class);
|
||||||
|
query.select(root)
|
||||||
|
.where(levelPredicate(cb, root, parentId))
|
||||||
|
.orderBy(
|
||||||
|
cb.asc(attractionsRank(cb, query, root)),
|
||||||
|
cb.asc(root.get(Area_.name)));
|
||||||
|
|
||||||
|
if (pageable.isUnpaged()) {
|
||||||
|
return new PageImpl<>(entityManager.createQuery(query).getResultList());
|
||||||
|
}
|
||||||
|
|
||||||
|
CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
|
||||||
|
Root<Area> countRoot = countQuery.from(Area.class);
|
||||||
|
countQuery.select(cb.count(countRoot))
|
||||||
|
.where(levelPredicate(cb, countRoot, parentId));
|
||||||
|
|
||||||
|
List<Area> content = entityManager.createQuery(query)
|
||||||
|
.setFirstResult((int) pageable.getOffset())
|
||||||
|
.setMaxResults(pageable.getPageSize())
|
||||||
|
.getResultList();
|
||||||
|
long total = entityManager.createQuery(countQuery).getSingleResult();
|
||||||
|
return new PageImpl<>(content, pageable, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate levelPredicate(CriteriaBuilder cb, Root<Area> root, UUID parentId) {
|
||||||
|
return parentId == null
|
||||||
|
? cb.isNull(root.get(Area_.parent))
|
||||||
|
: cb.equal(root.get(Area_.parent).get(Area_.id), parentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 0, если у зоны есть привязанные достопримечательности, иначе 1 — по возрастанию
|
||||||
|
* зоны с достопримечательностями оказываются первыми, алфавит добирает второй ORDER BY. */
|
||||||
|
private Expression<Integer> attractionsRank(CriteriaBuilder cb, CriteriaQuery<?> query, Root<Area> area) {
|
||||||
|
Subquery<Long> attractionCount = query.subquery(Long.class);
|
||||||
|
Root<Attraction> attraction = attractionCount.from(Attraction.class);
|
||||||
|
attractionCount.select(cb.count(attraction.get(Attraction_.id)))
|
||||||
|
.where(cb.equal(attraction.get(Attraction_.area).get(Area_.id), area.get(Area_.id)));
|
||||||
|
return cb.<Integer>selectCase()
|
||||||
|
.when(cb.greaterThan(attractionCount, 0L), 0)
|
||||||
|
.otherwise(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -66,9 +66,20 @@ public class AreaService {
|
|||||||
return result.map(this::toOverview);
|
return result.map(this::toOverview);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Публичный каталог: сначала зоны с достопримечательностями, затем по алфавиту.
|
||||||
|
* Порядок и пагинация — на стороне БД (AreaRepositoryCustomImpl, Criteria с CASE
|
||||||
|
* над подзапросом счёта достопримечательностей).
|
||||||
|
*/
|
||||||
|
public Page<AreaResponse> listPublic(UUID parentId, Pageable pageable) {
|
||||||
|
return areaRepository.findPageByAttractionsFirstThenName(parentId, pageable)
|
||||||
|
.map(this::toOverview);
|
||||||
|
}
|
||||||
|
|
||||||
public AreaWithChildrenResponse get(UUID id) {
|
public AreaWithChildrenResponse get(UUID id) {
|
||||||
Area area = getArea(id);
|
Area area = getArea(id);
|
||||||
List<AreaResponse> children = areaRepository.findByParentIdOrderByNameAsc(id).stream()
|
List<AreaResponse> children = areaRepository
|
||||||
|
.findPageByAttractionsFirstThenName(id, Pageable.unpaged()).getContent().stream()
|
||||||
.map(this::toOverview)
|
.map(this::toOverview)
|
||||||
.toList();
|
.toList();
|
||||||
AreaActiveSetInfo info = setService.getAreaActiveSetInfo(id);
|
AreaActiveSetInfo info = setService.getAreaActiveSetInfo(id);
|
||||||
|
|||||||
@@ -50,8 +50,8 @@ gorodar:
|
|||||||
# Вердикт вычисляем сами по confidence dino: >= match-threshold — match,
|
# Вердикт вычисляем сами по confidence dino: >= match-threshold — match,
|
||||||
# <= no-match-threshold — no_match, между ними — uncertain. Переопределяется
|
# <= no-match-threshold — no_match, между ними — uncertain. Переопределяется
|
||||||
# для конкретной достопримечательности (attractions.match_threshold и т.д.)
|
# для конкретной достопримечательности (attractions.match_threshold и т.д.)
|
||||||
match-threshold: ${GORODAR_DINOV2_MATCH_THRESHOLD:0.75}
|
match-threshold: ${GORODAR_DINOV2_MATCH_THRESHOLD:0.55}
|
||||||
no-match-threshold: ${GORODAR_DINOV2_NO_MATCH_THRESHOLD:0.55}
|
no-match-threshold: ${GORODAR_DINOV2_NO_MATCH_THRESHOLD:0.45}
|
||||||
max-reference-photos: ${GORODAR_DINOV2_MAX_REFERENCE_PHOTOS:15}
|
max-reference-photos: ${GORODAR_DINOV2_MAX_REFERENCE_PHOTOS:15}
|
||||||
unisender:
|
unisender:
|
||||||
base-url: ${GORODAR_UNISENDER_URL:https://goapi.unisender.ru}
|
base-url: ${GORODAR_UNISENDER_URL:https://goapi.unisender.ru}
|
||||||
|
|||||||
@@ -5,6 +5,14 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
|||||||
import org.mockito.InjectMocks;
|
import org.mockito.InjectMocks;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageImpl;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import ru.gorodar.api.dto.AreaDtos.AreaResponse;
|
||||||
|
import ru.gorodar.api.dto.AreaDtos.AreaWithChildrenResponse;
|
||||||
|
import ru.gorodar.api.dto.SetDtos.AreaActiveSetInfo;
|
||||||
|
import ru.gorodar.api.dto.VisitDtos.ProgressResponse;
|
||||||
import ru.gorodar.dao.AreaRepository;
|
import ru.gorodar.dao.AreaRepository;
|
||||||
import ru.gorodar.dao.AttractionPhotoRepository;
|
import ru.gorodar.dao.AttractionPhotoRepository;
|
||||||
import ru.gorodar.dao.AttractionRepository;
|
import ru.gorodar.dao.AttractionRepository;
|
||||||
@@ -29,7 +37,9 @@ import java.util.UUID;
|
|||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyList;
|
import static org.mockito.ArgumentMatchers.anyList;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.verifyNoInteractions;
|
import static org.mockito.Mockito.verifyNoInteractions;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
@@ -136,4 +146,62 @@ class AreaServiceTest {
|
|||||||
assertThat(error.getCode()).isEqualTo(ErrorCode.AREA_NOT_FOUND);
|
assertThat(error.getCode()).isEqualTo(ErrorCode.AREA_NOT_FOUND);
|
||||||
verifyNoInteractions(s3Storage);
|
verifyNoInteractions(s3Storage);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void publicListReturnsAreasInRepositoryCatalogOrder() {
|
||||||
|
Pageable pageable = PageRequest.of(0, 20);
|
||||||
|
// порядок (сначала зоны с достопримечательностями, затем по алфавиту) считает БД
|
||||||
|
Area alpha = areaNamed("Alpha");
|
||||||
|
Area gamma = areaNamed("Gamma");
|
||||||
|
Area beta = areaNamed("Beta");
|
||||||
|
when(areaRepository.findPageByAttractionsFirstThenName(null, pageable))
|
||||||
|
.thenReturn(new PageImpl<>(List.of(alpha, gamma, beta), pageable, 3));
|
||||||
|
stubOverview();
|
||||||
|
|
||||||
|
Page<AreaResponse> page = service.listPublic(null, pageable);
|
||||||
|
|
||||||
|
assertThat(page.getContent()).extracting(AreaResponse::name)
|
||||||
|
.containsExactly("Alpha", "Gamma", "Beta");
|
||||||
|
assertThat(page.getTotalElements()).isEqualTo(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getReturnsChildrenInRepositoryCatalogOrder() {
|
||||||
|
Area root = EntityTestHelper.areaOf(rootId);
|
||||||
|
Area alpha = areaNamed("Alpha");
|
||||||
|
Area gamma = areaNamed("Gamma");
|
||||||
|
Area beta = areaNamed("Beta");
|
||||||
|
when(areaRepository.findById(rootId)).thenReturn(Optional.of(root));
|
||||||
|
when(areaRepository.findPageByAttractionsFirstThenName(eq(rootId), any(Pageable.class)))
|
||||||
|
.thenReturn(new PageImpl<>(List.of(alpha, gamma, beta)));
|
||||||
|
AreaActiveSetInfo info = new AreaActiveSetInfo(List.of(), new ProgressResponse(0, 0));
|
||||||
|
when(setService.getAreaActiveSetInfo(any())).thenReturn(info);
|
||||||
|
when(areaMapper.toResponse(any(Area.class), anyList(), any())).thenAnswer(invocation -> {
|
||||||
|
Area area = invocation.getArgument(0);
|
||||||
|
return new AreaResponse(area.getId(), null, area.getName(), List.of(), null);
|
||||||
|
});
|
||||||
|
when(areaMapper.toWithChildrenResponse(eq(root), anyList(), anyList(), any()))
|
||||||
|
.thenAnswer(invocation -> new AreaWithChildrenResponse(
|
||||||
|
rootId, null, root.getName(), invocation.getArgument(1), List.of(), null));
|
||||||
|
|
||||||
|
AreaWithChildrenResponse response = service.get(rootId);
|
||||||
|
|
||||||
|
assertThat(response.children()).extracting(AreaResponse::name)
|
||||||
|
.containsExactly("Alpha", "Gamma", "Beta");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Area areaNamed(String name) {
|
||||||
|
Area area = EntityTestHelper.areaOf(UUID.randomUUID());
|
||||||
|
area.setName(name);
|
||||||
|
return area;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stubOverview() {
|
||||||
|
AreaActiveSetInfo info = new AreaActiveSetInfo(List.of(), new ProgressResponse(0, 0));
|
||||||
|
when(setService.getAreaActiveSetInfo(any())).thenReturn(info);
|
||||||
|
when(areaMapper.toResponse(any(Area.class), anyList(), any())).thenAnswer(invocation -> {
|
||||||
|
Area area = invocation.getArgument(0);
|
||||||
|
return new AreaResponse(area.getId(), null, area.getName(), List.of(), null);
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user