feat(pages): landing pages, page images and web sign-ups in services-counter

Pages and block rules are ported from babyboo's CMS, scoped per company.
Images are checked by their magic bytes. A WEB registration keeps its
page address and UTM tags and never counts as attended.

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 15:41:30 +08:00
1 parent 9741707156
commit b164110367
21 files changed
+1116 -13

No files matched your search

+3 -3
View File
@@ -23,15 +23,15 @@ Verify commands:
## 2. services-counter ## 2. services-counter
- [ ] 2.1 Page model, validation and endpoints: - [x] 2.1 Page model, validation and endpoints:
- save, which replaces the blocks; - save, which replaces the blocks;
- find by id within a company, list within a company with search, delete; - find by id within a company, list within a company with search, delete;
- find a published page by company and slug, ignoring case. - find a published page by company and slug, ignoring case.
- Port babyboo's field, block, link and limit rules, plus the script checks and the company checks on images and FORM events. - Port babyboo's field, block, link and limit rules, plus the script checks and the company checks on images and FORM events.
- [ ] 2.2 Page images: - [x] 2.2 Page images:
- upload (magic-byte check, 2 MB limit, company); - upload (magic-byte check, 2 MB limit, company);
- read by id, returning the bytes and the content type. - read by id, returning the bytes and the content type.
- [ ] 2.3 Registration: - [x] 2.3 Registration:
- source `WEB` with `pagePath` and the UTM values, each cut to 100 characters; - source `WEB` with `pagePath` and the UTM values, each cut to 100 characters;
- a WEB registration never sets the attended time; - a WEB registration never sets the attended time;
- its notes say "Registered by web page with: …". - its notes say "Registered by web page with: …".
@@ -0,0 +1,71 @@
package com.solvway.services.counter.controller;
import com.solvway.services.counter.dto.CmsPageDto;
import com.solvway.services.counter.dto.CmsPageRequests;
import com.solvway.services.counter.model.PageImage;
import com.solvway.services.counter.service.CmsPageService;
import com.solvway.services.counter.service.PageImageService;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.time.Duration;
import java.util.Map;
/** Landing pages and their images. mobile-api owns the module and company checks; visitor reads go through findPublished and the image read. */
@RestController
@RequestMapping("/counter")
@AllArgsConstructor
public class CmsPageController {
private final CmsPageService pages;
private final PageImageService images;
@PostMapping("/cmsPage/save")
public CmsPageDto save(@RequestBody CmsPageRequests.Save req) {
return pages.save(req.page(), req.user());
}
@GetMapping("/cmsPage/findById/{id}")
public CmsPageDto findById(@PathVariable("id") long id) {
return pages.findById(id);
}
@PostMapping("/cmsPage/search")
public Page<CmsPageDto> search(@RequestBody CmsPageRequests.Search req) {
return pages.search(req.companyId(), req.searchKey(), req.page(), req.size());
}
@PostMapping("/cmsPage/delete")
public void delete(@RequestBody Long id) {
pages.delete(id);
}
@GetMapping("/cmsPage/findPublished/{companyId}/{slug}")
public CmsPageDto findPublished(@PathVariable("companyId") long companyId, @PathVariable("slug") String slug) {
return pages.findPublished(companyId, slug).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "PagesNotFound"));
}
@PostMapping("/pageImage/upload")
public Map<String, Long> upload(@RequestBody CmsPageRequests.ImageUpload req) {
return Map.of("id", images.upload(req.companyId(), req.data(), req.user()));
}
/** Image ids are not secret: public pages show them to anyone. */
@GetMapping("/pageImage/{id}")
public ResponseEntity<byte[]> image(@PathVariable("id") long id) {
PageImage image = images.find(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "PagesNotFound"));
return ResponseEntity.ok().contentType(MediaType.parseMediaType(image.getContentType()))
.cacheControl(CacheControl.maxAge(Duration.ofDays(365)).cachePublic().immutable())
.body(image.getBytes());
}
@GetMapping("/pageImage/findCompany/{id}")
public Long imageCompany(@PathVariable("id") long id) {
return images.companyOf(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "PagesNotFound"));
}
}
@@ -0,0 +1,28 @@
package com.solvway.services.counter.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* One landing-page block. Which fields apply depends on {@code type}:
* HERO (imageId, heading, text, button), RICH_TEXT (html), IMAGE_TEXT (imageId, imagePosition, heading, html, button),
* FAQ (heading, items), FORM (heading, eventUuid).
*/
@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CmsBlock {
private String type;
private Long imageId;
private String heading;
private String text;
private String html;
private String imagePosition;
private String buttonLabel;
private String buttonUrl;
private List<CmsFaqItem> items;
private Long eventUuid;
}
@@ -0,0 +1,4 @@
package com.solvway.services.counter.dto;
/** One FAQ question and its plain-text answer. */
public record CmsFaqItem(String question, String answer) {}
@@ -0,0 +1,8 @@
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. */
public record CmsPageDto(Long id, Long companyId, String slug, String title, String metaDescription, String status,
List<CmsBlock> blocks, LocalDateTime updatedAt) {}
@@ -0,0 +1,14 @@
package com.solvway.services.counter.dto;
/** Request bodies for the landing-page endpoints. */
public final class CmsPageRequests {
private CmsPageRequests() {
}
public record Save(CmsPageDto page, String user) {}
/** companyId null searches every company (super admin). */
public record Search(Long companyId, String searchKey, int page, int size) {}
public record ImageUpload(Long companyId, String data, String user) {}
}
@@ -24,5 +24,9 @@ public record EventLeadDetail(
List<Long> interestIds, List<Long> interestIds,
Long companyId, Long companyId,
LocalDateTime attendedAt, LocalDateTime attendedAt,
String source String source,
String pagePath,
String utmSource,
String utmMedium,
String utmCampaign
) {} ) {}
@@ -0,0 +1,29 @@
package com.solvway.services.counter.model;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
@Getter
@Setter
@Entity
@Table(name = "cms_page")
public class CmsPage {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long companyId;
private String slug;
private String title;
private String metaDescription;
private String status = "DRAFT";
/** JSON array of blocks, replaced as a whole on every save. */
@Column(columnDefinition = "json")
private String blocks;
private String createdBy;
private LocalDateTime createdAt = LocalDateTime.now();
private String updatedBy;
private LocalDateTime updatedAt;
}
@@ -51,6 +51,12 @@ public class EventLead {
/** STAFF (captured in the portal) or QR (self-registered). */ /** STAFF (captured in the portal) or QR (self-registered). */
private String source = "STAFF"; private String source = "STAFF";
/** Web page sign-ups only: the landing page's public address and the visitor's UTM tags. */
private String pagePath;
private String utmSource;
private String utmMedium;
private String utmCampaign;
private LocalDateTime consentAt; private LocalDateTime consentAt;
private Long consentNoticeId; private Long consentNoticeId;
@@ -0,0 +1,24 @@
package com.solvway.services.counter.model;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
@Getter
@Setter
@Entity
@Table(name = "page_image")
public class PageImage {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long companyId;
private String contentType;
@Lob
@Column(columnDefinition = "mediumblob")
private byte[] bytes;
private String createdBy;
private LocalDateTime createdAt = LocalDateTime.now();
}
@@ -0,0 +1,21 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.model.CmsPage;
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.Query;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface CmsPageRepository extends JpaRepository<CmsPage, Long> {
boolean existsByCompanyIdAndSlugAndIdNot(Long companyId, String slug, Long id);
Optional<CmsPage> findByCompanyIdAndSlug(Long companyId, String slug);
/** companyId null lists every company (super admin); key null lists every page. */
@Query("select p from CmsPage p where (:companyId is null or p.companyId = :companyId)"
+ " and (:key is null or lower(p.title) like :key or p.slug like :key)")
Page<CmsPage> search(@Param("companyId") Long companyId, @Param("key") String key, Pageable pageable);
}
@@ -0,0 +1,14 @@
package com.solvway.services.counter.repo;
import com.solvway.services.counter.model.PageImage;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface PageImageRepository extends JpaRepository<PageImage, Long> {
/** The owning company without loading the bytes. */
@Query("select i.companyId from PageImage i where i.id = :id")
Optional<Long> findCompanyIdById(@Param("id") Long id);
}
@@ -0,0 +1,141 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.dto.CmsBlock;
import com.solvway.services.counter.dto.CmsFaqItem;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.function.LongPredicate;
import java.util.regex.Pattern;
/**
* Landing-page block rules, ported from babyboo's CmsBlockValidator (specs/cms-pages) without the product blocks.
* Co-Lite changes: images are uploaded ids of the page's company, FORM points at an event of that company,
* buttons may also use mailto: and tel:, and HTML holding scripts is refused (the public page sanitises as well).
* Throws 422 on the first violation, with the reason "path|MessageCode".
*/
public final class CmsBlockValidator {
private static final int MAX_BLOCKS = 30;
private static final Pattern SCRIPT = Pattern.compile("(?i)<\\s*script|\\son[a-z]+\\s*=|javascript\\s*:");
private CmsBlockValidator() {
}
public static void validate(List<CmsBlock> blocks, LongPredicate ownImage, LongPredicate ownEvent) {
if (blocks == null || blocks.isEmpty()) {
return;
}
if (blocks.size() > MAX_BLOCKS) {
throw refuse("blocks", "PagesTooManyBlocks");
}
for (int i = 0; i < blocks.size(); i++) {
CmsBlock b = blocks.get(i);
String path = "blocks[" + i + "]";
if (b == null || b.getType() == null) {
throw refuse(path + ".type", "PagesUnknownType");
}
switch (b.getType()) {
case "HERO" -> {
image(b, path, ownImage);
required(b.getHeading(), path + ".heading");
max(b.getHeading(), path + ".heading", 120);
max(b.getText(), path + ".text", 300);
button(b, path);
}
case "RICH_TEXT" -> html(b.getHtml(), path + ".html");
case "IMAGE_TEXT" -> {
image(b, path, ownImage);
max(b.getHeading(), path + ".heading", 120);
if (!"LEFT".equals(b.getImagePosition()) && !"RIGHT".equals(b.getImagePosition())) {
throw refuse(path + ".imagePosition", "PagesBadImagePosition");
}
html(b.getHtml(), path + ".html");
button(b, path);
}
case "FAQ" -> faq(b, path);
case "FORM" -> {
max(b.getHeading(), path + ".heading", 120);
if (b.getEventUuid() == null || !ownEvent.test(b.getEventUuid())) {
throw refuse(path + ".eventUuid", "PagesBadEvent");
}
}
default -> throw refuse(path + ".type", "PagesUnknownType");
}
}
}
static ResponseStatusException refuse(String path, String code) {
return new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, path + "|" + code);
}
static void required(String value, String path) {
if (value == null || value.isBlank()) {
throw refuse(path, "PagesRequired");
}
}
static void max(String value, String path, int limit) {
if (value != null && value.length() > limit) {
throw refuse(path, "PagesTooLong");
}
}
private static void image(CmsBlock b, String path, LongPredicate ownImage) {
if (b.getImageId() == null || !ownImage.test(b.getImageId())) {
throw refuse(path + ".imageId", "PagesBadImage");
}
}
private static void html(String value, String path) {
required(value, path);
max(value, path, 100_000);
if (SCRIPT.matcher(value).find()) {
throw refuse(path, "PagesScript");
}
}
private static void faq(CmsBlock b, String path) {
max(b.getHeading(), path + ".heading", 120);
List<CmsFaqItem> items = b.getItems();
if (items == null || items.isEmpty() || items.size() > 30) {
throw refuse(path + ".items", "PagesFaqCount");
}
for (int i = 0; i < items.size(); i++) {
CmsFaqItem item = items.get(i);
String itemPath = path + ".items[" + i + "]";
required(item == null ? null : item.question(), itemPath + ".question");
max(item.question(), itemPath + ".question", 300);
required(item.answer(), itemPath + ".answer");
max(item.answer(), itemPath + ".answer", 2000);
}
}
private static void button(CmsBlock b, String path) {
boolean hasLabel = b.getButtonLabel() != null && !b.getButtonLabel().isBlank();
boolean hasUrl = b.getButtonUrl() != null && !b.getButtonUrl().isBlank();
if (hasLabel != hasUrl) {
throw refuse(path + (hasLabel ? ".buttonUrl" : ".buttonLabel"), "PagesButtonPair");
}
if (hasLabel) {
max(b.getButtonLabel(), path + ".buttonLabel", 40);
if (!safeLink(b.getButtonUrl())) {
throw refuse(path + ".buttonUrl", "PagesBadLink");
}
}
}
/**
* A same-site path, https, mailto or tel link, at most 1000 characters. Browsers turn "\" into "/" and drop
* whitespace inside URLs, so "/\evil" would become protocol-relative: such characters are refused outright.
*/
static boolean safeLink(String url) {
if (url.length() > 1000 || url.chars().anyMatch(c -> c == '\\' || c <= 0x20 || c == 0x7f || Character.isSpaceChar(c) || c == 0xFEFF)) {
return false;
}
if (url.startsWith("//")) {
return false;
}
return url.startsWith("/") || url.startsWith("https://") || url.startsWith("mailto:") || url.startsWith("tel:");
}
}
@@ -0,0 +1,133 @@
package com.solvway.services.counter.service;
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.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 lombok.AllArgsConstructor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.regex.Pattern;
/** Landing pages, ported from babyboo's CmsPageService (specs/cms-pages) and scoped per company. Reasons are "path|MessageCode". */
@Service
@AllArgsConstructor
public class CmsPageService {
private static final Pattern SLUG = Pattern.compile("^[a-z0-9]+(-[a-z0-9]+)*$");
private static final TypeReference<List<CmsBlock>> BLOCKS = new TypeReference<>() {};
private final CmsPageRepository pages;
private final PageImageRepository images;
private final EventRepository events;
private final ObjectMapper json;
public CmsPageDto save(CmsPageDto dto, String user) {
CmsPage row;
if (dto.id() == null) {
if (dto.companyId() == null) {
throw CmsBlockValidator.refuse("companyId", "PagesRequired");
}
row = new CmsPage();
row.setCompanyId(dto.companyId());
row.setCreatedBy(user);
} else {
row = pages.findById(dto.id()).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "PagesNotFound"));
}
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),
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())) {
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.setBlocks(write(dto.blocks() == null ? List.of() : dto.blocks()));
row.setUpdatedBy(user);
row.setUpdatedAt(LocalDateTime.now());
try {
return toDto(pages.saveAndFlush(row), true);
} catch (DataIntegrityViolationException e) {
throw slugTaken();
}
}
public CmsPageDto findById(long id) {
return pages.findById(id).map(p -> toDto(p, true))
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "PagesNotFound"));
}
/** Newest update first; rows carry no blocks. */
public Page<CmsPageDto> search(Long companyId, String searchKey, int page, int size) {
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));
}
public void delete(long id) {
pages.deleteById(id);
}
/** A visitor's read: only published pages, the slug matched ignoring case. */
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));
}
private static ResponseStatusException slugTaken() {
return new ResponseStatusException(HttpStatus.CONFLICT, "slug|PagesSlugTaken");
}
private CmsPageDto toDto(CmsPage p, boolean withBlocks) {
return new CmsPageDto(p.getId(), p.getCompanyId(), p.getSlug(), p.getTitle(), p.getMetaDescription(), p.getStatus(),
withBlocks ? read(p.getBlocks()) : null, p.getUpdatedAt());
}
private String write(List<CmsBlock> blocks) {
try {
return json.writeValueAsString(blocks);
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
}
}
private List<CmsBlock> read(String blocks) {
if (blocks == null || blocks.isBlank()) {
return List.of();
}
try {
return json.readValue(blocks, BLOCKS);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unreadable page blocks", e);
}
}
}
@@ -255,7 +255,7 @@ public class EventLeadService {
return new EventLeadDetail(e.getUuid(), e.getEventUuid(), l.getUuid(), l.getName(), l.getMobileE164(), return new EventLeadDetail(e.getUuid(), e.getEventUuid(), l.getUuid(), l.getName(), l.getMobileE164(),
l.getEmailNormalised(), l.getCompanyName(), l.getJobTitle(), e.getLeadType(), e.getSalespersonUserId(), l.getEmailNormalised(), l.getCompanyName(), l.getJobTitle(), e.getLeadType(), e.getSalespersonUserId(),
e.getTemperature(), e.getStatus(), e.getNextFollowUpDate(), e.getNotes(), e.getCapturedAt(), interestIds, e.getCompanyId(), e.getTemperature(), e.getStatus(), e.getNextFollowUpDate(), e.getNotes(), e.getCapturedAt(), interestIds, e.getCompanyId(),
e.getAttendedAt(), e.getSource()); e.getAttendedAt(), e.getSource(), e.getPagePath(), e.getUtmSource(), e.getUtmMedium(), e.getUtmCampaign());
} }
private static void fillBlank(String current, String offered, Consumer<String> setter) { private static void fillBlank(String current, String offered, Consumer<String> setter) {
@@ -0,0 +1,74 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.PageImage;
import com.solvway.services.counter.repo.PageImageRepository;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.Base64;
import java.util.Optional;
/**
* Landing-page images, kept in MySQL. ponytail: fine for a few hundred images; move the bytes to object storage past that.
* The type comes from the magic bytes, never from the file name.
*/
@Service
@AllArgsConstructor
public class PageImageService {
static final int MAX_BYTES = 2 * 1024 * 1024;
private final PageImageRepository repository;
public long upload(Long companyId, String base64, String user) {
if (companyId == null) {
throw bad("companyId|PagesRequired");
}
byte[] bytes;
try {
bytes = Base64.getDecoder().decode(base64 == null ? "" : base64);
} catch (IllegalArgumentException e) {
throw bad("file|PagesBadImageType");
}
if (bytes.length > MAX_BYTES) {
throw bad("file|PagesImageTooLarge");
}
String type = typeOf(bytes);
if (type == null) {
throw bad("file|PagesBadImageType");
}
PageImage image = new PageImage();
image.setCompanyId(companyId);
image.setContentType(type);
image.setBytes(bytes);
image.setCreatedBy(user);
return repository.save(image).getId();
}
public Optional<PageImage> find(long id) {
return repository.findById(id);
}
public Optional<Long> companyOf(long id) {
return repository.findCompanyIdById(id);
}
static String typeOf(byte[] b) {
if (b.length >= 8 && (b[0] & 0xFF) == 0x89 && b[1] == 'P' && b[2] == 'N' && b[3] == 'G'
&& b[4] == 0x0D && b[5] == 0x0A && b[6] == 0x1A && b[7] == 0x0A) {
return "image/png";
}
if (b.length >= 3 && (b[0] & 0xFF) == 0xFF && (b[1] & 0xFF) == 0xD8 && (b[2] & 0xFF) == 0xFF) {
return "image/jpeg";
}
if (b.length >= 12 && b[0] == 'R' && b[1] == 'I' && b[2] == 'F' && b[3] == 'F'
&& b[8] == 'W' && b[9] == 'E' && b[10] == 'B' && b[11] == 'P') {
return "image/webp";
}
return null;
}
private static ResponseStatusException bad(String reason) {
return new ResponseStatusException(HttpStatus.BAD_REQUEST, reason);
}
}
@@ -25,24 +25,33 @@ public class RegistrationService {
public record RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164, public record RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164,
String email, String companyName, String jobTitle, List<Long> interestIds, String email, String companyName, String jobTitle, List<Long> interestIds,
Long consentNoticeId, LocalDateTime consentAt, boolean attend, Long consentNoticeId, LocalDateTime consentAt, boolean attend,
String source, Long guestId) { String source, Long guestId,
/** source null means QR; guestId, when set, is the invited guest this registration links to. */ String pagePath, String utmSource, String utmMedium, String utmCampaign) {
/** source null means QR; guestId, when set, is the invited guest this registration links to. pagePath and utm* come with source WEB. */
public RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164,
String email, String companyName, String jobTitle, List<Long> interestIds,
Long consentNoticeId, LocalDateTime consentAt, boolean attend, String source, Long guestId) {
this(companyId, eventUuid, salespersonUserId, name, mobileE164, email, companyName, jobTitle, interestIds,
consentNoticeId, consentAt, attend, source, guestId, null, null, null, null);
}
public RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164, public RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164,
String email, String companyName, String jobTitle, List<Long> interestIds, String email, String companyName, String jobTitle, List<Long> interestIds,
Long consentNoticeId, LocalDateTime consentAt, boolean attend) { Long consentNoticeId, LocalDateTime consentAt, boolean attend) {
this(companyId, eventUuid, salespersonUserId, name, mobileE164, email, companyName, jobTitle, interestIds, this(companyId, eventUuid, salespersonUserId, name, mobileE164, email, companyName, jobTitle, interestIds,
consentNoticeId, consentAt, attend, null, null); consentNoticeId, consentAt, attend, null, null, null, null, null, null);
} }
public RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164, public RegisterRequest(Long companyId, long eventUuid, Long salespersonUserId, String name, String mobileE164,
String email, String companyName, String jobTitle, List<Long> interestIds, String email, String companyName, String jobTitle, List<Long> interestIds,
Long consentNoticeId, LocalDateTime consentAt) { Long consentNoticeId, LocalDateTime consentAt) {
this(companyId, eventUuid, salespersonUserId, name, mobileE164, email, companyName, jobTitle, interestIds, this(companyId, eventUuid, salespersonUserId, name, mobileE164, email, companyName, jobTitle, interestIds,
consentNoticeId, consentAt, false, null, null); consentNoticeId, consentAt, false, null, null, null, null, null, null);
} }
} }
public record RegisterResult(String outcome, String eventLeadUuid) {} public record RegisterResult(String outcome, String eventLeadUuid) {}
private static final String QR = "qr"; private static final String QR = "qr";
private static final String WEB = "WEB";
private static final int UTM_MAX = 100;
private final TransactionTemplate transactionTemplate; private final TransactionTemplate transactionTemplate;
private final LeadRepository leadRepository; private final LeadRepository leadRepository;
@@ -96,7 +105,7 @@ public class RegistrationService {
lead = match.get(); lead = match.get();
Optional<EventLead> captured = eventLeadRepository.findByEventUuidAndLeadUuid(req.eventUuid(), lead.getUuid()); Optional<EventLead> captured = eventLeadRepository.findByEventUuidAndLeadUuid(req.eventUuid(), lead.getUuid());
if (captured.isPresent()) return alreadyCaptured(captured.get(), lead, req); if (captured.isPresent()) return alreadyCaptured(captured.get(), lead, req);
notes = differences(lead, req); notes = differences(lead, req, WEB.equals(req.source()) ? "web page" : "QR");
leadType = "EXISTING"; leadType = "EXISTING";
} }
@@ -112,8 +121,13 @@ public class RegistrationService {
e.setCapturedBy(QR); e.setCapturedBy(QR);
e.setConsentAt(req.consentAt()); e.setConsentAt(req.consentAt());
e.setConsentNoticeId(req.consentNoticeId()); e.setConsentNoticeId(req.consentNoticeId());
e.setPagePath(req.pagePath());
e.setUtmSource(cut(req.utmSource()));
e.setUtmMedium(cut(req.utmMedium()));
e.setUtmCampaign(cut(req.utmCampaign()));
// An invite link can be opened anywhere, so an invite registration never counts as attending; the guest checks in. // An invite link can be opened anywhere, so an invite registration never counts as attending; the guest checks in.
boolean atVenue = !"INVITE".equals(req.source()) && eventLeadService.isDuringEvent(req.eventUuid()); // A web page sign-up neither: a standing enquiries event is always running.
boolean atVenue = !"INVITE".equals(req.source()) && !WEB.equals(req.source()) && eventLeadService.isDuringEvent(req.eventUuid());
if (req.attend() || atVenue) e.setAttendedAt(LocalDateTime.now()); if (req.attend() || atVenue) e.setAttendedAt(LocalDateTime.now());
e = eventLeadRepository.saveAndFlush(e); e = eventLeadRepository.saveAndFlush(e);
eventLeadService.recordStatusChange(e, null, "OPEN", e.getCapturedAt(), QR); eventLeadService.recordStatusChange(e, null, "OPEN", e.getCapturedAt(), QR);
@@ -145,14 +159,18 @@ public class RegistrationService {
} }
/** Submitted non-blank values that differ from the lead's, as an event-lead note; null when nothing differs. */ /** Submitted non-blank values that differ from the lead's, as an event-lead note; null when nothing differs. */
private static String differences(Lead lead, RegisterRequest req) { private static String cut(String value) {
return value == null || value.isBlank() ? null : value.length() > UTM_MAX ? value.substring(0, UTM_MAX) : value;
}
private static String differences(Lead lead, RegisterRequest req, String channel) {
List<String> parts = new ArrayList<>(); List<String> parts = new ArrayList<>();
diff(parts, "name", req.name(), lead.getName()); diff(parts, "name", req.name(), lead.getName());
diff(parts, "mobile", req.mobileE164(), lead.getMobileE164()); diff(parts, "mobile", req.mobileE164(), lead.getMobileE164());
diff(parts, "email", req.email(), lead.getEmailNormalised()); diff(parts, "email", req.email(), lead.getEmailNormalised());
diff(parts, "company", req.companyName(), lead.getCompanyName()); diff(parts, "company", req.companyName(), lead.getCompanyName());
diff(parts, "job title", req.jobTitle(), lead.getJobTitle()); diff(parts, "job title", req.jobTitle(), lead.getJobTitle());
return parts.isEmpty() ? null : "Registered by QR with: " + String.join("; ", parts); return parts.isEmpty() ? null : "Registered by " + channel + " with: " + String.join("; ", parts);
} }
private static void diff(List<String> parts, String label, String submitted, String current) { private static void diff(List<String> parts, String label, String submitted, String current) {
@@ -0,0 +1,153 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.dto.CmsBlock;
import com.solvway.services.counter.dto.CmsFaqItem;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Block rules ported from babyboo CmsBlockValidator (specs/cms-pages), with Co-Lite's image ids, events, mail and phone links and script checks. */
class CmsBlockValidatorTest {
private static final long OWN_IMAGE = 5L;
private static final long OWN_EVENT = 900L;
private static void validate(List<CmsBlock> blocks) {
CmsBlockValidator.validate(blocks, id -> id == OWN_IMAGE, uuid -> uuid == OWN_EVENT);
}
private static void refused(List<CmsBlock> blocks, String path, String code) {
assertThatThrownBy(() -> validate(blocks))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY);
assertThat(e.getReason()).isEqualTo(path + "|" + code);
});
}
private static CmsBlock hero() {
CmsBlock b = new CmsBlock();
b.setType("HERO");
b.setImageId(OWN_IMAGE);
b.setHeading("Hotel technology that just works");
return b;
}
private static CmsBlock rich(String html) {
CmsBlock b = new CmsBlock();
b.setType("RICH_TEXT");
b.setHtml(html);
return b;
}
private static CmsBlock form(long eventUuid) {
CmsBlock b = new CmsBlock();
b.setType("FORM");
b.setEventUuid(eventUuid);
return b;
}
private static CmsBlock faq(int items) {
CmsBlock b = new CmsBlock();
b.setType("FAQ");
List<CmsFaqItem> list = new ArrayList<>();
for (int i = 0; i < items; i++) list.add(new CmsFaqItem("Q" + i, "A" + i));
b.setItems(list);
return b;
}
@Test
void aValidPageOfEveryTypePasses() {
CmsBlock imageText = hero();
imageText.setType("IMAGE_TEXT");
imageText.setImagePosition("LEFT");
imageText.setHtml("<p>Rooms</p>");
assertThatCode(() -> validate(List.of(hero(), rich("<p>Hi</p>"), imageText, faq(2), form(OWN_EVENT)))).doesNotThrowAnyException();
assertThatCode(() -> validate(List.of())).doesNotThrowAnyException();
}
@Test
void atMostThirtyBlocksOfKnownTypes() {
refused(Collections.nCopies(31, rich("<p>x</p>")), "blocks", "PagesTooManyBlocks");
CmsBlock odd = new CmsBlock();
odd.setType("FEATURED_PRODUCTS");
refused(List.of(odd), "blocks[0].type", "PagesUnknownType");
}
@Test
void requiredFieldsAndLengthLimits() {
CmsBlock noHeading = hero();
noHeading.setHeading(" ");
refused(List.of(noHeading), "blocks[0].heading", "PagesRequired");
CmsBlock longHeading = hero();
longHeading.setHeading("x".repeat(121));
refused(List.of(longHeading), "blocks[0].heading", "PagesTooLong");
CmsBlock longText = hero();
longText.setText("x".repeat(301));
refused(List.of(longText), "blocks[0].text", "PagesTooLong");
refused(List.of(rich("x".repeat(100_001))), "blocks[0].html", "PagesTooLong");
refused(List.of(rich("")), "blocks[0].html", "PagesRequired");
}
@Test
void faqHasOneToThirtyItemsWithinLimits() {
refused(List.of(faq(0)), "blocks[0].items", "PagesFaqCount");
refused(List.of(faq(31)), "blocks[0].items", "PagesFaqCount");
CmsBlock longAnswer = faq(1);
longAnswer.getItems().set(0, new CmsFaqItem("Q", "a".repeat(2001)));
refused(List.of(longAnswer), "blocks[0].items[0].answer", "PagesTooLong");
}
@Test
void imageTextNeedsLeftOrRight() {
CmsBlock b = hero();
b.setType("IMAGE_TEXT");
b.setHtml("<p>x</p>");
b.setImagePosition("TOP");
refused(List.of(b), "blocks[0].imagePosition", "PagesBadImagePosition");
}
@Test
void buttonsNeedBothLabelAndASafeLink() {
CmsBlock labelOnly = hero();
labelOnly.setButtonLabel("Talk to us");
refused(List.of(labelOnly), "blocks[0].buttonUrl", "PagesButtonPair");
for (String bad : List.of("javascript:alert(1)", "//evil.example", "http://plain.example", "/\\evil.example", "data:text/html,x")) {
CmsBlock b = hero();
b.setButtonLabel("Go");
b.setButtonUrl(bad);
refused(List.of(b), "blocks[0].buttonUrl", "PagesBadLink");
}
for (String good : List.of("/p/INS/contact", "https://ins.example/rooms", "mailto:sales@ins.example", "tel:+60312345678")) {
CmsBlock b = hero();
b.setButtonLabel("Go");
b.setButtonUrl(good);
assertThatCode(() -> validate(List.of(b))).as(good).doesNotThrowAnyException();
}
}
@Test
void htmlCannotCarryScripts() {
refused(List.of(rich("<p>x</p><script>alert(1)</script>")), "blocks[0].html", "PagesScript");
refused(List.of(rich("<img src=x onerror=alert(1)>")), "blocks[0].html", "PagesScript");
refused(List.of(rich("<a href=\"JavaScript:alert(1)\">x</a>")), "blocks[0].html", "PagesScript");
}
@Test
void imagesAndEventsMustBelongToThePagesCompany() {
CmsBlock foreignImage = hero();
foreignImage.setImageId(6L);
refused(List.of(foreignImage), "blocks[0].imageId", "PagesBadImage");
CmsBlock noImage = hero();
noImage.setImageId(null);
refused(List.of(noImage), "blocks[0].imageId", "PagesBadImage");
refused(List.of(form(901)), "blocks[0].eventUuid", "PagesBadEvent");
}
}
@@ -0,0 +1,161 @@
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.model.Event;
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.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.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Page rules ported from babyboo CmsPageService (specs/cms-pages), scoped per company. */
@ExtendWith(MockitoExtension.class)
class CmsPageServiceTest {
private static final long INS = 1L;
private static final long CV = 2L;
@Mock private CmsPageRepository pages;
@Mock private PageImageRepository images;
@Mock private EventRepository events;
private CmsPageService service;
@BeforeEach
void setUp() {
service = new CmsPageService(pages, images, events, new ObjectMapper());
lenient().when(pages.saveAndFlush(any())).thenAnswer(i -> {
CmsPage p = i.getArgument(0);
if (p.getId() == null) p.setId(77L);
return p;
});
}
private static CmsPageDto page(Long id, Long companyId, String slug, List<CmsBlock> blocks) {
return new CmsPageDto(id, companyId, slug, "Hotel technology", null, "DRAFT", blocks, null);
}
private static CmsBlock rich() {
CmsBlock b = new CmsBlock();
b.setType("RICH_TEXT");
b.setHtml("<p>Rooms</p>");
return b;
}
private void refused(CmsPageDto dto, HttpStatus status, String reason) {
assertThatThrownBy(() -> service.save(dto, "staff1"))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(status);
assertThat(e.getReason()).isEqualTo(reason);
});
verify(pages, never()).saveAndFlush(any());
}
@Test
void pageFieldsAreValidated() {
refused(page(null, INS, "Hotel_Tech", List.of()), HttpStatus.UNPROCESSABLE_ENTITY, "slug|PagesBadSlug");
refused(page(null, INS, "a".repeat(81), List.of()), HttpStatus.UNPROCESSABLE_ENTITY, "slug|PagesBadSlug");
refused(new CmsPageDto(null, INS, "ok", " ", null, "DRAFT", List.of(), null), HttpStatus.UNPROCESSABLE_ENTITY, "title|PagesRequired");
refused(new CmsPageDto(null, INS, "ok", "t".repeat(121), null, "DRAFT", List.of(), null), HttpStatus.UNPROCESSABLE_ENTITY, "title|PagesTooLong");
refused(new CmsPageDto(null, INS, "ok", "T", "m".repeat(161), "DRAFT", List.of(), null), HttpStatus.UNPROCESSABLE_ENTITY, "metaDescription|PagesTooLong");
refused(new CmsPageDto(null, INS, "ok", "T", null, "LIVE", List.of(), null), HttpStatus.UNPROCESSABLE_ENTITY, "status|PagesBadStatus");
refused(page(null, null, "ok", List.of()), HttpStatus.UNPROCESSABLE_ENTITY, "companyId|PagesRequired");
}
@Test
void aSlugIsUniqueWithinACompanyOnly() {
when(pages.existsByCompanyIdAndSlugAndIdNot(INS, "hotel-technology", -1L)).thenReturn(true);
refused(page(null, INS, "hotel-technology", List.of()), HttpStatus.CONFLICT, "slug|PagesSlugTaken");
when(pages.existsByCompanyIdAndSlugAndIdNot(CV, "hotel-technology", -1L)).thenReturn(false);
CmsPageDto saved = service.save(page(null, CV, "hotel-technology", List.of(rich())), "staff1");
assertThat(saved.id()).isEqualTo(77L);
assertThat(saved.companyId()).isEqualTo(CV);
}
@Test
void anUpdateKeepsTheStoredCompanyAndReplacesTheBlocks() {
CmsPage stored = new CmsPage();
stored.setId(12L);
stored.setCompanyId(INS);
stored.setSlug("about");
stored.setBlocks("[{\"type\":\"HERO\"},{\"type\":\"FAQ\"}]");
when(pages.findById(12L)).thenReturn(Optional.of(stored));
CmsPageDto saved = service.save(page(12L, CV, "about", List.of(rich())), "staff1");
ArgumentCaptor<CmsPage> row = ArgumentCaptor.forClass(CmsPage.class);
verify(pages).saveAndFlush(row.capture());
assertThat(row.getValue().getCompanyId()).isEqualTo(INS);
assertThat(row.getValue().getUpdatedBy()).isEqualTo("staff1");
assertThat(saved.blocks()).extracting(CmsBlock::getType).containsExactly("RICH_TEXT");
verify(pages).existsByCompanyIdAndSlugAndIdNot(INS, "about", 12L);
}
@Test
void blocksAreCheckedAgainstThePagesCompany() {
CmsBlock form = new CmsBlock();
form.setType("FORM");
form.setEventUuid(900L);
Event cvEvent = new Event();
cvEvent.setCompanyId(CV);
when(events.findByUuid(900L)).thenReturn(Optional.of(cvEvent));
refused(page(null, INS, "launch", List.of(form)), HttpStatus.UNPROCESSABLE_ENTITY, "blocks[0].eventUuid|PagesBadEvent");
CmsBlock hero = new CmsBlock();
hero.setType("HERO");
hero.setHeading("Hi");
hero.setImageId(5L);
when(images.findCompanyIdById(5L)).thenReturn(Optional.of(CV));
refused(page(null, INS, "launch", List.of(hero)), HttpStatus.UNPROCESSABLE_ENTITY, "blocks[0].imageId|PagesBadImage");
}
@Test
void blocksReadBackInTheirSavedOrder() {
CmsBlock faq = new CmsBlock();
faq.setType("FAQ");
faq.setItems(List.of(new com.solvway.services.counter.dto.CmsFaqItem("Q", "A")));
CmsPageDto saved = service.save(page(null, INS, "order", List.of(rich(), faq)), "staff1");
ArgumentCaptor<CmsPage> row = ArgumentCaptor.forClass(CmsPage.class);
verify(pages).saveAndFlush(row.capture());
when(pages.findById(77L)).thenReturn(Optional.of(row.getValue()));
assertThat(service.findById(77L).blocks()).extracting(CmsBlock::getType).containsExactly("RICH_TEXT", "FAQ");
assertThat(saved.blocks()).hasSize(2);
}
@Test
void onlyPublishedPagesAreFoundBySlugIgnoringCase() {
CmsPage draft = new CmsPage();
draft.setId(3L);
draft.setCompanyId(INS);
draft.setSlug("launch");
draft.setStatus("DRAFT");
draft.setBlocks("[]");
when(pages.findByCompanyIdAndSlug(INS, "launch")).thenReturn(Optional.of(draft));
assertThat(service.findPublished(INS, "LAUNCH")).isEmpty();
draft.setStatus("PUBLISHED");
assertThat(service.findPublished(INS, "Launch")).map(CmsPageDto::slug).contains("launch");
}
}
@@ -0,0 +1,76 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.PageImage;
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.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.util.Arrays;
import java.util.Base64;
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.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** Page images: the type comes from the file's magic bytes, never its name; at most 2 MB. */
@ExtendWith(MockitoExtension.class)
class PageImageServiceTest {
private static final byte[] PNG = {(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0};
private static final byte[] JPEG = {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0, 0, 0, 0, 0, 0, 0, 0, 0};
private static final byte[] WEBP = {'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'E', 'B', 'P'};
private static final byte[] PDF = {'%', 'P', 'D', 'F', '-', '1', '.', '7', 0, 0, 0, 0};
@Mock private PageImageRepository repository;
private PageImageService service;
@BeforeEach
void setUp() {
service = new PageImageService(repository);
lenient().when(repository.save(any())).thenAnswer(i -> {
PageImage p = i.getArgument(0);
p.setId(9L);
return p;
});
}
private static String b64(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
@Test
void storesPngJpegAndWebpWithTheirRealType() {
for (Object[] c : new Object[][]{{PNG, "image/png"}, {JPEG, "image/jpeg"}, {WEBP, "image/webp"}}) {
assertThat(service.upload(1L, b64((byte[]) c[0]), "staff1")).isEqualTo(9L);
}
ArgumentCaptor<PageImage> row = ArgumentCaptor.forClass(PageImage.class);
verify(repository, org.mockito.Mockito.times(3)).save(row.capture());
assertThat(row.getAllValues()).extracting(PageImage::getContentType).containsExactly("image/png", "image/jpeg", "image/webp");
assertThat(row.getAllValues()).allSatisfy(p -> assertThat(p.getCompanyId()).isEqualTo(1L));
}
@Test
void refusesOtherTypesTooLargeFilesAndNoCompany() {
refused(() -> service.upload(1L, b64(PDF), "staff1"), "file|PagesBadImageType");
refused(() -> service.upload(1L, "not base64!", "staff1"), "file|PagesBadImageType");
byte[] big = Arrays.copyOf(JPEG, 2 * 1024 * 1024 + 1);
refused(() -> service.upload(1L, b64(big), "staff1"), "file|PagesImageTooLarge");
refused(() -> service.upload(null, b64(PNG), "staff1"), "companyId|PagesRequired");
verify(repository, never()).save(any());
}
private static void refused(Runnable call, String reason) {
assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getReason()).isEqualTo(reason);
});
}
}
@@ -0,0 +1,124 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventGuestRepository;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Spec "Attendance at capture" and "The Form Block Registers For An Event": a landing-page sign-up is source WEB, never
* attended (a standing enquiries event is always running), and keeps its page address and UTM tags.
*/
class WebRegistrationTest {
private static final long EVENT = 1000L;
private final EventLeadRepository eventLeads = mock(EventLeadRepository.class);
private final LeadRepository leads = mock(LeadRepository.class);
private RegistrationService registration;
private EventLeadService eventLeadService;
@BeforeEach
void setUp() {
EventRepository events = mock(EventRepository.class);
Event today = new Event();
today.setDateStart(LocalDateTime.now().minusHours(1));
today.setDateEnd(LocalDateTime.now().plusDays(1));
when(events.findByUuid(EVENT)).thenReturn(Optional.of(today));
when(leads.saveAndFlush(any(Lead.class))).then(returnsFirstArg());
when(eventLeads.saveAndFlush(any(EventLead.class))).then(i -> {
EventLead e = i.getArgument(0);
e.setId(1L);
return e;
});
GuestLinker linker = new GuestLinker(mock(EventGuestRepository.class));
eventLeadService = new EventLeadService(leads, eventLeads, mock(EventLeadInterestRepository.class),
mock(EventLeadStatusChangeRepository.class), events, linker);
registration = new RegistrationService(new TransactionTemplate(mock(PlatformTransactionManager.class)),
leads, eventLeads, eventLeadService, linker);
}
private EventLead saved() {
ArgumentCaptor<EventLead> c = ArgumentCaptor.forClass(EventLead.class);
verify(eventLeads).saveAndFlush(c.capture());
return c.getValue();
}
private static RegistrationService.RegisterRequest web(String name, String campaign) {
return new RegistrationService.RegisterRequest(42L, EVENT, null, name, "+60125550101", null, null, null,
List.of(), null, null, false, "WEB", null, "/p/INS/hotel-technology", "facebook", "cpc", campaign);
}
@Test
void aWebSignUpDuringARunningEventIsNotAttendedAndKeepsItsOrigin() {
registration.register(web("Tan", "jan-launch"));
EventLead e = saved();
assertThat(e.getAttendedAt()).isNull();
assertThat(e.getSource()).isEqualTo("WEB");
assertThat(e.getSalespersonUserId()).isNull();
assertThat(e.getPagePath()).isEqualTo("/p/INS/hotel-technology");
assertThat(e.getUtmSource()).isEqualTo("facebook");
assertThat(e.getUtmMedium()).isEqualTo("cpc");
assertThat(e.getUtmCampaign()).isEqualTo("jan-launch");
}
@Test
void utmValuesAreCutToOneHundredCharacters() {
registration.register(web("Tan", "c".repeat(150)));
assertThat(saved().getUtmCampaign()).hasSize(100);
}
@Test
void aKnownVisitorsDifferencesAreNotedAsComingFromTheWebPage() {
Lead known = new Lead();
known.setCompanyId(42L);
known.setName("Tan Ah Kow");
known.setMobileE164("+60125550101");
when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(42L, "+60125550101")).thenReturn(Optional.of(known));
registration.register(web("Tan", null));
assertThat(saved().getNotes()).isEqualTo("Registered by web page with: name Tan");
}
@Test
void theEventLeadDetailCarriesThePageAndUtmTags() {
EventLead e = new EventLead();
e.setId(1L);
e.setCompanyId(42L);
e.setLeadUuid(5L);
e.setSource("WEB");
e.setPagePath("/p/INS/hotel-technology");
e.setUtmSource("facebook");
e.setUtmMedium("cpc");
e.setUtmCampaign("jan-launch");
Lead lead = new Lead();
when(eventLeads.findByUuidAndCompanyId(77L, 42L)).thenReturn(Optional.of(e));
when(leads.findByUuidAndCompanyId(5L, 42L)).thenReturn(Optional.of(lead));
var detail = eventLeadService.findByUuid(42L, 77L);
assertThat(detail.pagePath()).isEqualTo("/p/INS/hotel-technology");
assertThat(detail.utmSource()).isEqualTo("facebook");
assertThat(detail.utmMedium()).isEqualTo("cpc");
assertThat(detail.utmCampaign()).isEqualTo("jan-launch");
}
}