Compare commits
2
Commits
cbe752ad63
...
b8e7e3d2b9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8e7e3d2b9 | ||
|
|
1148e1c5cf |
@@ -24,7 +24,7 @@ Stateless CV-сервис (эволюция open_cv, тот же OpenAPI-кон
|
|||||||
probe_sha256 в БД), `confidence ≤ no-match-threshold` → no_match, между — uncertain;
|
probe_sha256 в БД), `confidence ≤ no-match-threshold` → no_match, между — uncertain;
|
||||||
uncertain/no_match → не фиксировать (UNCERTAIN/NOT_MATCHED клиенту). Модерации
|
uncertain/no_match → не фиксировать (UNCERTAIN/NOT_MATCHED клиенту). Модерации
|
||||||
uncertain нет.
|
uncertain нет.
|
||||||
- Границы: `gorodar.dinov2.match-threshold` (0.75) / `no-match-threshold` (0.55);
|
- Границы: `gorodar.dinov2.match-threshold` (0.55) / `no-match-threshold` (0.45);
|
||||||
переопределение на достопримечательность — `attractions.match_threshold` /
|
переопределение на достопримечательность — `attractions.match_threshold` /
|
||||||
`no_match_threshold` (NULL = глобальные; PUT `/api/admin/attractions/{id}/match-thresholds`,
|
`no_match_threshold` (NULL = глобальные; PUT `/api/admin/attractions/{id}/match-thresholds`,
|
||||||
null в теле = сброс к глобальным).
|
null в теле = сброс к глобальным).
|
||||||
|
|||||||
+3
-1
@@ -29,12 +29,14 @@ GORODAR_AUTH_ISSUER=
|
|||||||
GORODAR_AUTH_KEYS_DIR=
|
GORODAR_AUTH_KEYS_DIR=
|
||||||
GORODAR_AUTH_MAIL_LOG_ONLY=
|
GORODAR_AUTH_MAIL_LOG_ONLY=
|
||||||
|
|
||||||
# Отправка кодов подтверждения через Unisender Go (transactional API).
|
# Отправка кодов подтверждения через Unisender Go (transactional API):
|
||||||
|
# письмо рендерится по шаблону из ЛК Unisender, код уходит подстановкой "code".
|
||||||
# Пустой GORODAR_UNISENDER_API_KEY — код пишется в лог вместо отправки.
|
# Пустой GORODAR_UNISENDER_API_KEY — код пишется в лог вместо отправки.
|
||||||
GORODAR_UNISENDER_URL=
|
GORODAR_UNISENDER_URL=
|
||||||
GORODAR_UNISENDER_API_KEY=
|
GORODAR_UNISENDER_API_KEY=
|
||||||
GORODAR_UNISENDER_FROM_EMAIL=
|
GORODAR_UNISENDER_FROM_EMAIL=
|
||||||
GORODAR_UNISENDER_FROM_NAME=
|
GORODAR_UNISENDER_FROM_NAME=
|
||||||
|
GORODAR_UNISENDER_TEMPLATE_ID=
|
||||||
|
|
||||||
# Сервис распознавания dinoV2
|
# Сервис распознавания dinoV2
|
||||||
GORODAR_DINOV2_URL=
|
GORODAR_DINOV2_URL=
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ services:
|
|||||||
GORODAR_UNISENDER_API_KEY: ${GORODAR_UNISENDER_API_KEY:-}
|
GORODAR_UNISENDER_API_KEY: ${GORODAR_UNISENDER_API_KEY:-}
|
||||||
GORODAR_UNISENDER_FROM_EMAIL: ${GORODAR_UNISENDER_FROM_EMAIL:-}
|
GORODAR_UNISENDER_FROM_EMAIL: ${GORODAR_UNISENDER_FROM_EMAIL:-}
|
||||||
GORODAR_UNISENDER_FROM_NAME: ${GORODAR_UNISENDER_FROM_NAME:-Городар}
|
GORODAR_UNISENDER_FROM_NAME: ${GORODAR_UNISENDER_FROM_NAME:-Городар}
|
||||||
|
GORODAR_UNISENDER_TEMPLATE_ID: ${GORODAR_UNISENDER_TEMPLATE_ID:-b56a2912-c488-11f1-9ec1-faf9f44db93c}
|
||||||
GORODAR_DINOV2_URL: ${GORODAR_DINOV2_URL:-http://localhost:8011}
|
GORODAR_DINOV2_URL: ${GORODAR_DINOV2_URL:-http://localhost:8011}
|
||||||
GORODAR_DINOV2_API_KEY: ${GORODAR_DINOV2_API_KEY:-dev-key}
|
GORODAR_DINOV2_API_KEY: ${GORODAR_DINOV2_API_KEY:-dev-key}
|
||||||
GORODAR_DINOV2_MATCH_THRESHOLD: ${GORODAR_DINOV2_MATCH_THRESHOLD:-0.75}
|
GORODAR_DINOV2_MATCH_THRESHOLD: ${GORODAR_DINOV2_MATCH_THRESHOLD:-0.75}
|
||||||
|
|||||||
+11
-6
@@ -22,7 +22,7 @@
|
|||||||
| 0.15 | Удаление неактивного набора: `DELETE /api/admin/sets/{id}` (DRAFT/ARCHIVED, каскадно с составом; ACTIVE → 409 `SET_STATE_CONFLICT`) — исключение из I5. Админское чтение состава набора: `GET /api/admin/sets/{id}/items` (id, name, iconUrl — presigned), сортировка по названию |
|
| 0.15 | Удаление неактивного набора: `DELETE /api/admin/sets/{id}` (DRAFT/ARCHIVED, каскадно с составом; ACTIVE → 409 `SET_STATE_CONFLICT`) — исключение из I5. Админское чтение состава набора: `GET /api/admin/sets/{id}/items` (id, name, iconUrl — presigned), сортировка по названию |
|
||||||
| 0.16 | Каскадное удаление зоны (FR-M1): `DELETE /api/admin/areas/{id}` — всё поддерево зон; достопримечательности (строки БД + файлы S3: эталонные фото с `.npz`, иконки, медиа ачивок), наборы с составами, посещения пользователей; файлы S3 — best-effort после строк БД |
|
| 0.16 | Каскадное удаление зоны (FR-M1): `DELETE /api/admin/areas/{id}` — всё поддерево зон; достопримечательности (строки БД + файлы S3: эталонные фото с `.npz`, иконки, медиа ачивок), наборы с составами, посещения пользователей; файлы S3 — best-effort после строк БД |
|
||||||
| 0.17 | Распознавание переведено на сервис dinoV2: эталонные фото больше не предобрабатываются (`.npz`-блобы, `/features`, FR-M7 и `cv_profile` удалены), `/verify` получает probe + все эталонные фото как images (1…32); админская проверка — по всей коллекции фото: `POST /api/admin/attractions/{id}/photos/verify` |
|
| 0.17 | Распознавание переведено на сервис dinoV2: эталонные фото больше не предобрабатываются (`.npz`-блобы, `/features`, FR-M7 и `cv_profile` удалены), `/verify` получает probe + все эталонные фото как images (1…32); админская проверка — по всей коллекции фото: `POST /api/admin/attractions/{id}/photos/verify` |
|
||||||
| 0.18 | Вердикт вычисляется нашим сервисом по confidence dino против границ `gorodar.dinov2.match-threshold`/`no-match-threshold` (0.75/0.55, переопределяются на достопримечательность — `PUT /api/admin/attractions/{id}/match-thresholds`, FR-M11); лимит эталонных фото — 15 (16-я загрузка → 409 `REFERENCE_PHOTO_LIMIT_EXCEEDED`); админская проверка итеративна — по одному эталону за вызов dino с процентами по каждому (`references[]`) |
|
| 0.18 | Вердикт вычисляется нашим сервисом по confidence dino против границ `gorodar.dinov2.match-threshold`/`no-match-threshold` (0.55/0.45, переопределяются на достопримечательность — `PUT /api/admin/attractions/{id}/match-thresholds`, FR-M11, любые значения 0…1); лимит эталонных фото — 15 (16-я загрузка → 409 `REFERENCE_PHOTO_LIMIT_EXCEEDED`); админская проверка итеративна — по одному эталону за вызов dino с процентами по каждому (`references[]`); сортировка зон публичного каталога — сначала с достопримечательностями, затем по алфавиту (FR-U1); код подтверждения отправляется по шаблону Unisender (`template-id` + подстановка `code`, §7.1) |
|
||||||
|
|
||||||
## 1. Назначение документа
|
## 1. Назначение документа
|
||||||
|
|
||||||
@@ -108,6 +108,8 @@
|
|||||||
### 4.2 Пользовательская часть
|
### 4.2 Пользовательская часть
|
||||||
|
|
||||||
- **FR-U1.** Просмотр дерева зон — публично. Зона = название + вложенность (типа зоны нет).
|
- **FR-U1.** Просмотр дерева зон — публично. Зона = название + вложенность (типа зоны нет).
|
||||||
|
Порядок выдачи: сначала зоны, у которых есть достопримечательности (привязанные
|
||||||
|
напрямую), затем — по алфавиту.
|
||||||
- **FR-U2.** Просмотр активного набора зоны: список достопримечательностей с признаком
|
- **FR-U2.** Просмотр активного набора зоны: список достопримечательностей с признаком
|
||||||
«посещено текущим пользователем» (для анонима признак опускается/`false`).
|
«посещено текущим пользователем» (для анонима признак опускается/`false`).
|
||||||
- **FR-U3.** Просмотр карточки достопримечательности — публично. Состав карточки:
|
- **FR-U3.** Просмотр карточки достопримечательности — публично. Состав карточки:
|
||||||
@@ -172,8 +174,8 @@
|
|||||||
- **FR-M11.** *(0.18)* Границы вердикта задаёт наш сервис по confidence dino (вердикт
|
- **FR-M11.** *(0.18)* Границы вердикта задаёт наш сервис по confidence dino (вердикт
|
||||||
и `is_match` самого dino игнорируются): `confidence ≥ match-threshold` → `match`,
|
и `is_match` самого dino игнорируются): `confidence ≥ match-threshold` → `match`,
|
||||||
`confidence ≤ no-match-threshold` → `no_match`, между — `uncertain`. Значения по
|
`confidence ≤ no-match-threshold` → `no_match`, между — `uncertain`. Значения по
|
||||||
умолчанию — уровень приложения (`gorodar.dinov2.match-threshold` 0.75 /
|
умолчанию — уровень приложения (`gorodar.dinov2.match-threshold` 0.55 /
|
||||||
`no-match-threshold` 0.55, env-переменные, диапазон 0…1); для конкретной
|
`no-match-threshold` 0.45, env-переменные, диапазон 0…1); для конкретной
|
||||||
достопримечательности — переопределение колонками `match_threshold`/`no_match_threshold`
|
достопримечательности — переопределение колонками `match_threshold`/`no_match_threshold`
|
||||||
(NULL = глобальные; допустимы любые значения 0…1 — порядок порогов не ограничен,
|
(NULL = глобальные; допустимы любые значения 0…1 — порядок порогов не ограничен,
|
||||||
при `match ≤ no_match` зона `uncertain` исчезает). Управление —
|
при `match ≤ no_match` зона `uncertain` исчезает). Управление —
|
||||||
@@ -341,7 +343,10 @@ DRAFT ──activate──► ACTIVE ──archive──► ARCHIVED
|
|||||||
**Флоу входа.** `POST /oauth2/authorize {email}` (JSON) — пользователь создаётся при
|
**Флоу входа.** `POST /oauth2/authorize {email}` (JSON) — пользователь создаётся при
|
||||||
первом обращении; 6-значный код хэшируется SHA-256 и ложится в `auth_codes`
|
первом обращении; 6-значный код хэшируется SHA-256 и ложится в `auth_codes`
|
||||||
(TTL 10 мин, повторная отправка ≥ 60 с, максимум 5 попыток). Отправка кода — Unisender
|
(TTL 10 мин, повторная отправка ≥ 60 с, максимум 5 попыток). Отправка кода — Unisender
|
||||||
Go API `email/send.json` (`gorodar.unisender.*`); без API-ключа или при
|
Go API `email/send.json` (`gorodar.unisender.*`): письмо рендерится по шаблону из ЛК
|
||||||
|
Unisender (`gorodar.unisender.template-id`, подстановка `code`; `template_engine: simple`,
|
||||||
|
`global_language: ru`, `bypass_global`/`bypass_unavailable`), авторизация — заголовок
|
||||||
|
`X-API-KEY`. Без API-ключа или при
|
||||||
`gorodar.auth.mail-log-only=true` — код пишется в лог. `POST /oauth2/token` (form-urlencoded, RFC 6749):
|
`gorodar.auth.mail-log-only=true` — код пишется в лог. `POST /oauth2/token` (form-urlencoded, RFC 6749):
|
||||||
grant `urn:gorodar:params:oauth:grant-type:email-code` (`email`+`code`) или
|
grant `urn:gorodar:params:oauth:grant-type:email-code` (`email`+`code`) или
|
||||||
`refresh_token` (ротация: старый отзывается, выдаётся новая пара). Успех —
|
`refresh_token` (ротация: старый отзывается, выдаётся новая пара). Успех —
|
||||||
@@ -452,8 +457,8 @@ AWS SDK v2 (`software.amazon.awssdk:s3`), совместимые реализа
|
|||||||
|
|
||||||
| Метод и путь | Доступ | Назначение |
|
| Метод и путь | Доступ | Назначение |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `GET /api/areas` | публично | Список корневых зон; `?parent-id={id}` — дети. Каждая зона — с `attractions` (активный набор: id, name, iconUrl, visited) и `progress {visited, total}`; анониму — visited=false везде, прогресс 0 |
|
| `GET /api/areas` | публично | Список корневых зон; `?parent-id={id}` — дети. Каждая зона — с `attractions` (активный набор: id, name, iconUrl, visited) и `progress {visited, total}`; анониму — visited=false везде, прогресс 0. Порядок: сначала зоны с достопримечательностями, затем по алфавиту (параметр sort игнорируется) |
|
||||||
| `GET /api/areas/{id}` | публично | Зона + дочерние зоны (дети — с тем же обогащением) + собственные `attractions`/`progress` |
|
| `GET /api/areas/{id}` | публично | Зона + дочерние зоны (дети — с тем же обогащением и порядком: сначала с достопримечательностями, затем по алфавиту) + собственные `attractions`/`progress` |
|
||||||
| `GET /api/areas/{id}/active-set` | публично | Активный набор зоны с достопримечательностями; с токеном — флаги `visited` (404 `NO_ACTIVE_SET`, если нет) |
|
| `GET /api/areas/{id}/active-set` | публично | Активный набор зоны с достопримечательностями; с токеном — флаги `visited` (404 `NO_ACTIVE_SET`, если нет) |
|
||||||
| `GET /api/attractions/{id}` | публично | Карточка достопримечательности |
|
| `GET /api/attractions/{id}` | публично | Карточка достопримечательности |
|
||||||
| `POST /api/attractions/{id}/visits` | user | **Ключевой эндпоинт**: multipart `photo` → `/verify` → отметка посещения |
|
| `POST /api/attractions/{id}/visits` | user | **Ключевой эндпоинт**: multipart `photo` → `/verify` → отметка посещения |
|
||||||
|
|||||||
@@ -29,8 +29,8 @@ public class PublicAreaController {
|
|||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public Page<AreaResponse> list(@RequestParam(name = "parent-id", required = false) UUID parentId,
|
public Page<AreaResponse> list(@RequestParam(name = "parent-id", required = false) UUID parentId,
|
||||||
@PageableDefault(size = 20, sort = "name") Pageable pageable) {
|
@PageableDefault(size = 20) Pageable pageable) {
|
||||||
return areaService.list(parentId, pageable);
|
return areaService.listPublic(parentId, pageable);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{id}")
|
@GetMapping("/{id}")
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import ru.gorodar.config.AuthProperties;
|
|||||||
import ru.gorodar.config.UnisenderProperties;
|
import ru.gorodar.config.UnisenderProperties;
|
||||||
import ru.gorodar.integration.unisender.UnisenderClient;
|
import ru.gorodar.integration.unisender.UnisenderClient;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Отправка кода подтверждения через Unisender. Без API-ключа переходит в log-only режим —
|
* Отправка кода подтверждения через Unisender. Без API-ключа переходит в log-only режим —
|
||||||
* код пишется в лог, чтобы dev/docker поднимались без почты.
|
* код пишется в лог, чтобы dev/docker поднимались без почты.
|
||||||
@@ -27,7 +29,6 @@ public class MailCodeSender {
|
|||||||
log.warn("Unisender не настроен (log-only): код подтверждения для {} = {}", email, code);
|
log.warn("Unisender не настроен (log-only): код подтверждения для {} = {}", email, code);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
unisenderClient.sendEmail(email, "Городар: код подтверждения",
|
unisenderClient.sendEmail(email, "Городар — код подтверждения", Map.of("code", code));
|
||||||
"Ваш код подтверждения: %s\nКод действителен 10 минут.".formatted(code));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,10 +11,10 @@ public record DinoV2Properties(String baseUrl, String apiKey,
|
|||||||
|
|
||||||
public DinoV2Properties {
|
public DinoV2Properties {
|
||||||
if (matchThreshold == null) {
|
if (matchThreshold == null) {
|
||||||
matchThreshold = new BigDecimal("0.75");
|
matchThreshold = new BigDecimal("0.55");
|
||||||
}
|
}
|
||||||
if (noMatchThreshold == null) {
|
if (noMatchThreshold == null) {
|
||||||
noMatchThreshold = new BigDecimal("0.55");
|
noMatchThreshold = new BigDecimal("0.45");
|
||||||
}
|
}
|
||||||
if (maxReferencePhotos == null) {
|
if (maxReferencePhotos == null) {
|
||||||
maxReferencePhotos = 15;
|
maxReferencePhotos = 15;
|
||||||
|
|||||||
@@ -3,5 +3,6 @@ package ru.gorodar.config;
|
|||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
@ConfigurationProperties(prefix = "gorodar.unisender")
|
@ConfigurationProperties(prefix = "gorodar.unisender")
|
||||||
public record UnisenderProperties(String baseUrl, String apiKey, String fromEmail, String fromName) {
|
public record UnisenderProperties(String baseUrl, String apiKey, String fromEmail, String fromName,
|
||||||
|
String templateId) {
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import ru.gorodar.dao.entity.Area;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
public interface AreaRepository extends JpaRepository<Area, UUID> {
|
public interface AreaRepository extends JpaRepository<Area, UUID>, AreaRepositoryCustom {
|
||||||
|
|
||||||
Page<Area> findByParentIsNull(Pageable pageable);
|
Page<Area> findByParentIsNull(Pageable pageable);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package ru.gorodar.dao;
|
||||||
|
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import ru.gorodar.dao.entity.Area;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface AreaRepositoryCustom {
|
||||||
|
|
||||||
|
/** Публичный каталог: сначала зоны с достопримечательностями, затем по алфавиту. */
|
||||||
|
Page<Area> findPageByAttractionsFirstThenName(UUID parentId, Pageable pageable);
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package ru.gorodar.dao;
|
||||||
|
|
||||||
|
import jakarta.persistence.EntityManager;
|
||||||
|
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||||
|
import jakarta.persistence.criteria.CriteriaQuery;
|
||||||
|
import jakarta.persistence.criteria.Expression;
|
||||||
|
import jakarta.persistence.criteria.Predicate;
|
||||||
|
import jakarta.persistence.criteria.Root;
|
||||||
|
import jakarta.persistence.criteria.Subquery;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageImpl;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import ru.gorodar.dao.entity.Area;
|
||||||
|
import ru.gorodar.dao.entity.Area_;
|
||||||
|
import ru.gorodar.dao.entity.Attraction;
|
||||||
|
import ru.gorodar.dao.entity.Attraction_;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Фрагмент AreaRepository для порядка публичного каталога: ORDER BY с коррелированным
|
||||||
|
* подзапросом невыразим через Specification (Sort принимает только пути атрибутов),
|
||||||
|
* поэтому Criteria-запрос руками — с метамоделью, без @Query. Порядок считает БД:
|
||||||
|
* сначала зоны с достопримечательностями, затем по алфавиту.
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public class AreaRepositoryCustomImpl implements AreaRepositoryCustom {
|
||||||
|
|
||||||
|
private final EntityManager entityManager;
|
||||||
|
|
||||||
|
public AreaRepositoryCustomImpl(EntityManager entityManager) {
|
||||||
|
this.entityManager = entityManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Page<Area> findPageByAttractionsFirstThenName(UUID parentId, Pageable pageable) {
|
||||||
|
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||||
|
|
||||||
|
CriteriaQuery<Area> query = cb.createQuery(Area.class);
|
||||||
|
Root<Area> root = query.from(Area.class);
|
||||||
|
query.select(root)
|
||||||
|
.where(levelPredicate(cb, root, parentId))
|
||||||
|
.orderBy(
|
||||||
|
cb.asc(attractionsRank(cb, query, root)),
|
||||||
|
cb.asc(root.get(Area_.name)));
|
||||||
|
|
||||||
|
if (pageable.isUnpaged()) {
|
||||||
|
return new PageImpl<>(entityManager.createQuery(query).getResultList());
|
||||||
|
}
|
||||||
|
|
||||||
|
CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
|
||||||
|
Root<Area> countRoot = countQuery.from(Area.class);
|
||||||
|
countQuery.select(cb.count(countRoot))
|
||||||
|
.where(levelPredicate(cb, countRoot, parentId));
|
||||||
|
|
||||||
|
List<Area> content = entityManager.createQuery(query)
|
||||||
|
.setFirstResult((int) pageable.getOffset())
|
||||||
|
.setMaxResults(pageable.getPageSize())
|
||||||
|
.getResultList();
|
||||||
|
long total = entityManager.createQuery(countQuery).getSingleResult();
|
||||||
|
return new PageImpl<>(content, pageable, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate levelPredicate(CriteriaBuilder cb, Root<Area> root, UUID parentId) {
|
||||||
|
return parentId == null
|
||||||
|
? cb.isNull(root.get(Area_.parent))
|
||||||
|
: cb.equal(root.get(Area_.parent).get(Area_.id), parentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 0, если у зоны есть привязанные достопримечательности, иначе 1 — по возрастанию
|
||||||
|
* зоны с достопримечательностями оказываются первыми, алфавит добирает второй ORDER BY. */
|
||||||
|
private Expression<Integer> attractionsRank(CriteriaBuilder cb, CriteriaQuery<?> query, Root<Area> area) {
|
||||||
|
Subquery<Long> attractionCount = query.subquery(Long.class);
|
||||||
|
Root<Attraction> attraction = attractionCount.from(Attraction.class);
|
||||||
|
attractionCount.select(cb.count(attraction.get(Attraction_.id)))
|
||||||
|
.where(cb.equal(attraction.get(Attraction_.area).get(Area_.id), area.get(Area_.id)));
|
||||||
|
return cb.<Integer>selectCase()
|
||||||
|
.when(cb.greaterThan(attractionCount, 0L), 0)
|
||||||
|
.otherwise(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,13 +21,16 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Клиент Unisender Go (transactional API): отправка письма методом email/send.json.
|
* Клиент Unisender Go (transactional API): отправка письма по шаблону
|
||||||
|
* (email/send.json, template_id + подстановки).
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
public class UnisenderClient {
|
public class UnisenderClient {
|
||||||
|
|
||||||
private static final String SEND_PATH = "/ru/transactional/api/v1/email/send.json";
|
private static final String SEND_PATH = "/ru/transactional/api/v1/email/send.json";
|
||||||
|
private static final String GLOBAL_LANGUAGE = "ru";
|
||||||
|
private static final String TEMPLATE_ENGINE = "simple";
|
||||||
|
|
||||||
private final RestClient restClient;
|
private final RestClient restClient;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
@@ -42,13 +45,15 @@ public class UnisenderClient {
|
|||||||
this.properties = properties;
|
this.properties = properties;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void sendEmail(String to, String subject, String plaintext) {
|
public void sendEmail(String to, String subject, Map<String, String> substitutions) {
|
||||||
SendRequest request = new SendRequest(SendRequest.Message.builder()
|
SendRequest request = new SendRequest(SendRequest.Message.builder()
|
||||||
.recipients(List.of(new SendRequest.Recipient(to)))
|
.recipients(List.of(new SendRequest.Recipient(to, substitutions)))
|
||||||
.body(new SendRequest.Body(plaintext))
|
.templateId(properties.templateId())
|
||||||
.subject(subject)
|
.subject(subject)
|
||||||
.fromEmail(properties.fromEmail())
|
.fromEmail(properties.fromEmail())
|
||||||
.fromName(properties.fromName())
|
.fromName(properties.fromName())
|
||||||
|
.globalLanguage(GLOBAL_LANGUAGE)
|
||||||
|
.templateEngine(TEMPLATE_ENGINE)
|
||||||
.bypassGlobal(1)
|
.bypassGlobal(1)
|
||||||
.bypassUnavailable(1)
|
.bypassUnavailable(1)
|
||||||
.build());
|
.build());
|
||||||
@@ -102,13 +107,12 @@ public class UnisenderClient {
|
|||||||
|
|
||||||
@Builder
|
@Builder
|
||||||
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
|
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
|
||||||
record Message(List<Recipient> recipients, Body body, String subject, String fromEmail, String fromName, int bypassGlobal, int bypassUnavailable) {
|
record Message(List<Recipient> recipients, String templateId, String subject,
|
||||||
|
String fromEmail, String fromName, String globalLanguage, String templateEngine,
|
||||||
|
int bypassGlobal, int bypassUnavailable) {
|
||||||
}
|
}
|
||||||
|
|
||||||
record Recipient(String email) {
|
record Recipient(String email, Map<String, String> substitutions) {
|
||||||
}
|
|
||||||
|
|
||||||
record Body(String plaintext) {
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -66,9 +66,20 @@ public class AreaService {
|
|||||||
return result.map(this::toOverview);
|
return result.map(this::toOverview);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Публичный каталог: сначала зоны с достопримечательностями, затем по алфавиту.
|
||||||
|
* Порядок и пагинация — на стороне БД (AreaRepositoryCustomImpl, Criteria с CASE
|
||||||
|
* над подзапросом счёта достопримечательностей).
|
||||||
|
*/
|
||||||
|
public Page<AreaResponse> listPublic(UUID parentId, Pageable pageable) {
|
||||||
|
return areaRepository.findPageByAttractionsFirstThenName(parentId, pageable)
|
||||||
|
.map(this::toOverview);
|
||||||
|
}
|
||||||
|
|
||||||
public AreaWithChildrenResponse get(UUID id) {
|
public AreaWithChildrenResponse get(UUID id) {
|
||||||
Area area = getArea(id);
|
Area area = getArea(id);
|
||||||
List<AreaResponse> children = areaRepository.findByParentIdOrderByNameAsc(id).stream()
|
List<AreaResponse> children = areaRepository
|
||||||
|
.findPageByAttractionsFirstThenName(id, Pageable.unpaged()).getContent().stream()
|
||||||
.map(this::toOverview)
|
.map(this::toOverview)
|
||||||
.toList();
|
.toList();
|
||||||
AreaActiveSetInfo info = setService.getAreaActiveSetInfo(id);
|
AreaActiveSetInfo info = setService.getAreaActiveSetInfo(id);
|
||||||
|
|||||||
@@ -50,14 +50,16 @@ gorodar:
|
|||||||
# Вердикт вычисляем сами по confidence dino: >= match-threshold — match,
|
# Вердикт вычисляем сами по confidence dino: >= match-threshold — match,
|
||||||
# <= no-match-threshold — no_match, между ними — uncertain. Переопределяется
|
# <= no-match-threshold — no_match, между ними — uncertain. Переопределяется
|
||||||
# для конкретной достопримечательности (attractions.match_threshold и т.д.)
|
# для конкретной достопримечательности (attractions.match_threshold и т.д.)
|
||||||
match-threshold: ${GORODAR_DINOV2_MATCH_THRESHOLD:0.75}
|
match-threshold: ${GORODAR_DINOV2_MATCH_THRESHOLD:0.55}
|
||||||
no-match-threshold: ${GORODAR_DINOV2_NO_MATCH_THRESHOLD:0.55}
|
no-match-threshold: ${GORODAR_DINOV2_NO_MATCH_THRESHOLD:0.45}
|
||||||
max-reference-photos: ${GORODAR_DINOV2_MAX_REFERENCE_PHOTOS:15}
|
max-reference-photos: ${GORODAR_DINOV2_MAX_REFERENCE_PHOTOS:15}
|
||||||
unisender:
|
unisender:
|
||||||
base-url: ${GORODAR_UNISENDER_URL:https://goapi.unisender.ru}
|
base-url: ${GORODAR_UNISENDER_URL:https://goapi.unisender.ru}
|
||||||
api-key: ${GORODAR_UNISENDER_API_KEY:}
|
api-key: ${GORODAR_UNISENDER_API_KEY:}
|
||||||
from-email: ${GORODAR_UNISENDER_FROM_EMAIL:}
|
from-email: ${GORODAR_UNISENDER_FROM_EMAIL:}
|
||||||
from-name: ${GORODAR_UNISENDER_FROM_NAME:Городар}
|
from-name: ${GORODAR_UNISENDER_FROM_NAME:Городар}
|
||||||
|
# Шаблон письма с кодом в ЛК Unisender; код уходит подстановкой "code"
|
||||||
|
template-id: ${GORODAR_UNISENDER_TEMPLATE_ID:b56a2912-c488-11f1-9ec1-faf9f44db93c}
|
||||||
s3:
|
s3:
|
||||||
endpoint: ${GORODAR_S3_ENDPOINT:http://localhost:9000}
|
endpoint: ${GORODAR_S3_ENDPOINT:http://localhost:9000}
|
||||||
region: ${GORODAR_S3_REGION:ru-central-1}
|
region: ${GORODAR_S3_REGION:ru-central-1}
|
||||||
|
|||||||
@@ -10,9 +10,8 @@ import ru.gorodar.integration.unisender.UnisenderClient;
|
|||||||
|
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
|
||||||
import static org.mockito.ArgumentMatchers.argThat;
|
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.verifyNoInteractions;
|
import static org.mockito.Mockito.verifyNoInteractions;
|
||||||
@@ -22,19 +21,18 @@ class MailCodeSenderTest {
|
|||||||
|
|
||||||
private static final String EMAIL = "user@example.com";
|
private static final String EMAIL = "user@example.com";
|
||||||
private static final String CODE = "123456";
|
private static final String CODE = "123456";
|
||||||
private static final String SUBJECT = "Городар: код подтверждения";
|
private static final String SUBJECT = "Городар — код подтверждения";
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private UnisenderClient unisenderClient;
|
private UnisenderClient unisenderClient;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void sendsCodeViaUnisenderWhenApiKeyConfigured() {
|
void sendsCodeViaUnisenderTemplateSubstitution() {
|
||||||
MailCodeSender sender = new MailCodeSender(unisenderClient, authProperties(false), unisender("api-key"));
|
MailCodeSender sender = new MailCodeSender(unisenderClient, authProperties(false), unisender("api-key"));
|
||||||
|
|
||||||
sender.sendCode(EMAIL, CODE);
|
sender.sendCode(EMAIL, CODE);
|
||||||
|
|
||||||
verify(unisenderClient).sendEmail(eq(EMAIL), eq(SUBJECT),
|
verify(unisenderClient).sendEmail(eq(EMAIL), eq(SUBJECT), eq(Map.of("code", CODE)));
|
||||||
argThat(text -> text != null && text.contains(CODE)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -62,6 +60,6 @@ class MailCodeSenderTest {
|
|||||||
|
|
||||||
private UnisenderProperties unisender(String apiKey) {
|
private UnisenderProperties unisender(String apiKey) {
|
||||||
return new UnisenderProperties("https://goapi.unisender.ru", apiKey,
|
return new UnisenderProperties("https://goapi.unisender.ru", apiKey,
|
||||||
"noreply@gorodar.ru", "Городар");
|
"noreply@gorodar.ru", "Городар", "template-id");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,14 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
|||||||
import org.mockito.InjectMocks;
|
import org.mockito.InjectMocks;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageImpl;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import ru.gorodar.api.dto.AreaDtos.AreaResponse;
|
||||||
|
import ru.gorodar.api.dto.AreaDtos.AreaWithChildrenResponse;
|
||||||
|
import ru.gorodar.api.dto.SetDtos.AreaActiveSetInfo;
|
||||||
|
import ru.gorodar.api.dto.VisitDtos.ProgressResponse;
|
||||||
import ru.gorodar.dao.AreaRepository;
|
import ru.gorodar.dao.AreaRepository;
|
||||||
import ru.gorodar.dao.AttractionPhotoRepository;
|
import ru.gorodar.dao.AttractionPhotoRepository;
|
||||||
import ru.gorodar.dao.AttractionRepository;
|
import ru.gorodar.dao.AttractionRepository;
|
||||||
@@ -29,7 +37,9 @@ import java.util.UUID;
|
|||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.anyList;
|
import static org.mockito.ArgumentMatchers.anyList;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.mockito.Mockito.verifyNoInteractions;
|
import static org.mockito.Mockito.verifyNoInteractions;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
@@ -136,4 +146,62 @@ class AreaServiceTest {
|
|||||||
assertThat(error.getCode()).isEqualTo(ErrorCode.AREA_NOT_FOUND);
|
assertThat(error.getCode()).isEqualTo(ErrorCode.AREA_NOT_FOUND);
|
||||||
verifyNoInteractions(s3Storage);
|
verifyNoInteractions(s3Storage);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void publicListReturnsAreasInRepositoryCatalogOrder() {
|
||||||
|
Pageable pageable = PageRequest.of(0, 20);
|
||||||
|
// порядок (сначала зоны с достопримечательностями, затем по алфавиту) считает БД
|
||||||
|
Area alpha = areaNamed("Alpha");
|
||||||
|
Area gamma = areaNamed("Gamma");
|
||||||
|
Area beta = areaNamed("Beta");
|
||||||
|
when(areaRepository.findPageByAttractionsFirstThenName(null, pageable))
|
||||||
|
.thenReturn(new PageImpl<>(List.of(alpha, gamma, beta), pageable, 3));
|
||||||
|
stubOverview();
|
||||||
|
|
||||||
|
Page<AreaResponse> page = service.listPublic(null, pageable);
|
||||||
|
|
||||||
|
assertThat(page.getContent()).extracting(AreaResponse::name)
|
||||||
|
.containsExactly("Alpha", "Gamma", "Beta");
|
||||||
|
assertThat(page.getTotalElements()).isEqualTo(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getReturnsChildrenInRepositoryCatalogOrder() {
|
||||||
|
Area root = EntityTestHelper.areaOf(rootId);
|
||||||
|
Area alpha = areaNamed("Alpha");
|
||||||
|
Area gamma = areaNamed("Gamma");
|
||||||
|
Area beta = areaNamed("Beta");
|
||||||
|
when(areaRepository.findById(rootId)).thenReturn(Optional.of(root));
|
||||||
|
when(areaRepository.findPageByAttractionsFirstThenName(eq(rootId), any(Pageable.class)))
|
||||||
|
.thenReturn(new PageImpl<>(List.of(alpha, gamma, beta)));
|
||||||
|
AreaActiveSetInfo info = new AreaActiveSetInfo(List.of(), new ProgressResponse(0, 0));
|
||||||
|
when(setService.getAreaActiveSetInfo(any())).thenReturn(info);
|
||||||
|
when(areaMapper.toResponse(any(Area.class), anyList(), any())).thenAnswer(invocation -> {
|
||||||
|
Area area = invocation.getArgument(0);
|
||||||
|
return new AreaResponse(area.getId(), null, area.getName(), List.of(), null);
|
||||||
|
});
|
||||||
|
when(areaMapper.toWithChildrenResponse(eq(root), anyList(), anyList(), any()))
|
||||||
|
.thenAnswer(invocation -> new AreaWithChildrenResponse(
|
||||||
|
rootId, null, root.getName(), invocation.getArgument(1), List.of(), null));
|
||||||
|
|
||||||
|
AreaWithChildrenResponse response = service.get(rootId);
|
||||||
|
|
||||||
|
assertThat(response.children()).extracting(AreaResponse::name)
|
||||||
|
.containsExactly("Alpha", "Gamma", "Beta");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Area areaNamed(String name) {
|
||||||
|
Area area = EntityTestHelper.areaOf(UUID.randomUUID());
|
||||||
|
area.setName(name);
|
||||||
|
return area;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stubOverview() {
|
||||||
|
AreaActiveSetInfo info = new AreaActiveSetInfo(List.of(), new ProgressResponse(0, 0));
|
||||||
|
when(setService.getAreaActiveSetInfo(any())).thenReturn(info);
|
||||||
|
when(areaMapper.toResponse(any(Area.class), anyList(), any())).thenAnswer(invocation -> {
|
||||||
|
Area area = invocation.getArgument(0);
|
||||||
|
return new AreaResponse(area.getId(), null, area.getName(), List.of(), null);
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user