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

@@ -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);
}