feat(mobile-api): admin translations and languages APIs
Locales list, create and update; public enabled list; message catalog, version, search, detail, update, export and import. Refusals from services-system pass through as 409 with their reason code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
1 parent
45bd81cdbb
commit
27e0ec7bff
8 files changed
+617
-2
No files matched your search
@@ -29,8 +29,8 @@ Verify commands:
|
||||
|
||||
## 4. mobile-api
|
||||
|
||||
- [ ] 4.1 `AdminLocaleController` and the public `/api/public/locales`. Refusals pass through as 409 with the reason; locale writes are audited.
|
||||
- [ ] 4.2 `AdminMessageController`: catalog and catalog-version (API key, no session); list and search; detail; `PUT` (the path id wins); export (audited as a sensitive read); import (match by code ignoring case, per-row summary, audited); module `BO_MESSAGES`; no create and no delete mapping.
|
||||
- [x] 4.1 `AdminLocaleController` and the public `/api/public/locales`. Refusals pass through as 409 with the reason; locale writes are audited.
|
||||
- [x] 4.2 `AdminMessageController`: catalog and catalog-version (API key, no session); list and search; detail; `PUT` (the path id wins); export (audited as a sensitive read); import (match by code ignoring case, per-row summary, audited); module `BO_MESSAGES`; no create and no delete mapping.
|
||||
- Verify (4.1 and 4.2): `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
|
||||
## 5. Portal
|
||||
|
||||
+9
@@ -60,6 +60,15 @@ public class RestApiSystemServiceConstants {
|
||||
public static final String API_REST_SYSTEM_ADMIN_ACTIVE_PASSWORD_RULES = "/passwordRule/adminActive";
|
||||
|
||||
//Message
|
||||
public static final String API_REST_SYSTEM_MESSAGE_SEARCH = "/message/search";
|
||||
public static final String API_REST_SYSTEM_MESSAGE_FIND_BY_ID = "/message/findById/{id}";
|
||||
public static final String API_REST_SYSTEM_MESSAGE_SAVE = "/message/save";
|
||||
public static final String API_REST_SYSTEM_MESSAGE_ALL_BY_AREA = "/message/getAllMessages/{area}";
|
||||
public static final String API_REST_SYSTEM_MESSAGE_CATALOG_VERSION = "/message/catalogVersion";
|
||||
public static final String API_REST_SYSTEM_LOCALE_FIND_ALL = "/locale/findAll";
|
||||
public static final String API_REST_SYSTEM_LOCALE_FIND_ALL_ENABLED = "/locale/findAllEnabled";
|
||||
public static final String API_REST_SYSTEM_LOCALE_SAVE = "/locale/save";
|
||||
public static final String API_REST_SYSTEM_LOCALE_UPDATE = "/locale/update";
|
||||
public static final String API_REST_SYSTEM_MESSAGE_JSON_BY_AREA_AND_LOCALE = "/message/getMessageJsonByAreaAndLocale/{area}/{locale}";
|
||||
|
||||
//Nationality
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminTranslationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Enabled languages for the sign-in page switcher: API key only, no session. */
|
||||
@RestController
|
||||
@RequestMapping("/api/public")
|
||||
@RequiredArgsConstructor
|
||||
public class PublicLocaleController {
|
||||
private final AdminTranslationService translations;
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/locales")
|
||||
public ResponseEntity<List<Map<String, Object>>> enabled() {
|
||||
return ResponseEntity.ok(translations.locales(true));
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminTranslationService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
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.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Languages, ported from babyboo. Any signed-in admin reads the list for the switcher; writes need BO_LOCALES. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminLocaleController {
|
||||
private final AdminTranslationService translations;
|
||||
|
||||
@AppAuth
|
||||
@AdminModule(AdminModule.ANY_ADMIN)
|
||||
@GetMapping("/locales")
|
||||
public ResponseEntity<List<Map<String, Object>>> list() {
|
||||
return ResponseEntity.ok(translations.locales(false));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_LOCALES")
|
||||
@Audited(action = "LOCALE_CREATE")
|
||||
@PostMapping("/locales")
|
||||
public ResponseEntity<Map<String, Object>> create(@RequestBody Map<String, Object> body) {
|
||||
return ResponseEntity.ok(translations.createLocale(body));
|
||||
}
|
||||
|
||||
/** The path id wins over any id in the body. */
|
||||
@AppAuth
|
||||
@AdminModule("BO_LOCALES")
|
||||
@Audited(action = "LOCALE_UPDATE")
|
||||
@PutMapping("/locales/{id}")
|
||||
public ResponseEntity<Map<String, Object>> update(@PathVariable Long id, @RequestBody Map<String, Object> body) {
|
||||
return ResponseEntity.ok(translations.updateLocale(id, body));
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminTranslationService;
|
||||
import com.solvway.mobile.api.service.SystemService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
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.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Back-office labels (area A), ported from babyboo and trimmed: no area filter, no create, no delete.
|
||||
* The catalog and its version need only the API key, because the sign-in page shows labels before a session exists.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminMessageController {
|
||||
private final AdminTranslationService translations;
|
||||
private final SystemService systemService;
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/messages/catalog/{locale}")
|
||||
public ResponseEntity<Map<String, String>> catalog(@PathVariable String locale) {
|
||||
return ResponseEntity.ok(systemService.findMessageCatalog("A", locale));
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/messages/catalog-version")
|
||||
public ResponseEntity<Map<String, Object>> catalogVersion() {
|
||||
return ResponseEntity.ok(translations.catalogVersion());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_MESSAGES")
|
||||
@GetMapping("/messages")
|
||||
public ResponseEntity<Map<String, Object>> list(@RequestParam(required = false) String searchKey,
|
||||
@RequestParam(required = false) String missingLocale,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(translations.search(searchKey, missingLocale, page, size));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_MESSAGES")
|
||||
@Audited(action = "MESSAGES_EXPORT")
|
||||
@GetMapping("/messages/export")
|
||||
public ResponseEntity<List<Map<String, Object>>> export() {
|
||||
return ResponseEntity.ok(translations.export());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_MESSAGES")
|
||||
@GetMapping("/messages/{id}")
|
||||
public ResponseEntity<Map<String, Object>> detail(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(translations.message(id));
|
||||
}
|
||||
|
||||
/** The path id wins; only the content changes. */
|
||||
@AppAuth
|
||||
@AdminModule("BO_MESSAGES")
|
||||
@Audited(action = "MESSAGE_UPDATE")
|
||||
@PutMapping("/messages/{id}")
|
||||
public ResponseEntity<Void> update(@PathVariable Long id, @RequestBody Map<String, Object> body) {
|
||||
translations.updateMessage(id, body);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_MESSAGES")
|
||||
@Audited(action = "MESSAGES_IMPORT")
|
||||
@PostMapping("/messages/import")
|
||||
public ResponseEntity<Map<String, Object>> importMessages(@RequestBody List<Map<String, Object>> rows) {
|
||||
return ResponseEntity.ok(translations.importMessages(rows));
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Translations (area A labels) and languages for the admin portal, ported from babyboo
|
||||
* AdminMessageService and AdminLocaleService, trimmed to area A with no create or delete of labels.
|
||||
*/
|
||||
@Service
|
||||
public class AdminTranslationService {
|
||||
|
||||
static final String AREA = "A";
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final RestTemplateCustomUtil rest;
|
||||
|
||||
public AdminTranslationService(RestTemplateCustomUtil rest) {
|
||||
this.rest = rest;
|
||||
}
|
||||
|
||||
// ---- languages
|
||||
|
||||
public List<Map<String, Object>> locales(boolean enabledOnly) {
|
||||
String api = enabledOnly ? RestApiSystemServiceConstants.API_REST_SYSTEM_LOCALE_FIND_ALL_ENABLED
|
||||
: RestApiSystemServiceConstants.API_REST_SYSTEM_LOCALE_FIND_ALL;
|
||||
List<Map<String, Object>> body = rest.getForEntity(url(api), MAP_LIST).getBody();
|
||||
return body == null ? List.of() : body;
|
||||
}
|
||||
|
||||
public Map<String, Object> createLocale(Map<String, Object> body) {
|
||||
Map<String, Object> sent = new LinkedHashMap<>(body);
|
||||
sent.remove("id");
|
||||
return relay(() -> rest.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_LOCALE_SAVE), MAP, sent).getBody());
|
||||
}
|
||||
|
||||
public Map<String, Object> updateLocale(Long id, Map<String, Object> body) {
|
||||
Map<String, Object> sent = new LinkedHashMap<>(body);
|
||||
sent.put("id", id);
|
||||
return relay(() -> rest.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_LOCALE_UPDATE), MAP, sent).getBody());
|
||||
}
|
||||
|
||||
// ---- labels
|
||||
|
||||
public Map<String, Object> catalogVersion() {
|
||||
Map<String, Object> body = rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_MESSAGE_CATALOG_VERSION), MAP).getBody();
|
||||
return body == null ? Map.of("version", 0) : body;
|
||||
}
|
||||
|
||||
public Map<String, Object> search(String searchKey, String missingLocale, int page, int size) {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("searchKey", searchKey);
|
||||
req.put("missingLocale", missingLocale);
|
||||
req.put("area", AREA);
|
||||
req.put("page", page);
|
||||
req.put("size", size);
|
||||
return rest.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_MESSAGE_SEARCH), MAP, req).getBody();
|
||||
}
|
||||
|
||||
/** Area A only: other areas belong to portals Co-Lite does not run, so they answer 404. */
|
||||
public Map<String, Object> message(Long id) {
|
||||
Map<String, Object> row = rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_MESSAGE_FIND_BY_ID), MAP, id).getBody();
|
||||
if (row == null || !AREA.equals(row.get("area"))) {
|
||||
throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Translation not found", "MsgsNotFound");
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
/** The path id wins; code and area stay as stored, only content changes. */
|
||||
public void updateMessage(Long id, Map<String, Object> body) {
|
||||
Map<String, Object> stored = message(id);
|
||||
save(row(id, (String) stored.get("code"), body.get("content"), stored.get("description")));
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> export() {
|
||||
List<Map<String, Object>> body = rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_MESSAGE_ALL_BY_AREA), MAP_LIST, AREA).getBody();
|
||||
return body == null ? List.of() : body;
|
||||
}
|
||||
|
||||
/** Matches rows by code ignoring case, never by the file's id; one failed row does not stop the rest. */
|
||||
public Map<String, Object> importMessages(List<Map<String, Object>> rows) {
|
||||
Map<String, Map<String, Object>> byCode = new HashMap<>();
|
||||
for (Map<String, Object> m : export()) byCode.put(lower(m.get("code")), m);
|
||||
int created = 0;
|
||||
int updated = 0;
|
||||
List<Map<String, Object>> errors = new ArrayList<>();
|
||||
for (int i = 0; i < rows.size(); i++) {
|
||||
Map<String, Object> r = rows.get(i);
|
||||
Object code = r.get("code");
|
||||
if (!(code instanceof String c) || !StringUtils.hasText(c)) {
|
||||
errors.add(Map.of("index", i, "code", "", "error", "MsgsCodeRequired"));
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> existing = byCode.get(lower(c));
|
||||
try {
|
||||
if (existing == null) {
|
||||
save(row(0L, c.trim(), r.get("content"), r.get("description")));
|
||||
created++;
|
||||
} else {
|
||||
Object description = r.containsKey("description") ? r.get("description") : existing.get("description");
|
||||
save(row(((Number) existing.get("id")).longValue(), (String) existing.get("code"), r.get("content"), description));
|
||||
updated++;
|
||||
}
|
||||
} catch (CodedResponseStatusException e) {
|
||||
errors.add(Map.of("index", i, "code", c, "error", e.getCode()));
|
||||
}
|
||||
}
|
||||
Map<String, Object> summary = new LinkedHashMap<>();
|
||||
summary.put("created", created);
|
||||
summary.put("updated", updated);
|
||||
summary.put("errors", errors);
|
||||
return summary;
|
||||
}
|
||||
|
||||
private void save(Map<String, Object> row) {
|
||||
relay(() -> rest.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_MESSAGE_SAVE), Void.class, row));
|
||||
}
|
||||
|
||||
private static Map<String, Object> row(long id, String code, Object content, Object description) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("code", code);
|
||||
m.put("area", AREA);
|
||||
m.put("content", content);
|
||||
m.put("description", description);
|
||||
return m;
|
||||
}
|
||||
|
||||
/** services-system refuses with a ProblemDetail whose detail is the reason code; pass it through as a 409. */
|
||||
private static <T> T relay(java.util.function.Supplier<T> call) {
|
||||
try {
|
||||
return call.get();
|
||||
} catch (HttpClientErrorException.Conflict | HttpClientErrorException.NotFound e) {
|
||||
String reason = detail(e);
|
||||
throw new CodedResponseStatusException(e.getStatusCode(), reason, reason);
|
||||
}
|
||||
}
|
||||
|
||||
private static String detail(HttpClientErrorException e) {
|
||||
try {
|
||||
Object d = JSON.readValue(e.getResponseBodyAsString(), Map.class).get("detail");
|
||||
if (d != null) return String.valueOf(d);
|
||||
} catch (JsonProcessingException ignored) {
|
||||
// fall through to the generic reason
|
||||
}
|
||||
return e.getStatusCode().value() == 404 ? "NotFound" : "Conflict";
|
||||
}
|
||||
|
||||
private static String lower(Object code) {
|
||||
return code == null ? "" : code.toString().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return rest.getURLforApiService(api);
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.controller.PublicLocaleController;
|
||||
import com.solvway.mobile.api.service.AdminTranslationService;
|
||||
import com.solvway.mobile.api.service.SystemService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
class AdminTranslationControllersTest {
|
||||
|
||||
private AdminTranslationService translations;
|
||||
private SystemService system;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
translations = mock(AdminTranslationService.class);
|
||||
system = mock(SystemService.class);
|
||||
mvc = MockMvcBuilders.standaloneSetup(new AdminMessageController(translations, system), new AdminLocaleController(translations)).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void catalogAndVersionNeedOnlyTheApiKeyEverythingElseAModule() throws Exception {
|
||||
for (Method m : AdminMessageController.class.getDeclaredMethods()) {
|
||||
if (!m.isAnnotationPresent(AppAuth.class)) continue;
|
||||
boolean open = m.getName().startsWith("catalog");
|
||||
assertThat(m.getAnnotation(AppAuth.class).skipValidate()).as(m.getName()).isEqualTo(open);
|
||||
if (!open) assertThat(m.getAnnotation(AdminModule.class).value()).as(m.getName()).containsExactly("BO_MESSAGES");
|
||||
}
|
||||
assertThat(AdminLocaleController.class.getMethod("list").getAnnotation(AdminModule.class).value()).containsExactly(AdminModule.ANY_ADMIN);
|
||||
assertThat(AdminLocaleController.class.getMethod("create", Map.class).getAnnotation(AdminModule.class).value()).containsExactly("BO_LOCALES");
|
||||
assertThat(AdminLocaleController.class.getMethod("update", Long.class, Map.class).getAnnotation(AdminModule.class).value()).containsExactly("BO_LOCALES");
|
||||
}
|
||||
|
||||
@Test
|
||||
void labelsCannotBeAddedOrDeletedAndExportIsAudited() throws Exception {
|
||||
assertThat(Arrays.stream(AdminMessageController.class.getDeclaredMethods())
|
||||
.filter(m -> m.isAnnotationPresent(DeleteMapping.class)
|
||||
|| (m.isAnnotationPresent(PostMapping.class) && !m.getName().equals("importMessages")))).isEmpty();
|
||||
assertThat(AdminMessageController.class.getMethod("export").getAnnotation(Audited.class)).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPassesFiltersWithFirstPageOfTwentyByDefault() throws Exception {
|
||||
when(translations.search(null, "zh_CN", 0, 20)).thenReturn(Map.of("content", List.of(), "totalElements", 0));
|
||||
mvc.perform(get("/api/admin/messages").param("missingLocale", "zh_CN")).andExpect(status().isOk()).andExpect(jsonPath("$.totalElements").value(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUsesThePathId() throws Exception {
|
||||
mvc.perform(put("/api/admin/messages/7").contentType(MediaType.APPLICATION_JSON).content("{\"id\":9,\"content\":\"{}\"}"))
|
||||
.andExpect(status().isNoContent());
|
||||
verify(translations).updateMessage(eq(7L), eq(Map.of("id", 9, "content", "{}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publicLocalesAreEnabledOnlyAndNeedNoSession() throws Exception {
|
||||
assertThat(PublicLocaleController.class.getMethod("enabled").getAnnotation(AppAuth.class).skipValidate()).isTrue();
|
||||
when(translations.locales(true)).thenReturn(List.of(Map.of("code", "zh_CN")));
|
||||
MockMvcBuilders.standaloneSetup(new PublicLocaleController(translations)).build()
|
||||
.perform(get("/api/public/locales")).andExpect(status().isOk()).andExpect(jsonPath("$[0].code").value("zh_CN"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void catalogReadsAreaA() throws Exception {
|
||||
when(system.findMessageCatalog("A", "zh_CN")).thenReturn(Map.of("Leads", "线索"));
|
||||
mvc.perform(get("/api/admin/messages/catalog/zh_CN")).andExpect(status().isOk()).andExpect(jsonPath("$.Leads").value("线索"));
|
||||
}
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Translations and languages admin rules ported from babyboo message-admin-api and locale-registry. */
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminTranslationServiceTest {
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminTranslationService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
service = new AdminTranslationService(rest);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUsesThePathIdAndKeepsTheStoredCodeAndArea() {
|
||||
stored(7, "Leads", "A");
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("id", 99);
|
||||
body.put("code", "Contacts");
|
||||
body.put("content", "{\"en_US\":\"Leads\",\"zh_CN\":\"线索\"}");
|
||||
|
||||
service.updateMessage(7L, body);
|
||||
|
||||
Map<String, Object> sent = savedBody();
|
||||
assertThat(sent).containsEntry("id", 7L).containsEntry("code", "Leads").containsEntry("area", "A")
|
||||
.containsEntry("content", "{\"en_US\":\"Leads\",\"zh_CN\":\"线索\"}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusalReachesThePortalWithItsCode() {
|
||||
stored(7, "Leads", "A");
|
||||
doThrow(conflict("MsgsCodeAreaLocked")).when(rest).postForEntity(eq("/message/save"), eq(Void.class), any());
|
||||
|
||||
assertThatThrownBy(() -> service.updateMessage(7L, Map.of("content", "{}")))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
|
||||
assertThat(e.getCode()).isEqualTo("MsgsCodeAreaLocked");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyBackOfficeLabelsCanBeReadOrEdited() {
|
||||
stored(8, "Cart", "AP");
|
||||
|
||||
assertThatThrownBy(() -> service.message(8L))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||
assertThatThrownBy(() -> service.updateMessage(8L, Map.of("content", "{}")))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchAsksForBackOfficeLabelsWithTheFilters() {
|
||||
when(rest.postForEntity(eq("/message/search"), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(), "totalElements", 0)));
|
||||
|
||||
service.search("线索", "zh_CN", 2, 20);
|
||||
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq("/message/search"), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat((Map<String, Object>) body.getValue()).containsEntry("searchKey", "线索").containsEntry("missingLocale", "zh_CN")
|
||||
.containsEntry("area", "A").containsEntry("page", 2).containsEntry("size", 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void importMatchesByCodeIgnoringCaseNeverByIdAndKeepsGoingAfterAFailure() {
|
||||
when(rest.getForEntity(eq("/message/getAllMessages/{area}"), any(ParameterizedTypeReference.class), eq("A")))
|
||||
.thenReturn(ResponseEntity.ok(List.of(row(7, "Leads", "A"))));
|
||||
when(rest.postForEntity(eq("/message/save"), eq(Void.class), any())).thenAnswer(i -> {
|
||||
Map<String, Object> b = i.getArgument(2);
|
||||
if ("Broken".equals(b.get("code"))) throw conflict("MsgsDuplicateCode");
|
||||
return ResponseEntity.ok().build();
|
||||
});
|
||||
List<Map<String, Object>> rows = List.of(
|
||||
Map.of("id", 123, "code", "leads", "content", "{\"zh_CN\":\"线索\"}"),
|
||||
Map.of("code", "Broken", "content", "{}"),
|
||||
Map.of("code", "NewLabel", "content", "{\"en_US\":\"New\"}"));
|
||||
|
||||
Map<String, Object> summary = service.importMessages(rows);
|
||||
|
||||
assertThat(summary).containsEntry("created", 1).containsEntry("updated", 1);
|
||||
assertThat((List<Map<String, Object>>) summary.get("errors"))
|
||||
.containsExactly(Map.of("index", 1, "code", "Broken", "error", "MsgsDuplicateCode"));
|
||||
ArgumentCaptor<Object> bodies = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest, times(3)).postForEntity(eq("/message/save"), eq(Void.class), bodies.capture());
|
||||
Map<String, Object> first = (Map<String, Object>) bodies.getAllValues().get(0);
|
||||
assertThat(first).containsEntry("id", 7L).containsEntry("code", "Leads").containsEntry("area", "A");
|
||||
assertThat((Map<String, Object>) bodies.getAllValues().get(2)).containsEntry("id", 0L).containsEntry("area", "A");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRowWithoutACodeIsReportedNotSent() {
|
||||
when(rest.getForEntity(eq("/message/getAllMessages/{area}"), any(ParameterizedTypeReference.class), eq("A")))
|
||||
.thenReturn(ResponseEntity.ok(List.of()));
|
||||
|
||||
Map<String, Object> summary = service.importMessages(List.of(Map.of("content", "{}")));
|
||||
|
||||
assertThat((List<?>) summary.get("errors")).hasSize(1);
|
||||
verify(rest, times(0)).postForEntity(eq("/message/save"), eq(Void.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void languageCreateRelaysADuplicate() {
|
||||
when(rest.postForEntity(eq("/locale/save"), any(ParameterizedTypeReference.class), any())).thenThrow(conflict("LocalesDuplicateCode"));
|
||||
|
||||
assertThatThrownBy(() -> service.createLocale(Map.of("code", "zh_CN", "label", "x")))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getCode()).isEqualTo("LocalesDuplicateCode"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void languageUpdateUsesThePathId() {
|
||||
when(rest.postForEntity(eq("/locale/update"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of()));
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("id", 5);
|
||||
body.put("enabled", false);
|
||||
|
||||
service.updateLocale(2L, body);
|
||||
|
||||
ArgumentCaptor<Object> sent = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq("/locale/update"), any(ParameterizedTypeReference.class), sent.capture());
|
||||
assertThat((Map<String, Object>) sent.getValue()).containsEntry("id", 2L).containsEntry("enabled", false);
|
||||
}
|
||||
|
||||
private void stored(long id, String code, String area) {
|
||||
when(rest.getForEntity(eq("/message/findById/{id}"), any(ParameterizedTypeReference.class), eq(id)))
|
||||
.thenReturn(ResponseEntity.ok(row(id, code, area)));
|
||||
}
|
||||
|
||||
private Map<String, Object> savedBody() {
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq("/message/save"), eq(Void.class), body.capture());
|
||||
return (Map<String, Object>) body.getValue();
|
||||
}
|
||||
|
||||
private static Map<String, Object> row(long id, String code, String area) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("code", code);
|
||||
m.put("area", area);
|
||||
m.put("content", "{\"en_US\":\"" + code + "\"}");
|
||||
m.put("description", null);
|
||||
return m;
|
||||
}
|
||||
|
||||
private static HttpClientErrorException conflict(String reason) {
|
||||
String body = "{\"type\":\"about:blank\",\"title\":\"Conflict\",\"status\":409,\"detail\":\"" + reason + "\"}";
|
||||
return HttpClientErrorException.create(HttpStatus.CONFLICT, "Conflict", new HttpHeaders(), body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user