init
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
---
|
||||
name: jpa-entity
|
||||
description: Создание и изменение JPA-сущностей и репозиториев gorodar back: раскладка dao/entity и dao, явные имена колонок, LocalDateTime/UTC, enum-конвертеры, метамодель. Использовать при любой правке структуры сущностей, добавлении полей или нового агрегата. Use when creating or modifying JPA entities, fields, enums, or Spring Data repositories.
|
||||
---
|
||||
|
||||
# JPA-сущности и репозитории gorodar back
|
||||
|
||||
## Раскладка
|
||||
|
||||
- Entity — `ru.gorodar.dao.entity` (+ подпакет `converter` для AttributeConverter'ов).
|
||||
- Репозитории — в корне `ru.gorodar.dao`, наследуют `JpaRepository<X, UUID>` и `JpaSpecificationExecutor<X>`
|
||||
(второй обязателен: запросы только через Specification, см. скилл jpa-specification).
|
||||
- Новая сущность = пара: entity + Liquibase-миграция (скилл liquibase-migration).
|
||||
|
||||
## Обязательные правила entity
|
||||
|
||||
1. **Явное имя каждой колонки** — у любого поля есть `@Column(name = "…")` или `@JoinColumn(name = "…")`,
|
||||
включая `@Id` (`@Id @Column(name = "id")`). Неявная naming strategy не используется.
|
||||
2. **Время — только `LocalDateTime`** (никаких `Instant`). UTC обеспечивает `TimeZone.setDefault` в `main()`
|
||||
и `hibernate.jdbc.time_zone: UTC`; вручную — `LocalDateTime.now(ZoneOffset.UTC)`.
|
||||
Служебные поля: `@CreationTimestamp`/`@UpdateTimestamp` на created_at/updated_at.
|
||||
3. **Без пустых строк между полями** внутри класса — компактные блоки аннотация+поле.
|
||||
4. **ID генерирует приложение**: `entity.setId(UUID.randomUUID())`, никакой @GeneratedValue.
|
||||
5. Lombok `@Getter @Setter` на классе; связки `@ManyToOne(fetch = LAZY)` + `@JoinColumn`.
|
||||
6. Enum-хранение — всегда `@Enumerated(EnumType.STRING)` (в БД лежат имена констант в верхнем регистре:
|
||||
`DRAFT`, `FACADE`, `MATCH`). `AttributeConverter` для enum'ов не используется. Нижний регистр в API
|
||||
(`facade`, `match`) — только на границе: MapStruct-мапперы и клиенты конвертируют
|
||||
`enum.name().toLowerCase()`.
|
||||
|
||||
## Образец
|
||||
|
||||
```java
|
||||
@Entity
|
||||
@Table(name = "examples")
|
||||
@Getter
|
||||
@Setter
|
||||
public class Example {
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private UUID id;
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "area_id", nullable = false)
|
||||
private Area area;
|
||||
@Column(name = "name", nullable = false)
|
||||
private String name;
|
||||
@Column(name = "facts")
|
||||
@JdbcTypeCode(SqlTypes.JSON)
|
||||
private List<String> facts;
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
```
|
||||
|
||||
## Чтение связей без транзакции
|
||||
|
||||
`lazyProxy.getId()` безопасно (не инициализирует прокси) — используется вместо проекций.
|
||||
Обращение к другим полям связки — только внутри `@Transactional` (обычно `readOnly = true`).
|
||||
|
||||
После правки сущности код генерирует метамодель `X_` (hibernate-jpamodelgen) — Specification'ы
|
||||
в `dao.spec` должны ссылаться на новые поля через `Example_.name`, см. скилл jpa-specification.
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
name: jpa-specification
|
||||
description: Запросы к данным gorodar back через Spring Data JPA Specification и сгенерированную Hibernate-метамодель. Использовать вместо @Query при любых фильтрах, вложенных join'ах, проверках существования по связям; при модификации наборов предикатов. Use for repository queries and filtering — Specifications + JPA metamodel, never @Query or string criteria paths.
|
||||
---
|
||||
|
||||
# Specification + метамодель gorodar back
|
||||
|
||||
## Правила
|
||||
|
||||
1. **`@Query` в репозиториях не используется** — ни JPQL, ни native. Простые выборки — derived-методы
|
||||
(`findByAreaId`, `existsByAttractionIdAndSet_Status`), всё сложнее — Specification.
|
||||
2. **Строковые пути критерии запрещены**: никакого `root.get("name")` — только сгенерированная
|
||||
метамодель `Entity_.field` (процессор `hibernate-jpamodelgen` генерирует `X_`-классы рядом с entity
|
||||
в `build/generated`). Опечатка должна ломать компиляцию, а не рантайм.
|
||||
3. Предикаты живут в `ru.gorodar.dao.spec` — статические фабрики `XxxSpecs`:
|
||||
|
||||
```java
|
||||
public final class AttractionSetItemSpecs {
|
||||
public static Specification<AttractionSetItem> ofActiveSetInArea(UUID areaId) {
|
||||
return (root, query, cb) -> cb.and(
|
||||
cb.equal(root.get(AttractionSetItem_.set).get(AttractionSet_.area).get(Area_.id), areaId),
|
||||
cb.equal(root.get(AttractionSetItem_.set).get(AttractionSet_.status), SetStatus.ACTIVE));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Сортировка внутри предиката: `query.orderBy(cb.asc(root.get(X_.attraction).get(Attraction_.name)));`
|
||||
|
||||
4. Репозиторий обязан наследовать `JpaSpecificationExecutor<X>` (все dao-репозитории уже наследуют).
|
||||
|
||||
## Паттерны
|
||||
|
||||
- **Массовое обновление** (аналог modifying update): `findAll(spec)` → сменить поля → `saveAll`,
|
||||
всё внутри `@Transactional`. Пример — архивирование активного набора при активации нового в
|
||||
`AttractionSetService.activate`. Уникальные индексы БД продолжают охранять инварианты.
|
||||
- **Проекции**: селектить сущности, а не поля; id связки брать как `item.getAttraction().getId()`
|
||||
(безопасно на lazy-прокси, транзакция не нужна); другие поля связки — только в `@Transactional(readOnly = true)`.
|
||||
- **Фильтры списков** (admin): `VisitSpecs.filtered(areaId, attractionId, userId, from, to)` + `findAll(spec, pageable)`.
|
||||
|
||||
## В тестах
|
||||
|
||||
Mockito-стабы на `findAll(Specification)` пишут с типизированным матчером (голый `any()` двусмыслен из-за
|
||||
перегрузок):
|
||||
|
||||
```java
|
||||
private static <T> Specification<T> anySpec() {
|
||||
return ArgumentMatchers.any();
|
||||
}
|
||||
when(itemRepository.findAll(anySpec())).thenReturn(List.of(item));
|
||||
```
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
name: liquibase-migration
|
||||
description: Схемные изменения БД проекта gorodar back (новые таблицы, колонки, индексы, констрейнты). Использовать, когда нужно изменить схему PostgreSQL, добавить сущность с таблицей, или когда валидация Hibernate (ddl-auto=validate) падает на несовпадении схемы. Use for any database schema change, new table/column/index, or Liquibase validation errors.
|
||||
---
|
||||
|
||||
# Liquibase-миграции gorodar back
|
||||
|
||||
Все изменения схемы — только через Liquibase, никакого ad-hoc DDL. `spring.jpa.hibernate.ddl-auto=validate`,
|
||||
поэтому сущность и схема обязаны совпадать — миграция и правка entity идут парой.
|
||||
|
||||
## Порядок работы
|
||||
|
||||
1. Новый файл `src/main/resources/db/changelog/changelogs/NNN-имя.sql` (нумерация сквозная, следующий свободный номер).
|
||||
2. Зарегистрировать его в `src/main/resources/db/changelog/db.changelog-master.yaml` (порядок include = порядок применения).
|
||||
3. Синхронно поправить entity в `ru.gorodar.dao.entity` (см. скилл jpa-entity).
|
||||
4. Прогнать `./gradlew build` — validate поймает расхождение.
|
||||
|
||||
## Формат changelog
|
||||
|
||||
SQL-формат Liquibase:
|
||||
|
||||
```sql
|
||||
--liquibase formatted sql
|
||||
|
||||
--changeset gorodar:NNN-таблица
|
||||
create table example (
|
||||
id uuid primary key,
|
||||
created_at timestamp not null default (now() at time zone 'utc')
|
||||
);
|
||||
|
||||
--changeset gorodar:NNN-индексы
|
||||
create index idx_example_parent on example (parent_id);
|
||||
```
|
||||
|
||||
## Конвенции схемы
|
||||
|
||||
- PK — `uuid`, генерируется приложением (не БД).
|
||||
- Время — только `timestamp` **без** `timestamptz`, дефолт `(now() at time zone 'utc')`. Вся система в UTC.
|
||||
- Имена snake_case; FK-колонки `<сущность>_id`; индексы `idx_…`, уникальные `uq_…`.
|
||||
- Бизнес-инварианты — на стороне БД:
|
||||
- «не более одного активного набора на зону» — partial unique index:
|
||||
`create unique index uq_attraction_sets_active_area on attraction_sets (area_id) where status = 'ACTIVE';`
|
||||
- составная уникальность — `constraint uq_… unique (a, b)`;
|
||||
- enum-статусы — `constraint ck_… check (status in ('DRAFT', 'ACTIVE', 'ARCHIVED'))`.
|
||||
- Удаления данных нет (кроме эталонных фото) — DELETE-констрейнты не нужны.
|
||||
|
||||
## Пример: добавить колонку
|
||||
|
||||
```sql
|
||||
--changeset gorodar:005-add-example-column
|
||||
alter table attractions
|
||||
add column example_field varchar(64);
|
||||
```
|
||||
|
||||
И тут же `@Column(name = "example_field") private String exampleField;` в entity.
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
name: opencv-integration
|
||||
description: Интеграция gorodar back с сервисом распознавания open_cv — извлечение SIFT-признаков (/features), верификация фото посещений (/verify), трактовка вердиктов, маппинг ошибок, ключ X-API-Key. Использовать при любой правке сценария визита, загрузки/пересчёта эталонов или обработки ответов open_cv. Use for visit verification flow, reference photo features extraction, open_cv error mapping.
|
||||
---
|
||||
|
||||
# Интеграция с open_cv
|
||||
|
||||
Stateless CV-сервис, авторизация заголовком `X-API-Key` (конфиг `gorodar.opencv.base-url` / `api-key`).
|
||||
Клиент — `OpenCvClient` (RestClient; multipart-части с `application/octet-stream`).
|
||||
Ничего не хранит: фото и блобы признаков — наши, в S3.
|
||||
|
||||
## POST /api/v1/features — при загрузке и пересчёте эталона
|
||||
|
||||
- Запрос: часть `image` (бинарник) + часть `settings` (JSON-строка `{"profile":"facade|monument|repetitive"}`).
|
||||
Профиль берётся с достопримечательности (`attraction.cvProfile`), не с фото.
|
||||
- Ответ: тело — блоб `.npz` (непрозрачен: сохранить в S3 как есть, не разбирать); заголовки
|
||||
`X-Feature-Format-Version`, `X-Algo-Id`, `X-Keypoints-Count` — пишутся в `attraction_photos`.
|
||||
- Смена cvProfile существующие блобы не пересчитывает; пересчёт — эндпоинт `/photos/{photoId}/features`.
|
||||
- Ретраи допустимы (админская операция).
|
||||
|
||||
## POST /api/v1/verify — при подтверждении посещения
|
||||
|
||||
- Запрос: `probe` — байты фото пользователя **напрямую из запроса** (не сохранять) + `reference` —
|
||||
блобы `.npz`; на старте один reference: фото с минимальным `sort_order`.
|
||||
- Ответ: `verdict` (match | uncertain | no_match), `confidence`, `probe_sha256`.
|
||||
- Вердикты: `match` → фиксировать визит (confidence + probe_sha256 в БД), `uncertain`/`no_match` →
|
||||
не фиксировать (UNCERTAIN/NOT_MATCHED клиенту). Модерации uncertain нет.
|
||||
- Результат детерминирован — **ретраев нет**; недоступность/таймаут → 503 `OPENCV_UNAVAILABLE`.
|
||||
|
||||
## Маппинг ошибок open_cv → наши коды
|
||||
|
||||
| open_cv | Ответ |
|
||||
|---|---|
|
||||
| `IMAGE_DECODE_FAILED`, `IMAGE_TOO_SMALL`, 415 | 400 `INVALID_PHOTO` |
|
||||
| 413 | 413 `PAYLOAD_TOO_LARGE` |
|
||||
| `FEATURE_BLOB_INVALID`, `FEATURE_FORMAT_UNSUPPORTED` | 503 `REFERENCE_UNAVAILABLE` (пересчитать признаки) |
|
||||
| 401/403 от open_cv, 5xx, таймаут | 503 `OPENCV_UNAVAILABLE` |
|
||||
| прочие (`TOO_MANY_REFERENCES`, …) | 500 — ошибка нашего клиента |
|
||||
|
||||
## Ключевой сценарий (VisitService.submit)
|
||||
|
||||
Порядок: attraction существует → входит в **активный** набор зоны (иначе 409
|
||||
`ATTRACTION_NOT_IN_ACTIVE_SET`) → визита ещё нет (иначе `ALREADY_VISITED`) → взять npz эталона из S3 →
|
||||
`/verify` → при match вставка визита (гонку параллельных запросов закрывает unique-констрейнт
|
||||
`user_id+attraction_id`, ловим DataIntegrityViolation → `ALREADY_VISITED`).
|
||||
Ответ: `{status, confidence, progress{visited,total}}`.
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
name: rest-endpoint
|
||||
description: Добавление и изменение REST API gorodar back — контроллеры, DTO, пагинация, валидация, ошибки, MapStruct-маппинг. Использовать при любом новом эндпоинте (публичном, пользовательском, админском), правке контракта, DTO или формата ошибок. Use for any REST endpoint, controller, DTO, pagination, or error-model change.
|
||||
---
|
||||
|
||||
# REST-эндпоинты gorodar back
|
||||
|
||||
## Раскладка
|
||||
|
||||
- Контроллеры: `ru.gorodar.api.publicc` / `api.user` / `api.admin` (`publicc` — из-за ключевого слова `public`).
|
||||
- DTO: records-контейнеры `ru.gorodar.api.dto` (`AreaDtos`, `VisitDtos`, …): request/response — вложенные records.
|
||||
- Мапперы entity→DTO: `ru.gorodar.mapper` (MapStruct), `componentModel = "spring"`, `unmappedTargetPolicy = ERROR`.
|
||||
- Swagger-группы: `@Tag(name = "public" | "user" | "admin")`.
|
||||
|
||||
## Контракт
|
||||
|
||||
- База `/api`, админка `/api/admin/**`.
|
||||
- **Query- и multipart-параметры — kebab-case** (`parent-id`, `area-id`, `sort-order`, `file`, `photo`);
|
||||
**поля JSON-тел — camelCase**.
|
||||
- Пагинация: `Pageable` из query (`page`/`size`/`sort`) с дефолтом
|
||||
`@PageableDefault(size = 20, sort = "…")`; в телах параметров пагинации нет.
|
||||
Ответ — `org.springframework.data.domain.Page<T>` (на классе приложения включена сериализация
|
||||
`VIA_DTO` через `@EnableSpringDataWebSupport`) — не оборачивать в свои DTO.
|
||||
- Списки-фильтры с телом: POST + фильтры в body + Pageable из query (`POST /api/admin/visits` — образец).
|
||||
|
||||
## DTO и валидация
|
||||
|
||||
- Request-records: `@NotBlank`/`@NotNull`/`@Pattern` (+`@Valid` в контроллере), UUID приходят строкой-UUID.
|
||||
- Response с 4+ полями строит MapStruct — конструкторы в коде не шире трёх аргументов, builder'ы не используем.
|
||||
|
||||
## MapStruct-маппер
|
||||
|
||||
Вычисляемые сервисом значения (presigned-ссылки, счётчики, флаги) — вторыми-третьими аргументами
|
||||
(multi-source); enum ↔ строка в нижнем регистре — default-методом:
|
||||
|
||||
```java
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR)
|
||||
public interface ExampleMapper {
|
||||
@Mapping(target = "photoUrl", source = "photoUrl")
|
||||
ExampleResponse toResponse(Example example, String photoUrl);
|
||||
|
||||
default String map(CvProfile profile) {
|
||||
return profile == null ? null : profile.name().toLowerCase();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Вложенные пути — `@Mapping(target = "areaId", source = "example.area.id")`.
|
||||
|
||||
## Модель ошибок
|
||||
|
||||
1. Добавить код в `ErrorCode` (HTTP-статус + русское сообщение по умолчанию).
|
||||
2. Бросать `ApiException(ErrorCode.X)` из сервиса; свободный текст — вторым аргументом.
|
||||
3. `GlobalExceptionHandler` уже отдаёт `ApiError {code, message, timestamp(UTC)}`; валидация → 400
|
||||
`VALIDATION_ERROR`, oversized upload → 413. Новые handler'ы — только для новых типов исключений.
|
||||
|
||||
## Обязательная проверка
|
||||
|
||||
`./gradlew build` — MapStruct с `unmappedTargetPolicy = ERROR` и `ddl-auto=validate` ловят
|
||||
рассинхрон DTO/сущностей на этапе компиляции/старта.
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
name: s3-storage
|
||||
description: Хранение файлов gorodar back — эталонные фото, блобы признаков .npz, иконки достопримечательностей в S3/MinIO через AWS SDK v2: put/get/delete, presigned-ссылки, соглашения о ключах. Использовать при любой работе с файлами, загрузке/отдаче/удалении, построении URL. Use for file uploads, downloads, presigned URLs, S3 keys and lifecycle.
|
||||
---
|
||||
|
||||
# S3-хранилище gorodar back
|
||||
|
||||
Клиент — `S3Storage` (AWS SDK v2, обёртка над `S3Client` + `S3Presigner`). Один bucket,
|
||||
path-style доступ для MinIO, конфиг в `gorodar.s3.*` (`endpoint`, `region`, `access-key`,
|
||||
`secret-key`, `bucket`, `path-style-access`, `presign-ttl`).
|
||||
|
||||
## Методы
|
||||
|
||||
- `put(key, bytes, contentType)` / `get(key)` — throws `ApiException(S3_UNAVAILABLE)`;
|
||||
`get` по отсутствующему ключу → `REFERENCE_UNAVAILABLE`.
|
||||
- `delete(key)` — удаление объекта.
|
||||
- `presignGetUrl(key)` — URL на отдачу наружу. **Файлы непубличны**: наружу только presigned GET,
|
||||
никаких публичных bucket-политик.
|
||||
|
||||
## Соглашения о ключах
|
||||
|
||||
| Данные | Ключ |
|
||||
|---|---|
|
||||
| Эталонное фото | `attractions/{attractionId}/reference/{photoId}.jpg` |
|
||||
| Блоб признаков (.npz) | `attractions/{attractionId}/reference/{photoId}.npz` — рядом с фото, общий photoId |
|
||||
| Иконка | `attractions/{attractionId}/icon/{fileId}.{ext}` |
|
||||
|
||||
- Ключи формирует бэкенд, в БД хранятся только ключи (никаких URL).
|
||||
- Версионирование — новый `photoId`/`fileId`, старые файлы не перезаписываются.
|
||||
- **Фото пользователей не хранятся вовсе**: байты из запроса уходят в open_cv и отбрасываются.
|
||||
|
||||
## Паттерны
|
||||
|
||||
- Загрузка: сначала `put`, затем БД-строка; на каждое эталонное фото — извлечение признаков
|
||||
(см. скилл opencv-integration), `.npz` кладётся вторым объектом.
|
||||
- Отдача наружу: сервис вычисляет presigned URL и передаёт его в MapStruct-маппер отдельным
|
||||
аргументом (`toResponse(entity, iconUrl, photoUrl)`).
|
||||
- Удаление: сначала строка БД, затем файлы best-effort — сбой S3 логируется warn'ом и не ломает
|
||||
операцию (пример — `ReferencePhotoService.delete`).
|
||||
@@ -0,0 +1,54 @@
|
||||
---
|
||||
name: security-rules
|
||||
description: Авторизация gorodar back — Keycloak JWT, client roles клиента gorodar (manage_area/manage_attraction), разграничение public/user/admin эндпоинтов, CurrentUser с claim sub. Использовать при добавлении защищённых или публичных путей, смене ролей, работе с токеном/subject пользователя. Use for endpoint authorization, Keycloak roles, JWT validation, CurrentUser.
|
||||
---
|
||||
|
||||
# Security gorodar back
|
||||
|
||||
Resource-server only: бэкенд только валидирует входящие JWT (oauth2-client отсутствует).
|
||||
Стартер Boot 4: `spring-boot-starter-security-oauth2-resource-server` (+`-test`).
|
||||
|
||||
## Роли
|
||||
|
||||
Client roles клиента **`gorodar`** (настройка `gorodar.keycloak.client-id`), извлекаются из
|
||||
`resource_access.gorodar.roles` конвертером `KeycloakJwtAuthenticationConverter` и становятся
|
||||
authorities с точным совпадением имён:
|
||||
|
||||
- `manage_area` — зоны, наборы, статистика посещений;
|
||||
- `manage_attraction` — достопримечательности, иконки, эталонные фото, пересчёт признаков;
|
||||
- любой аутентифицированный — пользовательская часть.
|
||||
|
||||
## Матчеры в SecurityConfig (порядок важен)
|
||||
|
||||
```java
|
||||
.requestMatchers("/api/admin/attractions/**").hasAuthority("manage_attraction")
|
||||
.requestMatchers("/api/admin/areas/**", "/api/admin/sets/**", "/api/admin/visits/**")
|
||||
.hasAuthority("manage_area")
|
||||
.requestMatchers("/api/admin/**").denyAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/areas/**", "/api/attractions/**").permitAll()
|
||||
.requestMatchers("/api/**").authenticated()
|
||||
.requestMatchers("/error", "/actuator/health/**", "/actuator/info",
|
||||
"/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll()
|
||||
.anyRequest().denyAll()
|
||||
```
|
||||
|
||||
Новый админский эндпоинт должен попасть под существующий префикс роли; новый префикс — добавить
|
||||
матчер ДО `/api/admin/**`. Публичные GET каталога — permitAll с опциональной аутентификацией:
|
||||
ответ обогащается персональными данными, если токен пришёл и валиден.
|
||||
|
||||
## Валидация токена
|
||||
|
||||
`issuer-uri` из `spring.security.oauth2.resourceserver.jwt.*` (подпись/JWKS/срок/issuer — стандартные
|
||||
валидаторы) + audience-проверка в `SecurityConfig.jwtDecoder`: пропускаем, если `aud` содержит `gorodar`
|
||||
**или** `azp == gorodar` (Keycloak по умолчанию кладёт клиента только в azp). CSRF выключен, сессии stateless.
|
||||
|
||||
## Текущий пользователь
|
||||
|
||||
Claim `sub` — идентификатор пользователя (ключ визитов). Доступ — `CurrentUserProvider`:
|
||||
|
||||
```java
|
||||
Optional<CurrentUser> user = currentUserProvider.getCurrentUser(); // публичные эндпоинты
|
||||
CurrentUser user = currentUserProvider.requireUser(); // защищённые (401 гарантирует security)
|
||||
```
|
||||
|
||||
Прямо `Authentication`/`Jwt` в контроллеры не таскать.
|
||||
@@ -28,3 +28,5 @@ replay_pid*
|
||||
/gradlew.bat
|
||||
/.gradle/
|
||||
/build/
|
||||
/.zcode/plans/
|
||||
/.zcodeignore
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
# AGENTS.md
|
||||
|
||||
Backend service of the gorodar project (group `ru.gorodar`, version `0.0.1-SNAPSHOT`).
|
||||
Early-stage skeleton: Gradle build is configured, but `src/` does not exist yet — expect to create the standard Spring Boot layout (`src/main/java`, `src/main/resources`, `src/test/java`).
|
||||
Implements the API described in `docs/system-analysis.md` (public catalog / user visits / admin, in Russian).
|
||||
|
||||
## Stack
|
||||
|
||||
- Java 25 (Gradle toolchain; auto-downloaded if not installed locally)
|
||||
- Spring Boot 4.1.1, Gradle 9.6.0 wrapper
|
||||
- Spring Web MVC, Data JPA, Liquibase, OAuth2 client security, Actuator
|
||||
- Spring Web MVC, Data JPA, Liquibase, OAuth2 resource server security, Validation, Actuator
|
||||
- PostgreSQL (runtime driver), AWS SDK v2 S3 (MinIO-compatible, via `gorodar.s3.*` config)
|
||||
- springdoc-openapi (Swagger UI), Lombok
|
||||
|
||||
## Commands
|
||||
@@ -22,9 +23,14 @@ On Windows, `gradlew.bat` is equivalent (it is git-ignored but present locally).
|
||||
|
||||
## Conventions and gotchas
|
||||
|
||||
- **Spring Boot 4 starter names**: `spring-boot-starter-webmvc`, `spring-boot-starter-security-oauth2-client`, and matching `*-test` starters. Do not "fix" them to Boot 3 names (`spring-boot-starter-web`, `spring-boot-starter-oauth2-client`) — those do not exist in Boot 4.
|
||||
- **Spring Boot 4 starter names**: `spring-boot-starter-webmvc`, `spring-boot-starter-security-oauth2-resource-server`, and matching `*-test` starters. Do not "fix" them to Boot 3 names (`spring-boot-starter-web`, `spring-boot-starter-oauth2-resource-server`) — those do not exist in Boot 4. Auth is resource-server only (JWT from Keycloak, client `gorodar`); there is no oauth2-client.
|
||||
- **Lombok**: declared as `compileOnly` + `annotationProcessor` (plus test variants). Keep this pattern when adding modules; plain `implementation` breaks annotation processing.
|
||||
- **MapStruct** (entity↔DTO mappers in `ru.gorodar.mapper`, `componentModel = "spring"`, `unmappedTargetPolicy = ERROR`): `mapstruct` is an `implementation` dep, `mapstruct-processor` and `lombok-mapstruct-binding` are `annotationProcessor` entries — keep all three together, order matters for Lombok interop.
|
||||
- **Criteria queries use the generated JPA metamodel**: `hibernate-jpamodelgen` runs as an annotation processor and generates `X_` classes next to entities; Specifications (`ru.gorodar.dao.spec`) must reference attributes via `Entity_.field`, never string paths like `root.get("name")`.
|
||||
- **Liquibase**: schema changes go through Liquibase changelogs under `src/main/resources` (default `db/changelog`), not ad-hoc DDL.
|
||||
- **Timestamps are UTC everywhere**: DB columns are plain `timestamp` (no `timestamptz`), entities use `LocalDateTime`, the JVM default timezone is forced to UTC in `main()` — keep it that way when touching date/time code.
|
||||
- **Query/multipart params are kebab-case** (`parent-id`, `area-id`, `sort-order`); JSON body fields stay camelCase.
|
||||
- **Entities declare explicit column names**: every field carries `@Column(name = "…")` (or `@JoinColumn(name = "…")`) — no reliance on the implicit naming strategy.
|
||||
- **No `settings.gradle`**: single-project build; the project name falls back to the directory name (`back`). Add one only if the build becomes multi-module.
|
||||
- **Line endings** (`.gitattributes`): `gradlew` is forced to LF, `*.bat` to CRLF, `*.jar` is binary. Preserve this when adding scripts.
|
||||
- `.idea/` and `gradlew.bat` are git-ignored; do not commit them.
|
||||
|
||||
+10
-2
@@ -21,15 +21,23 @@ dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-actuator'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-liquibase'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security-oauth2-client'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security-oauth2-resource-server'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:3.1.0'
|
||||
implementation platform('software.amazon.awssdk:bom:2.54.13')
|
||||
implementation 'software.amazon.awssdk:s3'
|
||||
implementation 'org.mapstruct:mapstruct:1.6.3'
|
||||
compileOnly 'org.projectlombok:lombok'
|
||||
annotationProcessor 'org.projectlombok:lombok'
|
||||
annotationProcessor 'org.projectlombok:lombok-mapstruct-binding:0.2.0'
|
||||
annotationProcessor 'org.mapstruct:mapstruct-processor:1.6.3'
|
||||
annotationProcessor 'org.hibernate.orm:hibernate-jpamodelgen:7.4.5.Final'
|
||||
runtimeOnly 'org.postgresql:postgresql'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-actuator-test'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-liquibase-test'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-security-oauth2-client-test'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-security-oauth2-resource-server-test'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
|
||||
testCompileOnly 'org.projectlombok:lombok'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
|
||||
+55
-22
@@ -1,6 +1,6 @@
|
||||
# Системный анализ бэкенда «Городар»
|
||||
|
||||
Версия: 0.4
|
||||
Версия: 0.10
|
||||
Дата: 2026-09-29
|
||||
|
||||
| Версия | Что изменилось |
|
||||
@@ -9,6 +9,12 @@
|
||||
| 0.2 | Зафиксирован контракт open_cv (OpenAPI 1.0.0); эталонных фото может быть несколько; удаление не предусматривается; просмотр каталога публичный |
|
||||
| 0.3 | Фото пользователя не сохраняется в S3. Карточка достопримечательности расширена. `is_primary` → `sort_order`; `attraction_set_items` получил суррогатный ID. Решены Q1–Q10 (роли, активный набор, без типа зон, заливка через бэкенд, русский, без геолокации, один bucket, без модерации, один bucket, сервисный пересчёт признаков) |
|
||||
| 0.4 | Закрыты R1–R3: иконка — файл в S3 (в карточке presigned-ссылка); `cv_profile` хранится на уровне достопримечательности и берётся оттуда при извлечении признаков; Keycloak-клиент — `gorodar`. Открытых вопросов нет — документ готов как основа реализации |
|
||||
| 0.5 | Время: колонки БД `timestamp` вместо `timestamptz`, сущности на `LocalDateTime`, приём/выдача времени в API — UTC; JVM принудительно в UTC |
|
||||
| 0.6 | Добавлено удаление эталонного фото (FR-M8): DELETE-эндпоинт, запрет удаления единственного фото у достопримечательности из активного набора |
|
||||
| 0.7 | Добавлено удаление одной достопримечательности из набора: `DELETE /api/admin/sets/{id}/items/{attractionId}`; набор не может стать пустым (409 `LAST_SET_ITEM`) |
|
||||
| 0.8 | Публичные `GET /api/areas` и `GET /api/areas/{id}` обогащены: в каждой зоне — `attractions` активного набора (id, name, iconUrl, visited) и `progress {visited, total}`; анониму — все unvisited, прогресс 0 |
|
||||
| 0.9 | Карточка `GET /api/attractions/{id}` получила признак `visited` (по визиту текущего пользователя; анониму — false) |
|
||||
| 0.10 | Хранение enum'ов унифицировано: везде `@Enumerated(EnumType.STRING)` (в БД — верхний регистр), `AttributeConverter` для enum'ов убраны; API-контракт не изменился (нижний регистр на границе дают мапперы) |
|
||||
|
||||
## 1. Назначение документа
|
||||
|
||||
@@ -108,7 +114,9 @@
|
||||
существующие блобы не пересчитывает — она действует на новые загрузки и на явный
|
||||
пересчёт (FR-M7).
|
||||
- **FR-M4.** Создание и редактирование наборов достопримечательностей. Набор собирается
|
||||
только из достопримечательностей той же зоны. Удаления нет — только архивирование.
|
||||
только из достопримечательностей той же зоны; состав меняется целиком (PUT) или удалением
|
||||
одной достопримечательности (DELETE item; нельзя удалить последнюю — набор не бывает
|
||||
пустым). Удаления набора нет — только архивирование.
|
||||
- **FR-M5.** Активация набора: в зоне всегда не более одного активного набора; активация
|
||||
нового автоматически архивирует предыдущий (атомарно, в одной транзакции).
|
||||
- **FR-M6.** Просмотр посещений со фильтрами (зона, набор, достопримечательность,
|
||||
@@ -117,6 +125,9 @@
|
||||
`/features` по сохранённому в S3 фото (с текущим `cvProfile` достопримечательности),
|
||||
перезаписывает `.npz` и метаданные. Нужен при смене `feature_format_version` в open_cv
|
||||
(ошибка `FEATURE_FORMAT_UNSUPPORTED`) и для принудительного обновления.
|
||||
- **FR-M8.** Удаление эталонного фото (строка БД + фото и `.npz` в S3). Запрещено удалять
|
||||
единственное фото достопримечательности, входящей в активный набор (защита I6);
|
||||
если фото не первое по `sort_order`, после удаления сравнение продолжится по следующему.
|
||||
|
||||
## 5. Доменная модель
|
||||
|
||||
@@ -176,7 +187,7 @@ erDiagram
|
||||
numeric longitude
|
||||
varchar address
|
||||
jsonb facts "интересные факты, массив строк"
|
||||
varchar cv_profile "facade|monument|repetitive"
|
||||
varchar cv_profile "FACADE|MONUMENT|REPETITIVE (EnumType.STRING)"
|
||||
}
|
||||
attraction_photos {
|
||||
uuid id PK "photoId = часть S3-ключа"
|
||||
@@ -203,8 +214,8 @@ erDiagram
|
||||
uuid id PK
|
||||
varchar user_id "Keycloak sub"
|
||||
uuid attraction_id FK
|
||||
timestamptz visited_at
|
||||
varchar verdict "match"
|
||||
timestamp visited_at "UTC"
|
||||
varchar verdict "MATCH (EnumType.STRING)"
|
||||
numeric confidence
|
||||
varchar probe_sha256 "из /verify, для аудита"
|
||||
}
|
||||
@@ -218,7 +229,7 @@ erDiagram
|
||||
| I2 | Не более одного `ACTIVE` набора на зону | partial unique index `ON attraction_sets(area_id) WHERE status = 'ACTIVE'` |
|
||||
| I3 | Достопримечательности набора — только из зоны набора | сервисный слой (+ опционально триггер в БД) |
|
||||
| I4 | `parent` зоны не может быть самим собой / потомком (защита от циклов) | сервисный слой |
|
||||
| I5 | Удаление данных (зоны, достопримечательности, фото, иконки, наборы, посещения) не предусматривается; наборы выводятся из оборота архивированием | отсутствием delete-эндпоинтов |
|
||||
| I5 | Удаление данных (зоны, достопримечательности, иконки, наборы, посещения) не предусматривается; наборы выводятся из оборота архивированием. Исключение — эталонные фото (FR-M8), но не единственное фото достопримечательности из активного набора | отсутствие delete-эндпоинтов + проверка в FR-M8 |
|
||||
| I6 | У достопримечательности, включённой в активный набор, есть хотя бы одно эталонное фото с блобом признаков; в `/verify` идёт фото с минимальным `sort_order` | сервисный слой при включении в активный набор |
|
||||
| I7 | У фото и его блоба признаков общий `photoId` (лежат рядом в S3) | ключи формирует бэкенд |
|
||||
| I8 | Посещение фиксируется только для достопримечательностей из активного набора своей зоны | сервисный слой (проверка перед `/verify`) |
|
||||
@@ -241,6 +252,8 @@ DRAFT ──activate──► ACTIVE ──archive──► ARCHIVED
|
||||
### 6.1 PostgreSQL (через JPA + Liquibase)
|
||||
|
||||
- Схема ведётся только Liquibase-ченджлогами в `src/main/resources/db/changelog`.
|
||||
- Конвенция времени: колонки `timestamp` (без tz), в них всегда UTC; сущности —
|
||||
`LocalDateTime`; API принимает и выдаёт время в UTC; JVM принудительно в UTC.
|
||||
- Порядок миграций: `001-create-areas`, `002-create-attractions` (+ `attraction_photos`),
|
||||
`003-create-attraction-sets` (+ items), `004-create-visits`.
|
||||
- Идентификаторы — UUID (генерируются приложением), чтобы ключи S3 и внешние ссылки не
|
||||
@@ -353,7 +366,13 @@ multipart через бэкенд, эталон дополнительно пр
|
||||
|
||||
- База `/api`; админка — `/api/admin/**`, пользовательская — `/api/**` (без `admin`).
|
||||
- JSON, кроме эндпоинтов приёма файлов (multipart/form-data).
|
||||
- Пагинация: `page`/`size` (0-based) + `totalElements` в ответе.
|
||||
- Пагинация во всех списочных эндпоинтах — стандартный Spring `Pageable`: query-параметры
|
||||
`page`/`size`/`sort` (дефолты заданы в контроллерах через `@PageableDefault`); в теле
|
||||
запросов параметров пагинации нет. Ответ — `org.springframework.data.domain.Page`
|
||||
(сериализация VIA_DTO через `@EnableSpringDataWebSupport`): `content`, `totalElements`,
|
||||
`totalPages`, `number`, `size`, `sort`, `first`/`last` и т.п.
|
||||
- Имена query- и multipart-параметров — kebab-case (`parent-id`, `area-id`, `sort-order`);
|
||||
поля JSON-тел остаются camelCase.
|
||||
- Ошибки — единая модель:
|
||||
|
||||
```json
|
||||
@@ -370,13 +389,25 @@ multipart через бэкенд, эталон дополнительно пр
|
||||
|
||||
| Метод и путь | Доступ | Назначение |
|
||||
|---|---|---|
|
||||
| `GET /api/areas` | публично | Список корневых зон; `?parentId={id}` — дети |
|
||||
| `GET /api/areas/{id}` | публично | Зона + дочерние зоны |
|
||||
| `GET /api/areas` | публично | Список корневых зон; `?parent-id={id}` — дети. Каждая зона — с `attractions` (активный набор: id, name, iconUrl, visited) и `progress {visited, total}`; анониму — visited=false везде, прогресс 0 |
|
||||
| `GET /api/areas/{id}` | публично | Зона + дочерние зоны (дети — с тем же обогащением) + собственные `attractions`/`progress` |
|
||||
| `GET /api/areas/{id}/active-set` | публично | Активный набор зоны с достопримечательностями; с токеном — флаги `visited` (404 `NO_ACTIVE_SET`, если нет) |
|
||||
| `GET /api/attractions/{id}` | публично | Карточка достопримечательности |
|
||||
| `POST /api/attractions/{id}/visits` | user | **Ключевой эндпоинт**: multipart `photo` → `/verify` → отметка посещения |
|
||||
| `GET /api/me/visits` | user | Мои посещения (пагинация) |
|
||||
| `GET /api/me/progress?areaId={id}` | user | Прогресс по активному набору зоны: `{ visited, total }` |
|
||||
| `GET /api/me/progress?area-id={id}` | user | Прогресс по активному набору зоны: `{ visited, total }` |
|
||||
|
||||
Зона в ответе `GET /api/areas…` (обогащение одинаково для всех зон в списке и детей):
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "…", "parentId": null, "name": "Город",
|
||||
"attractions": [
|
||||
{ "id": "…", "name": "Достопримечательность", "iconUrl": "https://…presigned…", "visited": false }
|
||||
],
|
||||
"progress": { "visited": 0, "total": 10 }
|
||||
}
|
||||
```
|
||||
|
||||
Карточка достопримечательности (ответ):
|
||||
|
||||
@@ -387,7 +418,8 @@ multipart через бэкенд, эталон дополнительно пр
|
||||
"about": "О месте…",
|
||||
"latitude": 55.75, "longitude": 37.61, "address": "ул. Примерная, 1",
|
||||
"facts": ["Факт первый", "Факт второй"],
|
||||
"photoUrl": "https://…presigned…"
|
||||
"photoUrl": "https://…presigned…",
|
||||
"visited": false
|
||||
}
|
||||
```
|
||||
|
||||
@@ -406,25 +438,27 @@ multipart через бэкенд, эталон дополнительно пр
|
||||
| Метод и путь | Роль | Назначение |
|
||||
|---|---|---|
|
||||
| `POST /api/admin/areas` | manage_area | Создать зону (parentId, name) |
|
||||
| `GET /api/admin/areas` | manage_area | Список зон (фильтр parentId; пагинация) |
|
||||
| `GET /api/admin/areas` | manage_area | Список зон (фильтр `parent-id`; пагинация) |
|
||||
| `PATCH /api/admin/areas/{id}` | manage_area | Переименовать / сменить parent |
|
||||
| `POST /api/admin/areas/{areaId}/attractions` | manage_attraction | Создать достопримечательность (карточка + cvProfile) |
|
||||
| `GET /api/admin/areas/{areaId}/attractions` | manage_attraction | Список достопримечательностей зоны |
|
||||
| `POST /api/admin/attractions` | manage_attraction | Создать достопримечательность (areaId — в теле, карточка + cvProfile) |
|
||||
| `GET /api/admin/attractions?area-id={id}` | manage_attraction | Список достопримечательностей зоны (`area-id` — обязательный query-параметр) |
|
||||
| `PATCH /api/admin/attractions/{id}` | manage_attraction | Обновить карточку (name, about, координаты, address, facts, cvProfile) |
|
||||
| `POST /api/admin/attractions/{id}/icon` | manage_attraction | Загрузить/заменить иконку (multipart) → S3, в БД — ключ |
|
||||
| `POST /api/admin/attractions/{id}/photos` | manage_attraction | Загрузить эталонное фото (multipart + sortOrder; cvProfile — из достопримечательности) → фото + `.npz` в S3, метаданные в БД (FR-M3) |
|
||||
| `POST /api/admin/attractions/{id}/photos` | manage_attraction | Загрузить эталонное фото (multipart: `file` + `sort-order`; cvProfile — из достопримечательности) → фото + `.npz` в S3, метаданные в БД (FR-M3) |
|
||||
| `GET /api/admin/attractions/{id}/photos` | manage_attraction | Список эталонных фото с метаданными, отсортированный по `sort_order` |
|
||||
| `PATCH /api/admin/attractions/{id}/photos/{photoId}` | manage_attraction | Изменить `sortOrder` (на будущее — на старте одно фото) |
|
||||
| `POST /api/admin/attractions/{id}/photos/{photoId}/features` | manage_attraction | Пересчитать блоб признаков (FR-M7): `/features` по сохранённому фото → перезапись `.npz` и метаданных |
|
||||
| `DELETE /api/admin/attractions/{id}/photos/{photoId}` | manage_attraction | Удалить эталонное фото (FR-M8): строка БД + файлы из S3; 409 `LAST_REFERENCE_PHOTO`, если оно единственное у достопримечательности из активного набора |
|
||||
| `POST /api/admin/areas/{areaId}/sets` | manage_area | Создать набор (DRAFT) |
|
||||
| `GET /api/admin/areas/{areaId}/sets` | manage_area | Наборы зоны со статусами |
|
||||
| `PATCH /api/admin/sets/{id}` | manage_area | Переименовать |
|
||||
| `PUT /api/admin/sets/{id}/items` | manage_area | Задать состав набора (список attractionIds, все из той же зоны — I3) |
|
||||
| `DELETE /api/admin/sets/{id}/items/{attractionId}` | manage_area | Удалить достопримечательность из набора; 409 `LAST_SET_ITEM` — если она последняя, 404 `SET_ITEM_NOT_FOUND` — если её нет в наборе |
|
||||
| `POST /api/admin/sets/{id}/activate` | manage_area | Активировать (auto-archive предыдущего — FR-M5) |
|
||||
| `POST /api/admin/sets/{id}/archive` | manage_area | Архивировать |
|
||||
| `GET /api/admin/visits` | manage_area | Статистика посещений (фильтры: areaId, attractionId, userId, from, to) |
|
||||
| `POST /api/admin/visits` | manage_area | Статистика посещений; фильтры в теле: `{areaId, attractionId, userId, from, to}`, пагинация — стандартные query-параметры `page`/`size`/`sort` (Pageable) |
|
||||
|
||||
Delete-эндпоинтов нет (I5).
|
||||
Единственный delete-эндпоинт — удаление эталонного фото (FR-M8); остальное не удаляется (I5).
|
||||
|
||||
## 9. Ключевой сценарий: подтверждение посещения
|
||||
|
||||
@@ -477,13 +511,12 @@ Delete-эндпоинтов нет (I5).
|
||||
|
||||
```
|
||||
ru.gorodar
|
||||
├── config // SecurityConfig, OpenCvClientConfig (RestClient + X-API-Key), S3Config, OpenApiConfig
|
||||
├── api // publicc/user/admin-контроллеры + вложенный dto (request/response records)
|
||||
├── config // SecurityConfig, S3Config, OpenApiConfig
|
||||
├── security // CurrentUser, CurrentUserProvider
|
||||
├── web // public/*Controller, user/*Controller, admin/*Controller
|
||||
├── service // AreaService, AttractionService, ReferencePhotoService, SetService, VisitService
|
||||
├── repository // Spring Data JPA
|
||||
├── domain // entity + enum (SetStatus, VisitStatus, CvProfile, VerifyVerdict)
|
||||
├── dto // request/response records
|
||||
├── mapper // MapStruct-мапперы entity → DTO (componentModel = spring)
|
||||
├── dao // Spring Data JPA репозитории + entity (сущности, enum'ы, конвертеры) + spec (Specification-предикаты; @Query не используется)
|
||||
├── integration // opencv (features/verify client + маппинг ошибок), s3 (storage client)
|
||||
└── exception // ErrorCode, обработчики
|
||||
```
|
||||
|
||||
@@ -2,11 +2,22 @@ package ru.gorodar;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
import org.springframework.data.web.config.EnableSpringDataWebSupport;
|
||||
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.springframework.data.web.config.EnableSpringDataWebSupport.PageSerializationMode.VIA_DTO;
|
||||
|
||||
@SpringBootApplication
|
||||
@ConfigurationPropertiesScan
|
||||
@EnableSpringDataWebSupport(pageSerializationMode = VIA_DTO)
|
||||
public class GorodarBack {
|
||||
|
||||
static void main (String[] args) {
|
||||
// Конвенция сервиса: все метки времени — UTC (сущности LocalDateTime, колонки timestamp).
|
||||
// Без этого @CreationTimestamp возьмёт таймзону хоста.
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
|
||||
SpringApplication.run(GorodarBack.class, args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package ru.gorodar.api.admin;
|
||||
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.gorodar.api.dto.AreaDtos.AreaResponse;
|
||||
import ru.gorodar.api.dto.AreaDtos.CreateAreaRequest;
|
||||
import ru.gorodar.api.dto.AreaDtos.UpdateAreaRequest;
|
||||
import ru.gorodar.service.AreaService;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/areas")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "admin")
|
||||
public class AdminAreaController {
|
||||
|
||||
private final AreaService areaService;
|
||||
|
||||
@PostMapping
|
||||
public AreaResponse create(@Valid @RequestBody CreateAreaRequest request) {
|
||||
return areaService.create(request);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public Page<AreaResponse> list(@RequestParam(name = "parent-id", required = false) UUID parentId,
|
||||
@PageableDefault(size = 20, sort = "name") Pageable pageable) {
|
||||
return areaService.list(parentId, pageable);
|
||||
}
|
||||
|
||||
@PatchMapping("/{id}")
|
||||
public AreaResponse update(@PathVariable UUID id, @Valid @RequestBody UpdateAreaRequest request) {
|
||||
return areaService.update(id, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package ru.gorodar.api.admin;
|
||||
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import ru.gorodar.api.dto.AttractionDtos.AttractionAdminResponse;
|
||||
import ru.gorodar.api.dto.AttractionDtos.CreateAttractionRequest;
|
||||
import ru.gorodar.api.dto.AttractionDtos.UpdateAttractionRequest;
|
||||
import ru.gorodar.api.dto.PhotoDtos.PhotoResponse;
|
||||
import ru.gorodar.api.dto.PhotoDtos.UpdatePhotoRequest;
|
||||
import ru.gorodar.service.AttractionService;
|
||||
import ru.gorodar.service.ReferencePhotoService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "admin")
|
||||
public class AdminAttractionController {
|
||||
|
||||
private final AttractionService attractionService;
|
||||
private final ReferencePhotoService photoService;
|
||||
|
||||
@PostMapping("/api/admin/attractions")
|
||||
public AttractionAdminResponse create(@Valid @RequestBody CreateAttractionRequest request) {
|
||||
return attractionService.create(request);
|
||||
}
|
||||
|
||||
@GetMapping("/api/admin/attractions")
|
||||
public Page<AttractionAdminResponse> list(@RequestParam(name = "area-id") UUID areaId,
|
||||
@PageableDefault(size = 20, sort = "name") Pageable pageable) {
|
||||
return attractionService.listByArea(areaId, pageable);
|
||||
}
|
||||
|
||||
@PatchMapping("/api/admin/attractions/{id}")
|
||||
public AttractionAdminResponse update(@PathVariable UUID id,
|
||||
@Valid @RequestBody UpdateAttractionRequest request) {
|
||||
return attractionService.update(id, request);
|
||||
}
|
||||
|
||||
@PostMapping("/api/admin/attractions/{id}/icon")
|
||||
public AttractionAdminResponse uploadIcon(@PathVariable UUID id,
|
||||
@RequestParam("file") MultipartFile file) {
|
||||
return attractionService.uploadIcon(id, file);
|
||||
}
|
||||
|
||||
@PostMapping("/api/admin/attractions/{id}/photos")
|
||||
public PhotoResponse uploadPhoto(@PathVariable UUID id,
|
||||
@RequestParam("file") MultipartFile file,
|
||||
@RequestParam(name = "sort-order", required = false) Integer sortOrder) {
|
||||
return photoService.upload(id, file, sortOrder);
|
||||
}
|
||||
|
||||
@GetMapping("/api/admin/attractions/{id}/photos")
|
||||
public List<PhotoResponse> listPhotos(@PathVariable UUID id) {
|
||||
return photoService.list(id);
|
||||
}
|
||||
|
||||
@PatchMapping("/api/admin/attractions/{id}/photos/{photoId}")
|
||||
public PhotoResponse updatePhoto(@PathVariable UUID id,
|
||||
@PathVariable UUID photoId,
|
||||
@Valid @RequestBody UpdatePhotoRequest request) {
|
||||
return photoService.updateSortOrder(id, photoId, request.sortOrder());
|
||||
}
|
||||
|
||||
@PostMapping("/api/admin/attractions/{id}/photos/{photoId}/features")
|
||||
public PhotoResponse reextractFeatures(@PathVariable UUID id, @PathVariable UUID photoId) {
|
||||
return photoService.reextractFeatures(id, photoId);
|
||||
}
|
||||
|
||||
@DeleteMapping("/api/admin/attractions/{id}/photos/{photoId}")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void deletePhoto(@PathVariable UUID id, @PathVariable UUID photoId) {
|
||||
photoService.delete(id, photoId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package ru.gorodar.api.admin;
|
||||
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.gorodar.api.dto.SetDtos.CreateSetRequest;
|
||||
import ru.gorodar.api.dto.SetDtos.SetItemsRequest;
|
||||
import ru.gorodar.api.dto.SetDtos.SetResponse;
|
||||
import ru.gorodar.api.dto.SetDtos.UpdateSetRequest;
|
||||
import ru.gorodar.service.AttractionSetService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "admin")
|
||||
public class AdminSetController {
|
||||
|
||||
private final AttractionSetService setService;
|
||||
|
||||
@PostMapping("/api/admin/areas/{areaId}/sets")
|
||||
public SetResponse create(@PathVariable UUID areaId, @Valid @RequestBody CreateSetRequest request) {
|
||||
return setService.create(areaId, request);
|
||||
}
|
||||
|
||||
@GetMapping("/api/admin/areas/{areaId}/sets")
|
||||
public List<SetResponse> list(@PathVariable UUID areaId) {
|
||||
return setService.list(areaId);
|
||||
}
|
||||
|
||||
@PatchMapping("/api/admin/sets/{id}")
|
||||
public SetResponse rename(@PathVariable UUID id, @Valid @RequestBody UpdateSetRequest request) {
|
||||
return setService.rename(id, request);
|
||||
}
|
||||
|
||||
@PutMapping("/api/admin/sets/{id}/items")
|
||||
public SetResponse putItems(@PathVariable UUID id, @Valid @RequestBody SetItemsRequest request) {
|
||||
return setService.putItems(id, request);
|
||||
}
|
||||
|
||||
@DeleteMapping("/api/admin/sets/{id}/items/{attractionId}")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void removeItem(@PathVariable UUID id, @PathVariable UUID attractionId) {
|
||||
setService.removeItem(id, attractionId);
|
||||
}
|
||||
|
||||
@PostMapping("/api/admin/sets/{id}/activate")
|
||||
public SetResponse activate(@PathVariable UUID id) {
|
||||
return setService.activate(id);
|
||||
}
|
||||
|
||||
@PostMapping("/api/admin/sets/{id}/archive")
|
||||
public SetResponse archive(@PathVariable UUID id) {
|
||||
return setService.archive(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package ru.gorodar.api.admin;
|
||||
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.gorodar.api.dto.VisitDtos.VisitFilterRequest;
|
||||
import ru.gorodar.api.dto.VisitDtos.VisitResponse;
|
||||
import ru.gorodar.service.VisitService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/visits")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "admin")
|
||||
public class AdminVisitController {
|
||||
|
||||
private final VisitService visitService;
|
||||
|
||||
@PostMapping
|
||||
public Page<VisitResponse> list(@Valid @RequestBody VisitFilterRequest request,
|
||||
@PageableDefault(size = 20, sort = "visitedAt",
|
||||
direction = Sort.Direction.DESC) Pageable pageable) {
|
||||
return visitService.adminVisits(request, pageable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package ru.gorodar.api.dto;
|
||||
|
||||
import ru.gorodar.exception.ApiException;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
public record ApiError(String code, String message, String timestamp) {
|
||||
|
||||
public static ApiError from(ApiException e) {
|
||||
return new ApiError(e.getCode().name(), e.getMessage(), LocalDateTime.now(ZoneOffset.UTC).toString());
|
||||
}
|
||||
|
||||
public static ApiError of(String code, String message) {
|
||||
return new ApiError(code, message, LocalDateTime.now(ZoneOffset.UTC).toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package ru.gorodar.api.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import ru.gorodar.api.dto.SetDtos.ActiveSetAttractionResponse;
|
||||
import ru.gorodar.api.dto.VisitDtos.ProgressResponse;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class AreaDtos {
|
||||
|
||||
private AreaDtos() {
|
||||
}
|
||||
|
||||
public record AreaResponse(UUID id, UUID parentId, String name,
|
||||
List<ActiveSetAttractionResponse> attractions,
|
||||
ProgressResponse progress) {
|
||||
}
|
||||
|
||||
public record AreaWithChildrenResponse(UUID id, UUID parentId, String name, List<AreaResponse> children,
|
||||
List<ActiveSetAttractionResponse> attractions,
|
||||
ProgressResponse progress) {
|
||||
}
|
||||
|
||||
public record CreateAreaRequest(@NotBlank String name, UUID parentId) {
|
||||
}
|
||||
|
||||
public record UpdateAreaRequest(String name, UUID parentId) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package ru.gorodar.api.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class AttractionDtos {
|
||||
|
||||
public static final String CV_PROFILE_PATTERN = "facade|monument|repetitive";
|
||||
|
||||
private AttractionDtos() {
|
||||
}
|
||||
|
||||
public record AttractionCardResponse(UUID id, String name, String iconUrl, String about,
|
||||
BigDecimal latitude, BigDecimal longitude, String address,
|
||||
List<String> facts, String photoUrl, boolean visited) {
|
||||
}
|
||||
|
||||
public record AttractionAdminResponse(UUID id, UUID areaId, String name, String iconKey, String about,
|
||||
BigDecimal latitude, BigDecimal longitude, String address,
|
||||
List<String> facts, String cvProfile, long photoCount) {
|
||||
}
|
||||
|
||||
public record CreateAttractionRequest(@NotNull UUID areaId,
|
||||
@NotBlank String name, String about,
|
||||
BigDecimal latitude, BigDecimal longitude, String address,
|
||||
List<String> facts,
|
||||
@NotBlank @Pattern(regexp = CV_PROFILE_PATTERN) String cvProfile) {
|
||||
}
|
||||
|
||||
public record UpdateAttractionRequest(String name, String about,
|
||||
BigDecimal latitude, BigDecimal longitude, String address,
|
||||
List<String> facts,
|
||||
@Pattern(regexp = CV_PROFILE_PATTERN) String cvProfile) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package ru.gorodar.api.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class PhotoDtos {
|
||||
|
||||
private PhotoDtos() {
|
||||
}
|
||||
|
||||
public record PhotoResponse(UUID id, String photoUrl, int sortOrder,
|
||||
int featureFormatVersion, String algoId, int keypointsCount,
|
||||
LocalDateTime createdAt) {
|
||||
}
|
||||
|
||||
public record UpdatePhotoRequest(@NotNull Integer sortOrder) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package ru.gorodar.api.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import ru.gorodar.api.dto.VisitDtos.ProgressResponse;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class SetDtos {
|
||||
|
||||
private SetDtos() {
|
||||
}
|
||||
|
||||
public record SetResponse(UUID id, UUID areaId, String name, String status, long itemCount) {
|
||||
}
|
||||
|
||||
public record CreateSetRequest(@NotBlank String name) {
|
||||
}
|
||||
|
||||
public record UpdateSetRequest(@NotBlank String name) {
|
||||
}
|
||||
|
||||
public record SetItemsRequest(@NotEmpty List<UUID> attractionIds) {
|
||||
}
|
||||
|
||||
public record ActiveSetResponse(UUID id, String name, List<ActiveSetAttractionResponse> attractions) {
|
||||
}
|
||||
|
||||
public record ActiveSetAttractionResponse(UUID id, String name, String iconUrl, boolean visited) {
|
||||
}
|
||||
|
||||
public record AreaActiveSetInfo(List<ActiveSetAttractionResponse> attractions, ProgressResponse progress) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package ru.gorodar.api.dto;
|
||||
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class VisitDtos {
|
||||
|
||||
private VisitDtos() {
|
||||
}
|
||||
|
||||
public record VisitSubmitResponse(String status, Float confidence, ProgressResponse progress) {
|
||||
}
|
||||
|
||||
public record ProgressResponse(int visited, int total) {
|
||||
}
|
||||
|
||||
public record VisitResponse(UUID id, UUID attractionId, String attractionName,
|
||||
LocalDateTime visitedAt, String verdict, BigDecimal confidence) {
|
||||
}
|
||||
|
||||
public record VisitFilterRequest(UUID areaId,
|
||||
UUID attractionId,
|
||||
String userId,
|
||||
LocalDate from,
|
||||
LocalDate to) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package ru.gorodar.api.publicc;
|
||||
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.gorodar.api.dto.AreaDtos.AreaWithChildrenResponse;
|
||||
import ru.gorodar.api.dto.AreaDtos.AreaResponse;
|
||||
import ru.gorodar.api.dto.SetDtos.ActiveSetResponse;
|
||||
import ru.gorodar.service.AreaService;
|
||||
import ru.gorodar.service.AttractionSetService;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/areas")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "public")
|
||||
public class PublicAreaController {
|
||||
|
||||
private final AreaService areaService;
|
||||
private final AttractionSetService setService;
|
||||
|
||||
@GetMapping
|
||||
public Page<AreaResponse> list(@RequestParam(name = "parent-id", required = false) UUID parentId,
|
||||
@PageableDefault(size = 20, sort = "name") Pageable pageable) {
|
||||
return areaService.list(parentId, pageable);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public AreaWithChildrenResponse get(@PathVariable UUID id) {
|
||||
return areaService.get(id);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/active-set")
|
||||
public ActiveSetResponse activeSet(@PathVariable UUID id) {
|
||||
return setService.getActiveSet(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package ru.gorodar.api.publicc;
|
||||
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.gorodar.api.dto.AttractionDtos.AttractionCardResponse;
|
||||
import ru.gorodar.service.AttractionService;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/attractions")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "public")
|
||||
public class PublicAttractionController {
|
||||
|
||||
private final AttractionService attractionService;
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public AttractionCardResponse get(@PathVariable UUID id) {
|
||||
return attractionService.getCard(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package ru.gorodar.api.user;
|
||||
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.gorodar.api.dto.VisitDtos.ProgressResponse;
|
||||
import ru.gorodar.api.dto.VisitDtos.VisitResponse;
|
||||
import ru.gorodar.security.CurrentUserProvider;
|
||||
import ru.gorodar.service.VisitService;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/me")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "user")
|
||||
public class MeController {
|
||||
|
||||
private final VisitService visitService;
|
||||
private final CurrentUserProvider currentUserProvider;
|
||||
|
||||
@GetMapping("/visits")
|
||||
public Page<VisitResponse> visits(@PageableDefault(size = 20, sort = "visitedAt",
|
||||
direction = Sort.Direction.DESC) Pageable pageable) {
|
||||
return visitService.myVisits(currentUserProvider.requireUser().id(), pageable);
|
||||
}
|
||||
|
||||
@GetMapping("/progress")
|
||||
public ProgressResponse progress(@RequestParam(name = "area-id") UUID areaId) {
|
||||
return visitService.progress(currentUserProvider.requireUser().id(), areaId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package ru.gorodar.api.user;
|
||||
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import ru.gorodar.api.dto.VisitDtos.VisitSubmitResponse;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
import ru.gorodar.security.CurrentUserProvider;
|
||||
import ru.gorodar.service.VisitService;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/attractions")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "user")
|
||||
public class VisitController {
|
||||
|
||||
private final VisitService visitService;
|
||||
private final CurrentUserProvider currentUserProvider;
|
||||
|
||||
@PostMapping("/{attractionId}/visits")
|
||||
public VisitSubmitResponse submit(@PathVariable UUID attractionId,
|
||||
@RequestParam("photo") MultipartFile photo) {
|
||||
String userId = currentUserProvider.requireUser().id();
|
||||
try {
|
||||
return visitService.submit(userId, attractionId, photo.getBytes());
|
||||
} catch (IOException e) {
|
||||
throw new ApiException(ErrorCode.INVALID_PHOTO, "Не удалось прочитать файл фотографии", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package ru.gorodar.config;
|
||||
|
||||
import io.swagger.v3.oas.models.Components;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class OpenApiConfig {
|
||||
|
||||
@Bean
|
||||
public OpenAPI gorodarOpenApi() {
|
||||
return new OpenAPI()
|
||||
.info(new Info().title("Городар back API").version("0.0.1"))
|
||||
.components(new Components().addSecuritySchemes("bearer", new SecurityScheme()
|
||||
.type(SecurityScheme.Type.HTTP)
|
||||
.scheme("bearer")
|
||||
.bearerFormat("JWT")))
|
||||
.addSecurityItem(new SecurityRequirement().addList("bearer"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.gorodar.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "gorodar.opencv")
|
||||
public record OpenCvProperties(String baseUrl, String apiKey) {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package ru.gorodar.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@ConfigurationProperties(prefix = "gorodar.s3")
|
||||
public record S3Properties(
|
||||
String endpoint,
|
||||
String region,
|
||||
String accessKey,
|
||||
String secretKey,
|
||||
String bucket,
|
||||
boolean pathStyleAccess,
|
||||
Duration presignTtl) {
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package ru.gorodar.dao;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.gorodar.dao.entity.Area;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface AreaRepository extends JpaRepository<Area, UUID> {
|
||||
|
||||
Page<Area> findByParentIsNull(Pageable pageable);
|
||||
|
||||
Page<Area> findByParentId(UUID parentId, Pageable pageable);
|
||||
|
||||
List<Area> findByParentIdOrderByNameAsc(UUID parentId);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package ru.gorodar.dao;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.gorodar.dao.entity.AttractionPhoto;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface AttractionPhotoRepository extends JpaRepository<AttractionPhoto, UUID> {
|
||||
|
||||
List<AttractionPhoto> findByAttractionIdOrderBySortOrderAsc(UUID attractionId);
|
||||
|
||||
Optional<AttractionPhoto> findFirstByAttractionIdOrderBySortOrderAsc(UUID attractionId);
|
||||
|
||||
Optional<AttractionPhoto> findByIdAndAttractionId(UUID id, UUID attractionId);
|
||||
|
||||
long countByAttractionId(UUID attractionId);
|
||||
|
||||
long countDistinctByAttractionIdIn(Collection<UUID> attractionIds);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package ru.gorodar.dao;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import ru.gorodar.dao.entity.Attraction;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface AttractionRepository extends JpaRepository<Attraction, UUID>, JpaSpecificationExecutor<Attraction> {
|
||||
|
||||
Page<Attraction> findByAreaId(UUID areaId, Pageable pageable);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package ru.gorodar.dao;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import ru.gorodar.dao.entity.AttractionSetItem;
|
||||
import ru.gorodar.dao.entity.SetStatus;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface AttractionSetItemRepository
|
||||
extends JpaRepository<AttractionSetItem, UUID>, JpaSpecificationExecutor<AttractionSetItem> {
|
||||
|
||||
List<AttractionSetItem> findBySetId(UUID setId);
|
||||
|
||||
Optional<AttractionSetItem> findBySetIdAndAttractionId(UUID setId, UUID attractionId);
|
||||
|
||||
void deleteBySetId(UUID setId);
|
||||
|
||||
long countBySetId(UUID setId);
|
||||
|
||||
boolean existsByAttractionIdAndSet_Status(UUID attractionId, SetStatus status);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package ru.gorodar.dao;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import ru.gorodar.dao.entity.AttractionSet;
|
||||
import ru.gorodar.dao.entity.SetStatus;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface AttractionSetRepository
|
||||
extends JpaRepository<AttractionSet, UUID>, JpaSpecificationExecutor<AttractionSet> {
|
||||
|
||||
List<AttractionSet> findByAreaIdOrderByCreatedAtDesc(UUID areaId);
|
||||
|
||||
Optional<AttractionSet> findByAreaIdAndStatus(UUID areaId, SetStatus status);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package ru.gorodar.dao;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import ru.gorodar.dao.entity.AttractionUserVisit;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface AttractionUserVisitRepository
|
||||
extends JpaRepository<AttractionUserVisit, UUID>, JpaSpecificationExecutor<AttractionUserVisit> {
|
||||
|
||||
boolean existsByUserIdAndAttractionId(String userId, UUID attractionId);
|
||||
|
||||
Page<AttractionUserVisit> findByUserIdOrderByVisitedAtDesc(String userId, Pageable pageable);
|
||||
|
||||
long countByUserIdAndAttractionIdIn(String userId, Collection<UUID> attractionIds);
|
||||
|
||||
List<AttractionUserVisit> findByUserIdAndAttractionIdIn(String userId, Collection<UUID> attractionIds);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import org.hibernate.annotations.UpdateTimestamp;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "areas")
|
||||
@Getter
|
||||
@Setter
|
||||
public class Area {
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private UUID id;
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "parent_id")
|
||||
private Area parent;
|
||||
@Column(name = "name", nullable = false)
|
||||
private String name;
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
@UpdateTimestamp
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import org.hibernate.annotations.JdbcTypeCode;
|
||||
import org.hibernate.annotations.UpdateTimestamp;
|
||||
import org.hibernate.type.SqlTypes;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "attractions")
|
||||
@Getter
|
||||
@Setter
|
||||
public class Attraction {
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private UUID id;
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "area_id", nullable = false)
|
||||
private Area area;
|
||||
@Column(name = "name", nullable = false)
|
||||
private String name;
|
||||
@Column(name = "icon_key")
|
||||
private String iconKey;
|
||||
@Column(name = "about", columnDefinition = "text")
|
||||
private String about;
|
||||
@Column(name = "latitude", precision = 9, scale = 6)
|
||||
private BigDecimal latitude;
|
||||
@Column(name = "longitude", precision = 9, scale = 6)
|
||||
private BigDecimal longitude;
|
||||
@Column(name = "address")
|
||||
private String address;
|
||||
@Column(name = "facts")
|
||||
@JdbcTypeCode(SqlTypes.JSON)
|
||||
private List<String> facts;
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "cv_profile", nullable = false)
|
||||
private CvProfile cvProfile;
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
@UpdateTimestamp
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "attraction_photos")
|
||||
@Getter
|
||||
@Setter
|
||||
public class AttractionPhoto {
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private UUID id;
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "attraction_id", nullable = false)
|
||||
private Attraction attraction;
|
||||
@Column(name = "s3_photo_key", nullable = false)
|
||||
private String s3PhotoKey;
|
||||
@Column(name = "s3_features_key", nullable = false)
|
||||
private String s3FeaturesKey;
|
||||
@Column(name = "feature_format_version", nullable = false)
|
||||
private int featureFormatVersion;
|
||||
@Column(name = "algo_id", nullable = false)
|
||||
private String algoId;
|
||||
@Column(name = "keypoints_count", nullable = false)
|
||||
private int keypointsCount;
|
||||
@Column(name = "sort_order", nullable = false)
|
||||
private int sortOrder;
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import org.hibernate.annotations.UpdateTimestamp;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "attraction_sets")
|
||||
@Getter
|
||||
@Setter
|
||||
public class AttractionSet {
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private UUID id;
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "area_id", nullable = false)
|
||||
private Area area;
|
||||
@Column(name = "name", nullable = false)
|
||||
private String name;
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "status", nullable = false)
|
||||
private SetStatus status;
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
@UpdateTimestamp
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "attraction_set_items")
|
||||
@Getter
|
||||
@Setter
|
||||
public class AttractionSetItem {
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private UUID id;
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "set_id", nullable = false)
|
||||
private AttractionSet set;
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "attraction_id", nullable = false)
|
||||
private Attraction attraction;
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "attraction_users_visits")
|
||||
@Getter
|
||||
@Setter
|
||||
public class AttractionUserVisit {
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private UUID id;
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private String userId;
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "attraction_id", nullable = false)
|
||||
private Attraction attraction;
|
||||
@Column(name = "visited_at", nullable = false)
|
||||
private LocalDateTime visitedAt;
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "verdict", nullable = false)
|
||||
private VerifyVerdict verdict;
|
||||
@Column(name = "confidence", precision = 5, scale = 4)
|
||||
private BigDecimal confidence;
|
||||
@Column(name = "probe_sha256", length = 64)
|
||||
private String probeSha256;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
public enum CvProfile {
|
||||
FACADE,
|
||||
MONUMENT,
|
||||
REPETITIVE
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
public enum SetStatus {
|
||||
DRAFT,
|
||||
ACTIVE,
|
||||
ARCHIVED
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
public enum VerifyVerdict {
|
||||
MATCH,
|
||||
UNCERTAIN,
|
||||
NO_MATCH;
|
||||
|
||||
public static VerifyVerdict fromString(String value) {
|
||||
return switch (value) {
|
||||
case "match" -> MATCH;
|
||||
case "uncertain" -> UNCERTAIN;
|
||||
case "no_match" -> NO_MATCH;
|
||||
default -> throw new IllegalArgumentException("Неизвестный вердикт open_cv: " + value);
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package ru.gorodar.dao.entity;
|
||||
|
||||
public enum VisitStatus {
|
||||
VISITED,
|
||||
ALREADY_VISITED,
|
||||
NOT_MATCHED,
|
||||
UNCERTAIN
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package ru.gorodar.dao.spec;
|
||||
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import ru.gorodar.dao.entity.Area_;
|
||||
import ru.gorodar.dao.entity.Attraction_;
|
||||
import ru.gorodar.dao.entity.AttractionSet_;
|
||||
import ru.gorodar.dao.entity.AttractionSetItem;
|
||||
import ru.gorodar.dao.entity.AttractionSetItem_;
|
||||
import ru.gorodar.dao.entity.SetStatus;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public final class AttractionSetItemSpecs {
|
||||
|
||||
private AttractionSetItemSpecs() {
|
||||
}
|
||||
|
||||
public static Specification<AttractionSetItem> ofActiveSetInArea(UUID areaId) {
|
||||
return (root, query, cb) -> cb.and(
|
||||
cb.equal(root.get(AttractionSetItem_.set).get(AttractionSet_.area).get(Area_.id), areaId),
|
||||
cb.equal(root.get(AttractionSetItem_.set).get(AttractionSet_.status), SetStatus.ACTIVE));
|
||||
}
|
||||
|
||||
public static Specification<AttractionSetItem> ofActiveSetInAreaSortedByAttractionName(UUID areaId) {
|
||||
return (root, query, cb) -> {
|
||||
query.orderBy(cb.asc(root.get(AttractionSetItem_.attraction).get(Attraction_.name)));
|
||||
return cb.and(
|
||||
cb.equal(root.get(AttractionSetItem_.set).get(AttractionSet_.area).get(Area_.id), areaId),
|
||||
cb.equal(root.get(AttractionSetItem_.set).get(AttractionSet_.status), SetStatus.ACTIVE));
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package ru.gorodar.dao.spec;
|
||||
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import ru.gorodar.dao.entity.Area_;
|
||||
import ru.gorodar.dao.entity.AttractionSet;
|
||||
import ru.gorodar.dao.entity.AttractionSet_;
|
||||
import ru.gorodar.dao.entity.SetStatus;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public final class AttractionSetSpecs {
|
||||
|
||||
private AttractionSetSpecs() {
|
||||
}
|
||||
|
||||
public static Specification<AttractionSet> activeInAreaExcept(UUID areaId, UUID exceptSetId) {
|
||||
return (root, query, cb) -> cb.and(
|
||||
cb.equal(root.get(AttractionSet_.area).get(Area_.id), areaId),
|
||||
cb.equal(root.get(AttractionSet_.status), SetStatus.ACTIVE),
|
||||
cb.notEqual(root.get(AttractionSet_.id), exceptSetId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package ru.gorodar.dao.spec;
|
||||
|
||||
import jakarta.persistence.criteria.Predicate;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import ru.gorodar.dao.entity.Area_;
|
||||
import ru.gorodar.dao.entity.Attraction_;
|
||||
import ru.gorodar.dao.entity.AttractionUserVisit;
|
||||
import ru.gorodar.dao.entity.AttractionUserVisit_;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class VisitSpecs {
|
||||
|
||||
private VisitSpecs() {
|
||||
}
|
||||
|
||||
public static Specification<AttractionUserVisit> filtered(UUID areaId, UUID attractionId, String userId,
|
||||
LocalDate from, LocalDate to) {
|
||||
return (root, query, cb) -> {
|
||||
var predicates = new ArrayList<Predicate>();
|
||||
if (attractionId != null) {
|
||||
predicates.add(cb.equal(
|
||||
root.get(AttractionUserVisit_.attraction).get(Attraction_.id), attractionId));
|
||||
}
|
||||
if (areaId != null) {
|
||||
predicates.add(cb.equal(
|
||||
root.get(AttractionUserVisit_.attraction).get(Attraction_.area).get(Area_.id), areaId));
|
||||
}
|
||||
if (userId != null) {
|
||||
predicates.add(cb.equal(root.get(AttractionUserVisit_.userId), userId));
|
||||
}
|
||||
if (from != null) {
|
||||
predicates.add(cb.greaterThanOrEqualTo(
|
||||
root.get(AttractionUserVisit_.visitedAt), from.atStartOfDay()));
|
||||
}
|
||||
if (to != null) {
|
||||
predicates.add(cb.lessThan(
|
||||
root.get(AttractionUserVisit_.visitedAt), to.plusDays(1).atStartOfDay()));
|
||||
}
|
||||
return cb.and(predicates.toArray(new Predicate[0]));
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package ru.gorodar.exception;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class ApiException extends RuntimeException {
|
||||
|
||||
private final ErrorCode code;
|
||||
|
||||
public ApiException(ErrorCode code) {
|
||||
super(code.getDefaultMessage());
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public ApiException(ErrorCode code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public ApiException(ErrorCode code, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package ru.gorodar.exception;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public enum ErrorCode {
|
||||
|
||||
VALIDATION_ERROR(400, "Некорректный запрос"),
|
||||
INVALID_PHOTO(400, "Некорректный файл фотографии"),
|
||||
AREA_CYCLE(400, "Зона не может быть вложена в саму себя или своего потомка"),
|
||||
SET_NOT_READY(400, "Набор не готов к активации"),
|
||||
ATTRACTIONS_NOT_IN_AREA(400, "Достопримечательности из другой зоны не могут входить в набор"),
|
||||
SORT_ORDER_TAKEN(409, "Порядковый номер уже занят"),
|
||||
|
||||
AREA_NOT_FOUND(404, "Зона не найдена"),
|
||||
ATTRACTION_NOT_FOUND(404, "Достопримечательность не найдена"),
|
||||
SET_NOT_FOUND(404, "Набор не найден"),
|
||||
SET_ITEM_NOT_FOUND(404, "Достопримечательность не найдена в наборе"),
|
||||
PHOTO_NOT_FOUND(404, "Эталонное фото не найдено"),
|
||||
NO_ACTIVE_SET(404, "В зоне нет активного набора"),
|
||||
|
||||
ATTRACTION_NOT_IN_ACTIVE_SET(409, "Достопримечательность не входит в активный набор зоны"),
|
||||
SET_STATE_CONFLICT(409, "Недопустимый переход статуса набора или конкурентная активация"),
|
||||
LAST_REFERENCE_PHOTO(409, "Нельзя удалить единственное эталонное фото достопримечательности, входящей в активный набор"),
|
||||
LAST_SET_ITEM(409, "Нельзя удалить последнюю достопримечательность набора"),
|
||||
|
||||
PAYLOAD_TOO_LARGE(413, "Файл превышает допустимый размер"),
|
||||
UNSUPPORTED_MEDIA_TYPE(415, "Неподдерживаемый тип файла"),
|
||||
|
||||
NO_REFERENCE_PHOTO(503, "У достопримечательности нет эталонного фото с признаками"),
|
||||
REFERENCE_UNAVAILABLE(503, "Эталон недоступен или устарел, требуется пересчёт признаков"),
|
||||
OPENCV_UNAVAILABLE(503, "Сервис распознавания недоступен"),
|
||||
S3_UNAVAILABLE(503, "Хранилище файлов недоступно"),
|
||||
|
||||
INTERNAL(500, "Внутренняя ошибка сервиса");
|
||||
|
||||
private final int status;
|
||||
private final String defaultMessage;
|
||||
|
||||
ErrorCode(int status, String defaultMessage) {
|
||||
this.status = status;
|
||||
this.defaultMessage = defaultMessage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package ru.gorodar.exception;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.HandlerMethodValidationException;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
import ru.gorodar.api.dto.ApiError;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(ApiException.class)
|
||||
public ResponseEntity<ApiError> handleApiException(ApiException e) {
|
||||
return ResponseEntity.status(e.getCode().getStatus()).body(ApiError.from(e));
|
||||
}
|
||||
|
||||
@ExceptionHandler({MethodArgumentNotValidException.class, HandlerMethodValidationException.class})
|
||||
public ResponseEntity<ApiError> handleValidation(Exception e) {
|
||||
return ResponseEntity.badRequest().body(ApiError.of(ErrorCode.VALIDATION_ERROR.name(), "Некорректные параметры запроса"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(MaxUploadSizeExceededException.class)
|
||||
public ResponseEntity<ApiError> handleMaxUpload(MaxUploadSizeExceededException e) {
|
||||
return ResponseEntity.status(ErrorCode.PAYLOAD_TOO_LARGE.getStatus())
|
||||
.body(ApiError.of(ErrorCode.PAYLOAD_TOO_LARGE.name(), ErrorCode.PAYLOAD_TOO_LARGE.getDefaultMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ApiError> handleUnexpected(Exception e) {
|
||||
log.error("Необработанная ошибка", e);
|
||||
return ResponseEntity.internalServerError().body(ApiError.of(ErrorCode.INTERNAL.name(), ErrorCode.INTERNAL.getDefaultMessage()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.gorodar.integration.opencv;
|
||||
|
||||
import lombok.Builder;
|
||||
|
||||
@Builder
|
||||
public record FeaturesResult(byte[] blob, int formatVersion, String algoId, int keypointsCount) {
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package ru.gorodar.integration.opencv;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.client.ResourceAccessException;
|
||||
import org.springframework.web.client.RestClient;
|
||||
import ru.gorodar.config.OpenCvProperties;
|
||||
import ru.gorodar.dao.entity.CvProfile;
|
||||
import ru.gorodar.dao.entity.VerifyVerdict;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class OpenCvClient {
|
||||
|
||||
private static final String FEATURES_PATH = "/api/v1/features";
|
||||
private static final String VERIFY_PATH = "/api/v1/verify";
|
||||
|
||||
private final RestClient restClient;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final OpenCvResultMapper resultMapper;
|
||||
|
||||
public OpenCvClient(RestClient.Builder builder, OpenCvProperties properties, ObjectMapper objectMapper,
|
||||
OpenCvResultMapper resultMapper) {
|
||||
this.restClient = builder
|
||||
.baseUrl(properties.baseUrl())
|
||||
.defaultHeader("X-API-Key", properties.apiKey())
|
||||
.build();
|
||||
this.objectMapper = objectMapper;
|
||||
this.resultMapper = resultMapper;
|
||||
}
|
||||
|
||||
public FeaturesResult extractFeatures(byte[] image, CvProfile profile) {
|
||||
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
|
||||
body.add("image", octetStream(image, "reference.jpg"));
|
||||
body.add("settings", "{\"profile\":\"" + profile.name().toLowerCase() + "\"}");
|
||||
try {
|
||||
ResponseEntity<byte[]> response = restClient.post()
|
||||
.uri(FEATURES_PATH)
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.body(body)
|
||||
.retrieve()
|
||||
.onStatus(HttpStatusCode::isError, this::toApiException)
|
||||
.toEntity(byte[].class);
|
||||
return FeaturesResult.builder()
|
||||
.blob(response.getBody())
|
||||
.formatVersion(Integer.parseInt(header(response, "X-Feature-Format-Version")))
|
||||
.algoId(header(response, "X-Algo-Id"))
|
||||
.keypointsCount(Integer.parseInt(header(response, "X-Keypoints-Count")))
|
||||
.build();
|
||||
} catch (ResourceAccessException e) {
|
||||
throw new ApiException(ErrorCode.OPENCV_UNAVAILABLE, "Сервис распознавания недоступен", e);
|
||||
}
|
||||
}
|
||||
|
||||
public VerifyResult verify(byte[] probe, List<byte[]> references) {
|
||||
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
|
||||
body.add("probe", octetStream(probe, "probe.jpg"));
|
||||
references.forEach(reference -> body.add("reference", octetStream(reference, "reference.npz")));
|
||||
try {
|
||||
VerifyResponseDto response = restClient.post()
|
||||
.uri(VERIFY_PATH)
|
||||
.contentType(MediaType.MULTIPART_FORM_DATA)
|
||||
.body(body)
|
||||
.retrieve()
|
||||
.onStatus(HttpStatusCode::isError, this::toApiException)
|
||||
.body(VerifyResponseDto.class);
|
||||
if (response == null) {
|
||||
throw new ApiException(ErrorCode.OPENCV_UNAVAILABLE, "Пустой ответ сервиса распознавания");
|
||||
}
|
||||
return resultMapper.toVerifyResult(response);
|
||||
} catch (ResourceAccessException e) {
|
||||
throw new ApiException(ErrorCode.OPENCV_UNAVAILABLE, "Сервис распознавания недоступен", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void toApiException(org.springframework.http.HttpRequest request,
|
||||
ClientHttpResponse response) throws IOException {
|
||||
OpenCvErrorBody errorBody;
|
||||
try {
|
||||
errorBody = objectMapper.readValue(response.getBody(), OpenCvErrorBody.class);
|
||||
} catch (Exception parseFailure) {
|
||||
throw new ApiException(ErrorCode.OPENCV_UNAVAILABLE,
|
||||
"Неизвестная ошибка open_cv: HTTP " + response.getStatusCode().value());
|
||||
}
|
||||
String code = errorBody != null && errorBody.error() != null ? errorBody.error().code() : "UNKNOWN";
|
||||
String message = errorBody != null && errorBody.error() != null ? errorBody.error().message() : null;
|
||||
throw mapError(code, message);
|
||||
}
|
||||
|
||||
private ApiException mapError(String code, String message) {
|
||||
return switch (code == null ? "" : code) {
|
||||
case "IMAGE_DECODE_FAILED", "IMAGE_TOO_SMALL" ->
|
||||
new ApiException(ErrorCode.INVALID_PHOTO, "Фотография не распознаётся или её разрешение ниже 640×480");
|
||||
case "UNSUPPORTED_MEDIA_TYPE" -> new ApiException(ErrorCode.UNSUPPORTED_MEDIA_TYPE);
|
||||
case "PAYLOAD_TOO_LARGE" -> new ApiException(ErrorCode.PAYLOAD_TOO_LARGE);
|
||||
case "FEATURE_BLOB_INVALID", "FEATURE_FORMAT_UNSUPPORTED" ->
|
||||
new ApiException(ErrorCode.REFERENCE_UNAVAILABLE,
|
||||
message != null ? message : "Эталон повреждён или устарел, требуется пересчёт признаков");
|
||||
default -> new ApiException(ErrorCode.OPENCV_UNAVAILABLE, "Ошибка сервиса распознавания: " + code);
|
||||
};
|
||||
}
|
||||
|
||||
private Object octetStream(byte[] data, String filename) {
|
||||
return new ByteArrayResource(data) {
|
||||
@Override
|
||||
public String getFilename() {
|
||||
return filename;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private String header(ResponseEntity<byte[]> response, String name) {
|
||||
String value = response.getHeaders().getFirst(name);
|
||||
if (value == null) {
|
||||
throw new ApiException(ErrorCode.OPENCV_UNAVAILABLE,
|
||||
"Сервис распознавания не вернул обязательный заголовок " + name);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
record VerifyResponseDto(String verdict,
|
||||
@JsonProperty("is_match") boolean isMatch,
|
||||
float confidence,
|
||||
@JsonProperty("probe_sha256") String probeSha256) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package ru.gorodar.integration.opencv;
|
||||
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonNaming;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record OpenCvErrorBody(OpenCvError error) {
|
||||
|
||||
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
|
||||
public record OpenCvError(String code, String message, Map<String, Object> details, String traceId) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package ru.gorodar.integration.opencv;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class OpenCvException extends RuntimeException {
|
||||
|
||||
private final int status;
|
||||
private final String code;
|
||||
|
||||
public OpenCvException(int status, String code, String message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package ru.gorodar.integration.opencv;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
import ru.gorodar.dao.entity.VerifyVerdict;
|
||||
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR)
|
||||
public interface OpenCvResultMapper {
|
||||
|
||||
@Mapping(target = "verdict", source = "verdict")
|
||||
@Mapping(target = "match", source = "isMatch")
|
||||
VerifyResult toVerifyResult(OpenCvClient.VerifyResponseDto response);
|
||||
|
||||
default VerifyVerdict map(String verdict) {
|
||||
return VerifyVerdict.fromString(verdict);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package ru.gorodar.integration.opencv;
|
||||
|
||||
import lombok.Builder;
|
||||
import ru.gorodar.dao.entity.VerifyVerdict;
|
||||
|
||||
@Builder
|
||||
public record VerifyResult(VerifyVerdict verdict, boolean match, float confidence, String probeSha256) {
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package ru.gorodar.integration.s3;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import ru.gorodar.config.S3Properties;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.S3Configuration;
|
||||
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
@Configuration
|
||||
public class S3Config {
|
||||
|
||||
@Bean
|
||||
public S3Client s3Client(S3Properties props) {
|
||||
var builder = S3Client.builder()
|
||||
.region(Region.of(props.region()))
|
||||
.credentialsProvider(StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create(props.accessKey(), props.secretKey())))
|
||||
.serviceConfiguration(S3Configuration.builder()
|
||||
.pathStyleAccessEnabled(props.pathStyleAccess())
|
||||
.build());
|
||||
if (props.endpoint() != null && !props.endpoint().isBlank()) {
|
||||
builder.endpointOverride(URI.create(props.endpoint()));
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public S3Presigner s3Presigner(S3Properties props) {
|
||||
var builder = S3Presigner.builder()
|
||||
.region(Region.of(props.region()))
|
||||
.credentialsProvider(StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create(props.accessKey(), props.secretKey())))
|
||||
.serviceConfiguration(S3Configuration.builder()
|
||||
.pathStyleAccessEnabled(props.pathStyleAccess())
|
||||
.build());
|
||||
if (props.endpoint() != null && !props.endpoint().isBlank()) {
|
||||
builder.endpointOverride(URI.create(props.endpoint()));
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package ru.gorodar.integration.s3;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.gorodar.config.S3Properties;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
import software.amazon.awssdk.core.sync.RequestBody;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
|
||||
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
|
||||
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
|
||||
import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@Component
|
||||
public class S3Storage {
|
||||
|
||||
private final S3Client s3Client;
|
||||
private final S3Presigner s3Presigner;
|
||||
private final String bucket;
|
||||
private final Duration presignTtl;
|
||||
|
||||
public S3Storage(S3Client s3Client, S3Presigner s3Presigner, S3Properties props) {
|
||||
this.s3Client = s3Client;
|
||||
this.s3Presigner = s3Presigner;
|
||||
this.bucket = props.bucket();
|
||||
this.presignTtl = props.presignTtl();
|
||||
}
|
||||
|
||||
public void put(String key, byte[] data, String contentType) {
|
||||
try {
|
||||
s3Client.putObject(
|
||||
PutObjectRequest.builder().bucket(bucket).key(key).contentType(contentType).build(),
|
||||
RequestBody.fromBytes(data));
|
||||
} catch (Exception e) {
|
||||
throw new ApiException(ErrorCode.S3_UNAVAILABLE, "Не удалось сохранить файл в хранилище", e);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] get(String key) {
|
||||
try {
|
||||
return s3Client.getObjectAsBytes(builder -> builder.bucket(bucket).key(key)).asByteArray();
|
||||
} catch (NoSuchKeyException e) {
|
||||
throw new ApiException(ErrorCode.REFERENCE_UNAVAILABLE, "Объект не найден в хранилище: " + key, e);
|
||||
} catch (Exception e) {
|
||||
throw new ApiException(ErrorCode.S3_UNAVAILABLE, "Не удалось прочитать файл из хранилища", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(String key) {
|
||||
try {
|
||||
s3Client.deleteObject(builder -> builder.bucket(bucket).key(key));
|
||||
} catch (Exception e) {
|
||||
throw new ApiException(ErrorCode.S3_UNAVAILABLE, "Не удалось удалить файл из хранилища", e);
|
||||
}
|
||||
}
|
||||
|
||||
public String presignGetUrl(String key) {
|
||||
GetObjectRequest request = GetObjectRequest.builder().bucket(bucket).key(key).build();
|
||||
GetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder()
|
||||
.signatureDuration(presignTtl)
|
||||
.getObjectRequest(request)
|
||||
.build();
|
||||
PresignedGetObjectRequest presigned = s3Presigner.presignGetObject(presignRequest);
|
||||
return presigned.url().toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package ru.gorodar.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
import ru.gorodar.api.dto.AreaDtos.AreaResponse;
|
||||
import ru.gorodar.api.dto.AreaDtos.AreaWithChildrenResponse;
|
||||
import ru.gorodar.api.dto.SetDtos.ActiveSetAttractionResponse;
|
||||
import ru.gorodar.api.dto.VisitDtos.ProgressResponse;
|
||||
import ru.gorodar.dao.entity.Area;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR)
|
||||
public interface AreaMapper {
|
||||
|
||||
@Mapping(target = "parentId", source = "area.parent.id")
|
||||
@Mapping(target = "attractions", source = "attractions")
|
||||
@Mapping(target = "progress", source = "progress")
|
||||
AreaResponse toResponse(Area area, List<ActiveSetAttractionResponse> attractions, ProgressResponse progress);
|
||||
|
||||
@Mapping(target = "parentId", source = "area.parent.id")
|
||||
@Mapping(target = "children", source = "children")
|
||||
@Mapping(target = "attractions", source = "attractions")
|
||||
@Mapping(target = "progress", source = "progress")
|
||||
AreaWithChildrenResponse toWithChildrenResponse(Area area, List<AreaResponse> children,
|
||||
List<ActiveSetAttractionResponse> attractions,
|
||||
ProgressResponse progress);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package ru.gorodar.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
import ru.gorodar.api.dto.AttractionDtos.AttractionAdminResponse;
|
||||
import ru.gorodar.api.dto.AttractionDtos.AttractionCardResponse;
|
||||
import ru.gorodar.dao.entity.Attraction;
|
||||
import ru.gorodar.dao.entity.CvProfile;
|
||||
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR)
|
||||
public interface AttractionMapper {
|
||||
|
||||
@Mapping(target = "iconUrl", source = "iconUrl")
|
||||
@Mapping(target = "photoUrl", source = "photoUrl")
|
||||
@Mapping(target = "visited", source = "visited")
|
||||
AttractionCardResponse toCardResponse(Attraction attraction, String iconUrl, String photoUrl,
|
||||
boolean visited);
|
||||
|
||||
@Mapping(target = "areaId", source = "attraction.area.id")
|
||||
@Mapping(target = "cvProfile", source = "attraction.cvProfile")
|
||||
@Mapping(target = "photoCount", source = "photoCount")
|
||||
AttractionAdminResponse toAdminResponse(Attraction attraction, long photoCount);
|
||||
|
||||
default String map(CvProfile cvProfile) {
|
||||
return cvProfile == null ? null : cvProfile.name().toLowerCase();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package ru.gorodar.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
import ru.gorodar.api.dto.PhotoDtos.PhotoResponse;
|
||||
import ru.gorodar.dao.entity.AttractionPhoto;
|
||||
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR)
|
||||
public interface PhotoMapper {
|
||||
|
||||
@Mapping(target = "photoUrl", source = "photoUrl")
|
||||
PhotoResponse toResponse(AttractionPhoto photo, String photoUrl);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package ru.gorodar.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
import ru.gorodar.api.dto.SetDtos.ActiveSetAttractionResponse;
|
||||
import ru.gorodar.api.dto.SetDtos.ActiveSetResponse;
|
||||
import ru.gorodar.api.dto.SetDtos.SetResponse;
|
||||
import ru.gorodar.dao.entity.Attraction;
|
||||
import ru.gorodar.dao.entity.AttractionSet;
|
||||
import ru.gorodar.dao.entity.SetStatus;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR)
|
||||
public interface SetMapper {
|
||||
|
||||
@Mapping(target = "areaId", source = "set.area.id")
|
||||
@Mapping(target = "status", source = "set.status")
|
||||
@Mapping(target = "itemCount", source = "itemCount")
|
||||
SetResponse toResponse(AttractionSet set, long itemCount);
|
||||
|
||||
@Mapping(target = "attractions", source = "attractions")
|
||||
ActiveSetResponse toActiveSetResponse(AttractionSet set, List<ActiveSetAttractionResponse> attractions);
|
||||
|
||||
@Mapping(target = "iconUrl", source = "iconUrl")
|
||||
@Mapping(target = "visited", source = "visited")
|
||||
ActiveSetAttractionResponse toActiveSetAttraction(Attraction attraction, String iconUrl, boolean visited);
|
||||
|
||||
default String map(SetStatus status) {
|
||||
return status == null ? null : status.name();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package ru.gorodar.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
import ru.gorodar.api.dto.VisitDtos.VisitResponse;
|
||||
import ru.gorodar.dao.entity.AttractionUserVisit;
|
||||
import ru.gorodar.dao.entity.VerifyVerdict;
|
||||
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.ERROR)
|
||||
public interface VisitMapper {
|
||||
|
||||
@Mapping(target = "attractionId", source = "visit.attraction.id")
|
||||
@Mapping(target = "attractionName", source = "visit.attraction.name")
|
||||
@Mapping(target = "verdict", source = "visit.verdict")
|
||||
VisitResponse toResponse(AttractionUserVisit visit);
|
||||
|
||||
default String map(VerifyVerdict verdict) {
|
||||
return verdict == null ? null : verdict.name().toLowerCase();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package ru.gorodar.security;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public record CurrentUser(String id, Set<String> roles) {
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package ru.gorodar.security;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class CurrentUserProvider {
|
||||
|
||||
public Optional<CurrentUser> getCurrentUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication instanceof JwtAuthenticationToken jwtAuth) {
|
||||
Set<String> roles = jwtAuth.getAuthorities().stream()
|
||||
.map(GrantedAuthority::getAuthority)
|
||||
.collect(Collectors.toSet());
|
||||
return Optional.of(new CurrentUser(jwtAuth.getToken().getSubject(), roles));
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public CurrentUser requireUser() {
|
||||
return getCurrentUser().orElseThrow(() -> new ApiException(ErrorCode.INTERNAL, "Ожидался аутентифицированный пользователь"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package ru.gorodar.security;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Извлекает client roles токена Keycloak из claim resource_access.<client_id>.roles.
|
||||
* Роли используются как authorities с точным совпадением имён (manage_area, manage_attraction).
|
||||
*/
|
||||
@Component
|
||||
public class KeycloakJwtAuthenticationConverter implements Converter<Jwt, JwtAuthenticationToken> {
|
||||
|
||||
private final String clientId;
|
||||
|
||||
public KeycloakJwtAuthenticationConverter(@Value("${gorodar.keycloak.client-id}") String clientId) {
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JwtAuthenticationToken convert(Jwt jwt) {
|
||||
return new JwtAuthenticationToken(jwt, extractAuthorities(jwt));
|
||||
}
|
||||
|
||||
private Collection<GrantedAuthority> extractAuthorities(Jwt jwt) {
|
||||
Map<String, Object> resourceAccess = jwt.getClaimAsMap("resource_access");
|
||||
if (resourceAccess == null) {
|
||||
return List.of();
|
||||
}
|
||||
Object clientAccess = resourceAccess.get(clientId);
|
||||
if (!(clientAccess instanceof Map<?, ?> clientMap) || !(clientMap.get("roles") instanceof List<?> roles)) {
|
||||
return List.of();
|
||||
}
|
||||
return roles.stream()
|
||||
.filter(String.class::isInstance)
|
||||
.<GrantedAuthority>map(role -> new SimpleGrantedAuthority((String) role))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package ru.gorodar.security;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
|
||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
||||
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
|
||||
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtValidators;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain securityFilterChain(HttpSecurity http,
|
||||
Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter) throws Exception {
|
||||
http
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
// manage_area: зоны, наборы, статистика; manage_attraction: достопримечательности и эталоны
|
||||
.requestMatchers("/api/admin/attractions/**").hasAuthority("manage_attraction")
|
||||
.requestMatchers("/api/admin/areas/**", "/api/admin/sets/**", "/api/admin/visits/**")
|
||||
.hasAuthority("manage_area")
|
||||
.requestMatchers("/api/admin/**").denyAll()
|
||||
// публичный каталог
|
||||
.requestMatchers(HttpMethod.GET, "/api/areas/**", "/api/attractions/**").permitAll()
|
||||
// персональное
|
||||
.requestMatchers("/api/**").authenticated()
|
||||
// сервисные пути
|
||||
.requestMatchers("/error", "/actuator/health/**", "/actuator/info",
|
||||
"/swagger-ui/**", "/swagger-ui.html", "/v3/api-docs/**").permitAll()
|
||||
.anyRequest().denyAll())
|
||||
.oauth2ResourceServer(oauth2 -> oauth2
|
||||
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter)));
|
||||
return http.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Валидация по умолчанию (подпись/срок/issuer) плюс проверка, что токен выдан
|
||||
* нашему клиенту: audience содержит client_id либо azp равен ему.
|
||||
*/
|
||||
@Bean
|
||||
JwtDecoder jwtDecoder(@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") String issuerUri,
|
||||
@Value("${gorodar.keycloak.client-id}") String clientId) {
|
||||
NimbusJwtDecoder decoder = NimbusJwtDecoder.withIssuerLocation(issuerUri).build();
|
||||
OAuth2TokenValidator<Jwt> defaultValidators = JwtValidators.createDefaultWithIssuer(issuerUri);
|
||||
OAuth2TokenValidator<Jwt> audienceValidator = jwt -> {
|
||||
List<String> audience = jwt.getAudience();
|
||||
String authorizedParty = jwt.getClaimAsString("azp");
|
||||
if ((audience != null && audience.contains(clientId)) || clientId.equals(authorizedParty)) {
|
||||
return OAuth2TokenValidatorResult.success();
|
||||
}
|
||||
return OAuth2TokenValidatorResult.failure(new OAuth2Error(
|
||||
"invalid_token", "Токен выдан не для клиента " + clientId, null));
|
||||
};
|
||||
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(defaultValidators, audienceValidator));
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package ru.gorodar.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import ru.gorodar.api.dto.AreaDtos.AreaResponse;
|
||||
import ru.gorodar.api.dto.AreaDtos.AreaWithChildrenResponse;
|
||||
import ru.gorodar.api.dto.AreaDtos.CreateAreaRequest;
|
||||
import ru.gorodar.api.dto.AreaDtos.UpdateAreaRequest;
|
||||
import ru.gorodar.api.dto.SetDtos.AreaActiveSetInfo;
|
||||
import ru.gorodar.dao.AreaRepository;
|
||||
import ru.gorodar.dao.entity.Area;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
import ru.gorodar.mapper.AreaMapper;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AreaService {
|
||||
|
||||
private final AreaRepository areaRepository;
|
||||
private final AreaMapper areaMapper;
|
||||
private final AttractionSetService setService;
|
||||
|
||||
public AreaResponse create(CreateAreaRequest request) {
|
||||
Area area = new Area();
|
||||
area.setId(UUID.randomUUID());
|
||||
area.setName(request.name());
|
||||
if (request.parentId() != null) {
|
||||
area.setParent(getArea(request.parentId()));
|
||||
}
|
||||
return toOverview(areaRepository.save(area));
|
||||
}
|
||||
|
||||
public Page<AreaResponse> list(UUID parentId, Pageable pageable) {
|
||||
Page<Area> result = parentId == null
|
||||
? areaRepository.findByParentIsNull(pageable)
|
||||
: areaRepository.findByParentId(parentId, pageable);
|
||||
return result.map(this::toOverview);
|
||||
}
|
||||
|
||||
public AreaWithChildrenResponse get(UUID id) {
|
||||
Area area = getArea(id);
|
||||
List<AreaResponse> children = areaRepository.findByParentIdOrderByNameAsc(id).stream()
|
||||
.map(this::toOverview)
|
||||
.toList();
|
||||
AreaActiveSetInfo info = setService.getAreaActiveSetInfo(id);
|
||||
return areaMapper.toWithChildrenResponse(area, children, info.attractions(), info.progress());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AreaResponse update(UUID id, UpdateAreaRequest request) {
|
||||
Area area = getArea(id);
|
||||
if (StringUtils.hasText(request.name())) {
|
||||
area.setName(request.name());
|
||||
}
|
||||
if (request.parentId() != null) {
|
||||
if (request.parentId().equals(id)) {
|
||||
throw new ApiException(ErrorCode.AREA_CYCLE);
|
||||
}
|
||||
Area newParent = getArea(request.parentId());
|
||||
ensureNotDescendant(area, newParent);
|
||||
area.setParent(newParent);
|
||||
}
|
||||
return toOverview(areaRepository.save(area));
|
||||
}
|
||||
|
||||
private AreaResponse toOverview(Area area) {
|
||||
AreaActiveSetInfo info = setService.getAreaActiveSetInfo(area.getId());
|
||||
return areaMapper.toResponse(area, info.attractions(), info.progress());
|
||||
}
|
||||
|
||||
private void ensureNotDescendant(Area area, Area candidateParent) {
|
||||
Area current = candidateParent;
|
||||
while (current != null) {
|
||||
if (current.getId().equals(area.getId())) {
|
||||
throw new ApiException(ErrorCode.AREA_CYCLE);
|
||||
}
|
||||
current = current.getParent();
|
||||
}
|
||||
}
|
||||
|
||||
private Area getArea(UUID id) {
|
||||
return areaRepository.findById(id)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.AREA_NOT_FOUND));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package ru.gorodar.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import ru.gorodar.dao.entity.CvProfile;
|
||||
import ru.gorodar.dao.entity.Area;
|
||||
import ru.gorodar.dao.entity.Attraction;
|
||||
import ru.gorodar.dao.entity.AttractionPhoto;
|
||||
import ru.gorodar.api.dto.AttractionDtos.AttractionAdminResponse;
|
||||
import ru.gorodar.api.dto.AttractionDtos.AttractionCardResponse;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
import ru.gorodar.integration.s3.S3Storage;
|
||||
import ru.gorodar.dao.AreaRepository;
|
||||
import ru.gorodar.dao.AttractionPhotoRepository;
|
||||
import ru.gorodar.dao.AttractionRepository;
|
||||
import ru.gorodar.dao.AttractionUserVisitRepository;
|
||||
import ru.gorodar.mapper.AttractionMapper;
|
||||
import ru.gorodar.security.CurrentUser;
|
||||
import ru.gorodar.security.CurrentUserProvider;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AttractionService {
|
||||
|
||||
private static final Map<String, String> CONTENT_TYPE_EXTENSIONS = Map.of(
|
||||
"image/jpeg", "jpg",
|
||||
"image/png", "png",
|
||||
"image/webp", "webp",
|
||||
"image/svg+xml", "svg");
|
||||
|
||||
private final AreaRepository areaRepository;
|
||||
private final AttractionRepository attractionRepository;
|
||||
private final AttractionPhotoRepository photoRepository;
|
||||
private final AttractionUserVisitRepository visitRepository;
|
||||
private final S3Storage s3Storage;
|
||||
private final AttractionMapper attractionMapper;
|
||||
private final CurrentUserProvider currentUserProvider;
|
||||
|
||||
public AttractionAdminResponse create(ru.gorodar.api.dto.AttractionDtos.CreateAttractionRequest request) {
|
||||
Area area = areaRepository.findById(request.areaId())
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.AREA_NOT_FOUND));
|
||||
Attraction attraction = new Attraction();
|
||||
attraction.setId(UUID.randomUUID());
|
||||
attraction.setArea(area);
|
||||
attraction.setName(request.name());
|
||||
attraction.setAbout(request.about());
|
||||
attraction.setLatitude(request.latitude());
|
||||
attraction.setLongitude(request.longitude());
|
||||
attraction.setAddress(request.address());
|
||||
attraction.setFacts(request.facts());
|
||||
attraction.setCvProfile(CvProfile.valueOf(request.cvProfile().toUpperCase()));
|
||||
return toAdminResponse(attractionRepository.save(attraction));
|
||||
}
|
||||
|
||||
public Page<AttractionAdminResponse> listByArea(UUID areaId, Pageable pageable) {
|
||||
Page<Attraction> result = attractionRepository.findByAreaId(areaId, pageable);
|
||||
return result.map(this::toAdminResponse);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AttractionAdminResponse update(UUID id, ru.gorodar.api.dto.AttractionDtos.UpdateAttractionRequest request) {
|
||||
Attraction attraction = getAttraction(id);
|
||||
if (StringUtils.hasText(request.name())) {
|
||||
attraction.setName(request.name());
|
||||
}
|
||||
if (request.about() != null) {
|
||||
attraction.setAbout(request.about());
|
||||
}
|
||||
if (request.latitude() != null) {
|
||||
attraction.setLatitude(request.latitude());
|
||||
}
|
||||
if (request.longitude() != null) {
|
||||
attraction.setLongitude(request.longitude());
|
||||
}
|
||||
if (request.address() != null) {
|
||||
attraction.setAddress(request.address());
|
||||
}
|
||||
if (request.facts() != null) {
|
||||
attraction.setFacts(request.facts());
|
||||
}
|
||||
if (request.cvProfile() != null) {
|
||||
attraction.setCvProfile(CvProfile.valueOf(request.cvProfile().toUpperCase()));
|
||||
}
|
||||
return toAdminResponse(attractionRepository.save(attraction));
|
||||
}
|
||||
|
||||
public AttractionCardResponse getCard(UUID id) {
|
||||
Attraction attraction = getAttraction(id);
|
||||
String photoUrl = photoRepository.findFirstByAttractionIdOrderBySortOrderAsc(id)
|
||||
.map(photo -> s3Storage.presignGetUrl(photo.getS3PhotoKey()))
|
||||
.orElse(null);
|
||||
String iconUrl = attraction.getIconKey() == null ? null : s3Storage.presignGetUrl(attraction.getIconKey());
|
||||
CurrentUser user = currentUserProvider.getCurrentUser().orElse(null);
|
||||
boolean visited = user != null && visitRepository.existsByUserIdAndAttractionId(user.id(), id);
|
||||
return attractionMapper.toCardResponse(attraction, iconUrl, photoUrl, visited);
|
||||
}
|
||||
|
||||
public AttractionAdminResponse uploadIcon(UUID id, MultipartFile file) {
|
||||
Attraction attraction = getAttraction(id);
|
||||
String contentType = file.getContentType() == null ? "application/octet-stream" : file.getContentType();
|
||||
String extension = extensionOf(contentType);
|
||||
String key = "attractions/%s/icon/%s.%s".formatted(id, UUID.randomUUID(), extension);
|
||||
try {
|
||||
s3Storage.put(key, file.getBytes(), contentType);
|
||||
} catch (IOException e) {
|
||||
throw new ApiException(ErrorCode.INVALID_PHOTO, "Не удалось прочитать файл иконки", e);
|
||||
}
|
||||
attraction.setIconKey(key);
|
||||
return toAdminResponse(attractionRepository.save(attraction));
|
||||
}
|
||||
|
||||
public Attraction getAttraction(UUID id) {
|
||||
return attractionRepository.findById(id)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.ATTRACTION_NOT_FOUND));
|
||||
}
|
||||
|
||||
public AttractionAdminResponse toAdminResponse(Attraction attraction) {
|
||||
return attractionMapper.toAdminResponse(attraction, photoRepository.countByAttractionId(attraction.getId()));
|
||||
}
|
||||
|
||||
static String extensionOf(String contentType) {
|
||||
return CONTENT_TYPE_EXTENSIONS.getOrDefault(contentType, "bin");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package ru.gorodar.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.gorodar.dao.entity.SetStatus;
|
||||
import ru.gorodar.dao.entity.Area;
|
||||
import ru.gorodar.dao.entity.Attraction;
|
||||
import ru.gorodar.dao.entity.AttractionSet;
|
||||
import ru.gorodar.dao.entity.AttractionSetItem;
|
||||
import ru.gorodar.api.dto.SetDtos.ActiveSetAttractionResponse;
|
||||
import ru.gorodar.api.dto.SetDtos.ActiveSetResponse;
|
||||
import ru.gorodar.api.dto.SetDtos.AreaActiveSetInfo;
|
||||
import ru.gorodar.api.dto.SetDtos.SetResponse;
|
||||
import ru.gorodar.api.dto.VisitDtos.ProgressResponse;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
import ru.gorodar.integration.s3.S3Storage;
|
||||
import ru.gorodar.dao.AreaRepository;
|
||||
import ru.gorodar.dao.AttractionPhotoRepository;
|
||||
import ru.gorodar.dao.AttractionRepository;
|
||||
import ru.gorodar.dao.AttractionSetItemRepository;
|
||||
import ru.gorodar.dao.AttractionSetRepository;
|
||||
import ru.gorodar.dao.AttractionUserVisitRepository;
|
||||
import ru.gorodar.dao.spec.AttractionSetItemSpecs;
|
||||
import ru.gorodar.dao.spec.AttractionSetSpecs;
|
||||
import ru.gorodar.mapper.SetMapper;
|
||||
import ru.gorodar.security.CurrentUser;
|
||||
import ru.gorodar.security.CurrentUserProvider;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AttractionSetService {
|
||||
|
||||
private final AttractionSetRepository setRepository;
|
||||
private final AttractionSetItemRepository itemRepository;
|
||||
private final AttractionRepository attractionRepository;
|
||||
private final AreaRepository areaRepository;
|
||||
private final AttractionPhotoRepository photoRepository;
|
||||
private final AttractionUserVisitRepository visitRepository;
|
||||
private final S3Storage s3Storage;
|
||||
private final SetMapper setMapper;
|
||||
private final CurrentUserProvider currentUserProvider;
|
||||
|
||||
public SetResponse create(UUID areaId, ru.gorodar.api.dto.SetDtos.CreateSetRequest request) {
|
||||
Area area = areaRepository.findById(areaId)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.AREA_NOT_FOUND));
|
||||
AttractionSet set = new AttractionSet();
|
||||
set.setId(UUID.randomUUID());
|
||||
set.setArea(area);
|
||||
set.setName(request.name());
|
||||
set.setStatus(SetStatus.DRAFT);
|
||||
return toResponse(setRepository.save(set));
|
||||
}
|
||||
|
||||
public List<SetResponse> list(UUID areaId) {
|
||||
return setRepository.findByAreaIdOrderByCreatedAtDesc(areaId).stream()
|
||||
.map(this::toResponse)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SetResponse rename(UUID id, ru.gorodar.api.dto.SetDtos.UpdateSetRequest request) {
|
||||
AttractionSet set = getSet(id);
|
||||
if (set.getStatus() == SetStatus.ARCHIVED) {
|
||||
throw new ApiException(ErrorCode.SET_STATE_CONFLICT, "Архивный набор изменить нельзя");
|
||||
}
|
||||
set.setName(request.name());
|
||||
return toResponse(setRepository.save(set));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SetResponse putItems(UUID id, ru.gorodar.api.dto.SetDtos.SetItemsRequest request) {
|
||||
AttractionSet set = getSet(id);
|
||||
if (set.getStatus() == SetStatus.ARCHIVED) {
|
||||
throw new ApiException(ErrorCode.SET_STATE_CONFLICT, "Состав архивного набора изменить нельзя");
|
||||
}
|
||||
List<Attraction> attractions = attractionRepository.findAllById(request.attractionIds());
|
||||
if (attractions.size() != request.attractionIds().size()) {
|
||||
throw new ApiException(ErrorCode.ATTRACTION_NOT_FOUND);
|
||||
}
|
||||
for (Attraction attraction : attractions) {
|
||||
if (!attraction.getArea().getId().equals(set.getArea().getId())) {
|
||||
throw new ApiException(ErrorCode.ATTRACTIONS_NOT_IN_AREA);
|
||||
}
|
||||
}
|
||||
itemRepository.deleteBySetId(id);
|
||||
for (Attraction attraction : attractions) {
|
||||
AttractionSetItem item = new AttractionSetItem();
|
||||
item.setId(UUID.randomUUID());
|
||||
item.setSet(set);
|
||||
item.setAttraction(attraction);
|
||||
itemRepository.save(item);
|
||||
}
|
||||
return toResponse(set);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void removeItem(UUID id, UUID attractionId) {
|
||||
AttractionSet set = getSet(id);
|
||||
if (set.getStatus() == SetStatus.ARCHIVED) {
|
||||
throw new ApiException(ErrorCode.SET_STATE_CONFLICT, "Состав архивного набора изменить нельзя");
|
||||
}
|
||||
AttractionSetItem item = itemRepository.findBySetIdAndAttractionId(id, attractionId)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.SET_ITEM_NOT_FOUND));
|
||||
if (itemRepository.countBySetId(id) <= 1) {
|
||||
throw new ApiException(ErrorCode.LAST_SET_ITEM);
|
||||
}
|
||||
itemRepository.delete(item);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SetResponse activate(UUID id) {
|
||||
AttractionSet set = getSet(id);
|
||||
if (set.getStatus() != SetStatus.DRAFT) {
|
||||
throw new ApiException(ErrorCode.SET_STATE_CONFLICT,
|
||||
"Активировать можно только набор в статусе DRAFT");
|
||||
}
|
||||
List<AttractionSetItem> items = itemRepository.findBySetId(id);
|
||||
if (items.isEmpty()) {
|
||||
throw new ApiException(ErrorCode.SET_NOT_READY, "Набор пуст");
|
||||
}
|
||||
List<UUID> attractionIds = items.stream()
|
||||
.map(item -> item.getAttraction().getId())
|
||||
.toList();
|
||||
if (photoRepository.countDistinctByAttractionIdIn(attractionIds) != attractionIds.size()) {
|
||||
throw new ApiException(ErrorCode.SET_NOT_READY,
|
||||
"У каждой достопримечательности набора должно быть хотя бы одно эталонное фото");
|
||||
}
|
||||
List<AttractionSet> currentActiveSets = setRepository
|
||||
.findAll(AttractionSetSpecs.activeInAreaExcept(set.getArea().getId(), id));
|
||||
currentActiveSets.forEach(current -> {
|
||||
current.setStatus(SetStatus.ARCHIVED);
|
||||
current.setUpdatedAt(LocalDateTime.now(ZoneOffset.UTC));
|
||||
});
|
||||
setRepository.saveAll(currentActiveSets);
|
||||
set.setStatus(SetStatus.ACTIVE);
|
||||
try {
|
||||
return toResponse(setRepository.saveAndFlush(set));
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
throw new ApiException(ErrorCode.SET_STATE_CONFLICT,
|
||||
"В зоне уже активирован другой набор, повторите попытку");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SetResponse archive(UUID id) {
|
||||
AttractionSet set = getSet(id);
|
||||
if (set.getStatus() != SetStatus.ACTIVE) {
|
||||
throw new ApiException(ErrorCode.SET_STATE_CONFLICT, "Архивировать можно только активный набор");
|
||||
}
|
||||
set.setStatus(SetStatus.ARCHIVED);
|
||||
return toResponse(setRepository.save(set));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ActiveSetResponse getActiveSet(UUID areaId) {
|
||||
AttractionSet set = setRepository.findByAreaIdAndStatus(areaId, SetStatus.ACTIVE)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NO_ACTIVE_SET));
|
||||
List<AttractionSetItem> items = itemRepository
|
||||
.findAll(AttractionSetItemSpecs.ofActiveSetInAreaSortedByAttractionName(areaId));
|
||||
CurrentUser user = currentUserProvider.getCurrentUser().orElse(null);
|
||||
return setMapper.toActiveSetResponse(set, toActiveSetAttractions(items, user));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public AreaActiveSetInfo getAreaActiveSetInfo(UUID areaId) {
|
||||
if (setRepository.findByAreaIdAndStatus(areaId, SetStatus.ACTIVE).isEmpty()) {
|
||||
return new AreaActiveSetInfo(List.of(), new ProgressResponse(0, 0));
|
||||
}
|
||||
List<AttractionSetItem> items = itemRepository
|
||||
.findAll(AttractionSetItemSpecs.ofActiveSetInAreaSortedByAttractionName(areaId));
|
||||
CurrentUser user = currentUserProvider.getCurrentUser().orElse(null);
|
||||
List<ActiveSetAttractionResponse> attractions = toActiveSetAttractions(items, user);
|
||||
int visited = user == null
|
||||
? 0
|
||||
: (int) visitRepository.countByUserIdAndAttractionIdIn(user.id(), attractionIds(items));
|
||||
return new AreaActiveSetInfo(attractions, new ProgressResponse(visited, items.size()));
|
||||
}
|
||||
|
||||
private List<ActiveSetAttractionResponse> toActiveSetAttractions(List<AttractionSetItem> items,
|
||||
CurrentUser user) {
|
||||
Set<UUID> visitedAttractionIds = user == null
|
||||
? Set.of()
|
||||
: visitedAttractionIds(user.id(), attractionIds(items));
|
||||
return items.stream()
|
||||
.map(item -> {
|
||||
Attraction attraction = item.getAttraction();
|
||||
String iconUrl = attraction.getIconKey() == null
|
||||
? null
|
||||
: s3Storage.presignGetUrl(attraction.getIconKey());
|
||||
boolean visited = visitedAttractionIds.contains(attraction.getId());
|
||||
return setMapper.toActiveSetAttraction(attraction, iconUrl, visited);
|
||||
})
|
||||
.toList();
|
||||
}
|
||||
|
||||
private List<UUID> attractionIds(List<AttractionSetItem> items) {
|
||||
return items.stream().map(item -> item.getAttraction().getId()).toList();
|
||||
}
|
||||
|
||||
private Set<UUID> visitedAttractionIds(String userId, List<UUID> attractionIds) {
|
||||
return visitRepository.findByUserIdAndAttractionIdIn(userId, attractionIds).stream()
|
||||
.collect(HashSet::new, (set, visit) -> set.add(visit.getAttraction().getId()), Set::addAll);
|
||||
}
|
||||
|
||||
private AttractionSet getSet(UUID id) {
|
||||
return setRepository.findById(id)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.SET_NOT_FOUND));
|
||||
}
|
||||
|
||||
private SetResponse toResponse(AttractionSet set) {
|
||||
return setMapper.toResponse(set, itemRepository.countBySetId(set.getId()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package ru.gorodar.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import ru.gorodar.dao.AttractionPhotoRepository;
|
||||
import ru.gorodar.dao.AttractionSetItemRepository;
|
||||
import ru.gorodar.api.dto.PhotoDtos.PhotoResponse;
|
||||
import ru.gorodar.dao.entity.Attraction;
|
||||
import ru.gorodar.dao.entity.AttractionPhoto;
|
||||
import ru.gorodar.dao.entity.SetStatus;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
import ru.gorodar.integration.opencv.FeaturesResult;
|
||||
import ru.gorodar.integration.opencv.OpenCvClient;
|
||||
import ru.gorodar.integration.s3.S3Storage;
|
||||
import ru.gorodar.mapper.PhotoMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class ReferencePhotoService {
|
||||
|
||||
private final AttractionService attractionService;
|
||||
private final AttractionPhotoRepository photoRepository;
|
||||
private final AttractionSetItemRepository itemRepository;
|
||||
private final S3Storage s3Storage;
|
||||
private final OpenCvClient openCvClient;
|
||||
private final PhotoMapper photoMapper;
|
||||
|
||||
public PhotoResponse upload(UUID attractionId, MultipartFile file, Integer sortOrder) {
|
||||
Attraction attraction = attractionService.getAttraction(attractionId);
|
||||
String contentType = file.getContentType() == null ? "application/octet-stream" : file.getContentType();
|
||||
byte[] bytes;
|
||||
try {
|
||||
bytes = file.getBytes();
|
||||
} catch (IOException e) {
|
||||
throw new ApiException(ErrorCode.INVALID_PHOTO, "Не удалось прочитать файл фотографии", e);
|
||||
}
|
||||
|
||||
UUID photoId = UUID.randomUUID();
|
||||
String photoKey = "attractions/%s/reference/%s.%s"
|
||||
.formatted(attractionId, photoId, AttractionService.extensionOf(contentType));
|
||||
String featuresKey = "attractions/%s/reference/%s.npz".formatted(attractionId, photoId);
|
||||
|
||||
s3Storage.put(photoKey, bytes, contentType);
|
||||
FeaturesResult features = openCvClient.extractFeatures(bytes, attraction.getCvProfile());
|
||||
s3Storage.put(featuresKey, features.blob(), "application/octet-stream");
|
||||
|
||||
AttractionPhoto photo = new AttractionPhoto();
|
||||
photo.setId(photoId);
|
||||
photo.setAttraction(attraction);
|
||||
photo.setS3PhotoKey(photoKey);
|
||||
photo.setS3FeaturesKey(featuresKey);
|
||||
photo.setFeatureFormatVersion(features.formatVersion());
|
||||
photo.setAlgoId(features.algoId());
|
||||
photo.setKeypointsCount(features.keypointsCount());
|
||||
photo.setSortOrder(sortOrder != null
|
||||
? sortOrder
|
||||
: (int) photoRepository.countByAttractionId(attractionId) + 1);
|
||||
try {
|
||||
return toResponse(photoRepository.saveAndFlush(photo));
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
throw new ApiException(ErrorCode.SORT_ORDER_TAKEN);
|
||||
}
|
||||
}
|
||||
|
||||
public List<PhotoResponse> list(UUID attractionId) {
|
||||
attractionService.getAttraction(attractionId);
|
||||
return photoRepository.findByAttractionIdOrderBySortOrderAsc(attractionId).stream()
|
||||
.map(this::toResponse)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public PhotoResponse updateSortOrder(UUID attractionId, UUID photoId, int sortOrder) {
|
||||
AttractionPhoto photo = getPhoto(attractionId, photoId);
|
||||
photo.setSortOrder(sortOrder);
|
||||
try {
|
||||
return toResponse(photoRepository.saveAndFlush(photo));
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
throw new ApiException(ErrorCode.SORT_ORDER_TAKEN);
|
||||
}
|
||||
}
|
||||
|
||||
public PhotoResponse reextractFeatures(UUID attractionId, UUID photoId) {
|
||||
Attraction attraction = attractionService.getAttraction(attractionId);
|
||||
AttractionPhoto photo = getPhoto(attractionId, photoId);
|
||||
byte[] photoBytes = s3Storage.get(photo.getS3PhotoKey());
|
||||
FeaturesResult features = openCvClient.extractFeatures(photoBytes, attraction.getCvProfile());
|
||||
s3Storage.put(photo.getS3FeaturesKey(), features.blob(), "application/octet-stream");
|
||||
photo.setFeatureFormatVersion(features.formatVersion());
|
||||
photo.setAlgoId(features.algoId());
|
||||
photo.setKeypointsCount(features.keypointsCount());
|
||||
return toResponse(photoRepository.save(photo));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void delete(UUID attractionId, UUID photoId) {
|
||||
attractionService.getAttraction(attractionId);
|
||||
AttractionPhoto photo = getPhoto(attractionId, photoId);
|
||||
boolean inActiveSet = itemRepository.existsByAttractionIdAndSet_Status(attractionId, SetStatus.ACTIVE);
|
||||
boolean lastPhoto = photoRepository.countByAttractionId(attractionId) <= 1;
|
||||
if (inActiveSet && lastPhoto) {
|
||||
throw new ApiException(ErrorCode.LAST_REFERENCE_PHOTO);
|
||||
}
|
||||
photoRepository.delete(photo);
|
||||
// Строка уже удалена; файлы в S3 убираем best-effort, сбой не ломает удаление.
|
||||
try {
|
||||
s3Storage.delete(photo.getS3PhotoKey());
|
||||
s3Storage.delete(photo.getS3FeaturesKey());
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось удалить файлы эталонного фото {} из S3: {}", photoId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private AttractionPhoto getPhoto(UUID attractionId, UUID photoId) {
|
||||
return photoRepository.findByIdAndAttractionId(photoId, attractionId)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.PHOTO_NOT_FOUND));
|
||||
}
|
||||
|
||||
private PhotoResponse toResponse(AttractionPhoto photo) {
|
||||
return photoMapper.toResponse(photo, s3Storage.presignGetUrl(photo.getS3PhotoKey()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package ru.gorodar.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import ru.gorodar.dao.entity.SetStatus;
|
||||
import ru.gorodar.dao.entity.VerifyVerdict;
|
||||
import ru.gorodar.dao.entity.VisitStatus;
|
||||
import ru.gorodar.dao.entity.Attraction;
|
||||
import ru.gorodar.dao.entity.AttractionPhoto;
|
||||
import ru.gorodar.dao.entity.AttractionUserVisit;
|
||||
import ru.gorodar.api.dto.VisitDtos.ProgressResponse;
|
||||
import ru.gorodar.api.dto.VisitDtos.VisitFilterRequest;
|
||||
import ru.gorodar.api.dto.VisitDtos.VisitResponse;
|
||||
import ru.gorodar.api.dto.VisitDtos.VisitSubmitResponse;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
import ru.gorodar.integration.opencv.OpenCvClient;
|
||||
import ru.gorodar.integration.opencv.VerifyResult;
|
||||
import ru.gorodar.integration.s3.S3Storage;
|
||||
import ru.gorodar.dao.AttractionPhotoRepository;
|
||||
import ru.gorodar.dao.AttractionRepository;
|
||||
import ru.gorodar.dao.AttractionSetItemRepository;
|
||||
import ru.gorodar.dao.AttractionSetRepository;
|
||||
import ru.gorodar.dao.AttractionUserVisitRepository;
|
||||
import ru.gorodar.dao.spec.AttractionSetItemSpecs;
|
||||
import ru.gorodar.dao.spec.VisitSpecs;
|
||||
import ru.gorodar.mapper.VisitMapper;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class VisitService {
|
||||
|
||||
private final AttractionRepository attractionRepository;
|
||||
private final AttractionPhotoRepository photoRepository;
|
||||
private final AttractionSetRepository setRepository;
|
||||
private final AttractionSetItemRepository itemRepository;
|
||||
private final AttractionUserVisitRepository visitRepository;
|
||||
private final S3Storage s3Storage;
|
||||
private final OpenCvClient openCvClient;
|
||||
private final VisitMapper visitMapper;
|
||||
|
||||
public VisitSubmitResponse submit(String userId, UUID attractionId, byte[] photo) {
|
||||
Attraction attraction = attractionRepository.findById(attractionId)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.ATTRACTION_NOT_FOUND));
|
||||
UUID areaId = attraction.getArea().getId();
|
||||
if (!itemRepository.existsByAttractionIdAndSet_Status(attractionId, SetStatus.ACTIVE)) {
|
||||
throw new ApiException(ErrorCode.ATTRACTION_NOT_IN_ACTIVE_SET);
|
||||
}
|
||||
if (visitRepository.existsByUserIdAndAttractionId(userId, attractionId)) {
|
||||
return new VisitSubmitResponse(VisitStatus.ALREADY_VISITED.name(), null, progress(userId, areaId));
|
||||
}
|
||||
AttractionPhoto referencePhoto = photoRepository
|
||||
.findFirstByAttractionIdOrderBySortOrderAsc(attractionId)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NO_REFERENCE_PHOTO));
|
||||
byte[] features = s3Storage.get(referencePhoto.getS3FeaturesKey());
|
||||
VerifyResult result = openCvClient.verify(photo, List.of(features));
|
||||
|
||||
if (result.verdict() == VerifyVerdict.MATCH) {
|
||||
AttractionUserVisit visit = new AttractionUserVisit();
|
||||
visit.setId(UUID.randomUUID());
|
||||
visit.setUserId(userId);
|
||||
visit.setAttraction(attraction);
|
||||
visit.setVisitedAt(LocalDateTime.now(ZoneOffset.UTC));
|
||||
visit.setVerdict(VerifyVerdict.MATCH);
|
||||
visit.setConfidence(BigDecimal.valueOf(result.confidence()));
|
||||
visit.setProbeSha256(result.probeSha256());
|
||||
try {
|
||||
visitRepository.saveAndFlush(visit);
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
return new VisitSubmitResponse(VisitStatus.ALREADY_VISITED.name(), null, progress(userId, areaId));
|
||||
}
|
||||
}
|
||||
VisitStatus status = switch (result.verdict()) {
|
||||
case MATCH -> VisitStatus.VISITED;
|
||||
case UNCERTAIN -> VisitStatus.UNCERTAIN;
|
||||
case NO_MATCH -> VisitStatus.NOT_MATCHED;
|
||||
};
|
||||
return new VisitSubmitResponse(status.name(), result.confidence(), progress(userId, areaId));
|
||||
}
|
||||
|
||||
public ProgressResponse progress(String userId, UUID areaId) {
|
||||
setRepository.findByAreaIdAndStatus(areaId, SetStatus.ACTIVE)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NO_ACTIVE_SET));
|
||||
List<UUID> attractionIds = itemRepository.findAll(AttractionSetItemSpecs.ofActiveSetInArea(areaId)).stream()
|
||||
.map(item -> item.getAttraction().getId())
|
||||
.toList();
|
||||
if (attractionIds.isEmpty()) {
|
||||
return new ProgressResponse(0, 0);
|
||||
}
|
||||
long visited = visitRepository.countByUserIdAndAttractionIdIn(userId, attractionIds);
|
||||
return new ProgressResponse((int) visited, attractionIds.size());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<VisitResponse> myVisits(String userId, Pageable pageable) {
|
||||
return visitRepository
|
||||
.findByUserIdOrderByVisitedAtDesc(userId, pageable)
|
||||
.map(this::toResponse);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<VisitResponse> adminVisits(VisitFilterRequest request, Pageable pageable) {
|
||||
String userId = StringUtils.hasText(request.userId()) ? request.userId() : null;
|
||||
Specification<AttractionUserVisit> spec = VisitSpecs.filtered(
|
||||
request.areaId(), request.attractionId(), userId, request.from(), request.to());
|
||||
Page<VisitResponse> result = visitRepository.findAll(spec, pageable).map(this::toResponse);
|
||||
return result;
|
||||
}
|
||||
|
||||
private VisitResponse toResponse(AttractionUserVisit visit) {
|
||||
return visitMapper.toResponse(visit);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,55 @@
|
||||
spring:
|
||||
application:
|
||||
name: gorodar-back
|
||||
|
||||
datasource:
|
||||
url: jdbc:postgresql://${GORODAR_DB_HOST:localhost}:${GORODAR_DB_PORT:5432}/${GORODAR_DB_NAME:gorodar}
|
||||
username: ${GORODAR_DB_USER:gorodar}
|
||||
password: ${GORODAR_DB_PASSWORD:gorodar}
|
||||
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
open-in-view: false
|
||||
properties:
|
||||
hibernate.format_sql: false
|
||||
hibernate.jdbc.time_zone: UTC
|
||||
|
||||
liquibase:
|
||||
change-log: classpath:db/changelog/db.changelog-master.yaml
|
||||
|
||||
security:
|
||||
oauth2:
|
||||
resourceserver:
|
||||
jwt:
|
||||
issuer-uri: ${GORODAR_KEYCLOAK_ISSUER:http://localhost:8081/realms/gorodar}
|
||||
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 20MB
|
||||
max-request-size: 22MB
|
||||
|
||||
gorodar:
|
||||
keycloak:
|
||||
client-id: gorodar
|
||||
opencv:
|
||||
base-url: ${GORODAR_OPENCV_URL:http://localhost:8000}
|
||||
api-key: ${GORODAR_OPENCV_API_KEY:dev-key}
|
||||
s3:
|
||||
endpoint: ${GORODAR_S3_ENDPOINT:http://localhost:9000}
|
||||
region: ${GORODAR_S3_REGION:ru-central-1}
|
||||
access-key: ${GORODAR_S3_ACCESS_KEY:gorodar}
|
||||
secret-key: ${GORODAR_S3_SECRET_KEY:gorodar-secret}
|
||||
bucket: ${GORODAR_S3_BUCKET:gorodar}
|
||||
path-style-access: true
|
||||
presign-ttl: 1h
|
||||
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: health,info
|
||||
|
||||
springdoc:
|
||||
swagger-ui:
|
||||
path: /swagger-ui.html
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
--liquibase formatted sql
|
||||
|
||||
--changeset gorodar:001-areas
|
||||
create table areas (
|
||||
id uuid primary key,
|
||||
parent_id uuid references areas (id),
|
||||
name varchar(255) not null,
|
||||
created_at timestamp not null default (now() at time zone 'utc'),
|
||||
updated_at timestamp not null default (now() at time zone 'utc')
|
||||
);
|
||||
|
||||
--changeset gorodar:001-areas-index-parent
|
||||
create index idx_areas_parent_id on areas (parent_id);
|
||||
@@ -0,0 +1,37 @@
|
||||
--liquibase formatted sql
|
||||
|
||||
--changeset gorodar:002-attractions
|
||||
create table attractions (
|
||||
id uuid primary key,
|
||||
area_id uuid not null references areas (id),
|
||||
name varchar(255) not null,
|
||||
icon_key varchar(512),
|
||||
about text,
|
||||
latitude numeric(9, 6),
|
||||
longitude numeric(9, 6),
|
||||
address varchar(512),
|
||||
facts jsonb,
|
||||
cv_profile varchar(32) not null,
|
||||
created_at timestamp not null default (now() at time zone 'utc'),
|
||||
updated_at timestamp not null default (now() at time zone 'utc')
|
||||
);
|
||||
|
||||
--changeset gorodar:002-attractions-index-area
|
||||
create index idx_attractions_area_id on attractions (area_id);
|
||||
|
||||
--changeset gorodar:002-attraction-photos
|
||||
create table attraction_photos (
|
||||
id uuid primary key,
|
||||
attraction_id uuid not null references attractions (id),
|
||||
s3_photo_key varchar(512) not null,
|
||||
s3_features_key varchar(512) not null,
|
||||
feature_format_version integer not null,
|
||||
algo_id varchar(64) not null,
|
||||
keypoints_count integer not null,
|
||||
sort_order integer not null,
|
||||
created_at timestamp not null default (now() at time zone 'utc'),
|
||||
constraint uq_attraction_photos_sort_order unique (attraction_id, sort_order)
|
||||
);
|
||||
|
||||
--changeset gorodar:002-attraction-photos-index-attraction
|
||||
create index idx_attraction_photos_attraction_id on attraction_photos (attraction_id);
|
||||
@@ -0,0 +1,31 @@
|
||||
--liquibase formatted sql
|
||||
|
||||
--changeset gorodar:003-attraction-sets
|
||||
create table attraction_sets (
|
||||
id uuid primary key,
|
||||
area_id uuid not null references areas (id),
|
||||
name varchar(255) not null,
|
||||
status varchar(16) not null,
|
||||
created_at timestamp not null default (now() at time zone 'utc'),
|
||||
updated_at timestamp not null default (now() at time zone 'utc'),
|
||||
constraint ck_attraction_sets_status check (status in ('DRAFT', 'ACTIVE', 'ARCHIVED'))
|
||||
);
|
||||
|
||||
--changeset gorodar:003-attraction-sets-unique-active
|
||||
create unique index uq_attraction_sets_active_area on attraction_sets (area_id) where status = 'ACTIVE';
|
||||
|
||||
--changeset gorodar:003-attraction-sets-index-area
|
||||
create index idx_attraction_sets_area_id on attraction_sets (area_id);
|
||||
|
||||
--changeset gorodar:003-attraction-set-items
|
||||
create table attraction_set_items (
|
||||
id uuid primary key,
|
||||
set_id uuid not null references attraction_sets (id),
|
||||
attraction_id uuid not null references attractions (id),
|
||||
created_at timestamp not null default (now() at time zone 'utc'),
|
||||
constraint uq_attraction_set_items unique (set_id, attraction_id)
|
||||
);
|
||||
|
||||
--changeset gorodar:003-attraction-set-items-indexes
|
||||
create index idx_attraction_set_items_set_id on attraction_set_items (set_id);
|
||||
create index idx_attraction_set_items_attraction_id on attraction_set_items (attraction_id);
|
||||
@@ -0,0 +1,17 @@
|
||||
--liquibase formatted sql
|
||||
|
||||
--changeset gorodar:004-attraction-users-visits
|
||||
create table attraction_users_visits (
|
||||
id uuid primary key,
|
||||
user_id varchar(64) not null,
|
||||
attraction_id uuid not null references attractions (id),
|
||||
visited_at timestamp not null default (now() at time zone 'utc'),
|
||||
verdict varchar(16) not null,
|
||||
confidence numeric(5, 4),
|
||||
probe_sha256 varchar(64),
|
||||
constraint uq_visits_user_attraction unique (user_id, attraction_id)
|
||||
);
|
||||
|
||||
--changeset gorodar:004-visits-indexes
|
||||
create index idx_visits_user_id on attraction_users_visits (user_id);
|
||||
create index idx_visits_attraction_id on attraction_users_visits (attraction_id);
|
||||
@@ -0,0 +1,9 @@
|
||||
databaseChangeLog:
|
||||
- include:
|
||||
file: db/changelog/changelogs/001-create-areas.sql
|
||||
- include:
|
||||
file: db/changelog/changelogs/002-create-attractions.sql
|
||||
- include:
|
||||
file: db/changelog/changelogs/003-create-attraction-sets.sql
|
||||
- include:
|
||||
file: db/changelog/changelogs/004-create-attraction-users-visits.sql
|
||||
@@ -0,0 +1,70 @@
|
||||
package ru.gorodar.security;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class KeycloakJwtAuthenticationConverterTest {
|
||||
|
||||
private final KeycloakJwtAuthenticationConverter converter =
|
||||
new KeycloakJwtAuthenticationConverter("gorodar");
|
||||
|
||||
@Test
|
||||
void convertsClientRolesToAuthorities() {
|
||||
Jwt jwt = jwtWithClaims(Map.of("resource_access",
|
||||
Map.of("gorodar", Map.of("roles", List.of("manage_area", "manage_attraction")))));
|
||||
|
||||
var authentication = converter.convert(jwt);
|
||||
|
||||
assertThat(authentication).isNotNull();
|
||||
assertThat(authentication.getToken().getSubject()).isEqualTo("user-1");
|
||||
assertThat(authentication.getAuthorities())
|
||||
.extracting(GrantedAuthority::getAuthority)
|
||||
.containsExactlyInAnyOrder("manage_area", "manage_attraction");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ignoresRolesOfOtherClients() {
|
||||
Jwt jwt = jwtWithClaims(Map.of("resource_access",
|
||||
Map.of("other-client", Map.of("roles", List.of("manage_area")))));
|
||||
|
||||
var authentication = converter.convert(jwt);
|
||||
|
||||
assertThat(authentication.getAuthorities()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void toleratesMissingResourceAccessClaim() {
|
||||
Jwt jwt = jwtWithClaims(Map.of());
|
||||
|
||||
var authentication = converter.convert(jwt);
|
||||
|
||||
assertThat(authentication.getAuthorities()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void toleratesNonListRoles() {
|
||||
Jwt jwt = jwtWithClaims(Map.of("resource_access",
|
||||
Map.of("gorodar", Map.of("roles", "not-a-list"))));
|
||||
|
||||
var authentication = converter.convert(jwt);
|
||||
|
||||
assertThat(authentication.getAuthorities()).isEmpty();
|
||||
}
|
||||
|
||||
private Jwt jwtWithClaims(Map<String, Object> claims) {
|
||||
var builder = Jwt.withTokenValue("token")
|
||||
.header("alg", "RS256")
|
||||
.subject("user-1")
|
||||
.issuedAt(Instant.now())
|
||||
.expiresAt(Instant.now().plusSeconds(60));
|
||||
claims.forEach(builder::claim);
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package ru.gorodar.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import ru.gorodar.dao.AreaRepository;
|
||||
import ru.gorodar.dao.AttractionPhotoRepository;
|
||||
import ru.gorodar.dao.AttractionRepository;
|
||||
import ru.gorodar.dao.AttractionUserVisitRepository;
|
||||
import ru.gorodar.dao.entity.Attraction;
|
||||
import ru.gorodar.integration.s3.S3Storage;
|
||||
import ru.gorodar.mapper.AttractionMapper;
|
||||
import ru.gorodar.security.CurrentUser;
|
||||
import ru.gorodar.security.CurrentUserProvider;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AttractionServiceTest {
|
||||
|
||||
private final UUID areaId = UUID.randomUUID();
|
||||
private final UUID attractionId = UUID.randomUUID();
|
||||
|
||||
@Mock
|
||||
private AreaRepository areaRepository;
|
||||
@Mock
|
||||
private AttractionRepository attractionRepository;
|
||||
@Mock
|
||||
private AttractionPhotoRepository photoRepository;
|
||||
@Mock
|
||||
private AttractionUserVisitRepository visitRepository;
|
||||
@Mock
|
||||
private S3Storage s3Storage;
|
||||
@Mock
|
||||
private AttractionMapper attractionMapper;
|
||||
@Mock
|
||||
private CurrentUserProvider currentUserProvider;
|
||||
|
||||
@InjectMocks
|
||||
private AttractionService service;
|
||||
|
||||
@Test
|
||||
void cardForAnonymousIsNotVisitedAndSkipsVisitLookup() {
|
||||
Attraction attraction = EntityTestHelper.attractionOf(attractionId, areaId);
|
||||
when(attractionRepository.findById(attractionId)).thenReturn(Optional.of(attraction));
|
||||
when(photoRepository.findFirstByAttractionIdOrderBySortOrderAsc(attractionId))
|
||||
.thenReturn(Optional.empty());
|
||||
when(currentUserProvider.getCurrentUser()).thenReturn(Optional.empty());
|
||||
|
||||
service.getCard(attractionId);
|
||||
|
||||
verify(attractionMapper).toCardResponse(eq(attraction), isNull(), isNull(), eq(false));
|
||||
verifyNoInteractions(visitRepository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cardForUserReflectsExistingVisit() {
|
||||
Attraction attraction = EntityTestHelper.attractionOf(attractionId, areaId);
|
||||
when(attractionRepository.findById(attractionId)).thenReturn(Optional.of(attraction));
|
||||
when(photoRepository.findFirstByAttractionIdOrderBySortOrderAsc(attractionId))
|
||||
.thenReturn(Optional.empty());
|
||||
when(currentUserProvider.getCurrentUser())
|
||||
.thenReturn(Optional.of(new CurrentUser("user-1", Set.of())));
|
||||
when(visitRepository.existsByUserIdAndAttractionId("user-1", attractionId)).thenReturn(true);
|
||||
|
||||
service.getCard(attractionId);
|
||||
|
||||
verify(attractionMapper).toCardResponse(eq(attraction), isNull(), isNull(), eq(true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package ru.gorodar.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import ru.gorodar.dao.entity.SetStatus;
|
||||
import ru.gorodar.dao.entity.AttractionSetItem;
|
||||
import ru.gorodar.api.dto.SetDtos.ActiveSetAttractionResponse;
|
||||
import ru.gorodar.api.dto.SetDtos.SetItemsRequest;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
import ru.gorodar.integration.s3.S3Storage;
|
||||
import ru.gorodar.dao.AreaRepository;
|
||||
import ru.gorodar.dao.AttractionPhotoRepository;
|
||||
import ru.gorodar.dao.AttractionRepository;
|
||||
import ru.gorodar.dao.AttractionSetItemRepository;
|
||||
import ru.gorodar.dao.AttractionSetRepository;
|
||||
import ru.gorodar.dao.AttractionUserVisitRepository;
|
||||
import ru.gorodar.api.dto.SetDtos.SetResponse;
|
||||
import ru.gorodar.mapper.SetMapper;
|
||||
import ru.gorodar.dao.entity.AttractionSet;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AttractionSetServiceTest {
|
||||
|
||||
private final UUID areaId = UUID.randomUUID();
|
||||
private final UUID otherAreaId = UUID.randomUUID();
|
||||
private final UUID setId = UUID.randomUUID();
|
||||
private final UUID attractionId = UUID.randomUUID();
|
||||
|
||||
@Mock
|
||||
private AttractionSetRepository setRepository;
|
||||
@Mock
|
||||
private AttractionSetItemRepository itemRepository;
|
||||
@Mock
|
||||
private AttractionRepository attractionRepository;
|
||||
@Mock
|
||||
private AreaRepository areaRepository;
|
||||
@Mock
|
||||
private AttractionPhotoRepository photoRepository;
|
||||
@Mock
|
||||
private AttractionUserVisitRepository visitRepository;
|
||||
@Mock
|
||||
private S3Storage s3Storage;
|
||||
@Mock
|
||||
private SetMapper setMapper;
|
||||
@Mock
|
||||
private ru.gorodar.security.CurrentUserProvider currentUserProvider;
|
||||
|
||||
private SetResponse responseOf(AttractionSet set) {
|
||||
return new SetResponse(set.getId(), set.getArea().getId(), set.getName(),
|
||||
set.getStatus().name(), 1L);
|
||||
}
|
||||
|
||||
@InjectMocks
|
||||
private AttractionSetService service;
|
||||
|
||||
private static <T> org.springframework.data.jpa.domain.Specification<T> anySpec() {
|
||||
return org.mockito.ArgumentMatchers.any();
|
||||
}
|
||||
|
||||
@Test
|
||||
void activateArchivesCurrentActiveAndActivatesDraft() {
|
||||
var set = EntityTestHelper.setOf(setId, areaId, SetStatus.DRAFT);
|
||||
when(setRepository.findById(setId)).thenReturn(Optional.of(set));
|
||||
when(itemRepository.findBySetId(setId)).thenReturn(List.of(itemOf(setId, attractionId)));
|
||||
when(photoRepository.countDistinctByAttractionIdIn(List.of(attractionId))).thenReturn(1L);
|
||||
var currentActive = EntityTestHelper.setOf(UUID.randomUUID(), areaId, SetStatus.ACTIVE);
|
||||
when(setRepository.findAll(anySpec())).thenReturn(List.of(currentActive));
|
||||
when(setRepository.saveAll(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
when(setRepository.saveAndFlush(set)).thenReturn(set);
|
||||
when(itemRepository.countBySetId(setId)).thenReturn(1L);
|
||||
when(setMapper.toResponse(eq(set), anyLong()))
|
||||
.thenAnswer(invocation -> responseOf(invocation.getArgument(0)));
|
||||
|
||||
var response = service.activate(setId);
|
||||
|
||||
assertThat(response.status()).isEqualTo("ACTIVE");
|
||||
assertThat(set.getStatus()).isEqualTo(SetStatus.ACTIVE);
|
||||
assertThat(currentActive.getStatus()).isEqualTo(SetStatus.ARCHIVED);
|
||||
verify(setRepository).saveAll(List.of(currentActive));
|
||||
}
|
||||
|
||||
@Test
|
||||
void activateRejectedWhenAttractionHasNoReferencePhoto() {
|
||||
var set = EntityTestHelper.setOf(setId, areaId, SetStatus.DRAFT);
|
||||
when(setRepository.findById(setId)).thenReturn(Optional.of(set));
|
||||
when(itemRepository.findBySetId(setId)).thenReturn(List.of(itemOf(setId, attractionId)));
|
||||
when(photoRepository.countDistinctByAttractionIdIn(List.of(attractionId))).thenReturn(0L);
|
||||
|
||||
ApiException error = assertThrows(ApiException.class, () -> service.activate(setId));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.SET_NOT_READY);
|
||||
verify(setRepository, never()).saveAll(any());
|
||||
verify(setRepository, never()).saveAndFlush(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void activateRejectedForNonDraftSet() {
|
||||
var set = EntityTestHelper.setOf(setId, areaId, SetStatus.ARCHIVED);
|
||||
when(setRepository.findById(setId)).thenReturn(Optional.of(set));
|
||||
|
||||
ApiException error = assertThrows(ApiException.class, () -> service.activate(setId));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.SET_STATE_CONFLICT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void putItemsRejectsAttractionsFromAnotherArea() {
|
||||
var set = EntityTestHelper.setOf(setId, areaId, SetStatus.DRAFT);
|
||||
when(setRepository.findById(setId)).thenReturn(Optional.of(set));
|
||||
when(attractionRepository.findAllById(List.of(attractionId)))
|
||||
.thenReturn(List.of(EntityTestHelper.attractionOf(attractionId, otherAreaId)));
|
||||
|
||||
ApiException error = assertThrows(ApiException.class,
|
||||
() -> service.putItems(setId, new SetItemsRequest(List.of(attractionId))));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.ATTRACTIONS_NOT_IN_AREA);
|
||||
verify(itemRepository, never()).deleteBySetId(setId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void putItemsReplacesComposition() {
|
||||
var set = EntityTestHelper.setOf(setId, areaId, SetStatus.DRAFT);
|
||||
when(setRepository.findById(setId)).thenReturn(Optional.of(set));
|
||||
var attraction = EntityTestHelper.attractionOf(attractionId, areaId);
|
||||
when(attractionRepository.findAllById(List.of(attractionId))).thenReturn(List.of(attraction));
|
||||
when(itemRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
when(itemRepository.countBySetId(setId)).thenReturn(1L);
|
||||
when(setMapper.toResponse(eq(set), anyLong())).thenReturn(responseOf(set));
|
||||
|
||||
var response = service.putItems(setId, new SetItemsRequest(List.of(attractionId)));
|
||||
|
||||
assertThat(response.itemCount()).isEqualTo(1);
|
||||
verify(itemRepository).deleteBySetId(setId);
|
||||
verify(itemRepository).save(any(AttractionSetItem.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void areaActiveSetInfoForAnonymousShowsZeroProgressAndUnvisited() {
|
||||
when(currentUserProvider.getCurrentUser()).thenReturn(Optional.empty());
|
||||
when(setRepository.findByAreaIdAndStatus(areaId, SetStatus.ACTIVE))
|
||||
.thenReturn(Optional.of(EntityTestHelper.setOf(UUID.randomUUID(), areaId, SetStatus.ACTIVE)));
|
||||
var attraction = EntityTestHelper.attractionOf(attractionId, areaId);
|
||||
var item = new AttractionSetItem();
|
||||
item.setId(UUID.randomUUID());
|
||||
item.setAttraction(attraction);
|
||||
when(itemRepository.findAll(anySpec())).thenReturn(List.of(item));
|
||||
when(setMapper.toActiveSetAttraction(eq(attraction), any(), eq(false)))
|
||||
.thenReturn(new ActiveSetAttractionResponse(attractionId, "attraction", null, false));
|
||||
|
||||
var info = service.getAreaActiveSetInfo(areaId);
|
||||
|
||||
assertThat(info.progress().visited()).isZero();
|
||||
assertThat(info.progress().total()).isEqualTo(1);
|
||||
assertThat(info.attractions()).hasSize(1);
|
||||
assertThat(info.attractions().get(0).visited()).isFalse();
|
||||
verify(visitRepository, never()).countByUserIdAndAttractionIdIn(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void areaActiveSetInfoWithoutActiveSetReturnsEmpty() {
|
||||
when(setRepository.findByAreaIdAndStatus(areaId, SetStatus.ACTIVE)).thenReturn(Optional.empty());
|
||||
|
||||
var info = service.getAreaActiveSetInfo(areaId);
|
||||
|
||||
assertThat(info.attractions()).isEmpty();
|
||||
assertThat(info.progress().visited()).isZero();
|
||||
assertThat(info.progress().total()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeItemDeletesSingleItem() {
|
||||
var set = EntityTestHelper.setOf(setId, areaId, SetStatus.ACTIVE);
|
||||
when(setRepository.findById(setId)).thenReturn(Optional.of(set));
|
||||
var item = itemOf(setId, attractionId);
|
||||
when(itemRepository.findBySetIdAndAttractionId(setId, attractionId)).thenReturn(Optional.of(item));
|
||||
when(itemRepository.countBySetId(setId)).thenReturn(2L);
|
||||
|
||||
service.removeItem(setId, attractionId);
|
||||
|
||||
verify(itemRepository).delete(item);
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeLastItemRejected() {
|
||||
var set = EntityTestHelper.setOf(setId, areaId, SetStatus.DRAFT);
|
||||
when(setRepository.findById(setId)).thenReturn(Optional.of(set));
|
||||
when(itemRepository.findBySetIdAndAttractionId(setId, attractionId))
|
||||
.thenReturn(Optional.of(itemOf(setId, attractionId)));
|
||||
when(itemRepository.countBySetId(setId)).thenReturn(1L);
|
||||
|
||||
ApiException error = assertThrows(ApiException.class,
|
||||
() -> service.removeItem(setId, attractionId));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.LAST_SET_ITEM);
|
||||
verify(itemRepository, never()).delete(any(AttractionSetItem.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeItemRejectedForArchivedSet() {
|
||||
var set = EntityTestHelper.setOf(setId, areaId, SetStatus.ARCHIVED);
|
||||
when(setRepository.findById(setId)).thenReturn(Optional.of(set));
|
||||
|
||||
ApiException error = assertThrows(ApiException.class,
|
||||
() -> service.removeItem(setId, attractionId));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.SET_STATE_CONFLICT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeMissingItemRejected() {
|
||||
var set = EntityTestHelper.setOf(setId, areaId, SetStatus.DRAFT);
|
||||
when(setRepository.findById(setId)).thenReturn(Optional.of(set));
|
||||
when(itemRepository.findBySetIdAndAttractionId(setId, attractionId)).thenReturn(Optional.empty());
|
||||
|
||||
ApiException error = assertThrows(ApiException.class,
|
||||
() -> service.removeItem(setId, attractionId));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.SET_ITEM_NOT_FOUND);
|
||||
}
|
||||
|
||||
private AttractionSetItem itemOf(UUID setId, UUID attractionId) {
|
||||
var item = new AttractionSetItem();
|
||||
item.setId(UUID.randomUUID());
|
||||
item.setSet(EntityTestHelper.setOf(setId, areaId, SetStatus.DRAFT));
|
||||
item.setAttraction(EntityTestHelper.attractionOf(attractionId, areaId));
|
||||
return item;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package ru.gorodar.service;
|
||||
|
||||
import ru.gorodar.dao.entity.SetStatus;
|
||||
import ru.gorodar.dao.entity.Area;
|
||||
import ru.gorodar.dao.entity.Attraction;
|
||||
import ru.gorodar.dao.entity.AttractionSet;
|
||||
import ru.gorodar.dao.entity.AttractionSetItem;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
final class EntityTestHelper {
|
||||
|
||||
private EntityTestHelper() {
|
||||
}
|
||||
|
||||
static Area areaOf(UUID id) {
|
||||
Area area = new Area();
|
||||
area.setId(id);
|
||||
area.setName("area-" + id);
|
||||
return area;
|
||||
}
|
||||
|
||||
static AttractionSet setOf(UUID setId, UUID areaId, SetStatus status) {
|
||||
AttractionSet set = new AttractionSet();
|
||||
set.setId(setId);
|
||||
set.setArea(areaOf(areaId));
|
||||
set.setName("set");
|
||||
set.setStatus(status);
|
||||
return set;
|
||||
}
|
||||
|
||||
static Attraction attractionOf(UUID id, UUID areaId) {
|
||||
Attraction attraction = new Attraction();
|
||||
attraction.setId(id);
|
||||
attraction.setArea(areaOf(areaId));
|
||||
attraction.setName("attraction-" + id);
|
||||
return attraction;
|
||||
}
|
||||
|
||||
static AttractionSetItem itemOf(UUID attractionId, UUID areaId) {
|
||||
AttractionSetItem item = new AttractionSetItem();
|
||||
item.setId(UUID.randomUUID());
|
||||
item.setAttraction(attractionOf(attractionId, areaId));
|
||||
return item;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package ru.gorodar.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import ru.gorodar.dao.AttractionPhotoRepository;
|
||||
import ru.gorodar.dao.AttractionSetItemRepository;
|
||||
import ru.gorodar.dao.entity.Attraction;
|
||||
import ru.gorodar.dao.entity.AttractionPhoto;
|
||||
import ru.gorodar.dao.entity.SetStatus;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
import ru.gorodar.integration.opencv.OpenCvClient;
|
||||
import ru.gorodar.integration.s3.S3Storage;
|
||||
import ru.gorodar.mapper.PhotoMapper;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ReferencePhotoServiceTest {
|
||||
|
||||
private final UUID attractionId = UUID.randomUUID();
|
||||
private final UUID photoId = UUID.randomUUID();
|
||||
|
||||
@Mock
|
||||
private AttractionService attractionService;
|
||||
@Mock
|
||||
private AttractionPhotoRepository photoRepository;
|
||||
@Mock
|
||||
private AttractionSetItemRepository itemRepository;
|
||||
@Mock
|
||||
private S3Storage s3Storage;
|
||||
@Mock
|
||||
private OpenCvClient openCvClient;
|
||||
@Mock
|
||||
private PhotoMapper photoMapper;
|
||||
|
||||
@InjectMocks
|
||||
private ReferencePhotoService service;
|
||||
|
||||
@Test
|
||||
void deleteRemovesRowAndBothS3Objects() {
|
||||
AttractionPhoto photo = photo();
|
||||
when(attractionService.getAttraction(attractionId)).thenReturn(new Attraction());
|
||||
when(photoRepository.findByIdAndAttractionId(photoId, attractionId)).thenReturn(Optional.of(photo));
|
||||
when(itemRepository.existsByAttractionIdAndSet_Status(attractionId, SetStatus.ACTIVE)).thenReturn(true);
|
||||
when(photoRepository.countByAttractionId(attractionId)).thenReturn(2L);
|
||||
|
||||
service.delete(attractionId, photoId);
|
||||
|
||||
verify(photoRepository).delete(photo);
|
||||
verify(s3Storage).delete(photo.getS3PhotoKey());
|
||||
verify(s3Storage).delete(photo.getS3FeaturesKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lastPhotoOfActiveSetAttractionRejected() {
|
||||
when(attractionService.getAttraction(attractionId)).thenReturn(new Attraction());
|
||||
when(photoRepository.findByIdAndAttractionId(photoId, attractionId))
|
||||
.thenReturn(Optional.of(photo()));
|
||||
when(itemRepository.existsByAttractionIdAndSet_Status(attractionId, SetStatus.ACTIVE)).thenReturn(true);
|
||||
when(photoRepository.countByAttractionId(attractionId)).thenReturn(1L);
|
||||
|
||||
ApiException error = assertThrows(ApiException.class, () -> service.delete(attractionId, photoId));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.LAST_REFERENCE_PHOTO);
|
||||
verify(photoRepository, never()).delete(any(AttractionPhoto.class));
|
||||
verify(s3Storage, never()).delete(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lastPhotoAllowedWhenAttractionNotInActiveSet() {
|
||||
when(attractionService.getAttraction(attractionId)).thenReturn(new Attraction());
|
||||
AttractionPhoto photo = photo();
|
||||
when(photoRepository.findByIdAndAttractionId(photoId, attractionId)).thenReturn(Optional.of(photo));
|
||||
when(itemRepository.existsByAttractionIdAndSet_Status(attractionId, SetStatus.ACTIVE)).thenReturn(false);
|
||||
when(photoRepository.countByAttractionId(attractionId)).thenReturn(1L);
|
||||
|
||||
service.delete(attractionId, photoId);
|
||||
|
||||
verify(photoRepository).delete(photo);
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3FailureDoesNotBreakDeletion() {
|
||||
AttractionPhoto photo = photo();
|
||||
when(attractionService.getAttraction(attractionId)).thenReturn(new Attraction());
|
||||
when(photoRepository.findByIdAndAttractionId(photoId, attractionId)).thenReturn(Optional.of(photo));
|
||||
when(itemRepository.existsByAttractionIdAndSet_Status(attractionId, SetStatus.ACTIVE)).thenReturn(true);
|
||||
when(photoRepository.countByAttractionId(attractionId)).thenReturn(2L);
|
||||
doThrow(new ApiException(ErrorCode.S3_UNAVAILABLE)).when(s3Storage).delete(any());
|
||||
|
||||
service.delete(attractionId, photoId);
|
||||
|
||||
verify(photoRepository).delete(photo);
|
||||
}
|
||||
|
||||
private AttractionPhoto photo() {
|
||||
AttractionPhoto photo = new AttractionPhoto();
|
||||
photo.setId(photoId);
|
||||
photo.setS3PhotoKey("attractions/%s/reference/%s.jpg".formatted(attractionId, photoId));
|
||||
photo.setS3FeaturesKey("attractions/%s/reference/%s.npz".formatted(attractionId, photoId));
|
||||
return photo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package ru.gorodar.service;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import ru.gorodar.dao.entity.SetStatus;
|
||||
import ru.gorodar.dao.entity.VerifyVerdict;
|
||||
import ru.gorodar.dao.entity.AttractionPhoto;
|
||||
import ru.gorodar.dao.entity.AttractionUserVisit;
|
||||
import ru.gorodar.api.dto.VisitDtos.VisitSubmitResponse;
|
||||
import ru.gorodar.exception.ApiException;
|
||||
import ru.gorodar.exception.ErrorCode;
|
||||
import ru.gorodar.integration.opencv.OpenCvClient;
|
||||
import ru.gorodar.integration.opencv.VerifyResult;
|
||||
import ru.gorodar.integration.s3.S3Storage;
|
||||
import ru.gorodar.dao.AttractionPhotoRepository;
|
||||
import ru.gorodar.dao.AttractionRepository;
|
||||
import ru.gorodar.dao.AttractionSetItemRepository;
|
||||
import ru.gorodar.dao.AttractionSetRepository;
|
||||
import ru.gorodar.dao.AttractionUserVisitRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class VisitServiceTest {
|
||||
|
||||
private static <T> org.springframework.data.jpa.domain.Specification<T> anySpec() {
|
||||
return ArgumentMatchers.any();
|
||||
}
|
||||
|
||||
private static final String USER_ID = "sub-1";
|
||||
private static final byte[] PHOTO = new byte[]{1, 2, 3};
|
||||
private static final byte[] FEATURES = new byte[]{9, 8, 7};
|
||||
|
||||
private final UUID attractionId = UUID.randomUUID();
|
||||
private final UUID areaId = UUID.randomUUID();
|
||||
|
||||
@Mock
|
||||
private AttractionRepository attractionRepository;
|
||||
@Mock
|
||||
private AttractionPhotoRepository photoRepository;
|
||||
@Mock
|
||||
private AttractionSetRepository setRepository;
|
||||
@Mock
|
||||
private AttractionSetItemRepository itemRepository;
|
||||
@Mock
|
||||
private AttractionUserVisitRepository visitRepository;
|
||||
@Mock
|
||||
private S3Storage s3Storage;
|
||||
@Mock
|
||||
private OpenCvClient openCvClient;
|
||||
|
||||
@InjectMocks
|
||||
private VisitService visitService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(attractionRepository.findById(attractionId))
|
||||
.thenReturn(Optional.of(EntityTestHelper.attractionOf(attractionId, areaId)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchFixesVisitAndReturnsProgress() {
|
||||
visitAllowed();
|
||||
referencePhotoAvailable();
|
||||
when(openCvClient.verify(PHOTO, List.of(FEATURES)))
|
||||
.thenReturn(VerifyResult.builder().verdict(VerifyVerdict.MATCH).match(true)
|
||||
.confidence(0.87f).probeSha256("sha-256").build());
|
||||
when(setRepository.findByAreaIdAndStatus(areaId, SetStatus.ACTIVE))
|
||||
.thenReturn(Optional.of(EntityTestHelper.setOf(UUID.randomUUID(), areaId, SetStatus.ACTIVE)));
|
||||
when(itemRepository.findAll(anySpec())).thenReturn(List.of(EntityTestHelper.itemOf(attractionId, areaId)));
|
||||
when(visitRepository.countByUserIdAndAttractionIdIn(USER_ID, List.of(attractionId))).thenReturn(1L);
|
||||
|
||||
VisitSubmitResponse response = visitService.submit(USER_ID, attractionId, PHOTO);
|
||||
|
||||
assertThat(response.status()).isEqualTo("VISITED");
|
||||
assertThat(response.confidence()).isEqualTo(0.87f);
|
||||
assertThat(response.progress().visited()).isEqualTo(1);
|
||||
assertThat(response.progress().total()).isEqualTo(1);
|
||||
verify(visitRepository).saveAndFlush(any(AttractionUserVisit.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingVisitShortCircuitsWithoutCallingOpenCv() {
|
||||
visitAllowed();
|
||||
when(visitRepository.existsByUserIdAndAttractionId(USER_ID, attractionId)).thenReturn(true);
|
||||
when(setRepository.findByAreaIdAndStatus(areaId, SetStatus.ACTIVE))
|
||||
.thenReturn(Optional.of(EntityTestHelper.setOf(UUID.randomUUID(), areaId, SetStatus.ACTIVE)));
|
||||
when(itemRepository.findAll(anySpec())).thenReturn(List.of(EntityTestHelper.itemOf(attractionId, areaId)));
|
||||
when(visitRepository.countByUserIdAndAttractionIdIn(USER_ID, List.of(attractionId))).thenReturn(1L);
|
||||
|
||||
VisitSubmitResponse response = visitService.submit(USER_ID, attractionId, PHOTO);
|
||||
|
||||
assertThat(response.status()).isEqualTo("ALREADY_VISITED");
|
||||
verify(openCvClient, never()).verify(any(), anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void attractionOutsideActiveSetRejected() {
|
||||
when(itemRepository.existsByAttractionIdAndSet_Status(attractionId, SetStatus.ACTIVE)).thenReturn(false);
|
||||
|
||||
ApiException error = assertThrows(ApiException.class,
|
||||
() -> visitService.submit(USER_ID, attractionId, PHOTO));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.ATTRACTION_NOT_IN_ACTIVE_SET);
|
||||
verify(openCvClient, never()).verify(any(), anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void uncertainVerdictDoesNotFixVisit() {
|
||||
visitAllowed();
|
||||
referencePhotoAvailable();
|
||||
when(openCvClient.verify(PHOTO, List.of(FEATURES)))
|
||||
.thenReturn(VerifyResult.builder().verdict(VerifyVerdict.UNCERTAIN).match(false)
|
||||
.confidence(0.35f).probeSha256("sha-256").build());
|
||||
when(setRepository.findByAreaIdAndStatus(areaId, SetStatus.ACTIVE))
|
||||
.thenReturn(Optional.of(EntityTestHelper.setOf(UUID.randomUUID(), areaId, SetStatus.ACTIVE)));
|
||||
when(itemRepository.findAll(anySpec())).thenReturn(List.of(EntityTestHelper.itemOf(attractionId, areaId)));
|
||||
when(visitRepository.countByUserIdAndAttractionIdIn(USER_ID, List.of(attractionId))).thenReturn(0L);
|
||||
|
||||
VisitSubmitResponse response = visitService.submit(USER_ID, attractionId, PHOTO);
|
||||
|
||||
assertThat(response.status()).isEqualTo("UNCERTAIN");
|
||||
verify(visitRepository, never()).saveAndFlush(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noMatchVerdictDoesNotFixVisit() {
|
||||
visitAllowed();
|
||||
referencePhotoAvailable();
|
||||
when(openCvClient.verify(PHOTO, List.of(FEATURES)))
|
||||
.thenReturn(VerifyResult.builder().verdict(VerifyVerdict.NO_MATCH).match(false)
|
||||
.confidence(0.05f).probeSha256("sha-256").build());
|
||||
when(setRepository.findByAreaIdAndStatus(areaId, SetStatus.ACTIVE))
|
||||
.thenReturn(Optional.of(EntityTestHelper.setOf(UUID.randomUUID(), areaId, SetStatus.ACTIVE)));
|
||||
when(itemRepository.findAll(anySpec())).thenReturn(List.of(EntityTestHelper.itemOf(attractionId, areaId)));
|
||||
when(visitRepository.countByUserIdAndAttractionIdIn(USER_ID, List.of(attractionId))).thenReturn(0L);
|
||||
|
||||
VisitSubmitResponse response = visitService.submit(USER_ID, attractionId, PHOTO);
|
||||
|
||||
assertThat(response.status()).isEqualTo("NOT_MATCHED");
|
||||
verify(visitRepository, never()).saveAndFlush(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingReferencePhotoRejected() {
|
||||
when(itemRepository.existsByAttractionIdAndSet_Status(attractionId, SetStatus.ACTIVE)).thenReturn(true);
|
||||
when(visitRepository.existsByUserIdAndAttractionId(USER_ID, attractionId)).thenReturn(false);
|
||||
when(photoRepository.findFirstByAttractionIdOrderBySortOrderAsc(attractionId))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
ApiException error = assertThrows(ApiException.class,
|
||||
() -> visitService.submit(USER_ID, attractionId, PHOTO));
|
||||
|
||||
assertThat(error.getCode()).isEqualTo(ErrorCode.NO_REFERENCE_PHOTO);
|
||||
}
|
||||
|
||||
private void visitAllowed() {
|
||||
when(itemRepository.existsByAttractionIdAndSet_Status(attractionId, SetStatus.ACTIVE)).thenReturn(true);
|
||||
when(visitRepository.existsByUserIdAndAttractionId(USER_ID, attractionId)).thenReturn(false);
|
||||
}
|
||||
|
||||
private void referencePhotoAvailable() {
|
||||
AttractionPhoto photo = new AttractionPhoto();
|
||||
photo.setS3PhotoKey("attractions/%s/reference/%s.jpg".formatted(attractionId, UUID.randomUUID()));
|
||||
photo.setS3FeaturesKey("attractions/%s/reference/%s.npz".formatted(attractionId, UUID.randomUUID()));
|
||||
when(photoRepository.findFirstByAttractionIdOrderBySortOrderAsc(attractionId))
|
||||
.thenReturn(Optional.of(photo));
|
||||
when(s3Storage.get(photo.getS3FeaturesKey())).thenReturn(FEATURES);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user