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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
1 parent
bf6f2c8696
commit
98a77fa17d
17 files changed
+904
-3
No files matched your search
+9
@@ -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}";
|
||||
}
|
||||
+2
@@ -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";
|
||||
}
|
||||
+7
@@ -73,6 +73,13 @@ public class AdminCompanyController {
|
||||
return ResponseEntity.ok(companies.savePrivacyNotice(id, body, requireSuper().getUsername()));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@PutMapping("/{id}/branding")
|
||||
public ResponseEntity<Map<String, Object>> saveBranding(@PathVariable Long id, @RequestBody Map<String, Object> 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<Map<String, String>> upstream(CodedResponseStatusException e) {
|
||||
|
||||
+75
@@ -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<Map<String, Object>> 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<Map<String, Object>> get(@PathVariable long id) {
|
||||
return ResponseEntity.ok(pages.get(id));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_PAGES")
|
||||
@PostMapping("/pages")
|
||||
public ResponseEntity<Map<String, Object>> create(@RequestBody AdminPageRequest request) {
|
||||
return ResponseEntity.ok(pages.create(request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_PAGES")
|
||||
@PutMapping("/pages/{id}")
|
||||
public ResponseEntity<Map<String, Object>> update(@PathVariable long id, @RequestBody AdminPageRequest request) {
|
||||
return ResponseEntity.ok(pages.update(id, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_PAGES")
|
||||
@DeleteMapping("/pages/{id}")
|
||||
public ResponseEntity<Void> delete(@PathVariable long id) {
|
||||
pages.delete(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_PAGES")
|
||||
@PostMapping("/page-images")
|
||||
public ResponseEntity<Map<String, Object>> upload(@RequestBody ImageUpload request) {
|
||||
return ResponseEntity.ok(pages.uploadImage(request.companyId(), request.data()));
|
||||
}
|
||||
}
|
||||
+40
@@ -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<Map<String, Object>> 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<Map<String, Object>> 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<byte[]> image(@PathVariable long id) {
|
||||
return pages.image(id);
|
||||
}
|
||||
}
|
||||
+12
@@ -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<Long> 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);
|
||||
}
|
||||
}
|
||||
+8
@@ -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<Map<String, Object>> blocks) {}
|
||||
+36
@@ -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<String, Object> saveBranding(Long id, Map<String, ?> 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<String, Object> 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> T call(Supplier<T> 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");
|
||||
|
||||
+5
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+136
@@ -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<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
private final RestTemplateCustomUtil rest;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
private final AdminCompanyScope scope;
|
||||
|
||||
public Map<String, Object> list(String q, int page, int size, Long companyId) {
|
||||
Map<String, Object> 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<String, Object> get(long id) {
|
||||
return load(caller(), id);
|
||||
}
|
||||
|
||||
public Map<String, Object> create(AdminPageRequest r) {
|
||||
User caller = caller();
|
||||
Long company = scope.requireCompanyForCreate(caller, r.companyId());
|
||||
return save(caller, null, company, r);
|
||||
}
|
||||
|
||||
public Map<String, Object> update(long id, AdminPageRequest r) {
|
||||
User caller = caller();
|
||||
Map<String, Object> 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<String, Object> uploadImage(Long companyId, String data) {
|
||||
User caller = caller();
|
||||
Map<String, Object> 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<String, Object> save(User caller, Long id, long companyId, AdminPageRequest r) {
|
||||
Map<String, Object> 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<String, Object> 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<String, Object> load(User caller, long id) {
|
||||
Map<String, Object> 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> T relay(Supplier<T> 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);
|
||||
}
|
||||
}
|
||||
+136
@@ -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<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final RestTemplateCustomUtil rest;
|
||||
private final PublicRegistrationService registration;
|
||||
|
||||
private record Found(long companyId, Map<String, Object> company, Map<String, Object> page) {}
|
||||
|
||||
public Map<String, Object> 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<Map<String, Object>> blocks = new ArrayList<>();
|
||||
for (Object b : blocks(f.page())) {
|
||||
Map<String, Object> block = new LinkedHashMap<>((Map<String, Object>) 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<String, Object> 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<String, Object> 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<String, Object>) blocks.get(blockIndex));
|
||||
if (o == null) {
|
||||
throw new CodedResponseStatusException(HttpStatus.CONFLICT, "Sign-up is closed.", "FORM_CLOSED");
|
||||
}
|
||||
Map<String, Object> 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<String, Object> 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<byte[]> image(long id) {
|
||||
ResponseEntity<byte[]> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> block) {
|
||||
Map<String, Object> link = new LinkedHashMap<>();
|
||||
link.put("eventUuid", block.get("eventUuid"));
|
||||
link.put("companyId", companyId);
|
||||
return registration.load(link, true);
|
||||
}
|
||||
|
||||
private static List<?> blocks(Map<String, Object> 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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user