From 98a77fa17dc984f3cc90bde6868abb879a3ba791 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 15:59:44 +0800 Subject: [PATCH] feat(pages): admin and public landing page APIs in mobile-api Admin pages and images scoped by company, counter refusals relayed as code plus field; public page read, image passthrough and form sign-up through the QR registration rules with source WEB; company branding save checks the logo's company; lead detail and export show the web page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- openspec/changes/add-landing-pages/tasks.md | 6 +- .../api/RestApiCounterServiceConstants.java | 9 + .../api/RestApiSystemServiceConstants.java | 2 + .../admin/AdminCompanyController.java | 7 + .../controller/admin/AdminPageController.java | 75 ++++++++ .../publicapi/PublicPageController.java | 40 ++++ .../mobile/api/dto/PublicPageFormRequest.java | 12 ++ .../api/dto/admin/AdminPageRequest.java | 8 + .../api/service/AdminCompanyService.java | 36 ++++ .../api/service/AdminEventLeadService.java | 5 + .../mobile/api/service/AdminPageService.java | 136 +++++++++++++ .../mobile/api/service/PublicPageService.java | 136 +++++++++++++ .../api/service/AdminCompanyBrandingTest.java | 75 ++++++++ .../api/service/AdminEventLeadExportTest.java | 9 + .../service/AdminEventLeadServiceTest.java | 17 ++ .../api/service/AdminPageServiceTest.java | 156 +++++++++++++++ .../api/service/PublicPageServiceTest.java | 178 ++++++++++++++++++ 17 files changed, 904 insertions(+), 3 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminPageController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/publicapi/PublicPageController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/PublicPageFormRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminPageRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminPageService.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicPageService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminCompanyBrandingTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminPageServiceTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicPageServiceTest.java diff --git a/openspec/changes/add-landing-pages/tasks.md b/openspec/changes/add-landing-pages/tasks.md index 92ec67f..8fd7768 100644 --- a/openspec/changes/add-landing-pages/tasks.md +++ b/openspec/changes/add-landing-pages/tasks.md @@ -52,15 +52,15 @@ Verify commands: ## 5. mobile-api -- [ ] 5.1 `/api/admin/pages/**` and `/api/admin/page-images` (`BO_PAGES`): +- [x] 5.1 `/api/admin/pages/**` and `/api/admin/page-images` (`BO_PAGES`): - company scoping as on the other admin screens, with a super admin choosing a company on create; - saves and deletes audited; - field errors relayed with their path. -- [ ] 5.2 Public endpoints `/api/public/pages/{company}/{slug}` (published page and branding), `/api/public/page-images/{id}` and `POST /api/public/pages/{company}/{slug}/form/{block}`: +- [x] 5.2 Public endpoints `/api/public/pages/{company}/{slug}` (published page and branding), `/api/public/page-images/{id}` and `POST /api/public/pages/{company}/{slug}/form/{block}`: - the submit finds the FORM block's event; - it applies the QR flow's conditions, normalisation and abuse limits; - it registers with source WEB. -- [ ] 5.3 The company endpoints carry `logoImageId` and `accentColor`. The event lead detail carries `source`, `pagePath` and the UTM values. +- [x] 5.3 The company endpoints carry `logoImageId` and `accentColor`. The event lead detail carries `source`, `pagePath` and the UTM values. - Verify (5.1 to 5.3): `mvn -T 1C -B -q -pl solvway-mobile-api -am verify` ## 6. Portal diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java index 1bb4194..25beea4 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiCounterServiceConstants.java @@ -74,4 +74,13 @@ public class RestApiCounterServiceConstants { public static final String API_REST_COUNTER_REGISTRATION_LINK_SET_ENABLED="/counter/registrationLink/setEnabled"; public static final String API_REST_COUNTER_REGISTRATION_LINK_MINE="/counter/registrationLink/mine"; public static final String API_REST_COUNTER_REGISTRATION_REGISTER="/counter/registration/register"; + // Landing pages (add-landing-pages) + public static final String API_REST_COUNTER_CMS_PAGE_SAVE = "/counter/cmsPage/save"; + public static final String API_REST_COUNTER_CMS_PAGE_FIND_BY_ID = "/counter/cmsPage/findById/{id}"; + public static final String API_REST_COUNTER_CMS_PAGE_SEARCH = "/counter/cmsPage/search"; + public static final String API_REST_COUNTER_CMS_PAGE_DELETE = "/counter/cmsPage/delete"; + public static final String API_REST_COUNTER_CMS_PAGE_FIND_PUBLISHED = "/counter/cmsPage/findPublished/{companyId}/{slug}"; + public static final String API_REST_COUNTER_PAGE_IMAGE_UPLOAD = "/counter/pageImage/upload"; + public static final String API_REST_COUNTER_PAGE_IMAGE = "/counter/pageImage/{id}"; + public static final String API_REST_COUNTER_PAGE_IMAGE_COMPANY = "/counter/pageImage/findCompany/{id}"; } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java index 8242d1f..3c220bf 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java @@ -126,4 +126,6 @@ public class RestApiSystemServiceConstants { //Message public static final String API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE = "/message/findByCodeAndLocale/{code}/{locale}"; + public static final String API_REST_COMPANY_BRANDING = "/company/branding/{code}"; + public static final String API_REST_COMPANY_SAVE_BRANDING = "/company/{id}/branding"; } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminCompanyController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminCompanyController.java index 3533b3a..e0a759a 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminCompanyController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminCompanyController.java @@ -73,6 +73,13 @@ public class AdminCompanyController { return ResponseEntity.ok(companies.savePrivacyNotice(id, body, requireSuper().getUsername())); } + @AppAuth + @PutMapping("/{id}/branding") + public ResponseEntity> saveBranding(@PathVariable Long id, @RequestBody Map body) { + requireSuper(); + return ResponseEntity.ok(companies.saveBranding(id, body)); + } + /** Portal body is just {"message"}; the exception still reaches AppAccessAspect first, so the audit has the real status. */ @ExceptionHandler(CodedResponseStatusException.class) public ResponseEntity> upstream(CodedResponseStatusException e) { diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminPageController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminPageController.java new file mode 100644 index 0000000..1a3a409 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminPageController.java @@ -0,0 +1,75 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminPageRequest; +import com.solvway.mobile.api.service.AdminPageService; +import com.solvway.mobile.api.useraccess.AdminModule; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +/** Admin landing pages and their images. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin") +@RequiredArgsConstructor +public class AdminPageController { + public record ImageUpload(Long companyId, String data) {} + + private final AdminPageService pages; + + @AppAuth + @AdminModule("BO_PAGES") + @GetMapping("/pages") + public ResponseEntity> list(@RequestParam(required = false) String q, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size, + @RequestParam(required = false) Long companyId) { + return ResponseEntity.ok(pages.list(q, page, size, companyId)); + } + + @AppAuth + @AdminModule("BO_PAGES") + @GetMapping("/pages/{id}") + public ResponseEntity> get(@PathVariable long id) { + return ResponseEntity.ok(pages.get(id)); + } + + @AppAuth + @AdminModule("BO_PAGES") + @PostMapping("/pages") + public ResponseEntity> create(@RequestBody AdminPageRequest request) { + return ResponseEntity.ok(pages.create(request)); + } + + @AppAuth + @AdminModule("BO_PAGES") + @PutMapping("/pages/{id}") + public ResponseEntity> update(@PathVariable long id, @RequestBody AdminPageRequest request) { + return ResponseEntity.ok(pages.update(id, request)); + } + + @AppAuth + @AdminModule("BO_PAGES") + @DeleteMapping("/pages/{id}") + public ResponseEntity delete(@PathVariable long id) { + pages.delete(id); + return ResponseEntity.noContent().build(); + } + + @AppAuth + @AdminModule("BO_PAGES") + @PostMapping("/page-images") + public ResponseEntity> upload(@RequestBody ImageUpload request) { + return ResponseEntity.ok(pages.uploadImage(request.companyId(), request.data())); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/publicapi/PublicPageController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/publicapi/PublicPageController.java new file mode 100644 index 0000000..aaa802e --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/publicapi/PublicPageController.java @@ -0,0 +1,40 @@ +package com.solvway.mobile.api.controller.publicapi; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.PublicPageFormRequest; +import com.solvway.mobile.api.service.PublicPageService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +/** Published landing pages, their images and form sign-ups: no sign-in. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequiredArgsConstructor +public class PublicPageController { + private final PublicPageService pages; + + @AppAuth(skipValidate = true) + @GetMapping("/api/public/pages/{company}/{slug}") + public ResponseEntity> page(@PathVariable String company, @PathVariable String slug) { + return ResponseEntity.ok(pages.page(company, slug)); + } + + @AppAuth(skipValidate = true) + @PostMapping("/api/public/pages/{company}/{slug}/form/{block}") + public ResponseEntity> submit(@PathVariable String company, @PathVariable String slug, + @PathVariable int block, @RequestBody PublicPageFormRequest request) { + return ResponseEntity.ok(pages.submit(company, slug, block, request)); + } + + @AppAuth(skipValidate = true) + @GetMapping("/api/public/page-images/{id}") + public ResponseEntity image(@PathVariable long id) { + return pages.image(id); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/PublicPageFormRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/PublicPageFormRequest.java new file mode 100644 index 0000000..f35e1ee --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/PublicPageFormRequest.java @@ -0,0 +1,12 @@ +package com.solvway.mobile.api.dto; + +import java.util.List; + +/** A visitor's landing-page form: the QR registration fields plus the UTM tags of the page URL. {@code website} is the honeypot. */ +public record PublicPageFormRequest(String name, String mobile, String email, String companyName, String jobTitle, + List interestIds, Boolean consent, String website, + String utmSource, String utmMedium, String utmCampaign) { + public PublicRegistrationRequest registration() { + return new PublicRegistrationRequest(name, mobile, email, companyName, jobTitle, interestIds, consent, website); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminPageRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminPageRequest.java new file mode 100644 index 0000000..72261e7 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminPageRequest.java @@ -0,0 +1,8 @@ +package com.solvway.mobile.api.dto.admin; + +import java.util.List; +import java.util.Map; + +/** A landing page as the editor saves it. Blocks pass through to the counter, which validates them. companyId counts only on create. */ +public record AdminPageRequest(Long companyId, String slug, String title, String metaDescription, String status, + List> blocks) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminCompanyService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminCompanyService.java index 32d7350..7dba828 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminCompanyService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminCompanyService.java @@ -2,6 +2,7 @@ package com.solvway.mobile.api.service; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants; import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; import com.solvway.mobile.api.util.RestTemplateCustomUtil; @@ -58,6 +59,24 @@ public class AdminCompanyService { return call(() -> restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_PRIVACY_NOTICE).replace("{id}", String.valueOf(id)), MAP, body).getBody()); } + /** Logo and accent colour for the company's landing pages. The logo must be one of the company's own page images. */ + public Map saveBranding(Long id, Map branding) { + Long logo = branding.get("logoImageId") instanceof Number n ? n.longValue() : null; + if (logo != null) { + Long owner = PublicRegistrationService.found(() -> restTemplateUtil.getForEntity( + url(RestApiCounterServiceConstants.API_REST_COUNTER_PAGE_IMAGE_COMPANY), Long.class, logo).getBody()); + if (owner == null || !owner.equals(id)) { + CodedResponseStatusException e = new CodedResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "CompanyBadLogo", "CompanyBadLogo"); + e.getBody().setProperty("details", Map.of("field", "logoImageId")); + throw e; + } + } + Map body = new java.util.LinkedHashMap<>(); + body.put("logoImageId", logo); + body.put("accentColor", branding.get("accentColor")); + return call(() -> restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_SAVE_BRANDING).replace("{id}", String.valueOf(id)), MAP, body).getBody()); + } + private static T call(Supplier call) { try { return call.get(); @@ -66,10 +85,27 @@ public class AdminCompanyService { if (status == HttpStatus.BAD_REQUEST) throw new CodedResponseStatusException(status, reason(e, "Invalid request"), "INVALID_COMPANY"); if (status == HttpStatus.CONFLICT) throw new CodedResponseStatusException(status, reason(e, "Code is already taken"), "COMPANY_CODE_TAKEN"); if (status == HttpStatus.NOT_FOUND) throw new CodedResponseStatusException(status, reason(e, "Company not found"), "COMPANY_NOT_FOUND"); + if (status == HttpStatus.UNPROCESSABLE_ENTITY) throw fieldError(e); throw e; } } + /** services-system refuses branding with a ProblemDetail whose detail is "field|Code". */ + private static RuntimeException fieldError(HttpClientErrorException e) { + String detail; + try { + detail = JSON.readTree(e.getResponseBodyAsString()).path("detail").asText(""); + } catch (Exception ex) { + return e; + } + int bar = detail.indexOf('|'); + if (bar < 0) return e; + String code = detail.substring(bar + 1); + CodedResponseStatusException out = new CodedResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, code, code); + out.getBody().setProperty("details", Map.of("field", detail.substring(0, bar))); + return out; + } + private static String reason(HttpClientErrorException e, String fallback) { try { JsonNode message = JSON.readTree(e.getResponseBodyAsString()).get("message"); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java index adadb71..69d5414 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminEventLeadService.java @@ -225,6 +225,7 @@ public class AdminEventLeadService { case "STAFF" -> "Staff"; case "QR" -> "QR"; case "INVITE" -> "Invite"; + case "WEB" -> "Web page"; default -> source == null ? null : source.toString(); }; } @@ -364,6 +365,10 @@ public class AdminEventLeadService { m.put("capturedAt", d.get("capturedAt")); m.put("attended", d.get("attendedAt") != null); m.put("source", d.get("source")); + m.put("pagePath", d.get("pagePath")); + m.put("utmSource", d.get("utmSource")); + m.put("utmMedium", d.get("utmMedium")); + m.put("utmCampaign", d.get("utmCampaign")); return m; } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminPageService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminPageService.java new file mode 100644 index 0000000..b84c473 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminPageService.java @@ -0,0 +1,136 @@ +package com.solvway.mobile.api.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants; +import com.solvway.mobile.api.dto.admin.AdminPageRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +/** + * Admin landing pages and their images. Pages live in services-counter, which validates blocks, slugs and that images + * and form events belong to the page's company; this scopes every call to the caller's company and relays the counter's + * "path|Code" refusals as the code with the path as the field. + */ +@Service +@RequiredArgsConstructor +public class AdminPageService { + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final ObjectMapper JSON = new ObjectMapper(); + + private final RestTemplateCustomUtil rest; + private final AdminAuthenticationService adminAuthenticationService; + private final AdminCompanyScope scope; + + public Map list(String q, int page, int size, Long companyId) { + Map body = new LinkedHashMap<>(); + body.put("companyId", scope.scope(caller(), companyId)); + body.put("searchKey", q == null ? null : q.trim()); + body.put("page", Math.max(page, 0)); + body.put("size", size); + return rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_CMS_PAGE_SEARCH), MAP, body).getBody(); + } + + public Map get(long id) { + return load(caller(), id); + } + + public Map create(AdminPageRequest r) { + User caller = caller(); + Long company = scope.requireCompanyForCreate(caller, r.companyId()); + return save(caller, null, company, r); + } + + public Map update(long id, AdminPageRequest r) { + User caller = caller(); + Map stored = load(caller, id); + return save(caller, id, ((Number) stored.get("companyId")).longValue(), r); + } + + public void delete(long id) { + load(caller(), id); + rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_CMS_PAGE_DELETE), Void.class, id); + } + + /** base64 bytes; the counter checks type and size. */ + public Map uploadImage(Long companyId, String data) { + User caller = caller(); + Map body = new LinkedHashMap<>(); + body.put("companyId", scope.requireCompanyForCreate(caller, companyId)); + body.put("data", data); + body.put("user", caller.getUsername()); + return relay(() -> rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_PAGE_IMAGE_UPLOAD), MAP, body).getBody()); + } + + private Map save(User caller, Long id, long companyId, AdminPageRequest r) { + Map page = new LinkedHashMap<>(); + page.put("id", id); + page.put("companyId", companyId); + page.put("slug", r.slug()); + page.put("title", r.title()); + page.put("metaDescription", r.metaDescription()); + page.put("status", r.status()); + page.put("blocks", r.blocks() == null ? List.of() : r.blocks()); + Map body = new LinkedHashMap<>(); + body.put("page", page); + body.put("user", caller.getUsername()); + return relay(() -> rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_CMS_PAGE_SAVE), MAP, body).getBody()); + } + + /** The page when the caller's scope covers its company; another company's page is "not found", never "forbidden". */ + private Map load(User caller, long id) { + Map page = PublicRegistrationService.found(() -> + rest.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_CMS_PAGE_FIND_BY_ID), MAP, id).getBody()); + if (page == null || !(page.get("companyId") instanceof Number c)) throw notFound(); + Long own = scope.scope(caller, c.longValue()); + if (own != null && own != c.longValue()) throw notFound(); + return page; + } + + private static T relay(Supplier call) { + try { + return call.get(); + } catch (HttpClientErrorException e) { + if (e.getStatusCode().value() == 404) throw notFound(); + String detail; + try { + JsonNode body = JSON.readTree(e.getResponseBodyAsString()); + detail = body.path("detail").asText(""); + } catch (Exception ex) { + throw e; + } + int bar = detail.indexOf('|'); + if (bar < 0) throw e; + CodedResponseStatusException out = new CodedResponseStatusException(HttpStatus.valueOf(e.getStatusCode().value()), detail.substring(bar + 1), detail.substring(bar + 1)); + out.getBody().setProperty("details", Map.of("field", detail.substring(0, bar))); + throw out; + } + } + + private static CodedResponseStatusException notFound() { + return new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Page not found", "PAGE_NOT_FOUND"); + } + + private User caller() { + User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (caller == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED"); + return caller; + } + + private String url(String api) { + return rest.getURLforApiService(api); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicPageService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicPageService.java new file mode 100644 index 0000000..e87fdb2 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicPageService.java @@ -0,0 +1,136 @@ +package com.solvway.mobile.api.service; + +import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.dto.PublicPageFormRequest; +import com.solvway.mobile.api.dto.PublicRegistrationRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.CacheControl; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Public landing pages: a published page with its company's branding, and its form blocks' sign-ups. + * A form block registers under the QR rules (PublicRegistrationService): same event checks, form validation, + * honeypot and abuse limits, with source WEB, no salesperson, the page address and the UTM tags. + */ +@Service +@RequiredArgsConstructor +@SuppressWarnings("unchecked") +public class PublicPageService { + private static final Pattern CODE = Pattern.compile("[A-Za-z0-9-]{2,20}"); + private static final Pattern SLUG = Pattern.compile("[A-Za-z0-9-]{1,80}"); + private static final int LOAD_LIMIT = 300; + private static final int SUBMIT_LIMIT = 60; + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + + private final RestTemplateCustomUtil rest; + private final PublicRegistrationService registration; + + private record Found(long companyId, Map company, Map page) {} + + public Map page(String companyCode, String slug) { + registration.limit("page:load:" + PublicRegistrationService.ip(), LOAD_LIMIT, "Too many requests from this device. Try again later."); + Found f = find(companyCode, slug); + List> blocks = new ArrayList<>(); + for (Object b : blocks(f.page())) { + Map block = new LinkedHashMap<>((Map) b); + if ("FORM".equals(block.get("type"))) { + PublicRegistrationService.Open o = open(f.companyId(), block); + if (o == null) block.put("closed", true); + else block.put("form", registration.eventView(o)); + } + blocks.add(block); + } + Map page = new LinkedHashMap<>(); + page.put("slug", f.page().get("slug")); + page.put("title", f.page().get("title")); + page.put("metaDescription", f.page().get("metaDescription")); + page.put("blocks", blocks); + return Map.of("company", f.company(), "page", page); + } + + public Map submit(String companyCode, String slug, int blockIndex, PublicPageFormRequest r) { + registration.limit("page:load:" + PublicRegistrationService.ip(), LOAD_LIMIT, "Too many requests from this device. Try again later."); + Found f = find(companyCode, slug); + List blocks = blocks(f.page()); + if (blockIndex < 0 || blockIndex >= blocks.size() || !"FORM".equals(((Map) blocks.get(blockIndex)).get("type"))) { + throw notFound(); + } + PublicRegistrationService.Open o = open(f.companyId(), (Map) blocks.get(blockIndex)); + if (o == null) { + throw new CodedResponseStatusException(HttpStatus.CONFLICT, "Sign-up is closed.", "FORM_CLOSED"); + } + Map done = PublicRegistrationService.done(o.event()); + PublicRegistrationRequest form = r.registration(); + if (PublicRegistrationService.honeypot(form)) return done; // look like success, store nothing + registration.limit("reg:submit:" + o.event().getUuid() + ":" + PublicRegistrationService.ip(), SUBMIT_LIMIT, + "Too many registrations from this device. Try again later."); + Map body = registration.form(o, form); + body.put("eventUuid", o.event().getUuid()); + body.put("salespersonUserId", null); + body.put("source", "WEB"); + body.put("pagePath", "/p/" + f.company().get("code") + "/" + f.page().get("slug")); + body.put("utmSource", r.utmSource()); + body.put("utmMedium", r.utmMedium()); + body.put("utmCampaign", r.utmCampaign()); + rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_REGISTER), MAP, body); + return done; + } + + /** An image's bytes with the counter's type and long cache; a missing one is 404. Image ids are not secret. */ + public ResponseEntity image(long id) { + ResponseEntity r = PublicRegistrationService.found(() -> rest.getForEntity( + url(RestApiCounterServiceConstants.API_REST_COUNTER_PAGE_IMAGE), byte[].class, id)); + if (r == null || r.getBody() == null) throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Image not found", "IMAGE_NOT_FOUND"); + return ResponseEntity.ok().contentType(r.getHeaders().getContentType() == null ? MediaType.APPLICATION_OCTET_STREAM : r.getHeaders().getContentType()) + .cacheControl(CacheControl.maxAge(Duration.ofDays(365)).cachePublic().immutable()).body(r.getBody()); + } + + /** Unknown company, unknown or draft page, or a malformed address: one not-found for all. */ + private Found find(String companyCode, String slug) { + if (companyCode == null || slug == null || !CODE.matcher(companyCode).matches() || !SLUG.matcher(slug).matches()) throw notFound(); + Map company = PublicRegistrationService.found(() -> rest.getForEntity( + url(RestApiSystemServiceConstants.API_REST_COMPANY_BRANDING), MAP, companyCode.toUpperCase(Locale.ROOT)).getBody()); + if (company == null || !(company.get("id") instanceof Number id)) throw notFound(); + Map page = PublicRegistrationService.found(() -> rest.getForEntity( + url(RestApiCounterServiceConstants.API_REST_COUNTER_CMS_PAGE_FIND_PUBLISHED), MAP, id.longValue(), slug.toLowerCase(Locale.ROOT)).getBody()); + if (page == null) throw notFound(); + Map publicCompany = new LinkedHashMap<>(); + for (String k : List.of("code", "name", "logoImageId", "accentColor")) publicCompany.put(k, company.get(k)); + return new Found(id.longValue(), publicCompany, page); + } + + /** The form block's event when it can take sign-ups now, else null. companyId comes from the page's company, never the block. */ + private PublicRegistrationService.Open open(long companyId, Map block) { + Map link = new LinkedHashMap<>(); + link.put("eventUuid", block.get("eventUuid")); + link.put("companyId", companyId); + return registration.load(link, true); + } + + private static List blocks(Map page) { + return page.get("blocks") instanceof List l ? l : List.of(); + } + + private static CodedResponseStatusException notFound() { + return new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Page not found", "PAGE_NOT_FOUND"); + } + + private String url(String api) { + return rest.getURLforApiService(api); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminCompanyBrandingTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminCompanyBrandingTest.java new file mode 100644 index 0000000..7f07c57 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminCompanyBrandingTest.java @@ -0,0 +1,75 @@ +package com.solvway.mobile.api.service; + +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Company logo and accent colour: the logo must be one of that company's own page images. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminCompanyBrandingTest { + private static final String BRANDING = "/company/2/branding"; + private static final String IMAGE_COMPANY = "/counter/pageImage/findCompany/{id}"; + + private RestTemplateCustomUtil rest; + private AdminCompanyService service; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + service = new AdminCompanyService(rest); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + when(rest.getForEntity(eq(IMAGE_COMPANY), eq(Long.class), eq(44L))).thenReturn(ResponseEntity.ok(2L)); + when(rest.postForEntity(eq(BRANDING), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("id", 2))); + } + + @Test + void savesTheOwnLogoAndColour() { + Map body = new HashMap<>(); + body.put("logoImageId", 44); + body.put("accentColor", "#ff6600"); + service.saveBranding(2L, body); + ArgumentCaptor sent = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(BRANDING), any(ParameterizedTypeReference.class), sent.capture()); + assertThat((Map) sent.getValue()).containsEntry("logoImageId", 44L).containsEntry("accentColor", "#ff6600"); + } + + @Test + void refusesAnotherCompanysImageAsLogo() { + assertThatThrownBy(() -> service.saveBranding(3L, Map.of("logoImageId", 44))).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY); + assertThat(e.getCode()).isEqualTo("CompanyBadLogo"); + }); + verify(rest, never()).postForEntity(any(String.class), any(ParameterizedTypeReference.class), any()); + } + + @Test + void relaysABadColour() { + byte[] problem = "{\"status\":422,\"detail\":\"accentColor|CompanyBadAccent\"}".getBytes(StandardCharsets.UTF_8); + when(rest.postForEntity(eq(BRANDING), any(ParameterizedTypeReference.class), any())).thenThrow( + HttpClientErrorException.create(HttpStatus.UNPROCESSABLE_ENTITY, "x", HttpHeaders.EMPTY, problem, StandardCharsets.UTF_8)); + assertThatThrownBy(() -> service.saveBranding(2L, Map.of("accentColor", "red"))).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY); + assertThat(e.getCode()).isEqualTo("CompanyBadAccent"); + }); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadExportTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadExportTest.java index 3f72bce..eef5d4a 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadExportTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadExportTest.java @@ -171,6 +171,15 @@ class AdminEventLeadExportTest { assertThat(s.getRow(2).getCell(10).getStringCellValue()).isEqualTo("Invite"); } + @Test + void webPageSourceIsLabelled() throws Exception { + Map web = row(0); + web.put("source", "WEB"); + when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("content", List.of(web), "totalElements", 1))); + assertThat(sheet(export()).getRow(1).getCell(10).getStringCellValue()).isEqualTo("Web page"); + } + @Test void nullOptionalFieldsAreBlank() throws Exception { Map r = row(0); diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java index cb5f1fd..c955166 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminEventLeadServiceTest.java @@ -37,6 +37,7 @@ import static org.mockito.Mockito.when; @SuppressWarnings({"unchecked", "rawtypes"}) class AdminEventLeadServiceTest { + private static final ParameterizedTypeReference> MAP_TYPE = new ParameterizedTypeReference<>() {}; private static final String EVENTS = "/counter/event/findByPropertyAndPageable"; private static final String EVENT = "/counter/event/findByUuid/{uuid}"; @@ -548,6 +549,22 @@ class AdminEventLeadServiceTest { assertThat(out).containsEntry("attended", false).containsEntry("source", "STAFF"); } + @Test + void getShowsTheWebPageAndUtmTags() { + stubStored(EV, 21L, List.of(4L)); + Map d = (Map) rest.getForEntity(FIND, MAP_TYPE, EL).getBody(); + d.put("source", "WEB"); + d.put("pagePath", "/p/INS/hotel-technology"); + d.put("utmSource", "fb"); + d.put("utmMedium", "cpc"); + d.put("utmCampaign", "jan"); + + Map out = service.get(String.valueOf(EV), String.valueOf(EL)); + + assertThat(out).containsEntry("source", "WEB").containsEntry("pagePath", "/p/INS/hotel-technology") + .containsEntry("utmSource", "fb").containsEntry("utmMedium", "cpc").containsEntry("utmCampaign", "jan"); + } + @Test void getShowsSalespersonAndInterestsByName() { stubStored(EV, 21L, List.of(4L)); diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminPageServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminPageServiceTest.java new file mode 100644 index 0000000..e25b51d --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminPageServiceTest.java @@ -0,0 +1,156 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminPageRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Admin landing pages: company scoping and the counter's "path|Code" refusals relayed as code plus field. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminPageServiceTest { + private static final String SAVE = "/counter/cmsPage/save"; + private static final String BY_ID = "/counter/cmsPage/findById/{id}"; + private static final String SEARCH = "/counter/cmsPage/search"; + private static final String DELETE = "/counter/cmsPage/delete"; + private static final String UPLOAD = "/counter/pageImage/upload"; + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private AdminPageService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = mock(AdminAuthenticationService.class); + service = new AdminPageService(rest, auth, new AdminCompanyScope()); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())) + .thenAnswer(i -> ResponseEntity.ok(((Map) i.getArgument(2)).get("page"))); + when(rest.getForEntity(eq(BY_ID), any(ParameterizedTypeReference.class), eq(5L))) + .thenReturn(ResponseEntity.ok(new HashMap<>(Map.of("id", 5, "companyId", 2, "slug", "a", "title", "A", "status", "DRAFT", "blocks", List.of())))); + when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("content", List.of(), "totalElements", 0, "totalPages", 0, "number", 0, "size", 20))); + } + + @AfterEach + void close() { http.close(); } + + private void caller(Long companyId, boolean superAdmin) { + User u = new User(); + u.setUsername("boss"); + u.setCompanyId(companyId); + if (superAdmin) { + Role r = new Role("Super"); + r.setId(1L); + u.setRoles(List.of(r)); + } + when(auth.loadUserByToken("tok")).thenReturn(u); + } + + private static AdminPageRequest request(Long companyId) { + return new AdminPageRequest(companyId, "hotel", "Hotel", null, "DRAFT", List.of(Map.of("type", "RICH_TEXT", "html", "

x

"))); + } + + @Test + void staffListSeesOnlyTheirCompanyWhateverTheyAskFor() { + caller(3L, false); + service.list("ho", 0, 20, 2L); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) body.getValue()).containsEntry("companyId", 3L).containsEntry("searchKey", "ho"); + } + + @Test + void staffCannotReadOrChangeAnotherCompanysPage() { + caller(3L, false); + for (Runnable r : List.of(() -> service.get(5L), () -> service.update(5L, request(null)), () -> service.delete(5L))) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(e.getCode()).isEqualTo("PAGE_NOT_FOUND"); + }); + } + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + verify(rest, never()).postForEntity(eq(DELETE), any(Class.class), any()); + } + + @Test + void createUsesTheStaffCompanyAndTheCallerAsUser() { + caller(2L, false); + service.create(request(9L)); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + Map sent = (Map) body.getValue(); + assertThat(sent).containsEntry("user", "boss"); + assertThat((Map) sent.get("page")).containsEntry("companyId", 2L).containsEntry("slug", "hotel").containsEntry("id", null); + } + + @Test + void updateKeepsTheIdAndStoredCompany() { + caller(2L, false); + service.update(5L, request(9L)); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) ((Map) body.getValue()).get("page")).containsEntry("id", 5L).containsEntry("companyId", 2L); + } + + @Test + void counterRefusalBecomesCodeAndField() { + caller(2L, false); + byte[] problem = "{\"status\":422,\"detail\":\"blocks[2].heading|PagesRequired\"}".getBytes(StandardCharsets.UTF_8); + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())).thenThrow( + HttpClientErrorException.create(HttpStatus.UNPROCESSABLE_ENTITY, "x", HttpHeaders.EMPTY, problem, StandardCharsets.UTF_8)); + assertThatThrownBy(() -> service.create(request(null))).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY); + assertThat(e.getCode()).isEqualTo("PagesRequired"); + assertThat(e.getBody().getProperties()).containsEntry("details", Map.of("field", "blocks[2].heading")); + }); + } + + @Test + void imageUploadIsScopedToTheCallersCompany() { + caller(2L, false); + when(rest.postForEntity(eq(UPLOAD), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("id", 44))); + assertThat(service.uploadImage(7L, "aGk=")).containsEntry("id", 44); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(UPLOAD), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) body.getValue()).containsEntry("companyId", 2L).containsEntry("data", "aGk=").containsEntry("user", "boss"); + } + + @Test + void superAdminMustPickACompanyToCreate() { + caller(null, true); + assertThatThrownBy(() -> service.create(request(null))).isInstanceOf(CodedResponseStatusException.class); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicPageServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicPageServiceTest.java new file mode 100644 index 0000000..1487e9d --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicPageServiceTest.java @@ -0,0 +1,178 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.PublicPageFormRequest; +import com.solvway.mobile.api.dto.admin.CompanyEvent; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.useraccess.AdminCompanyScope; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Spec landing-pages: the public page, its form block's event and the web sign-up, under the QR registration rules. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class PublicPageServiceTest { + private static final String BRANDING = "/company/branding/{code}"; + private static final String PUBLISHED = "/counter/cmsPage/findPublished/{companyId}/{slug}"; + private static final String EVENT = "/counter/event/findByUuid/{uuid}"; + private static final String COMPANY_URL = "/company/findById/{id}"; + private static final String NOTICE = "/company/{id}/privacyNotice"; + private static final String INTERESTS = "/counter/interest/findByCompany/{companyId}"; + private static final String REGISTER = "/counter/registration/register"; + private static final long EV = 3312726793093644288L; + private static final long COMPANY = 1L; + + private RestTemplateCustomUtil rest; + private MockedStatic http; + private PublicPageService service; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + RedisTemplate redis = mock(RedisTemplate.class); + ValueOperations ops = mock(ValueOperations.class); + when(redis.opsForValue()).thenReturn(ops); + when(ops.increment(any())).thenReturn(1L); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getClientIpAddressIfServletRequestExist).thenReturn("1.2.3.4"); + AdminEventLeadService leads = new AdminEventLeadService(rest, mock(AdminAuthenticationService.class), new AdminCompanyScope()); + PublicRegistrationService registration = new PublicRegistrationService(rest, leads, redis, + Clock.fixed(Instant.parse("2027-01-16T04:00:00Z"), ZoneOffset.UTC)); + service = new PublicPageService(rest, registration); + + Map brand = new HashMap<>(Map.of("id", COMPANY, "code", "INS", "name", "INS", "accentColor", "#0B5FFF")); + brand.put("logoImageId", 4L); + stub(BRANDING, "INS", brand); + when(rest.getForEntity(eq(PUBLISHED), any(ParameterizedTypeReference.class), eq(COMPANY), eq("hotel-technology"))) + .thenReturn(ResponseEntity.ok(page())); + stubEvent(LocalDateTime.of(2027, 12, 31, 23, 59)); + stub(COMPANY_URL, COMPANY, Map.of("id", COMPANY, "name", "INS", "status", "A")); + stub(NOTICE, COMPANY, Map.of("id", 9L, "textEn", "English notice", "textMs", "Notis")); + stub(INTERESTS, COMPANY, List.of(Map.of("id", 3L, "companyId", COMPANY, "name", "Smart rooms", "active", true, "sortOrder", 0))); + when(rest.postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of())); + } + + @AfterEach + void close() { + http.close(); + } + + private static Map page() { + Map form = new HashMap<>(Map.of("type", "FORM", "heading", "Talk to us", "eventUuid", EV)); + return new HashMap<>(Map.of("id", 12L, "companyId", COMPANY, "slug", "hotel-technology", "title", "Hotel technology", + "status", "PUBLISHED", "blocks", List.of(Map.of("type", "RICH_TEXT", "html", "

Hi

"), form))); + } + + private void stub(String url, Object var, Object body) { + when(rest.getForEntity(eq(url), any(ParameterizedTypeReference.class), eq(var))).thenReturn(ResponseEntity.ok(body)); + } + + private void stubEvent(LocalDateTime end) { + CompanyEvent e = new CompanyEvent(); + e.setCompanyId(COMPANY); + e.setUuid(EV); + e.setName("INS website enquiries"); + e.setDateStart(LocalDateTime.of(2027, 1, 1, 0, 0)); + e.setDateEnd(end); + e.setEnabled(GeneralEnum.FlagYesNo.Y); + stub(EVENT, EV, e); + } + + private static PublicPageFormRequest visitor(String website) { + return new PublicPageFormRequest("Tan", "0125550101", null, null, null, List.of(3L), true, website, "facebook", "cpc", "jan-launch"); + } + + @Test + void thePageCarriesBrandingAndItsOpenFormsEvent() { + Map out = service.page("ins", "Hotel-Technology"); + + assertThat((Map) out.get("company")).containsEntry("code", "INS").containsEntry("logoImageId", 4L).containsEntry("accentColor", "#0B5FFF"); + List> blocks = (List>) ((Map) out.get("page")).get("blocks"); + assertThat(blocks).hasSize(2); + Map form = (Map) blocks.get(1).get("form"); + assertThat(form).containsEntry("eventName", "INS website enquiries").containsKey("notice").containsKey("interests"); + assertThat(blocks.get(1)).doesNotContainKey("closed"); + } + + @Test + void aFormWhoseEventEndedIsClosedButThePageStillShows() { + stubEvent(LocalDateTime.of(2027, 1, 15, 23, 59)); + List> blocks = (List>) ((Map) service.page("INS", "hotel-technology").get("page")).get("blocks"); + assertThat(blocks.get(0)).containsEntry("type", "RICH_TEXT"); + assertThat(blocks.get(1)).containsEntry("closed", true).doesNotContainKey("form"); + } + + @Test + void unknownCompanySlugOrShapeAllLookTheSame() { + when(rest.getForEntity(eq(BRANDING), any(ParameterizedTypeReference.class), eq("XX"))).thenThrow(HttpClientErrorException.NotFound.class); + when(rest.getForEntity(eq(PUBLISHED), any(ParameterizedTypeReference.class), eq(COMPANY), eq("launch"))).thenThrow(HttpClientErrorException.NotFound.class); + for (String[] c : new String[][]{{"XX", "hotel-technology"}, {"INS", "launch"}, {"INS", "../etc"}, {"I N S", "x"}}) { + assertThatThrownBy(() -> service.page(c[0], c[1])).as(c[0] + "/" + c[1]) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + assertThat(e.getCode()).isEqualTo("PAGE_NOT_FOUND"); + }); + } + } + + @Test + void aSubmitRegistersAWebSignUpWithThePageAndUtmTags() { + service.submit("ins", "hotel-technology", 1, visitor(null)); + + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), body.capture()); + Map sent = (Map) body.getValue(); + assertThat(sent).containsEntry("eventUuid", EV).containsEntry("companyId", COMPANY).containsEntry("source", "WEB") + .containsEntry("pagePath", "/p/INS/hotel-technology").containsEntry("utmSource", "facebook") + .containsEntry("utmMedium", "cpc").containsEntry("utmCampaign", "jan-launch").containsEntry("mobileE164", "+60125550101") + .containsEntry("consentNoticeId", 9L); + assertThat(sent.get("salespersonUserId")).isNull(); + } + + @Test + void aSubmitToAClosedFormOrANonFormBlockIsRefused() { + assertThatThrownBy(() -> service.submit("INS", "hotel-technology", 0, visitor(null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getCode()).isEqualTo("PAGE_NOT_FOUND")); + assertThatThrownBy(() -> service.submit("INS", "hotel-technology", 7, visitor(null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getCode()).isEqualTo("PAGE_NOT_FOUND")); + stubEvent(LocalDateTime.of(2027, 1, 15, 23, 59)); + assertThatThrownBy(() -> service.submit("INS", "hotel-technology", 1, visitor(null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getCode()).isEqualTo("FORM_CLOSED")); + verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any()); + } + + @Test + void theHoneypotLooksLikeSuccessAndStoresNothing() { + assertThat(service.submit("INS", "hotel-technology", 1, visitor("http://spam"))).containsKey("eventName"); + verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any()); + } +}