feat(pages): published pages keep a draft until publish or discard

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-03 11:26:50 +08:00
1 parent da39c9bd84
commit cd85faa60e
10 files changed
+315 -31

No files matched your search

+3
View File
@@ -520,3 +520,6 @@ ALTER TABLE `notification`
ADD COLUMN `read_at` datetime NULL AFTER `seen`,
ADD INDEX `idx_notification_inbox` (`recipient_type`, `receiver`, `seen`, `create_date_time`),
ADD INDEX `idx_notification_collapse` (`receiver`, `collapse_key`, `seen`);
-- add-page-drafts-and-templates: a published page's unpublished draft
USE `service-counter`;
ALTER TABLE `cms_page` ADD COLUMN `draft` json NULL COMMENT 'Unpublished changes of a published page: slug, title, metaDescription, hideHeader, blocks' AFTER `blocks`;
@@ -0,0 +1,4 @@
-- Co-Lite change add-page-drafts-and-templates: rollback. Dropping the column loses every unpublished draft:
-- publish or note them first. Then deploy the previous services-counter, which saves published pages directly.
USE `service-counter`;
ALTER TABLE `cms_page` DROP COLUMN `draft`;
@@ -4,8 +4,8 @@ Design: `design.md` and `docs/superpowers/specs/2026-12-03-page-builder-design.m
## 1. Data and services
- [ ] 1.1 SQL: `sql/01-page-draft.sql`, `sql/99-rollback.sql`; mirror 01 into `local/seed/`; apply locally.
- [ ] 1.2 services-counter: `draft` on the entity and DTO, `hasDraft` on list rows; save rules for published pages; publish (re-validate, slug check) and discard endpoints; `findPublished` unchanged.
- [x] 1.1 SQL: `sql/01-page-draft.sql`, `sql/99-rollback.sql`; mirror 01 into `local/seed/`; apply locally.
- [x] 1.2 services-counter: `draft` on the entity and DTO, `hasDraft` on list rows; save rules for published pages; publish (re-validate, slug check) and discard endpoints; `findPublished` unchanged.
- Verify: `mvn -T 1C -B -pl solvway-services-counter -am verify`
- [ ] 1.3 mobile-api: `POST /api/admin/pages/{id}/publish` and `/discard`, scoped, refusals relayed like save.
- Verify: `mvn -T 1C -B -pl solvway-mobile-api -am verify`
@@ -30,6 +30,16 @@ public class CmsPageController {
return pages.save(req.page(), req.user());
}
@PostMapping("/cmsPage/publish")
public CmsPageDto publish(@RequestBody CmsPageRequests.Publish req) {
return pages.publish(req.id(), req.user());
}
@PostMapping("/cmsPage/discard")
public CmsPageDto discard(@RequestBody Long id) {
return pages.discard(id);
}
@GetMapping("/cmsPage/findById/{id}")
public CmsPageDto findById(@PathVariable("id") long id) {
return pages.findById(id);
@@ -0,0 +1,6 @@
package com.solvway.services.counter.dto;
import java.util.List;
/** Unpublished changes of a published page; visitors keep seeing the live columns until Publish. */
public record CmsPageDraft(String slug, String title, String metaDescription, boolean hideHeader, List<CmsBlock> blocks) {}
@@ -3,9 +3,17 @@ package com.solvway.services.counter.dto;
import java.time.LocalDateTime;
import java.util.List;
/** A landing page as the API sends and receives it; blocks are omitted (null) in list rows. */
/**
* A landing page as the API sends and receives it; blocks are omitted (null) in list rows.
* draft is the unpublished change set of a published page (admin reads only); hasDraft flags it in list rows.
*/
public record CmsPageDto(Long id, Long companyId, String slug, String title, String metaDescription, String status,
boolean hideHeader, List<CmsBlock> blocks, LocalDateTime updatedAt) {
boolean hideHeader, List<CmsBlock> blocks, LocalDateTime updatedAt, CmsPageDraft draft, boolean hasDraft) {
public CmsPageDto(Long id, Long companyId, String slug, String title, String metaDescription, String status,
boolean hideHeader, List<CmsBlock> blocks, LocalDateTime updatedAt) {
this(id, companyId, slug, title, metaDescription, status, hideHeader, blocks, updatedAt, null, false);
}
/** A page that shows its header (the default). */
public CmsPageDto(Long id, Long companyId, String slug, String title, String metaDescription, String status,
@@ -7,6 +7,8 @@ public final class CmsPageRequests {
public record Save(CmsPageDto page, String user) {}
public record Publish(long id, String user) {}
/** companyId null searches every company (super admin). */
public record Search(Long companyId, String searchKey, int page, int size) {}
@@ -23,6 +23,10 @@ public class CmsPage {
/** JSON array of blocks, replaced as a whole on every save. */
@Column(columnDefinition = "json")
private String blocks;
/** JSON CmsPageDraft: unpublished changes of a published page, null when there are none. */
@Column(columnDefinition = "json")
private String draft;
private String createdBy;
private LocalDateTime createdAt = LocalDateTime.now();
private String updatedBy;
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.services.counter.dto.CmsBlock;
import com.solvway.services.counter.dto.CmsPageDraft;
import com.solvway.services.counter.dto.CmsPageDto;
import com.solvway.services.counter.model.CmsPage;
import com.solvway.services.counter.repo.CmsPageRepository;
@@ -46,43 +47,84 @@ public class CmsPageService {
row.setCompanyId(dto.companyId());
row.setCreatedBy(user);
} else {
row = pages.findById(dto.id()).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "PagesNotFound"));
row = load(dto.id());
}
long companyId = row.getCompanyId();
String slug = dto.slug() == null ? "" : dto.slug();
if (slug.length() > 80 || !SLUG.matcher(slug).matches()) {
throw CmsBlockValidator.refuse("slug", "PagesBadSlug");
}
CmsBlockValidator.required(dto.title(), "title");
CmsBlockValidator.max(dto.title(), "title", 120);
CmsBlockValidator.max(dto.metaDescription(), "metaDescription", 160);
if (!"DRAFT".equals(dto.status()) && !"PUBLISHED".equals(dto.status())) {
throw CmsBlockValidator.refuse("status", "PagesBadStatus");
}
CmsBlockValidator.validate(dto.blocks(),
id -> images.findCompanyIdById(id).map(c -> c == companyId).orElse(false),
CmsPageDraft content = check(row, new CmsPageDraft(dto.slug(), dto.title(), dto.metaDescription(), dto.hideHeader(), dto.blocks()));
if ("PUBLISHED".equals(row.getStatus()) && "PUBLISHED".equals(dto.status())) {
// Visitors keep the live page; the edit waits for Publish.
row.setDraft(writeJson(content));
} else {
goLive(row, content);
row.setStatus(dto.status());
}
return store(row, user);
}
/** Makes the draft live after checking it again (an event or image may have gone, or the slug been taken). */
public CmsPageDto publish(long id, String user) {
CmsPage row = load(id);
if (row.getDraft() == null) {
return toDto(row, true, true);
}
goLive(row, check(row, readDraft(row.getDraft())));
return store(row, user);
}
public CmsPageDto discard(long id) {
CmsPage row = load(id);
row.setDraft(null);
return toDto(pages.saveAndFlush(row), true, true);
}
/** Validates page content against the page's company and returns it trimmed. */
private CmsPageDraft check(CmsPage row, CmsPageDraft c) {
long companyId = row.getCompanyId();
String slug = c.slug() == null ? "" : c.slug();
if (slug.length() > 80 || !SLUG.matcher(slug).matches()) {
throw CmsBlockValidator.refuse("slug", "PagesBadSlug");
}
CmsBlockValidator.required(c.title(), "title");
CmsBlockValidator.max(c.title(), "title", 120);
CmsBlockValidator.max(c.metaDescription(), "metaDescription", 160);
CmsBlockValidator.validate(c.blocks(),
id -> images.findCompanyIdById(id).map(co -> co == companyId).orElse(false),
uuid -> events.findByUuid(uuid).map(e -> e.getCompanyId() != null && e.getCompanyId() == companyId).orElse(false));
if (pages.existsByCompanyIdAndSlugAndIdNot(companyId, slug, dto.id() == null ? -1L : dto.id())) {
if (pages.existsByCompanyIdAndSlugAndIdNot(companyId, slug, row.getId() == null ? -1L : row.getId())) {
throw slugTaken();
}
row.setSlug(slug);
row.setTitle(dto.title().trim());
row.setMetaDescription(dto.metaDescription() == null || dto.metaDescription().isBlank() ? null : dto.metaDescription().trim());
row.setStatus(dto.status());
row.setHideHeader(dto.hideHeader());
row.setBlocks(write(dto.blocks() == null ? List.of() : dto.blocks()));
return new CmsPageDraft(slug, c.title().trim(),
c.metaDescription() == null || c.metaDescription().isBlank() ? null : c.metaDescription().trim(),
c.hideHeader(), c.blocks() == null ? List.of() : c.blocks());
}
private void goLive(CmsPage row, CmsPageDraft c) {
row.setSlug(c.slug());
row.setTitle(c.title());
row.setMetaDescription(c.metaDescription());
row.setHideHeader(c.hideHeader());
row.setBlocks(writeJson(c.blocks()));
row.setDraft(null);
}
private CmsPageDto store(CmsPage row, String user) {
row.setUpdatedBy(user);
row.setUpdatedAt(LocalDateTime.now());
try {
return toDto(pages.saveAndFlush(row), true);
return toDto(pages.saveAndFlush(row), true, true);
} catch (DataIntegrityViolationException e) {
throw slugTaken();
}
}
private CmsPage load(long id) {
return pages.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "PagesNotFound"));
}
public CmsPageDto findById(long id) {
return pages.findById(id).map(p -> toDto(p, true))
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "PagesNotFound"));
return toDto(load(id), true, true);
}
/** Newest update first; rows carry no blocks. */
@@ -90,7 +132,7 @@ public class CmsPageService {
String key = searchKey == null || searchKey.isBlank() ? null : "%" + searchKey.trim().toLowerCase(Locale.ROOT) + "%";
PageRequest request = PageRequest.of(Math.max(page, 0), size >= 1 ? Math.min(size, 100) : 20,
Sort.by(Sort.Order.desc("updatedAt"), Sort.Order.desc("id")));
return pages.search(companyId, key, request).map(p -> toDto(p, false));
return pages.search(companyId, key, request).map(p -> toDto(p, false, true));
}
public void delete(long id) {
@@ -101,21 +143,32 @@ public class CmsPageService {
public Optional<CmsPageDto> findPublished(long companyId, String slug) {
return pages.findByCompanyIdAndSlug(companyId, slug.toLowerCase(Locale.ROOT))
.filter(p -> "PUBLISHED".equals(p.getStatus()))
.map(p -> toDto(p, true));
.map(p -> toDto(p, true, false));
}
private static ResponseStatusException slugTaken() {
return new ResponseStatusException(HttpStatus.CONFLICT, "slug|PagesSlugTaken");
}
private CmsPageDto toDto(CmsPage p, boolean withBlocks) {
/** admin: the caller may see the draft (full read) or whether one exists (list row); visitors see neither. */
private CmsPageDto toDto(CmsPage p, boolean withBlocks, boolean admin) {
boolean hasDraft = admin && p.getDraft() != null;
return new CmsPageDto(p.getId(), p.getCompanyId(), p.getSlug(), p.getTitle(), p.getMetaDescription(), p.getStatus(),
p.isHideHeader(), withBlocks ? read(p.getBlocks()) : null, p.getUpdatedAt());
p.isHideHeader(), withBlocks ? read(p.getBlocks()) : null, p.getUpdatedAt(),
hasDraft && withBlocks ? readDraft(p.getDraft()) : null, hasDraft);
}
private String write(List<CmsBlock> blocks) {
private CmsPageDraft readDraft(String draft) {
try {
return json.writeValueAsString(blocks);
return json.readValue(draft, CmsPageDraft.class);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unreadable page draft", e);
}
}
private String writeJson(Object value) {
try {
return json.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
}
@@ -0,0 +1,194 @@
package com.solvway.services.counter.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.services.counter.dto.CmsBlock;
import com.solvway.services.counter.dto.CmsPageDto;
import com.solvway.services.counter.model.CmsPage;
import com.solvway.services.counter.repo.CmsPageRepository;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.PageImageRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.PageImpl;
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.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** add-page-drafts-and-templates: a published page's edits stay a draft until Publish; Discard drops them. */
@ExtendWith(MockitoExtension.class)
class CmsPageDraftTest {
private static final long INS = 1L;
@Mock private CmsPageRepository pages;
@Mock private PageImageRepository images;
@Mock private EventRepository events;
private CmsPageService service;
private CmsPage stored;
@BeforeEach
void setUp() {
service = new CmsPageService(pages, images, events, new ObjectMapper());
lenient().when(pages.saveAndFlush(any())).thenAnswer(i -> i.getArgument(0));
stored = new CmsPage();
stored.setId(12L);
stored.setCompanyId(INS);
stored.setSlug("hotel");
stored.setTitle("Hotel day");
stored.setStatus("PUBLISHED");
stored.setBlocks("[{\"type\":\"CTA\",\"heading\":\"Hotel day\",\"buttonLabel\":\"Go\",\"buttonUrl\":\"#signup\"}]");
lenient().when(pages.findById(12L)).thenReturn(Optional.of(stored));
}
private static CmsBlock cta(String heading) {
CmsBlock b = new CmsBlock();
b.setType("CTA");
b.setHeading(heading);
b.setButtonLabel("Go");
b.setButtonUrl("#signup");
return b;
}
private static CmsPageDto edit(String status, String slug, String heading) {
return new CmsPageDto(12L, INS, slug, "Hotel week", "New description", status, true, List.of(cta(heading)), null);
}
private CmsPage saved() {
ArgumentCaptor<CmsPage> row = ArgumentCaptor.forClass(CmsPage.class);
verify(pages).saveAndFlush(row.capture());
return row.getValue();
}
@Test
void savingAPublishedPageStoresADraftAndLeavesWhatVisitorsSee() {
CmsPageDto dto = service.save(edit("PUBLISHED", "hotel-week", "Hotel week"), "staff1");
CmsPage row = saved();
assertThat(row.getTitle()).isEqualTo("Hotel day");
assertThat(row.getSlug()).isEqualTo("hotel");
assertThat(row.getBlocks()).contains("Hotel day").doesNotContain("Hotel week");
assertThat(row.getDraft()).contains("Hotel week").contains("hotel-week").contains("New description");
assertThat(row.getUpdatedBy()).isEqualTo("staff1");
assertThat(dto.title()).isEqualTo("Hotel day");
assertThat(dto.draft().title()).isEqualTo("Hotel week");
assertThat(dto.draft().slug()).isEqualTo("hotel-week");
assertThat(dto.draft().hideHeader()).isTrue();
assertThat(dto.draft().blocks()).extracting(CmsBlock::getHeading).containsExactly("Hotel week");
assertThat(dto.hasDraft()).isTrue();
}
@Test
void aDraftIsCheckedLikeAnySave() {
CmsBlock bad = cta("x");
bad.setButtonUrl("javascript:alert(1)");
assertThatThrownBy(() -> service.save(new CmsPageDto(12L, INS, "hotel", "T", null, "PUBLISHED", false, List.of(bad), null), "staff1"))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("blocks[0].buttonUrl|PagesBadLink"));
when(pages.existsByCompanyIdAndSlugAndIdNot(INS, "launch", 12L)).thenReturn(true);
assertThatThrownBy(() -> service.save(edit("PUBLISHED", "launch", "x"), "staff1"))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("slug|PagesSlugTaken"));
verify(pages, never()).saveAndFlush(any());
}
@Test
void unpublishingWritesThePageAndDropsTheDraft() {
stored.setDraft("{\"slug\":\"x\",\"title\":\"Old draft\",\"hideHeader\":false,\"blocks\":[]}");
service.save(edit("DRAFT", "hotel", "Hotel week"), "staff1");
CmsPage row = saved();
assertThat(row.getStatus()).isEqualTo("DRAFT");
assertThat(row.getTitle()).isEqualTo("Hotel week");
assertThat(row.getDraft()).isNull();
}
@Test
void aPageNeverPublishedSavesDirectly() {
stored.setStatus("DRAFT");
service.save(edit("DRAFT", "hotel", "Hotel week"), "staff1");
CmsPage row = saved();
assertThat(row.getTitle()).isEqualTo("Hotel week");
assertThat(row.getDraft()).isNull();
}
@Test
void publishMakesTheDraftLiveAfterCheckingItAgain() {
service.save(edit("PUBLISHED", "hotel-week", "Hotel week"), "staff1");
CmsPageDto live = service.publish(12L, "staff2");
ArgumentCaptor<CmsPage> rows = ArgumentCaptor.forClass(CmsPage.class);
verify(pages, org.mockito.Mockito.times(2)).saveAndFlush(rows.capture());
CmsPage row = rows.getAllValues().get(1);
assertThat(row.getTitle()).isEqualTo("Hotel week");
assertThat(row.getSlug()).isEqualTo("hotel-week");
assertThat(row.getMetaDescription()).isEqualTo("New description");
assertThat(row.isHideHeader()).isTrue();
assertThat(row.getBlocks()).contains("Hotel week");
assertThat(row.getDraft()).isNull();
assertThat(row.getStatus()).isEqualTo("PUBLISHED");
assertThat(row.getUpdatedBy()).isEqualTo("staff2");
assertThat(live.hasDraft()).isFalse();
assertThat(live.draft()).isNull();
}
@Test
void publishRefusesADraftThatNoLongerPassesAndChangesNothing() {
stored.setDraft("{\"slug\":\"launch\",\"title\":\"T\",\"hideHeader\":false,\"blocks\":[]}");
when(pages.existsByCompanyIdAndSlugAndIdNot(INS, "launch", 12L)).thenReturn(true);
assertThatThrownBy(() -> service.publish(12L, "staff1"))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("slug|PagesSlugTaken"));
stored.setDraft("{\"slug\":\"hotel\",\"title\":\"T\",\"hideHeader\":false,\"blocks\":[{\"type\":\"FORM\",\"eventUuid\":\"55\"}]}");
assertThatThrownBy(() -> service.publish(12L, "staff1"))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("blocks[0].eventUuid|PagesBadEvent"));
verify(pages, never()).saveAndFlush(any());
assertThat(stored.getTitle()).isEqualTo("Hotel day");
}
@Test
void publishWithoutADraftChangesNothing() {
CmsPageDto dto = service.publish(12L, "staff1");
assertThat(dto.title()).isEqualTo("Hotel day");
verify(pages, never()).saveAndFlush(any());
}
@Test
void discardDropsTheDraft() {
stored.setDraft("{\"slug\":\"hotel\",\"title\":\"T\",\"hideHeader\":false,\"blocks\":[]}");
CmsPageDto dto = service.discard(12L);
assertThat(saved().getDraft()).isNull();
assertThat(dto.title()).isEqualTo("Hotel day");
assertThat(dto.hasDraft()).isFalse();
}
@Test
void listRowsSayWhetherAPageHasADraftAndVisitorsNeverSeeIt() {
stored.setDraft("{\"slug\":\"hotel\",\"title\":\"Secret\",\"hideHeader\":false,\"blocks\":[]}");
when(pages.search(eq(INS), any(), any())).thenReturn(new PageImpl<>(List.of(stored)));
CmsPageDto row = service.search(INS, null, 0, 20).getContent().get(0);
assertThat(row.hasDraft()).isTrue();
assertThat(row.draft()).isNull();
when(pages.findByCompanyIdAndSlug(INS, "hotel")).thenReturn(Optional.of(stored));
CmsPageDto visitor = service.findPublished(INS, "hotel").orElseThrow();
assertThat(visitor.title()).isEqualTo("Hotel day");
assertThat(visitor.draft()).isNull();
}
@Test
void publishAndDiscardOfAMissingPageAreNotFound() {
when(pages.findById(anyLong())).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.publish(99L, "staff1")).isInstanceOf(ResponseStatusException.class).hasMessageContaining("404");
assertThatThrownBy(() -> service.discard(99L)).isInstanceOf(ResponseStatusException.class).hasMessageContaining("404");
}
}