feat(system): language registry with guarded updates and a catalog version

Ported from babyboo locale-registry: a duplicate code, a code change, switching
English off and switching off the last enabled language are refused as 409s
with a message code; every accepted change bumps the catalog version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-02 12:40:15 +08:00
1 parent 075a3a34d1
commit 4622a5219d
9 files changed
+359 -1

No files matched your search

+1 -1
View File
@@ -13,7 +13,7 @@ Verify commands:
## 2. services-system
- [ ] 2.1 Language registry: entity, repository, service and `/locale/*` controller, with the duplicate, code-locked, English-locked and last-enabled refusals, and the catalog version bump on save and update.
- [x] 2.1 Language registry: entity, repository, service and `/locale/*` controller, with the duplicate, code-locked, English-locked and last-enabled refusals, and the catalog version bump on save and update.
- Verify: `mvn -T 1C -B -q -pl solvway-services-system -am verify`
- [ ] 2.2 Messages:
- `catalog_meta` with `/message/catalogVersion`;
@@ -0,0 +1,42 @@
package com.solvway.services.system.controller;
import com.solvway.services.system.model.SupportedLocale;
import com.solvway.services.system.service.SupportedLocaleService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
/** Language registry. Only findAllEnabled is readable without a user token (gateway). */
@RestController
@RequestMapping("/locale")
@RequiredArgsConstructor
public class SupportedLocaleController {
private final SupportedLocaleService service;
@GetMapping("/findAll")
public List<SupportedLocale> findAll() {
return service.findAll();
}
@GetMapping("/findAllEnabled")
public List<SupportedLocale> findAllEnabled() {
return service.findAllEnabled();
}
@GetMapping("/findById/{id}")
public Optional<SupportedLocale> findById(@PathVariable Long id) {
return service.findById(id);
}
@PostMapping("/save")
public SupportedLocale save(@RequestBody SupportedLocale bean) {
return service.save(bean);
}
@PostMapping("/update")
public SupportedLocale update(@RequestBody SupportedLocale bean) {
return service.update(bean);
}
}
@@ -0,0 +1,19 @@
package com.solvway.services.system.model;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
/** The single row (id 1) holding the catalog version; created by SQL, only ever incremented here. */
@Entity
@Table(name = "catalog_meta")
@Getter
@Setter
public class CatalogMeta {
@Id
private Long id;
private Long version;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,20 @@
package com.solvway.services.system.model;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
/** A UI language. {@code code} matches the language keys of message.content and is unique; disabled languages stay out of the picker. */
@Entity
@Table(name = "supported_locale")
@Getter
@Setter
public class SupportedLocale {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String code;
private String label;
private Boolean enabled;
private Integer sortOrder;
}
@@ -0,0 +1,13 @@
package com.solvway.services.system.repo;
import com.solvway.services.system.model.CatalogMeta;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
public interface CatalogMetaRepository extends JpaRepository<CatalogMeta, Long> {
/** Atomic increment inside the caller's write transaction, so no reader sees a change without a new version. */
@Modifying
@Query(value = "UPDATE catalog_meta SET version = version + 1, updated_at = NOW() WHERE id = 1", nativeQuery = true)
int bumpVersion();
}
@@ -0,0 +1,15 @@
package com.solvway.services.system.repo;
import com.solvway.services.system.model.SupportedLocale;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface SupportedLocaleRepository extends JpaRepository<SupportedLocale, Long> {
Optional<SupportedLocale> findByCode(String code);
List<SupportedLocale> findByEnabledTrueOrderBySortOrderAsc();
List<SupportedLocale> findAllByOrderBySortOrderAsc();
}
@@ -0,0 +1,23 @@
package com.solvway.services.system.service;
import com.solvway.services.system.model.CatalogMeta;
import com.solvway.services.system.repo.CatalogMetaRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/** The catalog version the portals key their catalog cache on. Every message or language write bumps it in its own transaction. */
@Service
@RequiredArgsConstructor
public class CatalogVersionService {
private final CatalogMetaRepository repository;
public long current() {
return repository.findById(1L).map(CatalogMeta::getVersion).orElse(0L);
}
@Transactional
public void bump() {
repository.bumpVersion();
}
}
@@ -0,0 +1,87 @@
package com.solvway.services.system.service;
import com.solvway.services.system.model.SupportedLocale;
import com.solvway.services.system.repo.SupportedLocaleRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Optional;
/**
* The language registry (ported from babyboo locale-registry). Refusals are 409s whose reason is a UI message code:
* a duplicate code, a code change, switching English off, switching off the last enabled language. A refusal
* changes nothing and does not bump the catalog version.
*/
@Service
@RequiredArgsConstructor
public class SupportedLocaleService {
private static final String FALLBACK = "en_US";
private final SupportedLocaleRepository repository;
private final CatalogVersionService catalogVersion;
public List<SupportedLocale> findAll() {
return repository.findAllByOrderBySortOrderAsc();
}
public List<SupportedLocale> findAllEnabled() {
return repository.findByEnabledTrueOrderBySortOrderAsc();
}
public Optional<SupportedLocale> findById(Long id) {
return repository.findById(id);
}
@Transactional
public SupportedLocale save(SupportedLocale bean) {
if (repository.findByCode(bean.getCode()).isPresent()) {
throw refused("LocalesDuplicateCode");
}
bean.setId(null);
SupportedLocale saved = persist(bean);
catalogVersion.bump();
return saved;
}
/** Applies label, order and enabled; a field the body leaves out keeps its stored value. */
@Transactional
public SupportedLocale update(SupportedLocale bean) {
SupportedLocale stored = (bean.getId() == null ? Optional.<SupportedLocale>empty() : repository.findById(bean.getId()))
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "LocaleNotFound"));
if (bean.getCode() != null && !bean.getCode().equals(stored.getCode())) {
throw refused("LocalesCodeLocked");
}
if (Boolean.FALSE.equals(bean.getEnabled()) && Boolean.TRUE.equals(stored.getEnabled())) {
if (FALLBACK.equals(stored.getCode())) {
throw refused("LocalesFallbackLocked");
}
if (repository.findByEnabledTrueOrderBySortOrderAsc().size() <= 1) {
throw refused("LocalesLastEnabledLocked");
}
}
if (bean.getLabel() != null) stored.setLabel(bean.getLabel());
if (bean.getEnabled() != null) stored.setEnabled(bean.getEnabled());
if (bean.getSortOrder() != null) stored.setSortOrder(bean.getSortOrder());
SupportedLocale saved = persist(stored);
catalogVersion.bump();
return saved;
}
private SupportedLocale persist(SupportedLocale l) {
try {
return repository.save(l);
} catch (DataIntegrityViolationException e) {
// Two creates raced past the pre-check; the unique key caught the loser.
throw refused("LocalesDuplicateCode");
}
}
private static ResponseStatusException refused(String reason) {
return new ResponseStatusException(HttpStatus.CONFLICT, reason);
}
}
@@ -0,0 +1,139 @@
package com.solvway.services.system.service;
import com.solvway.services.system.model.SupportedLocale;
import com.solvway.services.system.repo.SupportedLocaleRepository;
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 org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Optional;
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.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Language registry rules ported from babyboo locale-registry: duplicates, locked code, English and last enabled, version bump. */
@ExtendWith(MockitoExtension.class)
class SupportedLocaleServiceTest {
@Mock
private SupportedLocaleRepository repository;
@Mock
private CatalogVersionService catalogVersion;
@InjectMocks
private SupportedLocaleService service;
@Test
void enabledListComesInOrder() {
List<SupportedLocale> enabled = List.of(locale(1L, "en_US", true), locale(2L, "zh_CN", true));
when(repository.findByEnabledTrueOrderBySortOrderAsc()).thenReturn(enabled);
assertThat(service.findAllEnabled()).isEqualTo(enabled);
}
@Test
void addingANewCodeSavesAndBumpsTheVersion() {
SupportedLocale ms = locale(null, "ms_MY", false);
when(repository.findByCode("ms_MY")).thenReturn(Optional.empty());
when(repository.save(ms)).thenReturn(ms);
assertThat(service.save(ms)).isSameAs(ms);
verify(catalogVersion).bump();
}
@Test
void addingAnExistingCodeIsRefusedWithoutABump() {
when(repository.findByCode("zh_CN")).thenReturn(Optional.of(locale(2L, "zh_CN", true)));
assertRefused(() -> service.save(locale(null, "zh_CN", true)), "LocalesDuplicateCode");
verify(repository, never()).save(any());
verify(catalogVersion, never()).bump();
}
@Test
void aRaceOnTheUniqueKeyIsStillADuplicate() {
SupportedLocale ms = locale(null, "ms_MY", true);
when(repository.findByCode("ms_MY")).thenReturn(Optional.empty());
when(repository.save(ms)).thenThrow(new DataIntegrityViolationException("uk_supported_locale_code"));
assertRefused(() -> service.save(ms), "LocalesDuplicateCode");
verify(catalogVersion, never()).bump();
}
@Test
void renamingACodeIsRefused() {
when(repository.findById(2L)).thenReturn(Optional.of(locale(2L, "zh_CN", true)));
assertRefused(() -> service.update(locale(2L, "zh_TW", true)), "LocalesCodeLocked");
verify(repository, never()).save(any());
verify(catalogVersion, never()).bump();
}
@Test
void switchingEnglishOffIsRefused() {
when(repository.findById(1L)).thenReturn(Optional.of(locale(1L, "en_US", true)));
assertRefused(() -> service.update(locale(1L, "en_US", false)), "LocalesFallbackLocked");
verify(catalogVersion, never()).bump();
}
@Test
void switchingOffTheLastEnabledLanguageIsRefused() {
when(repository.findById(2L)).thenReturn(Optional.of(locale(2L, "zh_CN", true)));
when(repository.findByEnabledTrueOrderBySortOrderAsc()).thenReturn(List.of(locale(2L, "zh_CN", true)));
assertRefused(() -> service.update(locale(2L, "zh_CN", false)), "LocalesLastEnabledLocked");
}
@Test
void updateKeepsFieldsTheBodyLeavesOutAndBumps() {
SupportedLocale stored = locale(3L, "ms_MY", false);
stored.setLabel("Bahasa Melayu");
stored.setSortOrder(3);
when(repository.findById(3L)).thenReturn(Optional.of(stored));
when(repository.save(stored)).thenReturn(stored);
SupportedLocale body = new SupportedLocale();
body.setId(3L);
body.setEnabled(true);
SupportedLocale saved = service.update(body);
assertThat(saved.getCode()).isEqualTo("ms_MY");
assertThat(saved.getLabel()).isEqualTo("Bahasa Melayu");
assertThat(saved.getSortOrder()).isEqualTo(3);
assertThat(saved.getEnabled()).isTrue();
verify(catalogVersion).bump();
}
@Test
void updatingAnUnknownIdIsNotFound() {
when(repository.findById(9L)).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.update(locale(9L, "xx", true)))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
}
private static void assertRefused(Runnable call, String reason) {
assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
assertThat(e.getReason()).isEqualTo(reason);
});
}
private static SupportedLocale locale(Long id, String code, boolean enabled) {
SupportedLocale l = new SupportedLocale();
l.setId(id);
l.setCode(code);
l.setEnabled(enabled);
return l;
}
}