init
This commit is contained in:
@@ -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
|
||||
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