账户登录
This commit is contained in:
1 parent
f08dcee83a
commit
8e80e26c91
57 files changed
+1401
-100
No files matched your search
+1
-2
@@ -1,6 +1,5 @@
|
||||
package com.shoplix.admin.modules.content.res;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 运营后台内容详情响应。 */
|
||||
public record ContentDetailAdminRes(
|
||||
@@ -18,6 +17,6 @@ public record ContentDetailAdminRes(
|
||||
/** 推荐标识。 */ Boolean featured,
|
||||
/** 排序值。 */ Integer sortNo,
|
||||
/** 发布状态。 */ String status,
|
||||
/** 发布时间。 */ LocalDateTime publishTime) {
|
||||
/** 发布时间毫秒时间戳。 */ Long publishTime) {
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
package com.shoplix.admin.modules.content.res;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 运营后台内容列表项响应。 */
|
||||
public record ContentItemAdminRes(String contentCode, String contentType, String title, String slug,
|
||||
String primaryCategoryCode, String status, Boolean featured,
|
||||
LocalDateTime publishTime) {
|
||||
Long publishTime) {
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
package com.shoplix.admin.modules.inquiry.req; import com.shoplix.modules.inquiry.enums.InquiryStatusEnum; import jakarta.validation.constraints.*; import java.time.LocalDateTime;
|
||||
/** 后台变更询盘状态请求。 */ public record ChangeInquiryStatusAdminReq(/** 站点业务编号。 */ @NotBlank @Size(max=16) String siteCode, /** 询盘业务编号。 */ @NotBlank @Size(max=16) String inquiryCode, /** 目标状态。 */ @NotNull InquiryStatusEnum status, /** 操作用户编号。 */ @NotBlank @Size(max=16) String operatorUserCode, /** 操作备注。 */ @Size(max=1000) String remark, /** 下次跟进时间。 */ LocalDateTime nextFollowTime) {}
|
||||
package com.shoplix.admin.modules.inquiry.req; import com.shoplix.modules.inquiry.enums.InquiryStatusEnum; import jakarta.validation.constraints.*;
|
||||
/** 后台变更询盘状态请求。 */ public record ChangeInquiryStatusAdminReq(/** 站点业务编号。 */ @NotBlank @Size(max=16) String siteCode, /** 询盘业务编号。 */ @NotBlank @Size(max=16) String inquiryCode, /** 目标状态。 */ @NotNull InquiryStatusEnum status, /** 操作用户编号。 */ @NotBlank @Size(max=16) String operatorUserCode, /** 操作备注。 */ @Size(max=1000) String remark, /** 下次跟进毫秒时间戳。 */ Long nextFollowTime) {}
|
||||
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
package com.shoplix.admin.modules.inquiry.res; import java.time.LocalDateTime; import java.util.*;
|
||||
/** 后台询盘详情响应。 */ public record InquiryDetailAdminRes(String inquiryCode,String formCode,Integer formVersion,String sourceType,String sourceCode,String sourceUrl,String productCode,String productName,String customerName,String customerEmail,String customerPhone,String companyName,String countryCode,String message,String status,String statusLabel,Set<String> allowedOperations,String priority,String ownerUserCode,String crmLeadCode,String utmSource,String utmMedium,String utmCampaign,String referrerUrl,String landingUrl,String deviceType,Boolean privacyConsent,LocalDateTime privacyConsentTime,Boolean duplicate,Boolean spam,String spamReason,LocalDateTime nextFollowTime,LocalDateTime createTime,List<InquiryFieldValueAdminRes> fieldValues) {}
|
||||
package com.shoplix.admin.modules.inquiry.res; import java.util.*;
|
||||
/** 后台询盘详情响应。 */ public record InquiryDetailAdminRes(String inquiryCode,String formCode,Integer formVersion,String sourceType,String sourceCode,String sourceUrl,String productCode,String productName,String customerName,String customerEmail,String customerPhone,String companyName,String countryCode,String message,String status,String statusLabel,Set<String> allowedOperations,String priority,String ownerUserCode,String crmLeadCode,String utmSource,String utmMedium,String utmCampaign,String referrerUrl,String landingUrl,String deviceType,Boolean privacyConsent,Long privacyConsentTime,Boolean duplicate,Boolean spam,String spamReason,Long nextFollowTime,Long createTime,List<InquiryFieldValueAdminRes> fieldValues) {}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
package com.shoplix.admin.modules.inquiry.res; import java.time.LocalDateTime; import java.util.Set;
|
||||
/** 后台询盘列表项响应。 */ public record InquiryItemAdminRes(String inquiryCode,String inquiryTitle,String sourceType,String sourceCode,String productName,String customerName,String customerEmail,String customerPhone,String companyName,String countryCode,String countryName,String provinceName,String cityName,String clientIp,Integer readStatus,String remark,String message,String status,String statusLabel,Set<String> allowedOperations,String priority,String ownerUserCode,Boolean duplicate,Boolean spam,LocalDateTime createTime) {}
|
||||
package com.shoplix.admin.modules.inquiry.res; import java.util.Set;
|
||||
/** 后台询盘列表项响应。 */ public record InquiryItemAdminRes(String inquiryCode,String inquiryTitle,String sourceType,String sourceCode,String productName,String customerName,String customerEmail,String customerPhone,String companyName,String countryCode,String countryName,String provinceName,String cityName,String clientIp,Integer readStatus,String remark,String message,String status,String statusLabel,Set<String> allowedOperations,String priority,String ownerUserCode,Boolean duplicate,Boolean spam,Long createTime) {}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
package com.shoplix.admin.modules.product.res;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 运营后台产品列表项响应。 */
|
||||
public record ProductItemAdminRes(String productCode, String productName, String slug, String model,
|
||||
String primaryCategoryCode, String status, Boolean featured,
|
||||
Boolean inquiryEnabled, LocalDateTime publishTime) {
|
||||
Boolean inquiryEnabled, Long publishTime) {
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import com.shoplix.admin.modules.account.res.AccountAdminRes;
|
||||
import com.shoplix.common.exception.BusinessException;
|
||||
import com.shoplix.modules.account.repository.entity.AdminUserEntity;
|
||||
import com.shoplix.modules.account.repository.service.AdminUserRepositoryService;
|
||||
import java.time.LocalDateTime;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -29,7 +28,7 @@ public class AdminAccountService {
|
||||
@Transactional
|
||||
public AccountAdminRes recordLogin(String userCode) {
|
||||
AdminUserEntity entity = required(userCode);
|
||||
entity.setLastLoginTime(LocalDateTime.now());
|
||||
entity.setLastLoginTime(System.currentTimeMillis());
|
||||
if (repository.update(entity) != 1) throw new BusinessException("ACCOUNT_LOGIN_SAVE_FAILED", "登录状态保存失败");
|
||||
return toResponse(entity);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ import com.shoplix.modules.media.repository.service.MediaAssetRepositoryService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/** 运营后台新闻、案例和帮助业务。 */
|
||||
@@ -49,7 +48,7 @@ public class AdminContentService {
|
||||
entity.setAuthorName(request.authorName()); entity.setSourceName(request.sourceName());
|
||||
entity.setFeaturedFlag(Boolean.TRUE.equals(request.featured()) ? 1 : 0); entity.setSortNo(request.sortNo());
|
||||
entity.setStatus(request.status().name());
|
||||
if (request.status().name().equals("PUBLISHED") && entity.getPublishTime() == null) entity.setPublishTime(LocalDateTime.now());
|
||||
if (request.status().name().equals("PUBLISHED") && entity.getPublishTime() == null) entity.setPublishTime(System.currentTimeMillis());
|
||||
int affected = creating ? repository.insert(entity) : repository.updateByCode(entity);
|
||||
if (affected != 1) throw new BusinessException("CONTENT_SAVE_FAILED", "内容保存失败");
|
||||
return entity.getContentCode();
|
||||
@@ -91,13 +90,13 @@ public class AdminContentService {
|
||||
.orElseThrow(() -> new BusinessException("CONTENT_NOT_FOUND", "内容不存在"));
|
||||
if (!entity.getContentType().equals(request.contentType().name()))
|
||||
throw new BusinessException("CONTENT_TYPE_MISMATCH", "内容类型不匹配");
|
||||
LocalDateTime publishTime = entity.getPublishTime();
|
||||
LocalDateTime offlineTime = entity.getOfflineTime();
|
||||
Long publishTime = entity.getPublishTime();
|
||||
Long offlineTime = entity.getOfflineTime();
|
||||
if (request.status().name().equals("PUBLISHED")) {
|
||||
if (publishTime == null) publishTime = LocalDateTime.now();
|
||||
if (publishTime == null) publishTime = System.currentTimeMillis();
|
||||
offlineTime = null;
|
||||
} else if (request.status().name().equals("OFFLINE")) {
|
||||
offlineTime = LocalDateTime.now();
|
||||
offlineTime = System.currentTimeMillis();
|
||||
}
|
||||
if (repository.updateStatus(request.siteCode(), request.contentCode(), request.status().name(), publishTime, offlineTime) != 1)
|
||||
throw new BusinessException("CONTENT_STATUS_UPDATE_FAILED", "内容状态更新失败");
|
||||
|
||||
@@ -11,7 +11,6 @@ import com.shoplix.modules.decoration.repository.entity.SiteDecorationEntity;
|
||||
import com.shoplix.modules.decoration.repository.service.SiteDecorationRepositoryService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 运营后台页面装修业务。 */
|
||||
@Service
|
||||
@@ -53,7 +52,7 @@ public class AdminDecorationService {
|
||||
validateSchema(entity.getDraftSchema());
|
||||
entity.setPublishedSchema(entity.getDraftSchema()); entity.setStatus("PUBLISHED");
|
||||
entity.setPublishedVersion((entity.getPublishedVersion() == null ? 0 : entity.getPublishedVersion()) + 1);
|
||||
entity.setPublishTime(LocalDateTime.now());
|
||||
entity.setPublishTime(System.currentTimeMillis());
|
||||
if (repository.updateByCode(entity) != 1) throw new BusinessException("DECORATION_PUBLISH_FAILED", "页面装修发布失败");
|
||||
}
|
||||
/** 校验装修 JSON 的根结构和区块集合。 */
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.shoplix.admin.service;
|
||||
import com.shoplix.admin.modules.inquiry.req.*; import com.shoplix.admin.modules.inquiry.res.*; import com.shoplix.admin.modules.setting.req.*; import com.shoplix.admin.modules.setting.res.*; import com.shoplix.common.code.enums.BusinessCodePrefixEnum; import com.shoplix.common.exception.BusinessException; import com.shoplix.common.utils.BusinessCodeUtils;
|
||||
import com.shoplix.modules.inquiry.enums.InquiryStatusEnum; import com.shoplix.modules.inquiry.repository.entity.*; import com.shoplix.modules.inquiry.repository.service.*; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
|
||||
import java.time.LocalDateTime; import java.util.*;
|
||||
import java.util.*;
|
||||
/** 运营后台询盘设置、表单与处理业务。 */ @Service
|
||||
public class AdminInquiryService {
|
||||
private final InquirySettingRepositoryService settings; private final InquiryFormRepositoryService forms; private final InquiryFormFieldRepositoryService fields; private final InquiryRecordRepositoryService records; private final InquiryFieldValueRepositoryService values; private final InquiryOperationLogRepositoryService logs; private final BusinessCodeUtils codes;
|
||||
@@ -13,7 +13,7 @@ public class AdminInquiryService {
|
||||
/** 查询后台询盘列表。 */ public List<InquiryItemAdminRes> list(String site,InquiryStatusEnum status){return records.list(site,status==null?null:status.name()).stream().map(this::toItem).toList();}
|
||||
/** 查询后台询盘详情。 */ public InquiryDetailAdminRes detail(String site,String code){InquiryRecordEntity e=records.find(site,code).orElseThrow(()->new BusinessException("INQUIRY_NOT_FOUND","询盘不存在"));InquiryStatusEnum s=InquiryStatusEnum.valueOf(e.getStatus());return new InquiryDetailAdminRes(e.getInquiryCode(),e.getFormCode(),e.getFormVersion(),e.getSourceType(),e.getSourceCode(),e.getSourceUrl(),e.getProductCode(),e.getProductNameSnapshot(),e.getCustomerName(),e.getCustomerEmail(),e.getCustomerPhone(),e.getCompanyName(),e.getCountryCode(),e.getMessage(),s.name(),s.getLabel(),s.getOperations(),e.getPriority(),e.getOwnerUserCode(),e.getCrmLeadCode(),e.getUtmSource(),e.getUtmMedium(),e.getUtmCampaign(),e.getReferrerUrl(),e.getLandingUrl(),e.getDeviceType(),e.getPrivacyConsentFlag()==1,e.getPrivacyConsentTime(),e.getDuplicateFlag()==1,e.getSpamFlag()==1,e.getSpamReason(),e.getNextFollowTime(),e.getCreateTime(),values.list(site,code).stream().map(v->new InquiryFieldValueAdminRes(v.getFieldCode(),v.getFieldKey(),v.getFieldLabelSnapshot(),v.getFieldTypeSnapshot(),v.getFieldValue(),v.getSortNo())).toList());}
|
||||
/** 分配询盘负责人。 */ @Transactional public void assign(AssignInquiryAdminReq r){InquiryRecordEntity e=records.find(r.siteCode(),r.inquiryCode()).orElseThrow(()->new BusinessException("INQUIRY_NOT_FOUND","询盘不存在"));e.setOwnerUserCode(r.ownerUserCode());if(records.update(e)!=1)throw new BusinessException("INQUIRY_ASSIGN_FAILED","询盘分配失败");log(e,r.operatorUserCode(),"ASSIGN",e.getStatus(),e.getStatus(),"负责人:"+r.ownerUserCode());}
|
||||
/** 按合法状态机变更询盘状态。 */ @Transactional public void changeStatus(ChangeInquiryStatusAdminReq r){InquiryRecordEntity e=records.find(r.siteCode(),r.inquiryCode()).orElseThrow(()->new BusinessException("INQUIRY_NOT_FOUND","询盘不存在"));InquiryStatusEnum before=InquiryStatusEnum.valueOf(e.getStatus());if(!canTransition(before,r.status()))throw new BusinessException("INQUIRY_STATUS_INVALID","当前状态不允许执行此操作");e.setStatus(r.status().name());e.setSpamFlag(r.status()==InquiryStatusEnum.SPAM?1:0);if(r.status()==InquiryStatusEnum.SPAM)e.setSpamReason(r.remark());if(r.status()==InquiryStatusEnum.FOLLOWING||r.status()==InquiryStatusEnum.QUOTED){if(e.getFirstFollowTime()==null)e.setFirstFollowTime(LocalDateTime.now());e.setLastFollowTime(LocalDateTime.now());e.setNextFollowTime(r.nextFollowTime());}if(r.status()==InquiryStatusEnum.CLOSED)e.setCloseTime(LocalDateTime.now());if(records.update(e)!=1)throw new BusinessException("INQUIRY_STATUS_SAVE_FAILED","询盘状态更新失败");log(e,r.operatorUserCode(),r.status()==InquiryStatusEnum.SPAM?"MARK_SPAM":"STATUS_CHANGE",before.name(),r.status().name(),r.remark());}
|
||||
/** 按合法状态机变更询盘状态。 */ @Transactional public void changeStatus(ChangeInquiryStatusAdminReq r){InquiryRecordEntity e=records.find(r.siteCode(),r.inquiryCode()).orElseThrow(()->new BusinessException("INQUIRY_NOT_FOUND","询盘不存在"));InquiryStatusEnum before=InquiryStatusEnum.valueOf(e.getStatus());if(!canTransition(before,r.status()))throw new BusinessException("INQUIRY_STATUS_INVALID","当前状态不允许执行此操作");e.setStatus(r.status().name());e.setSpamFlag(r.status()==InquiryStatusEnum.SPAM?1:0);if(r.status()==InquiryStatusEnum.SPAM)e.setSpamReason(r.remark());if(r.status()==InquiryStatusEnum.FOLLOWING||r.status()==InquiryStatusEnum.QUOTED){if(e.getFirstFollowTime()==null)e.setFirstFollowTime(System.currentTimeMillis());e.setLastFollowTime(System.currentTimeMillis());e.setNextFollowTime(r.nextFollowTime());}if(r.status()==InquiryStatusEnum.CLOSED)e.setCloseTime(System.currentTimeMillis());if(records.update(e)!=1)throw new BusinessException("INQUIRY_STATUS_SAVE_FAILED","询盘状态更新失败");log(e,r.operatorUserCode(),r.status()==InquiryStatusEnum.SPAM?"MARK_SPAM":"STATUS_CHANGE",before.name(),r.status().name(),r.remark());}
|
||||
/** 判断状态流转是否合法。 */ private boolean canTransition(InquiryStatusEnum from,InquiryStatusEnum to){if(from==to)return false;return switch(from){case NEW->Set.of(InquiryStatusEnum.VALID,InquiryStatusEnum.SPAM,InquiryStatusEnum.CLOSED).contains(to);case VALID->Set.of(InquiryStatusEnum.FOLLOWING,InquiryStatusEnum.SPAM,InquiryStatusEnum.CLOSED).contains(to);case FOLLOWING->Set.of(InquiryStatusEnum.QUOTED,InquiryStatusEnum.WON,InquiryStatusEnum.LOST,InquiryStatusEnum.CLOSED).contains(to);case QUOTED->Set.of(InquiryStatusEnum.FOLLOWING,InquiryStatusEnum.WON,InquiryStatusEnum.LOST,InquiryStatusEnum.CLOSED).contains(to);case WON,LOST->to==InquiryStatusEnum.CLOSED||to==InquiryStatusEnum.FOLLOWING;case SPAM,CLOSED->to==InquiryStatusEnum.NEW;};}
|
||||
/** 写入询盘操作日志。 */ private void log(InquiryRecordEntity e,String user,String type,String before,String after,String content){InquiryOperationLogEntity l=new InquiryOperationLogEntity();l.setLogCode(codes.generate(BusinessCodePrefixEnum.INQUIRY_LOG));l.setSiteCode(e.getSiteCode());l.setInquiryCode(e.getInquiryCode());l.setOperatorUserCode(user);l.setOperationType(type);l.setBeforeStatus(before);l.setAfterStatus(after);l.setOperationContent(content);logs.insert(l);}
|
||||
/** 转换设置响应。 */ private InquirySettingAdminRes toSetting(InquirySettingEntity e){return new InquirySettingAdminRes(e.getSettingCode(),e.getSiteCode(),e.getInquiryEnabled()==1,e.getCaptchaEnabled()==1,e.getPrivacyConsentRequired()==1,e.getDuplicateWindowMinutes(),e.getIpHourLimit(),e.getEmailDayLimit(),e.getSuccessAction(),e.getSuccessPageCode(),e.getSuccessRedirectUrl(),e.getNotificationEnabled()==1,e.getAutoReplyEnabled()==1,e.getAutoReplySubject(),e.getAutoReplyContent(),e.getDataRetentionDays());}
|
||||
|
||||
@@ -12,7 +12,6 @@ import com.shoplix.modules.media.repository.service.MediaAssetRepositoryService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/** 运营后台页面业务。 */
|
||||
@@ -41,7 +40,7 @@ public class AdminPageService {
|
||||
entity.setPageName(request.pageName()); entity.setSlug(request.slug()); entity.setPageContent(request.pageContent());
|
||||
entity.setSummary(request.summary()); entity.setCoverMediaCode(request.coverMediaCode()); entity.setSortNo(request.sortNo());
|
||||
entity.setStatus(request.status().name());
|
||||
if (request.status().name().equals("PUBLISHED") && entity.getPublishTime() == null) entity.setPublishTime(LocalDateTime.now());
|
||||
if (request.status().name().equals("PUBLISHED") && entity.getPublishTime() == null) entity.setPublishTime(System.currentTimeMillis());
|
||||
int affected = creating ? repository.insert(entity) : repository.updateByCode(entity);
|
||||
if (affected != 1) throw new BusinessException("PAGE_SAVE_FAILED", "页面保存失败");
|
||||
return entity.getPageCode();
|
||||
|
||||
@@ -25,7 +25,6 @@ import com.shoplix.modules.product.repository.service.ProductAttributeValueRepos
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/** 运营后台 B2B 产品业务。 */
|
||||
@@ -62,7 +61,7 @@ public class AdminProductService {
|
||||
entity.setSummary(request.summary()); entity.setProductContent(request.productContent());
|
||||
entity.setCoverMediaCode(request.coverMediaCode()); entity.setFeaturedFlag(request.featured() ? 1 : 0);
|
||||
entity.setInquiryEnabled(request.inquiryEnabled() ? 1 : 0); entity.setSortNo(request.sortNo()); entity.setStatus(request.status().name());
|
||||
if (request.status().name().equals("PUBLISHED") && entity.getPublishTime() == null) entity.setPublishTime(LocalDateTime.now());
|
||||
if (request.status().name().equals("PUBLISHED") && entity.getPublishTime() == null) entity.setPublishTime(System.currentTimeMillis());
|
||||
int affected = creating ? repository.insert(entity) : repository.updateByCode(entity);
|
||||
if (affected != 1) throw new BusinessException("PRODUCT_SAVE_FAILED", "产品保存失败");
|
||||
specificationRepository.delete(entity.getSiteCode(), entity.getProductCode());
|
||||
@@ -120,13 +119,13 @@ public class AdminProductService {
|
||||
public void changeStatus(ProductStatusAdminReq request) {
|
||||
ProductEntity entity = repository.findByCode(request.siteCode(), request.productCode())
|
||||
.orElseThrow(() -> new BusinessException("PRODUCT_NOT_FOUND", "产品不存在"));
|
||||
LocalDateTime publishTime = entity.getPublishTime();
|
||||
LocalDateTime offlineTime = entity.getOfflineTime();
|
||||
Long publishTime = entity.getPublishTime();
|
||||
Long offlineTime = entity.getOfflineTime();
|
||||
if (request.status().name().equals("PUBLISHED")) {
|
||||
if (publishTime == null) publishTime = LocalDateTime.now();
|
||||
if (publishTime == null) publishTime = System.currentTimeMillis();
|
||||
offlineTime = null;
|
||||
} else if (request.status().name().equals("OFFLINE")) {
|
||||
offlineTime = LocalDateTime.now();
|
||||
offlineTime = System.currentTimeMillis();
|
||||
}
|
||||
if (repository.updateStatus(request.siteCode(), request.productCode(), request.status().name(), publishTime, offlineTime) != 1)
|
||||
throw new BusinessException("PRODUCT_STATUS_UPDATE_FAILED", "产品状态更新失败");
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
CREATE TABLE flow_log (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '数据库内部主键',
|
||||
flow_code VARCHAR(16) NOT NULL COMMENT '打点业务编号',
|
||||
site_code VARCHAR(16) NOT NULL COMMENT '站点业务编号',
|
||||
language VARCHAR(50) NULL COMMENT '语言编码',
|
||||
ts BIGINT NOT NULL COMMENT '事件发生毫秒时间戳',
|
||||
dt INT NOT NULL COMMENT '日期,格式yyyyMMdd',
|
||||
yyyy INT NOT NULL COMMENT '年份',
|
||||
mm TINYINT NOT NULL COMMENT '月份,取值1至12',
|
||||
week TINYINT NOT NULL COMMENT 'ISO周序号,取值1至53',
|
||||
hh TINYINT NOT NULL COMMENT '小时,取值0至23',
|
||||
event_name VARCHAR(100) NOT NULL COMMENT '事件编码:page_view页面访问、page_leave页面离开、search搜索、submit_inquiry提交询盘、click点击',
|
||||
event_detail VARCHAR(255) NULL COMMENT '事件详情',
|
||||
start_time BIGINT NULL COMMENT '进入页面毫秒时间戳',
|
||||
end_time BIGINT NULL COMMENT '离开页面毫秒时间戳',
|
||||
cuid VARCHAR(100) NOT NULL COMMENT '匿名访客标识',
|
||||
user_code VARCHAR(16) NULL COMMENT '登录用户业务编号',
|
||||
scene VARCHAR(255) NULL COMMENT '访问场景',
|
||||
new_visitor_flag TINYINT NOT NULL DEFAULT 0 COMMENT '新访客标识:0否,1是',
|
||||
session_first_flag TINYINT NOT NULL DEFAULT 0 COMMENT '会话首次访问标识:0否,1是',
|
||||
session_code VARCHAR(100) NOT NULL COMMENT '用户单次会话标识',
|
||||
page_name VARCHAR(255) NULL COMMENT '页面名称',
|
||||
page_code VARCHAR(50) NULL COMMENT '页面类型编码',
|
||||
page_title VARCHAR(500) NULL COMMENT '页面标题',
|
||||
target_code VARCHAR(16) NULL COMMENT '页面关联业务编号',
|
||||
seo_link VARCHAR(512) NULL COMMENT 'SEO路径',
|
||||
pixel_ratio VARCHAR(20) NULL COMMENT '设备像素比',
|
||||
platform VARCHAR(100) NULL COMMENT '浏览器平台',
|
||||
social_media_channel VARCHAR(100) NULL COMMENT '社媒渠道',
|
||||
flow_channel VARCHAR(100) NULL COMMENT '流量渠道',
|
||||
utm_source VARCHAR(100) NULL COMMENT 'UTM来源平台',
|
||||
utm_campaign VARCHAR(100) NULL COMMENT 'UTM活动',
|
||||
utm_adgroup VARCHAR(100) NULL COMMENT 'UTM广告组',
|
||||
landing_domain VARCHAR(255) NULL COMMENT '落地页域名',
|
||||
landing_url VARCHAR(512) NULL COMMENT '落地页完整地址',
|
||||
landing_url_body VARCHAR(512) NULL COMMENT '落地页路径',
|
||||
landing VARCHAR(767) NULL COMMENT '落地页域名及路径',
|
||||
win_height INT NULL COMMENT '窗口高度',
|
||||
win_width INT NULL COMMENT '窗口宽度',
|
||||
domain VARCHAR(500) NULL COMMENT '当前域名',
|
||||
url_info TEXT NULL COMMENT '当前地址,不包含查询参数',
|
||||
url TEXT NULL COMMENT '当前完整地址',
|
||||
url_body TEXT NULL COMMENT '当前路径',
|
||||
url_args TEXT NULL COMMENT '当前查询参数',
|
||||
screen_width INT NULL COMMENT '屏幕宽度',
|
||||
screen_height INT NULL COMMENT '屏幕高度',
|
||||
ip_address VARCHAR(50) NULL COMMENT '客户端IP地址',
|
||||
iso_code VARCHAR(50) NULL COMMENT '国家或地区ISO编码',
|
||||
country_name VARCHAR(100) NULL COMMENT '国家或地区名称',
|
||||
province_name VARCHAR(100) NULL COMMENT '省或州名称',
|
||||
city_name VARCHAR(100) NULL COMMENT '城市名称',
|
||||
referrer_url VARCHAR(512) NULL COMMENT '来源地址',
|
||||
duration INT NULL COMMENT '页面停留时长秒',
|
||||
ua TEXT NULL COMMENT '用户代理',
|
||||
network VARCHAR(50) NULL COMMENT '网络类型',
|
||||
operating_system VARCHAR(100) NULL COMMENT '操作系统',
|
||||
browser VARCHAR(255) NULL COMMENT '浏览器名称',
|
||||
browser_version VARCHAR(255) NULL COMMENT '浏览器版本',
|
||||
device VARCHAR(50) NULL COMMENT '设备类型:DESKTOP桌面端、MOBILE移动端、TABLET平板',
|
||||
deleted TINYINT NOT NULL DEFAULT 0 COMMENT '逻辑删除状态:0未删除,1已删除',
|
||||
create_time BIGINT NOT NULL COMMENT '创建毫秒时间戳',
|
||||
update_time BIGINT NOT NULL COMMENT '更新毫秒时间戳',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_flow_log_code (flow_code),
|
||||
KEY idx_flow_log_site_time (site_code, ts),
|
||||
KEY idx_flow_log_session (session_code),
|
||||
KEY idx_flow_log_date_event_visitor (site_code, dt, event_name, cuid)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='前台访问打点数据';
|
||||
@@ -0,0 +1,86 @@
|
||||
-- 将历史DATETIME时间转换为Unix毫秒时间戳。先转为字符串可保留原索引,再转换为BIGINT。
|
||||
DELIMITER $$
|
||||
CREATE PROCEDURE migrate_datetime_to_millis()
|
||||
BEGIN
|
||||
DECLARE done INT DEFAULT 0;
|
||||
DECLARE table_name_value VARCHAR(64);
|
||||
DECLARE column_name_value VARCHAR(64);
|
||||
DECLARE nullable_value VARCHAR(3);
|
||||
DECLARE comment_value TEXT;
|
||||
DECLARE column_cursor CURSOR FOR
|
||||
SELECT TABLE_NAME, COLUMN_NAME, IS_NULLABLE, COLUMN_COMMENT
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME <> 'flyway_schema_history'
|
||||
AND DATA_TYPE IN ('datetime', 'timestamp');
|
||||
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
|
||||
|
||||
OPEN column_cursor;
|
||||
conversion_loop: LOOP
|
||||
FETCH column_cursor INTO table_name_value, column_name_value, nullable_value, comment_value;
|
||||
IF done = 1 THEN LEAVE conversion_loop; END IF;
|
||||
SET @sql_text = CONCAT('ALTER TABLE `', table_name_value, '` MODIFY `', column_name_value,
|
||||
'` VARCHAR(30) ', IF(nullable_value = 'YES', 'NULL', 'NOT NULL'), ' COMMENT ', QUOTE(comment_value));
|
||||
PREPARE statement_value FROM @sql_text;
|
||||
EXECUTE statement_value;
|
||||
DEALLOCATE PREPARE statement_value;
|
||||
SET @sql_text = CONCAT('UPDATE `', table_name_value, '` SET `', column_name_value,
|
||||
'` = CAST(ROUND(UNIX_TIMESTAMP(`', column_name_value, '`) * 1000) AS CHAR) WHERE `',
|
||||
column_name_value, '` IS NOT NULL');
|
||||
PREPARE statement_value FROM @sql_text;
|
||||
EXECUTE statement_value;
|
||||
DEALLOCATE PREPARE statement_value;
|
||||
SET @sql_text = CONCAT('ALTER TABLE `', table_name_value, '` MODIFY `', column_name_value,
|
||||
'` BIGINT ', IF(nullable_value = 'YES', 'NULL', 'NOT NULL'),
|
||||
IF(column_name_value IN ('create_time', 'update_time'),
|
||||
' DEFAULT (ROUND(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000))', ''),
|
||||
' COMMENT ', QUOTE(CONCAT(comment_value, '(Unix毫秒时间戳)')));
|
||||
PREPARE statement_value FROM @sql_text;
|
||||
EXECUTE statement_value;
|
||||
DEALLOCATE PREPARE statement_value;
|
||||
END LOOP;
|
||||
CLOSE column_cursor;
|
||||
END$$
|
||||
DELIMITER ;
|
||||
|
||||
CALL migrate_datetime_to_millis();
|
||||
DROP PROCEDURE migrate_datetime_to_millis;
|
||||
|
||||
-- 审计字段使用幂等方式补充,兼容已部分执行过迁移的数据库。
|
||||
DELIMITER $$
|
||||
CREATE PROCEDURE add_column_if_missing(
|
||||
IN table_name_value VARCHAR(64),
|
||||
IN column_name_value VARCHAR(64),
|
||||
IN column_definition_value TEXT
|
||||
)
|
||||
BEGIN
|
||||
DECLARE column_count INT DEFAULT 0;
|
||||
SELECT COUNT(*) INTO column_count
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = table_name_value
|
||||
AND COLUMN_NAME = column_name_value;
|
||||
IF column_count = 0 THEN
|
||||
SET @sql_text = CONCAT('ALTER TABLE `', table_name_value, '` ADD COLUMN `',
|
||||
column_name_value, '` ', column_definition_value);
|
||||
PREPARE statement_value FROM @sql_text;
|
||||
EXECUTE statement_value;
|
||||
DEALLOCATE PREPARE statement_value;
|
||||
END IF;
|
||||
END$$
|
||||
DELIMITER ;
|
||||
|
||||
CALL add_column_if_missing('site_custom_code', 'deleted',
|
||||
'TINYINT NOT NULL DEFAULT 0 COMMENT ''逻辑删除状态:0未删除,1已删除'' AFTER `sort_no`');
|
||||
CALL add_column_if_missing('email_campaign_recipient', 'deleted',
|
||||
'TINYINT NOT NULL DEFAULT 0 COMMENT ''逻辑删除状态:0未删除,1已删除'' AFTER `sent_time`');
|
||||
CALL add_column_if_missing('email_campaign_recipient', 'create_time',
|
||||
'BIGINT NOT NULL DEFAULT (ROUND(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000)) COMMENT ''创建毫秒时间戳'' AFTER `deleted`');
|
||||
CALL add_column_if_missing('email_campaign_recipient', 'update_time',
|
||||
'BIGINT NOT NULL DEFAULT (ROUND(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000)) COMMENT ''更新毫秒时间戳'' AFTER `create_time`');
|
||||
CALL add_column_if_missing('inquiry_operation_log', 'deleted',
|
||||
'TINYINT NOT NULL DEFAULT 0 COMMENT ''逻辑删除状态:0未删除,1已删除'' AFTER `operation_content`');
|
||||
CALL add_column_if_missing('inquiry_operation_log', 'update_time',
|
||||
'BIGINT NOT NULL DEFAULT (ROUND(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000)) COMMENT ''更新毫秒时间戳'' AFTER `create_time`');
|
||||
|
||||
DROP PROCEDURE add_column_if_missing;
|
||||
@@ -13,7 +13,7 @@ public enum BusinessCodePrefixEnum {
|
||||
INQUIRY_SETTING("IST"), INQUIRY_FIELD_VALUE("IFV"), INQUIRY_ATTACHMENT("IAT"),
|
||||
INQUIRY_LOG("ILG"), INQUIRY_RECEIVER("IRC"), MAIL_TASK("MLT"), CUSTOMER("CUS"),
|
||||
CONTACT("CON"), LEAD("LED"), FOLLOW_UP("FLW"), MEDIA("MED"), SEO("SEO"), SEO_HEADING("SEH"),
|
||||
PUBLISH("PUB"), JOB("JOB"), USER("USR"), ROLE("ROL");
|
||||
PUBLISH("PUB"), JOB("JOB"), USER("USR"), ROLE("ROL"), FLOW_LOG("FLO");
|
||||
|
||||
/** 三位业务前缀。 */
|
||||
private final String prefix;
|
||||
|
||||
+1
-2
@@ -3,7 +3,6 @@ package com.shoplix.modules.account.repository.entity;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.Data;
|
||||
|
||||
/** 运营后台管理员账户持久化实体。 */
|
||||
@@ -17,6 +16,6 @@ public class AdminUserEntity {
|
||||
/** BCrypt密码哈希。 */ private String passwordHash;
|
||||
/** 管理员显示名称。 */ private String displayName;
|
||||
/** 账户状态。 */ private String status;
|
||||
/** 最近登录时间。 */ private LocalDateTime lastLoginTime;
|
||||
/** 最近登录毫秒时间戳。 */ private Long lastLoginTime;
|
||||
/** 逻辑删除状态。 */ private Integer deleted;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.shoplix.modules.analytics.enums;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/** 前台访问打点事件。 */
|
||||
public enum FlowEventEnum {
|
||||
PAGE_VIEW("page_view"),
|
||||
PAGE_LEAVE("page_leave"),
|
||||
SEARCH("search"),
|
||||
SUBMIT_INQUIRY("submit_inquiry"),
|
||||
CLICK("click");
|
||||
|
||||
/** 事件编码。 */
|
||||
private final String value;
|
||||
|
||||
/** 创建事件枚举。 */
|
||||
FlowEventEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/** 获取事件编码。 */
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
/** 判断事件编码是否受支持。 */
|
||||
public static boolean supports(String value) {
|
||||
return Arrays.stream(values()).anyMatch(item -> item.value.equals(value));
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.shoplix.modules.analytics.repository.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
/** 前台访问打点持久化实体。 */
|
||||
@Data
|
||||
@TableName("flow_log")
|
||||
public class FlowLogEntity {
|
||||
/** 数据库内部主键。 */ @TableId(type = IdType.AUTO) private Long id;
|
||||
/** 打点业务编号。 */ private String flowCode;
|
||||
/** 站点业务编号。 */ private String siteCode;
|
||||
/** 语言编码。 */ private String language;
|
||||
/** 事件发生毫秒时间戳。 */ private Long ts;
|
||||
/** 日期,格式yyyyMMdd。 */ private Integer dt;
|
||||
/** 年份。 */ private Integer yyyy;
|
||||
/** 月份,取值1至12。 */ private Integer mm;
|
||||
/** ISO周序号,取值1至53。 */ private Integer week;
|
||||
/** 小时,取值0至23。 */ private Integer hh;
|
||||
/** 事件编码。 */ private String eventName;
|
||||
/** 事件详情。 */ private String eventDetail;
|
||||
/** 进入页面毫秒时间戳。 */ private Long startTime;
|
||||
/** 离开页面毫秒时间戳。 */ private Long endTime;
|
||||
/** 匿名访客标识。 */ private String cuid;
|
||||
/** 登录用户业务编号。 */ private String userCode;
|
||||
/** 访问场景。 */ private String scene;
|
||||
/** 新访客标识:0否,1是。 */ private Integer newVisitorFlag;
|
||||
/** 会话首次访问标识:0否,1是。 */ private Integer sessionFirstFlag;
|
||||
/** 单次会话标识。 */ private String sessionCode;
|
||||
/** 页面名称。 */ private String pageName;
|
||||
/** 页面类型编码。 */ private String pageCode;
|
||||
/** 页面标题。 */ private String pageTitle;
|
||||
/** 页面关联业务编号。 */ private String targetCode;
|
||||
/** SEO路径。 */ private String seoLink;
|
||||
/** 设备像素比。 */ private String pixelRatio;
|
||||
/** 浏览器平台。 */ private String platform;
|
||||
/** 社媒渠道。 */ private String socialMediaChannel;
|
||||
/** 流量渠道。 */ private String flowChannel;
|
||||
/** UTM来源平台。 */ private String utmSource;
|
||||
/** UTM活动。 */ private String utmCampaign;
|
||||
/** UTM广告组。 */ private String utmAdgroup;
|
||||
/** 落地页域名。 */ private String landingDomain;
|
||||
/** 落地页完整地址。 */ private String landingUrl;
|
||||
/** 落地页路径。 */ private String landingUrlBody;
|
||||
/** 落地页域名及路径。 */ private String landing;
|
||||
/** 窗口高度。 */ private Integer winHeight;
|
||||
/** 窗口宽度。 */ private Integer winWidth;
|
||||
/** 当前域名。 */ private String domain;
|
||||
/** 当前地址,不包含查询参数。 */ private String urlInfo;
|
||||
/** 当前完整地址。 */ private String url;
|
||||
/** 当前路径。 */ private String urlBody;
|
||||
/** 当前查询参数。 */ private String urlArgs;
|
||||
/** 屏幕宽度。 */ private Integer screenWidth;
|
||||
/** 屏幕高度。 */ private Integer screenHeight;
|
||||
/** 客户端IP地址。 */ private String ipAddress;
|
||||
/** 国家或地区ISO编码。 */ private String isoCode;
|
||||
/** 国家或地区名称。 */ private String countryName;
|
||||
/** 省或州名称。 */ private String provinceName;
|
||||
/** 城市名称。 */ private String cityName;
|
||||
/** 来源地址。 */ private String referrerUrl;
|
||||
/** 页面停留秒数。 */ private Integer duration;
|
||||
/** 用户代理。 */ private String ua;
|
||||
/** 网络类型。 */ private String network;
|
||||
/** 操作系统。 */ private String operatingSystem;
|
||||
/** 浏览器名称。 */ private String browser;
|
||||
/** 浏览器版本。 */ private String browserVersion;
|
||||
/** 设备类型。 */ private String device;
|
||||
/** 逻辑删除状态:0未删除,1已删除。 */ private Integer deleted;
|
||||
/** 创建毫秒时间戳。 */ private Long createTime;
|
||||
/** 更新毫秒时间戳。 */ private Long updateTime;
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.shoplix.modules.analytics.repository.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.shoplix.modules.analytics.repository.entity.FlowLogEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/** 前台访问打点Mapper。 */
|
||||
@Mapper
|
||||
public interface FlowLogMapper extends BaseMapper<FlowLogEntity> {
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.shoplix.modules.analytics.repository.service;
|
||||
|
||||
import com.shoplix.modules.analytics.repository.entity.FlowLogEntity;
|
||||
import com.shoplix.modules.analytics.repository.mapper.FlowLogMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/** 前台访问打点单表数据源服务。 */
|
||||
@Service
|
||||
public class FlowLogRepositoryService {
|
||||
/** 打点Mapper。 */
|
||||
private final FlowLogMapper mapper;
|
||||
|
||||
/** 注入打点Mapper。 */
|
||||
public FlowLogRepositoryService(FlowLogMapper mapper) {
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
/** 新增一条访问打点。 */
|
||||
public int insert(FlowLogEntity entity) {
|
||||
return mapper.insert(entity);
|
||||
}
|
||||
}
|
||||
+4
-5
@@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 新闻、案例和帮助统一内容持久化实体。 */
|
||||
@Data
|
||||
@@ -26,10 +25,10 @@ public class ContentEntity {
|
||||
/** 推荐标识。 */ private Integer featuredFlag;
|
||||
/** 排序值。 */ private Integer sortNo;
|
||||
/** 发布状态。 */ private String status;
|
||||
/** 发布时间。 */ private LocalDateTime publishTime;
|
||||
/** 下线时间。 */ private LocalDateTime offlineTime;
|
||||
/** 发布时间毫秒时间戳。 */ private Long publishTime;
|
||||
/** 下线时间毫秒时间戳。 */ private Long offlineTime;
|
||||
/** 浏览次数。 */ private Long viewCount;
|
||||
/** 逻辑删除状态。 */ private Integer deleted;
|
||||
/** 创建时间。 */ private LocalDateTime createTime;
|
||||
/** 更新时间。 */ private LocalDateTime updateTime;
|
||||
/** 创建毫秒时间戳。 */ private Long createTime;
|
||||
/** 更新毫秒时间戳。 */ private Long updateTime;
|
||||
}
|
||||
+2
-2
@@ -51,8 +51,8 @@ public class ContentRepositoryService {
|
||||
.eq(ContentEntity::getDeleted, 0));
|
||||
}
|
||||
/** 按业务编号更新内容发布状态。 */
|
||||
public int updateStatus(String siteCode, String contentCode, String status, java.time.LocalDateTime publishTime,
|
||||
java.time.LocalDateTime offlineTime) {
|
||||
public int updateStatus(String siteCode, String contentCode, String status, Long publishTime,
|
||||
Long offlineTime) {
|
||||
return mapper.update(null, Wrappers.<ContentEntity>lambdaUpdate().set(ContentEntity::getStatus, status)
|
||||
.set(ContentEntity::getPublishTime, publishTime).set(ContentEntity::getOfflineTime, offlineTime)
|
||||
.eq(ContentEntity::getSiteCode, siteCode).eq(ContentEntity::getContentCode, contentCode)
|
||||
|
||||
+3
-3
@@ -4,7 +4,6 @@ import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 前台站自定义代码持久化实体。 */
|
||||
@Data
|
||||
@@ -20,6 +19,7 @@ public class SiteCustomCodeEntity {
|
||||
/** 注入位置:HEAD顶部,BODY_START正文顶部,BODY_END正文底部。 */ private String position;
|
||||
/** 是否启用:0停用,1启用。 */ private Integer enabled;
|
||||
/** 排序号。 */ private Integer sortNo;
|
||||
/** 创建时间。 */ private LocalDateTime createTime;
|
||||
/** 更新时间。 */ private LocalDateTime updateTime;
|
||||
/** 逻辑删除状态:0未删除,1已删除。 */ private Integer deleted;
|
||||
/** 创建毫秒时间戳。 */ private Long createTime;
|
||||
/** 更新毫秒时间戳。 */ private Long updateTime;
|
||||
}
|
||||
+3
-4
@@ -4,7 +4,6 @@ import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 前台站页面装修持久化实体。 */
|
||||
@Data
|
||||
@@ -19,7 +18,7 @@ public class SiteDecorationEntity {
|
||||
/** 已发布版本号。 */ private Integer publishedVersion;
|
||||
/** 装修状态:DRAFT草稿,PUBLISHED已发布。 */ private String status;
|
||||
/** 逻辑删除状态:0未删除,1已删除。 */ private Integer deleted;
|
||||
/** 创建时间。 */ private LocalDateTime createTime;
|
||||
/** 更新时间。 */ private LocalDateTime updateTime;
|
||||
/** 最近发布时间。 */ private LocalDateTime publishTime;
|
||||
/** 创建毫秒时间戳。 */ private Long createTime;
|
||||
/** 更新毫秒时间戳。 */ private Long updateTime;
|
||||
/** 最近发布毫秒时间戳。 */ private Long publishTime;
|
||||
}
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
package com.shoplix.modules.inquiry.repository.entity;
|
||||
import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.time.LocalDateTime;
|
||||
import com.baomidou.mybatisplus.annotation.*; import lombok.Data;
|
||||
/** 询盘操作日志持久化实体。 */ @Data @TableName("inquiry_operation_log")
|
||||
public class InquiryOperationLogEntity {
|
||||
/** 数据库内部主键。 */ @TableId(type=IdType.AUTO) private Long id; /** 日志业务编号。 */ private String logCode;
|
||||
/** 站点业务编号。 */ private String siteCode; /** 询盘业务编号。 */ private String inquiryCode; /** 操作用户编号。 */ private String operatorUserCode;
|
||||
/** 操作类型。 */ private String operationType; /** 操作前状态。 */ private String beforeStatus; /** 操作后状态。 */ private String afterStatus;
|
||||
/** 操作说明。 */ private String operationContent; /** 创建时间。 */ private LocalDateTime createTime;
|
||||
/** 操作说明。 */ private String operationContent; /** 逻辑删除状态。 */ private Integer deleted; /** 创建毫秒时间戳。 */ private Long createTime; /** 更新毫秒时间戳。 */ private Long updateTime;
|
||||
}
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
package com.shoplix.modules.inquiry.repository.entity;
|
||||
import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.time.LocalDateTime;
|
||||
import com.baomidou.mybatisplus.annotation.*; import lombok.Data;
|
||||
/** 客户原始询盘持久化实体。 */ @Data @TableName("inquiry_record")
|
||||
public class InquiryRecordEntity {
|
||||
/** 数据库内部主键。 */ @TableId(type=IdType.AUTO) private Long id; /** 询盘业务编号。 */ private String inquiryCode;
|
||||
@@ -16,9 +16,9 @@ public class InquiryRecordEntity {
|
||||
/** UTM来源。 */ private String utmSource; /** UTM媒介。 */ private String utmMedium; /** UTM活动。 */ private String utmCampaign;
|
||||
/** UTM内容。 */ private String utmContent; /** UTM关键词。 */ private String utmTerm; /** 来源地址。 */ private String referrerUrl;
|
||||
/** 落地地址。 */ private String landingUrl; /** 客户访问IP地址。 */ private String clientIp; /** IP摘要。 */ private String ipHash; /** 浏览器标识。 */ private String userAgent;
|
||||
/** 设备类型。 */ private String deviceType; /** 隐私授权标识。 */ private Integer privacyConsentFlag; /** 隐私授权时间。 */ private LocalDateTime privacyConsentTime;
|
||||
/** 设备类型。 */ private String deviceType; /** 隐私授权标识。 */ private Integer privacyConsentFlag; /** 隐私授权毫秒时间戳。 */ private Long privacyConsentTime;
|
||||
/** 重复标识。 */ private Integer duplicateFlag; /** 垃圾标识。 */ private Integer spamFlag; /** 垃圾原因。 */ private String spamReason;
|
||||
/** 首次跟进时间。 */ private LocalDateTime firstFollowTime; /** 最近跟进时间。 */ private LocalDateTime lastFollowTime;
|
||||
/** 下次跟进时间。 */ private LocalDateTime nextFollowTime; /** 关闭时间。 */ private LocalDateTime closeTime;
|
||||
/** 逻辑删除状态。 */ private Integer deleted; /** 创建时间。 */ private LocalDateTime createTime;
|
||||
/** 首次跟进毫秒时间戳。 */ private Long firstFollowTime; /** 最近跟进毫秒时间戳。 */ private Long lastFollowTime;
|
||||
/** 下次跟进毫秒时间戳。 */ private Long nextFollowTime; /** 关闭毫秒时间戳。 */ private Long closeTime;
|
||||
/** 逻辑删除状态。 */ private Integer deleted; /** 创建毫秒时间戳。 */ private Long createTime;
|
||||
}
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
package com.shoplix.modules.inquiry.repository.entity;
|
||||
import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.time.LocalDateTime;
|
||||
/** 邮件任务持久化实体。 */ @Data @TableName("mail_task") public class MailTaskEntity {/** 数据库内部主键。 */ @TableId(type=IdType.AUTO) private Long id; /** 任务业务编号。 */ private String taskCode; /** 站点业务编号。 */ private String siteCode; /** 业务类型。 */ private String businessType; /** 业务编号。 */ private String businessCode; /** 邮件类型。 */ private String mailType; /** 收件邮箱。 */ private String recipient; /** 邮件主题。 */ private String subject; /** 邮件正文。 */ private String content; /** 任务状态。 */ private String status; /** 重试次数。 */ private Integer retryCount; /** 下次重试时间。 */ private LocalDateTime nextRetryTime; /** 最近错误。 */ private String lastError; /** 发送时间。 */ private LocalDateTime sendTime; /** 逻辑删除状态。 */ private Integer deleted;}
|
||||
import com.baomidou.mybatisplus.annotation.*; import lombok.Data;
|
||||
/** 邮件任务持久化实体。 */ @Data @TableName("mail_task") public class MailTaskEntity {/** 数据库内部主键。 */ @TableId(type=IdType.AUTO) private Long id; /** 任务业务编号。 */ private String taskCode; /** 站点业务编号。 */ private String siteCode; /** 业务类型。 */ private String businessType; /** 业务编号。 */ private String businessCode; /** 邮件类型。 */ private String mailType; /** 收件邮箱。 */ private String recipient; /** 邮件主题。 */ private String subject; /** 邮件正文。 */ private String content; /** 任务状态。 */ private String status; /** 重试次数。 */ private Integer retryCount; /** 下次重试毫秒时间戳。 */ private Long nextRetryTime; /** 最近错误。 */ private String lastError; /** 发送毫秒时间戳。 */ private Long sendTime; /** 逻辑删除状态。 */ private Integer deleted;}
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
package com.shoplix.modules.inquiry.repository.service;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.shoplix.modules.inquiry.repository.entity.InquiryRecordEntity; import com.shoplix.modules.inquiry.repository.mapper.InquiryRecordMapper; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.*;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.shoplix.modules.inquiry.repository.entity.InquiryRecordEntity; import com.shoplix.modules.inquiry.repository.mapper.InquiryRecordMapper; import org.springframework.stereotype.Service; import java.util.*;
|
||||
/** 询盘记录单表数据源服务。 */ @Service
|
||||
public class InquiryRecordRepositoryService {
|
||||
private final InquiryRecordMapper mapper; /** 注入Mapper。 */ public InquiryRecordRepositoryService(InquiryRecordMapper mapper){this.mapper=mapper;}
|
||||
@@ -7,6 +7,6 @@ public class InquiryRecordRepositoryService {
|
||||
/** 查询后台询盘列表。 */ public List<InquiryRecordEntity> list(String site,String status){var q=Wrappers.<InquiryRecordEntity>lambdaQuery().eq(InquiryRecordEntity::getSiteCode,site);if(status!=null&&!status.isBlank())q.eq(InquiryRecordEntity::getStatus,status);return mapper.selectList(q.orderByDesc(InquiryRecordEntity::getCreateTime).last("LIMIT 500"));}
|
||||
/** 按编号查询询盘。 */ public Optional<InquiryRecordEntity> find(String site,String code){return Optional.ofNullable(mapper.selectOne(Wrappers.<InquiryRecordEntity>lambdaQuery().eq(InquiryRecordEntity::getSiteCode,site).eq(InquiryRecordEntity::getInquiryCode,code)));}
|
||||
/** 更新可变处理字段。 */ public int update(InquiryRecordEntity e){return mapper.update(e,Wrappers.<InquiryRecordEntity>lambdaUpdate().eq(InquiryRecordEntity::getSiteCode,e.getSiteCode()).eq(InquiryRecordEntity::getInquiryCode,e.getInquiryCode()));}
|
||||
/** 统计IP时间窗口提交数。 */ public long countIp(String site,String hash,LocalDateTime start){return mapper.selectCount(Wrappers.<InquiryRecordEntity>lambdaQuery().eq(InquiryRecordEntity::getSiteCode,site).eq(InquiryRecordEntity::getIpHash,hash).ge(InquiryRecordEntity::getCreateTime,start));}
|
||||
/** 统计邮箱时间窗口提交数。 */ public long countEmail(String site,String hash,LocalDateTime start){return mapper.selectCount(Wrappers.<InquiryRecordEntity>lambdaQuery().eq(InquiryRecordEntity::getSiteCode,site).eq(InquiryRecordEntity::getEmailHash,hash).ge(InquiryRecordEntity::getCreateTime,start));}
|
||||
/** 统计IP时间窗口提交数。 */ public long countIp(String site,String hash,Long start){return mapper.selectCount(Wrappers.<InquiryRecordEntity>lambdaQuery().eq(InquiryRecordEntity::getSiteCode,site).eq(InquiryRecordEntity::getIpHash,hash).ge(InquiryRecordEntity::getCreateTime,start));}
|
||||
/** 统计邮箱时间窗口提交数。 */ public long countEmail(String site,String hash,Long start){return mapper.selectCount(Wrappers.<InquiryRecordEntity>lambdaQuery().eq(InquiryRecordEntity::getSiteCode,site).eq(InquiryRecordEntity::getEmailHash,hash).ge(InquiryRecordEntity::getCreateTime,start));}
|
||||
}
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
package com.shoplix.modules.media.repository.entity;
|
||||
import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.time.LocalDateTime;
|
||||
/** 站点媒体资源持久化实体。 */ @Data @TableName("media_asset") public class MediaAssetEntity {/** 数据库内部主键。 */ @TableId(type=IdType.AUTO) private Long id; /** 媒体业务编号。 */ private String mediaCode; /** 站点业务编号。 */ private String siteCode; /** 媒体类型。 */ private String mediaType; /** 原始文件名。 */ private String originalFileName; /** 存储文件名。 */ private String storageFileName; /** 相对访问地址。 */ private String relativeUrl; /** MIME类型。 */ private String mimeType; /** 文件扩展名。 */ private String fileExtension; /** 文件字节数。 */ private Long fileSize; /** 图片英文替代文本。 */ private String altText; /** 状态。 */ private String status; /** 逻辑删除状态。 */ private Integer deleted; /** 创建时间。 */ private LocalDateTime createTime;}
|
||||
import com.baomidou.mybatisplus.annotation.*; import lombok.Data;
|
||||
/** 站点媒体资源持久化实体。 */ @Data @TableName("media_asset") public class MediaAssetEntity {/** 数据库内部主键。 */ @TableId(type=IdType.AUTO) private Long id; /** 媒体业务编号。 */ private String mediaCode; /** 站点业务编号。 */ private String siteCode; /** 媒体类型。 */ private String mediaType; /** 原始文件名。 */ private String originalFileName; /** 存储文件名。 */ private String storageFileName; /** 相对访问地址。 */ private String relativeUrl; /** MIME类型。 */ private String mimeType; /** 文件扩展名。 */ private String fileExtension; /** 文件字节数。 */ private Long fileSize; /** 图片英文替代文本。 */ private String altText; /** 状态。 */ private String status; /** 逻辑删除状态。 */ private Integer deleted; /** 创建毫秒时间戳。 */ private Long createTime;}
|
||||
@@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 固定页面和自定义页面持久化实体。 */
|
||||
@Data
|
||||
@@ -23,10 +22,10 @@ public class PageEntity {
|
||||
/** 封面媒体业务编号。 */ private String coverMediaCode;
|
||||
/** 排序值。 */ private Integer sortNo;
|
||||
/** 发布状态。 */ private String status;
|
||||
/** 发布时间。 */ private LocalDateTime publishTime;
|
||||
/** 下线时间。 */ private LocalDateTime offlineTime;
|
||||
/** 发布时间毫秒时间戳。 */ private Long publishTime;
|
||||
/** 下线时间毫秒时间戳。 */ private Long offlineTime;
|
||||
/** 已发布版本号。 */ private Integer publishedVersion;
|
||||
/** 逻辑删除状态。 */ private Integer deleted;
|
||||
/** 创建时间。 */ private LocalDateTime createTime;
|
||||
/** 更新时间。 */ private LocalDateTime updateTime;
|
||||
/** 创建毫秒时间戳。 */ private Long createTime;
|
||||
/** 更新毫秒时间戳。 */ private Long updateTime;
|
||||
}
|
||||
+8
@@ -35,6 +35,14 @@ public class PageRepositoryService {
|
||||
.orderByAsc(PageEntity::getSortNo).orderByDesc(PageEntity::getUpdateTime));
|
||||
}
|
||||
|
||||
/** 查询站点全部已发布固定页面和自定义页面。 */
|
||||
public List<PageEntity> listPublished(String siteCode) {
|
||||
return mapper.selectList(Wrappers.<PageEntity>lambdaQuery()
|
||||
.eq(PageEntity::getSiteCode, siteCode)
|
||||
.eq(PageEntity::getStatus, "PUBLISHED")
|
||||
.orderByAsc(PageEntity::getSortNo));
|
||||
}
|
||||
|
||||
/** 新增页面。 */ public int insert(PageEntity entity) { return mapper.insert(entity); }
|
||||
/** 按页面业务编号更新页面。 */
|
||||
public int updateByCode(PageEntity entity) {
|
||||
|
||||
+4
-5
@@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** B2B 产品持久化实体。 */
|
||||
@Data
|
||||
@@ -25,9 +24,9 @@ public class ProductEntity {
|
||||
/** 询盘启用标识。 */ private Integer inquiryEnabled;
|
||||
/** 排序值。 */ private Integer sortNo;
|
||||
/** 发布状态。 */ private String status;
|
||||
/** 发布时间。 */ private LocalDateTime publishTime;
|
||||
/** 下线时间。 */ private LocalDateTime offlineTime;
|
||||
/** 发布时间毫秒时间戳。 */ private Long publishTime;
|
||||
/** 下线时间毫秒时间戳。 */ private Long offlineTime;
|
||||
/** 逻辑删除状态。 */ private Integer deleted;
|
||||
/** 创建时间。 */ private LocalDateTime createTime;
|
||||
/** 更新时间。 */ private LocalDateTime updateTime;
|
||||
/** 创建毫秒时间戳。 */ private Long createTime;
|
||||
/** 更新毫秒时间戳。 */ private Long updateTime;
|
||||
}
|
||||
+2
-2
@@ -51,8 +51,8 @@ public class ProductRepositoryService {
|
||||
.eq(ProductEntity::getDeleted, 0));
|
||||
}
|
||||
/** 按业务编号更新产品发布状态。 */
|
||||
public int updateStatus(String siteCode, String productCode, String status, java.time.LocalDateTime publishTime,
|
||||
java.time.LocalDateTime offlineTime) {
|
||||
public int updateStatus(String siteCode, String productCode, String status, Long publishTime,
|
||||
Long offlineTime) {
|
||||
return mapper.update(null, Wrappers.<ProductEntity>lambdaUpdate().set(ProductEntity::getStatus, status)
|
||||
.set(ProductEntity::getPublishTime, publishTime).set(ProductEntity::getOfflineTime, offlineTime)
|
||||
.eq(ProductEntity::getSiteCode, siteCode).eq(ProductEntity::getProductCode, productCode)
|
||||
|
||||
+8
@@ -7,6 +7,7 @@ import com.shoplix.modules.seo.repository.mapper.SeoMetadataMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.List;
|
||||
|
||||
/** 封装 SEO 元数据单表读写。 */
|
||||
@Service
|
||||
@@ -36,6 +37,13 @@ public class SeoMetadataRepositoryService {
|
||||
.last("LIMIT 1")));
|
||||
}
|
||||
|
||||
/** 查询站点全部已发布 SEO 配置,用于生成站点地图。 */
|
||||
public List<SeoMetadataEntity> listPublished(String siteCode) {
|
||||
return mapper.selectList(Wrappers.<SeoMetadataEntity>lambdaQuery()
|
||||
.eq(SeoMetadataEntity::getSiteCode, siteCode)
|
||||
.eq(SeoMetadataEntity::getStatus, SeoPublishStatusEnum.PUBLISHED.name()));
|
||||
}
|
||||
|
||||
/** 新增 SEO 配置并返回影响行数。 */
|
||||
public int insert(SeoMetadataEntity entity) { return mapper.insert(entity); }
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.shoplix.site.controller;
|
||||
|
||||
import com.shoplix.site.dto.FlowVisitorDto;
|
||||
import com.shoplix.site.facade.SiteAnalyticsFacade;
|
||||
import com.shoplix.site.modules.analytics.req.FlowReportSiteReq;
|
||||
import com.shoplix.site.modules.analytics.req.SensorsBeaconSiteReq;
|
||||
import com.shoplix.site.modules.common.res.CommonSiteRes;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
/** 前台访问打点接口。 */
|
||||
@RestController
|
||||
@RequestMapping("/api/site/v1/analytics")
|
||||
public class SiteAnalyticsController {
|
||||
/** 打点统一出口。 */ private final SiteAnalyticsFacade facade;
|
||||
|
||||
/** 注入打点统一出口。 */
|
||||
public SiteAnalyticsController(SiteAnalyticsFacade facade) {
|
||||
this.facade = facade;
|
||||
}
|
||||
|
||||
/** 接收并立即保存单条前台访问打点。 */
|
||||
@PostMapping("/report")
|
||||
public CommonSiteRes report(@Valid @RequestBody FlowReportSiteReq request, HttpServletRequest servletRequest) {
|
||||
facade.report(request, new FlowVisitorDto(resolveIp(servletRequest), servletRequest.getHeader("User-Agent")));
|
||||
return CommonSiteRes.success();
|
||||
}
|
||||
|
||||
/** 接收神策Web SDK协议并立即保存单条前台访问打点。 */
|
||||
@PostMapping(value = "/beacon-report-flow", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
|
||||
public CommonSiteRes reportSensors(@Valid SensorsBeaconSiteReq request, HttpServletRequest servletRequest) {
|
||||
facade.reportSensors(request,
|
||||
new FlowVisitorDto(resolveIp(servletRequest), servletRequest.getHeader("User-Agent")));
|
||||
return CommonSiteRes.success();
|
||||
}
|
||||
|
||||
/** 优先读取反向代理传递的原始客户端IP。 */
|
||||
private String resolveIp(HttpServletRequest request) {
|
||||
String forwarded = request.getHeader("X-Forwarded-For");
|
||||
if (forwarded != null && !forwarded.isBlank()) return forwarded.split(",", 2)[0].trim();
|
||||
String realIp = request.getHeader("X-Real-IP");
|
||||
return realIp == null || realIp.isBlank() ? request.getRemoteAddr() : realIp.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.shoplix.site.controller;
|
||||
|
||||
import com.shoplix.site.modules.seo.res.SeoDocumentSiteRes;
|
||||
import com.shoplix.site.service.SiteSeoDocumentService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/** 前台站 Sitemap 与 Robots 标准文档接口。 */
|
||||
@RestController
|
||||
public class SiteSeoDocumentController {
|
||||
/** 站点 SEO 文档服务。 */
|
||||
private final SiteSeoDocumentService service;
|
||||
|
||||
/** 注入站点 SEO 文档服务。 */
|
||||
public SiteSeoDocumentController(SiteSeoDocumentService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
/** 输出当前域名站点地图。 */
|
||||
@GetMapping(value = {"/sitemap.xml", "/api/site/v1/seo/sitemap.xml"})
|
||||
public ResponseEntity<String> sitemap() {
|
||||
return response(service.sitemap());
|
||||
}
|
||||
|
||||
/** 输出当前域名搜索引擎抓取规则。 */
|
||||
@GetMapping(value = {"/robots.txt", "/api/site/v1/seo/robots.txt"})
|
||||
public ResponseEntity<String> robots() {
|
||||
return response(service.robots());
|
||||
}
|
||||
|
||||
/** 构造带标准媒体类型的文档响应。 */
|
||||
private ResponseEntity<String> response(SeoDocumentSiteRes document) {
|
||||
return ResponseEntity.ok().header("Content-Type", document.contentType() + ";charset=UTF-8")
|
||||
.body(document.content());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.shoplix.site.dto;
|
||||
|
||||
/** 服务端采集的访问打点信息。 */
|
||||
public record FlowVisitorDto(
|
||||
/** 客户端IP地址。 */ String ipAddress,
|
||||
/** 用户代理。 */ String userAgent) {
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.shoplix.site.dto;
|
||||
|
||||
/** Sitemap 单个地址内部传输模型。 */
|
||||
public record SitemapEntryDto(String location, String lastModified) {
|
||||
/** location 为绝对地址,lastModified 为 ISO 日期。 */
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.shoplix.site.facade;
|
||||
|
||||
import com.shoplix.site.dto.FlowVisitorDto;
|
||||
import com.shoplix.site.modules.analytics.req.FlowReportSiteReq;
|
||||
import com.shoplix.site.modules.analytics.req.SensorsBeaconSiteReq;
|
||||
import com.shoplix.site.service.SiteAnalyticsService;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** 前台访问打点统一出口。 */
|
||||
@Component
|
||||
public class SiteAnalyticsFacade {
|
||||
/** 打点业务服务。 */ private final SiteAnalyticsService service;
|
||||
|
||||
/** 注入打点业务服务。 */
|
||||
public SiteAnalyticsFacade(SiteAnalyticsService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
/** 保存单条访问打点。 */
|
||||
public void report(FlowReportSiteReq request, FlowVisitorDto visitor) {
|
||||
service.report(request, visitor);
|
||||
}
|
||||
|
||||
/** 解码并保存神策Web SDK单条打点。 */
|
||||
public void reportSensors(SensorsBeaconSiteReq request, FlowVisitorDto visitor) {
|
||||
service.reportSensors(request, visitor);
|
||||
}
|
||||
}
|
||||
@@ -34,9 +34,12 @@ public class SiteContextFilter extends OncePerRequestFilter {
|
||||
}
|
||||
}
|
||||
|
||||
/** 仅处理前台站接口。 */
|
||||
/** 处理前台接口及搜索引擎标准文档路径。 */
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
return !request.getRequestURI().startsWith("/api/site/");
|
||||
String uri = request.getRequestURI();
|
||||
return !request.getRequestURI().startsWith("/api/site/")
|
||||
&& !"/sitemap.xml".equals(uri)
|
||||
&& !"/robots.txt".equals(uri);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.shoplix.site.modules.analytics.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.Map;
|
||||
|
||||
/** 神策Web SDK事件传输模型。 */
|
||||
public record SensorsEventSiteDto(
|
||||
/** 匿名访客标识。 */ @JsonProperty("distinct_id") String distinctId,
|
||||
/** 事件毫秒时间戳。 */ Long time,
|
||||
/** 神策事件类型。 */ String type,
|
||||
/** 神策事件名称。 */ String event,
|
||||
/** 神策事件属性。 */ Map<String, Object> properties) {
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.shoplix.site.modules.analytics.req;
|
||||
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
/** 前台访问打点上报请求。 */
|
||||
public record FlowReportSiteReq(
|
||||
/** 语言编码。 */ @Size(max = 50) String language,
|
||||
/** 事件编码:page_view、page_leave、search、submit_inquiry或click。 */ @NotBlank @Size(max = 100) String eventName,
|
||||
/** 事件详情。 */ @Size(max = 255) String eventDetail,
|
||||
/** 进入页面毫秒时间戳。 */ Long startTime,
|
||||
/** 离开页面毫秒时间戳。 */ Long endTime,
|
||||
/** 匿名访客标识。 */ @NotBlank @Size(max = 100) String cuid,
|
||||
/** 访问场景。 */ @Size(max = 255) String scene,
|
||||
/** 新访客标识:0否,1是。 */ @Min(0) @Max(1) Integer newVisitorFlag,
|
||||
/** 会话首次访问标识:0否,1是。 */ @Min(0) @Max(1) Integer sessionFirstFlag,
|
||||
/** 单次会话标识。 */ @NotBlank @Size(max = 100) String sessionCode,
|
||||
/** 页面名称。 */ @Size(max = 255) String pageName,
|
||||
/** 页面类型编码。 */ @Size(max = 50) String pageCode,
|
||||
/** 页面标题。 */ @Size(max = 500) String pageTitle,
|
||||
/** 页面关联业务编号。 */ @Size(max = 16) String targetCode,
|
||||
/** SEO路径。 */ @Size(max = 512) String seoLink,
|
||||
/** 设备像素比。 */ @Size(max = 20) String pixelRatio,
|
||||
/** 浏览器平台。 */ @Size(max = 100) String platform,
|
||||
/** 社媒渠道。 */ @Size(max = 100) String socialMediaChannel,
|
||||
/** 流量渠道。 */ @Size(max = 100) String flowChannel,
|
||||
/** UTM来源平台。 */ @Size(max = 100) String utmSource,
|
||||
/** UTM活动。 */ @Size(max = 100) String utmCampaign,
|
||||
/** UTM广告组。 */ @Size(max = 100) String utmAdgroup,
|
||||
/** 落地页域名。 */ @Size(max = 255) String landingDomain,
|
||||
/** 落地页完整地址。 */ @Size(max = 512) String landingUrl,
|
||||
/** 落地页路径。 */ @Size(max = 512) String landingUrlBody,
|
||||
/** 窗口高度。 */ @Min(0) Integer winHeight,
|
||||
/** 窗口宽度。 */ @Min(0) Integer winWidth,
|
||||
/** 当前域名。 */ @Size(max = 500) String domain,
|
||||
/** 当前地址,不包含查询参数。 */ @Size(max = 2000) String urlInfo,
|
||||
/** 当前完整地址。 */ @Size(max = 4000) String url,
|
||||
/** 当前路径。 */ @Size(max = 2000) String urlBody,
|
||||
/** 当前查询参数。 */ @Size(max = 2000) String urlArgs,
|
||||
/** 屏幕宽度。 */ @Min(0) Integer screenWidth,
|
||||
/** 屏幕高度。 */ @Min(0) Integer screenHeight,
|
||||
/** 来源地址。 */ @Size(max = 512) String referrerUrl,
|
||||
/** 页面停留时长秒。 */ @Min(0) Integer duration,
|
||||
/** 网络类型。 */ @Size(max = 50) String network,
|
||||
/** 操作系统。 */ @Size(max = 100) String system,
|
||||
/** 浏览器名称。 */ @Size(max = 255) String browser,
|
||||
/** 浏览器版本。 */ @Size(max = 255) String browserVersion,
|
||||
/** 设备类型:DESKTOP、MOBILE或TABLET。 */ @Size(max = 50) String device) {
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.shoplix.site.modules.analytics.req;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
/** 神策Web SDK打点上报请求。 */
|
||||
public class SensorsBeaconSiteReq {
|
||||
/** Base64编码的神策事件JSON。 */
|
||||
@NotBlank
|
||||
private String data;
|
||||
/** 神策SDK附加校验信息。 */
|
||||
private String ext;
|
||||
|
||||
/** 获取事件数据。 */
|
||||
public String getData() { return data; }
|
||||
/** 设置事件数据。 */
|
||||
public void setData(String data) { this.data = data; }
|
||||
/** 获取附加校验信息。 */
|
||||
public String getExt() { return ext; }
|
||||
/** 设置附加校验信息。 */
|
||||
public void setExt(String ext) { this.ext = ext; }
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.shoplix.site.modules.content.res;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 前台站内容详情响应。 */
|
||||
public record ContentDetailSiteRes(
|
||||
@@ -13,6 +12,6 @@ public record ContentDetailSiteRes(
|
||||
/** 封面媒体业务编号。 */ String coverMediaCode,
|
||||
/** 封面媒体访问地址。 */ String coverMediaUrl,
|
||||
/** 作者名称。 */ String authorName,
|
||||
/** 发布时间。 */ LocalDateTime publishTime) {
|
||||
/** 发布时间毫秒时间戳。 */ Long publishTime) {
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.shoplix.site.modules.content.res;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 前台站内容列表项响应。 */
|
||||
public record ContentItemSiteRes(
|
||||
@@ -11,6 +10,6 @@ public record ContentItemSiteRes(
|
||||
/** 英文摘要。 */ String summary,
|
||||
/** 封面媒体业务编号。 */ String coverMediaCode,
|
||||
/** 封面媒体访问地址。 */ String coverMediaUrl,
|
||||
/** 发布时间。 */ LocalDateTime publishTime) {
|
||||
/** 发布时间毫秒时间戳。 */ Long publishTime) {
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.shoplix.site.modules.seo.res;
|
||||
|
||||
/** 搜索引擎标准文档响应。 */
|
||||
public record SeoDocumentSiteRes(String content, String contentType) {
|
||||
/** content 为文档正文,contentType 为标准媒体类型。 */
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package com.shoplix.site.service;
|
||||
|
||||
import com.shoplix.common.code.enums.BusinessCodePrefixEnum;
|
||||
import com.shoplix.common.context.SiteContextHolder;
|
||||
import com.shoplix.common.exception.BusinessException;
|
||||
import com.shoplix.common.utils.BusinessCodeUtils;
|
||||
import com.shoplix.modules.analytics.enums.FlowEventEnum;
|
||||
import com.shoplix.modules.analytics.repository.entity.FlowLogEntity;
|
||||
import com.shoplix.modules.analytics.repository.service.FlowLogRepositoryService;
|
||||
import com.shoplix.site.dto.FlowVisitorDto;
|
||||
import com.shoplix.site.modules.analytics.dto.SensorsEventSiteDto;
|
||||
import com.shoplix.site.modules.analytics.req.FlowReportSiteReq;
|
||||
import com.shoplix.site.modules.analytics.req.SensorsBeaconSiteReq;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.WeekFields;
|
||||
import java.util.Locale;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/** 前台访问打点业务。 */
|
||||
@Service
|
||||
public class SiteAnalyticsService {
|
||||
/** 打点仓储服务。 */ private final FlowLogRepositoryService repository;
|
||||
/** 业务编号生成器。 */ private final BusinessCodeUtils codes;
|
||||
/** JSON转换器。 */ private final ObjectMapper objectMapper;
|
||||
|
||||
/** 注入打点业务依赖。 */
|
||||
public SiteAnalyticsService(FlowLogRepositoryService repository, BusinessCodeUtils codes,
|
||||
ObjectMapper objectMapper) {
|
||||
this.repository = repository;
|
||||
this.codes = codes;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/** 解码神策Web SDK协议并立即保存单条打点。 */
|
||||
public void reportSensors(SensorsBeaconSiteReq request, FlowVisitorDto visitor) {
|
||||
SensorsEventSiteDto event;
|
||||
try {
|
||||
byte[] decoded;
|
||||
try {
|
||||
decoded = Base64.getDecoder().decode(request.getData());
|
||||
} catch (IllegalArgumentException exception) {
|
||||
decoded = Base64.getUrlDecoder().decode(request.getData());
|
||||
}
|
||||
event = objectMapper.readValue(new String(decoded, StandardCharsets.UTF_8), SensorsEventSiteDto.class);
|
||||
} catch (Exception exception) {
|
||||
throw new BusinessException("FLOW_PAYLOAD_INVALID", "Invalid analytics payload");
|
||||
}
|
||||
Map<String, Object> properties = event.properties() == null ? Map.of() : event.properties();
|
||||
report(new FlowReportSiteReq(
|
||||
text(properties, "language"), eventName(event.event()), text(properties, "event_detail"),
|
||||
number(properties, "start_time"), event.time(), event.distinctId(), text(properties, "scene"),
|
||||
integer(properties, "is_new_visitor"), integer(properties, "is_session_first"),
|
||||
text(properties, "session_id"), text(properties, "$title"), text(properties, "page_code"),
|
||||
text(properties, "$title"), text(properties, "target_code"), text(properties, "$url_path"),
|
||||
text(properties, "pixel_ratio"), text(properties, "$os"), text(properties, "social_media_channel"),
|
||||
text(properties, "flow_channel"), text(properties, "utm_source"), text(properties, "utm_campaign"),
|
||||
text(properties, "utm_adgroup"), text(properties, "landing_domain"), text(properties, "landing_url"),
|
||||
text(properties, "landing_url_body"), integer(properties, "win_height"), integer(properties, "win_width"),
|
||||
text(properties, "domain"), text(properties, "$url"), text(properties, "$url"),
|
||||
text(properties, "$url_path"), text(properties, "url_args"), integer(properties, "$screen_width"),
|
||||
integer(properties, "$screen_height"), text(properties, "$referrer"), integer(properties, "duration"),
|
||||
text(properties, "network"), text(properties, "$os"), text(properties, "$browser"),
|
||||
text(properties, "$browser_version"), text(properties, "$device_type")), visitor);
|
||||
}
|
||||
|
||||
/** 校验并立即保存单条访问打点。 */
|
||||
@Transactional
|
||||
public void report(FlowReportSiteReq request, FlowVisitorDto visitor) {
|
||||
if (!FlowEventEnum.supports(request.eventName())) {
|
||||
throw new BusinessException("FLOW_EVENT_UNSUPPORTED", "Unsupported analytics event");
|
||||
}
|
||||
long now = Instant.now().toEpochMilli();
|
||||
long eventTime = validClientTime(request.endTime(), validClientTime(request.startTime(), now));
|
||||
ZonedDateTime dateTime = Instant.ofEpochMilli(eventTime).atZone(ZoneOffset.UTC);
|
||||
FlowLogEntity entity = new FlowLogEntity();
|
||||
entity.setFlowCode(codes.generate(BusinessCodePrefixEnum.FLOW_LOG));
|
||||
entity.setSiteCode(SiteContextHolder.getRequired().siteCode());
|
||||
entity.setLanguage(defaultValue(request.language(), "en"));
|
||||
entity.setTs(eventTime);
|
||||
entity.setDt(dateTime.getYear() * 10000 + dateTime.getMonthValue() * 100 + dateTime.getDayOfMonth());
|
||||
entity.setYyyy(dateTime.getYear());
|
||||
entity.setMm(dateTime.getMonthValue());
|
||||
entity.setWeek(dateTime.get(WeekFields.ISO.weekOfWeekBasedYear()));
|
||||
entity.setHh(dateTime.getHour());
|
||||
entity.setEventName(request.eventName());
|
||||
entity.setEventDetail(request.eventDetail());
|
||||
entity.setStartTime(request.startTime());
|
||||
entity.setEndTime(request.endTime());
|
||||
entity.setCuid(request.cuid());
|
||||
entity.setUserCode(null);
|
||||
entity.setScene(request.scene());
|
||||
entity.setNewVisitorFlag(defaultValue(request.newVisitorFlag(), 0));
|
||||
entity.setSessionFirstFlag(defaultValue(request.sessionFirstFlag(), 0));
|
||||
entity.setSessionCode(request.sessionCode());
|
||||
entity.setPageName(request.pageName());
|
||||
entity.setPageCode(request.pageCode());
|
||||
entity.setPageTitle(request.pageTitle());
|
||||
entity.setTargetCode(request.targetCode());
|
||||
entity.setSeoLink(request.seoLink());
|
||||
entity.setPixelRatio(request.pixelRatio());
|
||||
entity.setPlatform(request.platform());
|
||||
entity.setSocialMediaChannel(request.socialMediaChannel());
|
||||
entity.setFlowChannel(request.flowChannel());
|
||||
entity.setUtmSource(request.utmSource());
|
||||
entity.setUtmCampaign(request.utmCampaign());
|
||||
entity.setUtmAdgroup(request.utmAdgroup());
|
||||
entity.setLandingDomain(request.landingDomain());
|
||||
entity.setLandingUrl(request.landingUrl());
|
||||
entity.setLandingUrlBody(request.landingUrlBody());
|
||||
entity.setLanding(joinLanding(request.landingDomain(), request.landingUrlBody()));
|
||||
entity.setWinHeight(request.winHeight());
|
||||
entity.setWinWidth(request.winWidth());
|
||||
entity.setDomain(request.domain());
|
||||
entity.setUrlInfo(request.urlInfo());
|
||||
entity.setUrl(request.url());
|
||||
entity.setUrlBody(request.urlBody());
|
||||
entity.setUrlArgs(request.urlArgs());
|
||||
entity.setScreenWidth(request.screenWidth());
|
||||
entity.setScreenHeight(request.screenHeight());
|
||||
entity.setIpAddress(visitor.ipAddress());
|
||||
entity.setIsoCode(null);
|
||||
entity.setCountryName(null);
|
||||
entity.setProvinceName(null);
|
||||
entity.setCityName(null);
|
||||
entity.setReferrerUrl(request.referrerUrl());
|
||||
entity.setDuration(request.duration());
|
||||
entity.setUa(visitor.userAgent());
|
||||
entity.setNetwork(request.network());
|
||||
entity.setOperatingSystem(request.system());
|
||||
entity.setBrowser(request.browser());
|
||||
entity.setBrowserVersion(request.browserVersion());
|
||||
entity.setDevice(request.device());
|
||||
entity.setDeleted(0);
|
||||
entity.setCreateTime(now);
|
||||
entity.setUpdateTime(now);
|
||||
if (repository.insert(entity) != 1) {
|
||||
throw new BusinessException("FLOW_LOG_SAVE_FAILED", "Analytics event could not be saved");
|
||||
}
|
||||
}
|
||||
|
||||
/** 防止客户端伪造明显异常的事件时间。 */
|
||||
private long validClientTime(Long value, long fallback) {
|
||||
if (value == null || Math.abs(Instant.now().toEpochMilli() - value) > 86_400_000L) return fallback;
|
||||
return value;
|
||||
}
|
||||
|
||||
/** 返回非空值或默认值。 */
|
||||
private <T> T defaultValue(T value, T fallback) {
|
||||
return value == null ? fallback : value;
|
||||
}
|
||||
|
||||
/** 将神策事件名映射为项目事件编码。 */
|
||||
private String eventName(String event) {
|
||||
return switch (event == null ? "" : event) {
|
||||
case "PageView", "$pageview" -> FlowEventEnum.PAGE_VIEW.getValue();
|
||||
case "PageLeave" -> FlowEventEnum.PAGE_LEAVE.getValue();
|
||||
case "SubmitInquiry" -> FlowEventEnum.SUBMIT_INQUIRY.getValue();
|
||||
case "Search" -> FlowEventEnum.SEARCH.getValue();
|
||||
default -> FlowEventEnum.CLICK.getValue();
|
||||
};
|
||||
}
|
||||
|
||||
/** 读取字符串属性。 */
|
||||
private String text(Map<String, Object> properties, String key) {
|
||||
Object value = properties.get(key);
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
|
||||
/** 读取长整数属性。 */
|
||||
private Long number(Map<String, Object> properties, String key) {
|
||||
Object value = properties.get(key);
|
||||
if (value instanceof Number number) return number.longValue();
|
||||
try { return value == null ? null : Long.valueOf(String.valueOf(value)); }
|
||||
catch (NumberFormatException exception) { return null; }
|
||||
}
|
||||
|
||||
/** 读取整数属性。 */
|
||||
private Integer integer(Map<String, Object> properties, String key) {
|
||||
Long value = number(properties, key);
|
||||
return value == null ? null : value.intValue();
|
||||
}
|
||||
|
||||
/** 合并落地页域名和路径。 */
|
||||
private String joinLanding(String domain, String path) {
|
||||
if (domain == null || domain.isBlank()) return path;
|
||||
if (path == null || path.isBlank()) return domain;
|
||||
return domain + (path.startsWith("/") ? path : "/" + path);
|
||||
}
|
||||
}
|
||||
@@ -33,13 +33,15 @@ public class SiteInquiryService {
|
||||
if(req.website()!=null&&!req.website().isBlank())throw new BusinessException("INQUIRY_REJECTED","Submission rejected");
|
||||
if(setting.getCaptchaEnabled()==1&&(req.captchaToken()==null||req.captchaToken().isBlank()))throw new BusinessException("CAPTCHA_REQUIRED","Captcha verification is required");
|
||||
String email=req.email().trim().toLowerCase(Locale.ROOT), emailHash=HashUtils.sha256(email,hashSalt), ipHash=HashUtils.sha256(visitor.ip()==null?"unknown":visitor.ip(),hashSalt);
|
||||
if(records.countIp(site,ipHash,LocalDateTime.now().minusHours(1))>=setting.getIpHourLimit())throw new BusinessException("INQUIRY_RATE_LIMITED","Too many submissions. Please try again later");
|
||||
if(records.countEmail(site,emailHash,LocalDate.now().atStartOfDay())>=setting.getEmailDayLimit())throw new BusinessException("INQUIRY_RATE_LIMITED","Too many submissions. Please try again later");
|
||||
long now=System.currentTimeMillis();
|
||||
if(records.countIp(site,ipHash,now-3_600_000L)>=setting.getIpHourLimit())throw new BusinessException("INQUIRY_RATE_LIMITED","Too many submissions. Please try again later");
|
||||
long dayStart=LocalDate.now(ZoneOffset.UTC).atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli();
|
||||
if(records.countEmail(site,emailHash,dayStart)>=setting.getEmailDayLimit())throw new BusinessException("INQUIRY_RATE_LIMITED","Too many submissions. Please try again later");
|
||||
List<InquiryFormFieldEntity> defined=fields.list(site,form.getFormCode(),true); Map<String,InquiryFieldValueSiteReq> submitted=(req.fieldValues()==null?List.<InquiryFieldValueSiteReq>of():req.fieldValues()).stream().collect(Collectors.toMap(InquiryFieldValueSiteReq::fieldCode,Function.identity(),(a,b)->b));
|
||||
for(InquiryFormFieldEntity field:defined){InquiryFieldValueSiteReq value=submitted.get(field.getFieldCode());if(field.getRequiredFlag()==1&&(value==null||value.value()==null||value.value().isBlank()))throw new BusinessException("INQUIRY_FIELD_REQUIRED",field.getFieldLabel()+" is required");if(value!=null&&value.value()!=null&&field.getMaxLength()!=null&&value.value().length()>field.getMaxLength())throw new BusinessException("INQUIRY_FIELD_TOO_LONG",field.getFieldLabel()+" is too long");}
|
||||
InquiryRecordEntity record=new InquiryRecordEntity(); record.setInquiryCode(codes.generate(BusinessCodePrefixEnum.INQUIRY));record.setSiteCode(site);record.setFormCode(form.getFormCode());record.setFormVersion(form.getPublishedVersion());record.setInquiryTitleSnapshot(form.getFormName());record.setSourceType(req.sourceType().name());record.setSourceCode(orEmpty(req.sourceCode()));record.setSourceUrl(req.sourceUrl());record.setProductCode("PRODUCT".equals(req.sourceType().name())?orEmpty(req.sourceCode()):"");
|
||||
if(!record.getProductCode().isBlank())products.findByCode(site,record.getProductCode()).ifPresent(p->record.setProductNameSnapshot(p.getProductName()));
|
||||
record.setCustomerName(req.name().trim());record.setCustomerEmail(email);record.setEmailHash(emailHash);record.setCustomerPhone(req.phone());record.setCompanyName(req.company());record.setCountryCode(req.countryCode());record.setCountryName(req.countryCode());record.setMessage(req.message().trim());record.setStatus("NEW");record.setReadStatus(0);record.setRemark("");record.setInquirySnapshot(formSnapshot(form,defined));record.setPriority("NORMAL");record.setOwnerUserCode("");record.setCrmLeadCode("");record.setUtmSource(req.utmSource());record.setUtmMedium(req.utmMedium());record.setUtmCampaign(req.utmCampaign());record.setUtmContent(req.utmContent());record.setUtmTerm(req.utmTerm());record.setReferrerUrl(visitor.referrer());record.setLandingUrl(req.landingUrl());record.setClientIp(visitor.ip());record.setIpHash(ipHash);record.setUserAgent(visitor.userAgent());record.setDeviceType(device(visitor.userAgent()));record.setPrivacyConsentFlag(Boolean.TRUE.equals(req.privacyConsent())?1:0);record.setPrivacyConsentTime(Boolean.TRUE.equals(req.privacyConsent())?LocalDateTime.now():null);record.setDuplicateFlag(records.countEmail(site,emailHash,LocalDateTime.now().minusMinutes(setting.getDuplicateWindowMinutes()))>0?1:0);record.setSpamFlag(0);
|
||||
record.setCustomerName(req.name().trim());record.setCustomerEmail(email);record.setEmailHash(emailHash);record.setCustomerPhone(req.phone());record.setCompanyName(req.company());record.setCountryCode(req.countryCode());record.setCountryName(req.countryCode());record.setMessage(req.message().trim());record.setStatus("NEW");record.setReadStatus(0);record.setRemark("");record.setInquirySnapshot(formSnapshot(form,defined));record.setPriority("NORMAL");record.setOwnerUserCode("");record.setCrmLeadCode("");record.setUtmSource(req.utmSource());record.setUtmMedium(req.utmMedium());record.setUtmCampaign(req.utmCampaign());record.setUtmContent(req.utmContent());record.setUtmTerm(req.utmTerm());record.setReferrerUrl(visitor.referrer());record.setLandingUrl(req.landingUrl());record.setClientIp(visitor.ip());record.setIpHash(ipHash);record.setUserAgent(visitor.userAgent());record.setDeviceType(device(visitor.userAgent()));record.setPrivacyConsentFlag(Boolean.TRUE.equals(req.privacyConsent())?1:0);record.setPrivacyConsentTime(Boolean.TRUE.equals(req.privacyConsent())?now:null);record.setDuplicateFlag(records.countEmail(site,emailHash,now-setting.getDuplicateWindowMinutes()*60_000L)>0?1:0);record.setSpamFlag(0);
|
||||
if(records.insert(record)!=1)throw new BusinessException("INQUIRY_SAVE_FAILED","Inquiry submission failed");
|
||||
int sort=0;for(InquiryFormFieldEntity field:defined){InquiryFieldValueSiteReq value=submitted.get(field.getFieldCode());if(value==null||value.value()==null||value.value().isBlank())continue;InquiryFieldValueEntity e=new InquiryFieldValueEntity();e.setValueCode(codes.generate(BusinessCodePrefixEnum.INQUIRY_FIELD_VALUE));e.setSiteCode(site);e.setInquiryCode(record.getInquiryCode());e.setFieldCode(field.getFieldCode());e.setFieldKey(field.getFieldKey());e.setFieldLabelSnapshot(field.getFieldLabel());e.setFieldTypeSnapshot(field.getFieldType());e.setFieldValue(value.value());e.setSortNo(sort++);if(values.insert(e)!=1)throw new BusinessException("INQUIRY_VALUE_SAVE_FAILED","Inquiry submission failed");}
|
||||
addLog(site,record.getInquiryCode(),"CREATE",null,"NEW","Created from site form");createMailTasks(setting,record,form);
|
||||
@@ -48,7 +50,7 @@ public class SiteInquiryService {
|
||||
/** 转换表单响应。 */ private InquiryFormDetailSiteRes toForm(InquiryFormEntity form,boolean enabled){return new InquiryFormDetailSiteRes(form.getFormCode(),form.getFormName(),form.getDescription(),form.getFormScene(),form.getSubmitButtonText(),form.getSuccessMessage(),form.getPrivacyPageCode(),fields.list(form.getSiteCode(),form.getFormCode(),enabled).stream().map(f->new InquiryFormFieldSiteRes(f.getFieldCode(),f.getFieldKey(),f.getFieldLabel(),f.getFieldType(),f.getPlaceholder(),f.getHelpText(),f.getMaxLength(),f.getRequiredFlag()==1,f.getOptionsJson(),f.getWidthType(),f.getSortNo())).toList());}
|
||||
/** 写入创建日志。 */ private void addLog(String site,String code,String type,String before,String after,String content){InquiryOperationLogEntity e=new InquiryOperationLogEntity();e.setLogCode(codes.generate(BusinessCodePrefixEnum.INQUIRY_LOG));e.setSiteCode(site);e.setInquiryCode(code);e.setOperatorUserCode("");e.setOperationType(type);e.setBeforeStatus(before);e.setAfterStatus(after);e.setOperationContent(content);logs.insert(e);}
|
||||
/** 创建负责人通知和客户确认邮件任务。 */ private void createMailTasks(InquirySettingEntity setting,InquiryRecordEntity record,InquiryFormEntity form){if(setting.getNotificationEnabled()==1)for(var receiver:receivers.listEnabled(record.getSiteCode()))addMail(record,"INQUIRY_NOTIFICATION",receiver.getReceiverEmail(),"New inquiry: "+record.getCustomerName(),record.getMessage());if(setting.getAutoReplyEnabled()==1)addMail(record,"CUSTOMER_CONFIRMATION",record.getCustomerEmail(),setting.getAutoReplySubject()==null?"We received your inquiry":setting.getAutoReplySubject(),setting.getAutoReplyContent()==null?form.getSuccessMessage():setting.getAutoReplyContent());}
|
||||
/** 新建待发送邮件任务。 */ private void addMail(InquiryRecordEntity record,String type,String recipient,String subject,String content){MailTaskEntity e=new MailTaskEntity();e.setTaskCode(codes.generate(BusinessCodePrefixEnum.MAIL_TASK));e.setSiteCode(record.getSiteCode());e.setBusinessType("INQUIRY");e.setBusinessCode(record.getInquiryCode());e.setMailType(type);e.setRecipient(recipient);e.setSubject(subject);e.setContent(content);e.setStatus("PENDING");e.setRetryCount(0);e.setNextRetryTime(LocalDateTime.now());mailTasks.insert(e);}
|
||||
/** 新建待发送邮件任务。 */ private void addMail(InquiryRecordEntity record,String type,String recipient,String subject,String content){MailTaskEntity e=new MailTaskEntity();e.setTaskCode(codes.generate(BusinessCodePrefixEnum.MAIL_TASK));e.setSiteCode(record.getSiteCode());e.setBusinessType("INQUIRY");e.setBusinessCode(record.getInquiryCode());e.setMailType(type);e.setRecipient(recipient);e.setSubject(subject);e.setContent(content);e.setStatus("PENDING");e.setRetryCount(0);e.setNextRetryTime(System.currentTimeMillis());mailTasks.insert(e);}
|
||||
/** 判断设备类型。 */ private String device(String ua){return ua!=null&&ua.toLowerCase(Locale.ROOT).contains("mobile")?"MOBILE":"DESKTOP";} /** 空值转换。 */ private String orEmpty(String value){return value==null?"":value;}
|
||||
/** 生成提交时表单结构快照。 */ private String formSnapshot(InquiryFormEntity form,List<InquiryFormFieldEntity> defined){try{return objectMapper.writeValueAsString(Map.of("formCode",form.getFormCode(),"formName",form.getFormName(),"version",form.getPublishedVersion(),"fields",defined.stream().map(field->Map.of("fieldCode",field.getFieldCode(),"fieldKey",field.getFieldKey(),"label",field.getFieldLabel(),"type",field.getFieldType(),"required",field.getRequiredFlag())).toList()));}catch(JsonProcessingException exception){throw new BusinessException("INQUIRY_SNAPSHOT_FAILED","Inquiry form snapshot failed");}}
|
||||
/** 识别上传图片真实类型。 */ private String detectImageType(MultipartFile file){try{byte[] bytes=file.getBytes();if(bytes.length>=8&&bytes[0]==(byte)0x89&&bytes[1]==0x50&&bytes[2]==0x4E&&bytes[3]==0x47)return "image/png";if(bytes.length>=3&&bytes[0]==(byte)0xFF&&bytes[1]==(byte)0xD8&&bytes[2]==(byte)0xFF)return "image/jpeg";if(bytes.length>=6&&bytes[0]=='G'&&bytes[1]=='I'&&bytes[2]=='F')return "image/gif";if(bytes.length>=12&&bytes[0]=='R'&&bytes[1]=='I'&&bytes[2]=='F'&&bytes[8]=='W'&&bytes[9]=='E'&&bytes[10]=='B'&&bytes[11]=='P')return "image/webp";}catch(IOException exception){throw new BusinessException("INQUIRY_IMAGE_READ_FAILED","Image could not be read");}throw new BusinessException("INQUIRY_IMAGE_TYPE_INVALID","Only JPG, PNG, WebP and GIF images are supported");}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
package com.shoplix.site.service;
|
||||
|
||||
import com.shoplix.common.context.SiteContext;
|
||||
import com.shoplix.common.context.SiteContextHolder;
|
||||
import com.shoplix.modules.content.repository.entity.ContentEntity;
|
||||
import com.shoplix.modules.content.repository.service.ContentRepositoryService;
|
||||
import com.shoplix.modules.page.repository.entity.PageEntity;
|
||||
import com.shoplix.modules.page.repository.service.PageRepositoryService;
|
||||
import com.shoplix.modules.product.repository.entity.ProductEntity;
|
||||
import com.shoplix.modules.product.repository.service.ProductRepositoryService;
|
||||
import com.shoplix.modules.seo.repository.entity.SeoMetadataEntity;
|
||||
import com.shoplix.modules.seo.repository.service.SeoMetadataRepositoryService;
|
||||
import com.shoplix.site.modules.seo.res.SeoDocumentSiteRes;
|
||||
import com.shoplix.site.dto.SitemapEntryDto;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/** 生成站点 Sitemap 与 Robots 标准文档。 */
|
||||
@Service
|
||||
public class SiteSeoDocumentService {
|
||||
/** Sitemap 日期格式。 */
|
||||
private static final DateTimeFormatter SITEMAP_DATE = DateTimeFormatter.ISO_LOCAL_DATE;
|
||||
/** 产品仓储服务。 */
|
||||
private final ProductRepositoryService productRepository;
|
||||
/** 内容仓储服务。 */
|
||||
private final ContentRepositoryService contentRepository;
|
||||
/** 页面仓储服务。 */
|
||||
private final PageRepositoryService pageRepository;
|
||||
/** SEO 元数据仓储服务。 */
|
||||
private final SeoMetadataRepositoryService seoRepository;
|
||||
|
||||
/** 注入站点 SEO 文档依赖。 */
|
||||
public SiteSeoDocumentService(ProductRepositoryService productRepository,
|
||||
ContentRepositoryService contentRepository,
|
||||
PageRepositoryService pageRepository,
|
||||
SeoMetadataRepositoryService seoRepository) {
|
||||
this.productRepository = productRepository;
|
||||
this.contentRepository = contentRepository;
|
||||
this.pageRepository = pageRepository;
|
||||
this.seoRepository = seoRepository;
|
||||
}
|
||||
|
||||
/** 生成当前域名的 XML Sitemap,只收录允许索引的已发布页面。 */
|
||||
public SeoDocumentSiteRes sitemap() {
|
||||
SiteContext context = SiteContextHolder.getRequired();
|
||||
String origin = origin(context.domain());
|
||||
Map<String, SeoMetadataEntity> seoByTarget = publishedSeo(context.siteCode());
|
||||
List<SitemapEntryDto> entries = new ArrayList<>();
|
||||
add(entries, origin, "/", null, seoByTarget.get(key("HOME", "")));
|
||||
add(entries, origin, "/products", null, seoByTarget.get(key("PRODUCT_LIST", "")));
|
||||
add(entries, origin, "/news", null, seoByTarget.get(key("NEWS_LIST", "")));
|
||||
add(entries, origin, "/cases", null, seoByTarget.get(key("CASE_LIST", "")));
|
||||
add(entries, origin, "/help", null, seoByTarget.get(key("HELP_CATEGORY_LIST", "")));
|
||||
for (ProductEntity item : productRepository.listPublished(context.siteCode(), null)) {
|
||||
add(entries, origin, "/products/" + item.getSlug(), item.getUpdateTime(),
|
||||
seoByTarget.get(key("PRODUCT_DETAIL", item.getProductCode())));
|
||||
}
|
||||
addContents(entries, origin, context.siteCode(), "NEWS", "news", "NEWS_DETAIL", seoByTarget);
|
||||
addContents(entries, origin, context.siteCode(), "CASE", "cases", "CASE_DETAIL", seoByTarget);
|
||||
addContents(entries, origin, context.siteCode(), "HELP", "help", "HELP_DETAIL", seoByTarget);
|
||||
for (PageEntity item : pageRepository.listPublished(context.siteCode())) {
|
||||
String pageType = "SYSTEM_PAGE".equals(item.getPageType()) ? "SYSTEM_PAGE" : "CUSTOM_PAGE";
|
||||
add(entries, origin, "/" + item.getSlug(), item.getUpdateTime(),
|
||||
seoByTarget.get(key(pageType, item.getPageCode())));
|
||||
}
|
||||
StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
|
||||
.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n");
|
||||
for (SitemapEntryDto entry : entries) {
|
||||
xml.append(" <url>\n <loc>").append(escape(entry.location())).append("</loc>\n");
|
||||
if (entry.lastModified() != null) {
|
||||
xml.append(" <lastmod>").append(entry.lastModified()).append("</lastmod>\n");
|
||||
}
|
||||
xml.append(" </url>\n");
|
||||
}
|
||||
xml.append("</urlset>\n");
|
||||
return new SeoDocumentSiteRes(xml.toString(), MediaType.APPLICATION_XML_VALUE);
|
||||
}
|
||||
|
||||
/** 生成当前域名的 Robots 文档并声明 Sitemap 地址。 */
|
||||
public SeoDocumentSiteRes robots() {
|
||||
String content = "User-agent: *\nAllow: /\nDisallow: /api/\n\nSitemap: "
|
||||
+ origin(SiteContextHolder.getRequired().domain()) + "/sitemap.xml\n";
|
||||
return new SeoDocumentSiteRes(content, MediaType.TEXT_PLAIN_VALUE);
|
||||
}
|
||||
|
||||
/** 添加指定类型的已发布内容页面。 */
|
||||
private void addContents(List<SitemapEntryDto> entries, String origin, String siteCode, String contentType,
|
||||
String path, String seoType, Map<String, SeoMetadataEntity> seoByTarget) {
|
||||
for (ContentEntity item : contentRepository.listPublished(siteCode, contentType)) {
|
||||
add(entries, origin, "/" + path + "/" + item.getSlug(), item.getUpdateTime(),
|
||||
seoByTarget.get(key(seoType, item.getContentCode())));
|
||||
}
|
||||
}
|
||||
|
||||
/** 添加允许索引的 Sitemap 条目,并优先采用已配置 Canonical。 */
|
||||
private void add(List<SitemapEntryDto> entries, String origin, String defaultPath, Long updateTime,
|
||||
SeoMetadataEntity seo) {
|
||||
if (seo != null && seo.getRobots() != null
|
||||
&& seo.getRobots().toLowerCase(Locale.ROOT).contains("noindex")) {
|
||||
return;
|
||||
}
|
||||
String canonical = seo == null ? null : seo.getCanonicalUrl();
|
||||
String location = canonical == null || canonical.isBlank() ? origin + defaultPath
|
||||
: absoluteUrl(origin, canonical.trim());
|
||||
String lastModified = updateTime == null ? null
|
||||
: SITEMAP_DATE.format(Instant.ofEpochMilli(updateTime).atZone(ZoneOffset.UTC));
|
||||
entries.add(new SitemapEntryDto(location, lastModified));
|
||||
}
|
||||
|
||||
/** 按页面类型和目标编号索引已发布 SEO。 */
|
||||
private Map<String, SeoMetadataEntity> publishedSeo(String siteCode) {
|
||||
Map<String, SeoMetadataEntity> result = new HashMap<>();
|
||||
for (SeoMetadataEntity item : seoRepository.listPublished(siteCode)) {
|
||||
result.put(key(item.getPageType(), item.getTargetCode()), item);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 构造页面类型和目标编号联合键。 */
|
||||
private String key(String pageType, String targetCode) {
|
||||
return pageType + ':' + (targetCode == null ? "" : targetCode);
|
||||
}
|
||||
|
||||
/** 构造当前站点来源地址。 */
|
||||
private String origin(String domain) {
|
||||
boolean local = "localhost".equalsIgnoreCase(domain) || domain.startsWith("127.");
|
||||
return (local ? "http://" : "https://") + domain;
|
||||
}
|
||||
|
||||
/** 将相对 Canonical 转为当前站点绝对地址。 */
|
||||
private String absoluteUrl(String origin, String value) {
|
||||
if (value.startsWith("http://") || value.startsWith("https://")) return value;
|
||||
return origin + (value.startsWith("/") ? value : "/" + value);
|
||||
}
|
||||
|
||||
/** 转义 XML 文本。 */
|
||||
private String escape(String value) {
|
||||
return HtmlUtils.htmlEscape(value, "UTF-8");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.shoplix.site.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.shoplix.common.code.enums.BusinessCodePrefixEnum;
|
||||
import com.shoplix.common.context.SiteContext;
|
||||
import com.shoplix.common.context.SiteContextHolder;
|
||||
import com.shoplix.common.utils.BusinessCodeUtils;
|
||||
import com.shoplix.modules.analytics.repository.entity.FlowLogEntity;
|
||||
import com.shoplix.modules.analytics.repository.service.FlowLogRepositoryService;
|
||||
import com.shoplix.site.dto.FlowVisitorDto;
|
||||
import com.shoplix.site.modules.analytics.req.SensorsBeaconSiteReq;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
/** 前台神策打点协议业务测试。 */
|
||||
class SiteAnalyticsServiceTest {
|
||||
/** 每次测试后清理线程站点上下文。 */
|
||||
@AfterEach
|
||||
void clearContext() {
|
||||
SiteContextHolder.clear();
|
||||
}
|
||||
|
||||
/** 验证神策页面访问事件被映射并立即写入MySQL仓储。 */
|
||||
@Test
|
||||
void shouldDecodeSensorsPageViewAndSaveMilliseconds() {
|
||||
FlowLogRepositoryService repository = Mockito.mock(FlowLogRepositoryService.class);
|
||||
BusinessCodeUtils codes = Mockito.mock(BusinessCodeUtils.class);
|
||||
when(codes.generate(BusinessCodePrefixEnum.FLOW_LOG)).thenReturn("FLO0000000000001");
|
||||
when(repository.insert(any())).thenReturn(1);
|
||||
SiteContextHolder.set(new SiteContext("SIT0000000000001", "site.steliro.com"));
|
||||
SiteAnalyticsService service = new SiteAnalyticsService(repository, codes, new ObjectMapper());
|
||||
long eventTime = System.currentTimeMillis();
|
||||
String json = """
|
||||
{"distinct_id":"visitor-1","time":%d,"type":"track","event":"PageView",
|
||||
"properties":{"session_id":"session-1","page_code":"HOME","$title":"Home",
|
||||
"$url":"https://site.steliro.com/","$url_path":"/","is_new_visitor":1}}
|
||||
""".formatted(eventTime);
|
||||
SensorsBeaconSiteReq request = new SensorsBeaconSiteReq();
|
||||
request.setData(Base64.getEncoder().encodeToString(json.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
service.reportSensors(request, new FlowVisitorDto("203.0.113.10", "Test Browser"));
|
||||
|
||||
ArgumentCaptor<FlowLogEntity> captor = ArgumentCaptor.forClass(FlowLogEntity.class);
|
||||
verify(repository).insert(captor.capture());
|
||||
FlowLogEntity saved = captor.getValue();
|
||||
assertEquals("page_view", saved.getEventName());
|
||||
assertEquals(eventTime, saved.getTs());
|
||||
assertEquals("visitor-1", saved.getCuid());
|
||||
assertEquals("session-1", saved.getSessionCode());
|
||||
assertEquals("203.0.113.10", saved.getIpAddress());
|
||||
assertEquals("Test Browser", saved.getUa());
|
||||
assertNotNull(saved.getCreateTime());
|
||||
assertEquals(13, String.valueOf(saved.getCreateTime()).length());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.shoplix.site.service;
|
||||
|
||||
import com.shoplix.common.context.SiteContext;
|
||||
import com.shoplix.common.context.SiteContextHolder;
|
||||
import com.shoplix.modules.content.repository.service.ContentRepositoryService;
|
||||
import com.shoplix.modules.page.repository.service.PageRepositoryService;
|
||||
import com.shoplix.modules.product.repository.entity.ProductEntity;
|
||||
import com.shoplix.modules.product.repository.service.ProductRepositoryService;
|
||||
import com.shoplix.modules.seo.repository.entity.SeoMetadataEntity;
|
||||
import com.shoplix.modules.seo.repository.service.SeoMetadataRepositoryService;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** 站点 Sitemap 与 Robots 生成规则测试。 */
|
||||
class SiteSeoDocumentServiceTest {
|
||||
/** 测试站点业务编号。 */
|
||||
private static final String SITE_CODE = "SIT0000000000001";
|
||||
/** 产品仓储模拟。 */
|
||||
private ProductRepositoryService productRepository;
|
||||
/** 内容仓储模拟。 */
|
||||
private ContentRepositoryService contentRepository;
|
||||
/** 页面仓储模拟。 */
|
||||
private PageRepositoryService pageRepository;
|
||||
/** SEO 仓储模拟。 */
|
||||
private SeoMetadataRepositoryService seoRepository;
|
||||
/** 被测试服务。 */
|
||||
private SiteSeoDocumentService service;
|
||||
|
||||
/** 初始化站点上下文和仓储模拟。 */
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
productRepository = mock(ProductRepositoryService.class);
|
||||
contentRepository = mock(ContentRepositoryService.class);
|
||||
pageRepository = mock(PageRepositoryService.class);
|
||||
seoRepository = mock(SeoMetadataRepositoryService.class);
|
||||
service = new SiteSeoDocumentService(productRepository, contentRepository, pageRepository, seoRepository);
|
||||
SiteContextHolder.set(new SiteContext(SITE_CODE, "site.steliro.com"));
|
||||
when(contentRepository.listPublished(SITE_CODE, "NEWS")).thenReturn(List.of());
|
||||
when(contentRepository.listPublished(SITE_CODE, "CASE")).thenReturn(List.of());
|
||||
when(contentRepository.listPublished(SITE_CODE, "HELP")).thenReturn(List.of());
|
||||
when(pageRepository.listPublished(SITE_CODE)).thenReturn(List.of());
|
||||
}
|
||||
|
||||
/** 清理线程站点上下文。 */
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
SiteContextHolder.clear();
|
||||
}
|
||||
|
||||
/** Sitemap 应采用 canonical,并排除 noindex 页面。 */
|
||||
@Test
|
||||
void shouldUseCanonicalAndExcludeNoindexPage() {
|
||||
ProductEntity indexed = product("PRD001", "indexed", 1_700_000_000_000L);
|
||||
ProductEntity excluded = product("PRD002", "excluded", 1_700_000_000_000L);
|
||||
SeoMetadataEntity canonical = seo("PRODUCT_DETAIL", "PRD001", "/canonical-product", "index,follow");
|
||||
SeoMetadataEntity noindex = seo("PRODUCT_DETAIL", "PRD002", null, "noindex,nofollow");
|
||||
when(productRepository.listPublished(SITE_CODE, null)).thenReturn(List.of(indexed, excluded));
|
||||
when(seoRepository.listPublished(SITE_CODE)).thenReturn(List.of(canonical, noindex));
|
||||
|
||||
String sitemap = service.sitemap().content();
|
||||
|
||||
assertThat(sitemap).contains("https://site.steliro.com/canonical-product")
|
||||
.contains("<lastmod>2023-11-14</lastmod>")
|
||||
.doesNotContain("/products/excluded");
|
||||
}
|
||||
|
||||
/** Robots 应允许前台抓取、屏蔽接口并声明当前域名 Sitemap。 */
|
||||
@Test
|
||||
void shouldGenerateRobotsForCurrentDomain() {
|
||||
assertThat(service.robots().content())
|
||||
.contains("Allow: /")
|
||||
.contains("Disallow: /api/")
|
||||
.contains("Sitemap: https://site.steliro.com/sitemap.xml");
|
||||
}
|
||||
|
||||
/** 构造测试产品。 */
|
||||
private ProductEntity product(String code, String slug, Long updateTime) {
|
||||
ProductEntity entity = new ProductEntity();
|
||||
entity.setProductCode(code);
|
||||
entity.setSlug(slug);
|
||||
entity.setUpdateTime(updateTime);
|
||||
return entity;
|
||||
}
|
||||
|
||||
/** 构造测试 SEO 配置。 */
|
||||
private SeoMetadataEntity seo(String pageType, String targetCode, String canonical, String robots) {
|
||||
SeoMetadataEntity entity = new SeoMetadataEntity();
|
||||
entity.setPageType(pageType);
|
||||
entity.setTargetCode(targetCode);
|
||||
entity.setCanonicalUrl(canonical);
|
||||
entity.setRobots(robots);
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
+11
-3
@@ -46,7 +46,7 @@ type Item = {
|
||||
slug: string;
|
||||
status: string;
|
||||
model?: string;
|
||||
publishTime?: string;
|
||||
publishTime?: number;
|
||||
inquiryCode?: string;
|
||||
customerName?: string;
|
||||
customerEmail?: string;
|
||||
@@ -60,9 +60,17 @@ type Item = {
|
||||
inquiryTitle?: string;
|
||||
sourceType?: string;
|
||||
statusLabel?: string;
|
||||
createTime?: string;
|
||||
createTime?: number;
|
||||
};
|
||||
|
||||
/** 将毫秒时间戳格式化为本地列表时间。 */
|
||||
function formatTime(value?: number): string {
|
||||
if (!value) return "--";
|
||||
return new Intl.DateTimeFormat("zh-CN", {
|
||||
year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hour12: false,
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
async function post(path: string, body: unknown) {
|
||||
return apiPost(path, body);
|
||||
}
|
||||
@@ -371,7 +379,7 @@ function App({ account, onAccount, onLogout }: { account: Account; onAccount: (v
|
||||
item.productCode || item.contentCode || item.pageCode || item.inquiryCode || index
|
||||
}
|
||||
>
|
||||
{section === "inquiries" ? <><span><strong>{item.companyName || item.customerName || "--"}</strong><small>{item.customerName || "--"}</small></span><span>{item.customerEmail || "--"}</span><span>{item.countryName || item.countryCode || "未知"}({item.clientIp || "--"})</span><span>{item.createTime?.replace("T", " ").slice(0, 16) || "--"}</span><span>{item.productName || item.inquiryTitle || item.sourceType || "网站询盘"}</span><span className={`status ${item.status.toLowerCase()}`}>{item.readStatus === 0 ? "未读" : item.statusLabel || item.status}</span><div className="row-actions"><button className="link">查看</button></div></> : <><span><strong>{item.productName || item.title || item.pageName}</strong><small>{item.model || item.productCode || item.contentCode || item.pageCode}</small></span><code>/{item.slug}</code><span className={`status ${item.status.toLowerCase()}`}>{statusLabels[item.status] || item.status}</span><span>{item.publishTime?.replace("T", " ").slice(0, 16) || "--"}</span><div className="row-actions">{["products", "NEWS", "CASE", "HELP"].includes(section) && item.slug && <a className="link" href={`${SITE_WEB}/${section === "products" ? "products" : section === "CASE" ? "cases" : section === "NEWS" ? "news" : "help"}/${encodeURIComponent(item.slug)}`} target="_blank" rel="noreferrer">查看前台</a>}<button className="link" onClick={() => section === "products" && item.productCode ? openProductEditor(item.productCode) : ["NEWS", "CASE", "HELP"].includes(section) && item.contentCode ? openContentEditor(section as EditorialSection, item.contentCode) : section === "pages" && item.pageCode ? openPageEditor(item.pageCode) : undefined}>编辑</button>{["products", "NEWS", "CASE", "HELP"].includes(section) && <><button className="link" onClick={() => void changeItemStatus(item)}>{item.status === "PUBLISHED" ? "下架" : "上架"}</button><button className="link danger" onClick={() => void deleteItem(item)}>删除</button></>}</div></>}
|
||||
{section === "inquiries" ? <><span><strong>{item.companyName || item.customerName || "--"}</strong><small>{item.customerName || "--"}</small></span><span>{item.customerEmail || "--"}</span><span>{item.countryName || item.countryCode || "未知"}({item.clientIp || "--"})</span><span>{formatTime(item.createTime)}</span><span>{item.productName || item.inquiryTitle || item.sourceType || "网站询盘"}</span><span className={`status ${item.status.toLowerCase()}`}>{item.readStatus === 0 ? "未读" : item.statusLabel || item.status}</span><div className="row-actions"><button className="link">查看</button></div></> : <><span><strong>{item.productName || item.title || item.pageName}</strong><small>{item.model || item.productCode || item.contentCode || item.pageCode}</small></span><code>/{item.slug}</code><span className={`status ${item.status.toLowerCase()}`}>{statusLabels[item.status] || item.status}</span><span>{formatTime(item.publishTime)}</span><div className="row-actions">{["products", "NEWS", "CASE", "HELP"].includes(section) && item.slug && <a className="link" href={`${SITE_WEB}/${section === "products" ? "products" : section === "CASE" ? "cases" : section === "NEWS" ? "news" : "help"}/${encodeURIComponent(item.slug)}`} target="_blank" rel="noreferrer">查看前台</a>}<button className="link" onClick={() => section === "products" && item.productCode ? openProductEditor(item.productCode) : ["NEWS", "CASE", "HELP"].includes(section) && item.contentCode ? openContentEditor(section as EditorialSection, item.contentCode) : section === "pages" && item.pageCode ? openPageEditor(item.pageCode) : undefined}>编辑</button>{["products", "NEWS", "CASE", "HELP"].includes(section) && <><button className="link" onClick={() => void changeItemStatus(item)}>{item.status === "PUBLISHED" ? "下架" : "上架"}</button><button className="link danger" onClick={() => void deleteItem(item)}>删除</button></>}</div></>}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
|
||||
Generated
+8
-1
@@ -10,7 +10,8 @@
|
||||
"dependencies": {
|
||||
"lucide-react": "0.468.0",
|
||||
"react": "19.2.0",
|
||||
"react-dom": "19.2.0"
|
||||
"react-dom": "19.2.0",
|
||||
"sa-sdk-javascript": "1.28.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "19.0.3",
|
||||
@@ -1109,6 +1110,12 @@
|
||||
"fsevents": "~2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/sa-sdk-javascript": {
|
||||
"version": "1.28.2",
|
||||
"resolved": "https://registry.npmjs.org/sa-sdk-javascript/-/sa-sdk-javascript-1.28.2.tgz",
|
||||
"integrity": "sha512-uPMdaYqaZ4B3VapZnIeR1hBhbyTgG2DgPLojQ2PSoc5o35e/AQDhE2cKEAnO22KX2Zzm7MrkCCrGg0iNfM3D+g==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/scheduler": {
|
||||
"version": "0.27.0",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"name":"shoplix-web-site","private":true,"version":"0.1.0","type":"module","scripts":{"dev":"vite","build":"tsc -b && vite build"},"dependencies":{"react":"19.2.0","react-dom":"19.2.0","lucide-react":"0.468.0"},"devDependencies":{"@types/react":"19.0.3","@types/react-dom":"19.0.2","typescript":"5.7.3","vite":"6.4.6"}}
|
||||
{"name":"shoplix-web-site","private":true,"version":"0.1.0","type":"module","scripts":{"dev":"vite","build":"tsc -b && vite build"},"dependencies":{"lucide-react":"0.468.0","react":"19.2.0","react-dom":"19.2.0","sa-sdk-javascript":"1.28.2"},"devDependencies":{"@types/react":"19.0.3","@types/react-dom":"19.0.2","typescript":"5.7.3","vite":"6.4.6"}}
|
||||
@@ -0,0 +1,164 @@
|
||||
import sensors from "sa-sdk-javascript";
|
||||
|
||||
const API_BASE = import.meta.env.VITE_SITE_API_BASE || "/api/site/v1";
|
||||
const SESSION_TIMEOUT = 30 * 60 * 1000;
|
||||
const VISITOR_KEY = "shoplix_analytics_visitor";
|
||||
const SESSION_KEY = "shoplix_analytics_session";
|
||||
const SESSION_TIME_KEY = "shoplix_analytics_session_time";
|
||||
const LANDING_KEY = "shoplix_analytics_landing";
|
||||
|
||||
type EventProperties = Record<string, string | number | boolean | undefined>;
|
||||
|
||||
/** 页面访问上下文。 */
|
||||
export type PageAnalyticsContext = {
|
||||
pageCode: string;
|
||||
pageName: string;
|
||||
targetCode?: string;
|
||||
scene?: string;
|
||||
};
|
||||
|
||||
let initialized = false;
|
||||
let pageStartTime = Date.now();
|
||||
|
||||
/** 初始化神策Web SDK并将数据发送到项目自建接收端。 */
|
||||
export function initializeAnalytics(): void {
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
const visitor = ensureVisitor();
|
||||
const session = ensureSession();
|
||||
sensors.init({
|
||||
server_url: new URL(`${API_BASE}/analytics/beacon-report-flow`, location.origin).href,
|
||||
send_type: "ajax",
|
||||
batch_send: false,
|
||||
show_log: import.meta.env.DEV,
|
||||
is_track_single_page: false,
|
||||
use_client_time: true,
|
||||
});
|
||||
sensors.identify(visitor.code, true);
|
||||
sensors.registerPage({
|
||||
language: document.documentElement.lang || "en",
|
||||
session_id: session.code,
|
||||
is_new_visitor: visitor.isNew ? 1 : 0,
|
||||
is_session_first: session.isFirst ? 1 : 0,
|
||||
landing_domain: landing().host,
|
||||
landing_url: landing().href,
|
||||
landing_url_body: landing().pathname,
|
||||
});
|
||||
}
|
||||
|
||||
/** 上报页面访问事件。 */
|
||||
export function trackPageView(context: PageAnalyticsContext): void {
|
||||
initializeAnalytics();
|
||||
pageStartTime = Date.now();
|
||||
sensors.track("PageView", commonProperties(context));
|
||||
markSessionVisited();
|
||||
}
|
||||
|
||||
/** 上报页面离开事件及停留时长。 */
|
||||
export function trackPageLeave(context: PageAnalyticsContext): void {
|
||||
const now = Date.now();
|
||||
sensors.track("PageLeave", {
|
||||
...commonProperties(context),
|
||||
start_time: pageStartTime,
|
||||
duration: Math.max(0, Math.round((now - pageStartTime) / 1000)),
|
||||
});
|
||||
}
|
||||
|
||||
/** 上报询盘提交成功事件。 */
|
||||
export function trackInquirySubmitted(inquiryCode: string, scene: string): void {
|
||||
sensors.track("SubmitInquiry", {
|
||||
...commonProperties({ pageCode: routePageCode(), pageName: document.title, scene }),
|
||||
event_detail: inquiryCode,
|
||||
});
|
||||
}
|
||||
|
||||
/** 上报通用点击事件。 */
|
||||
export function trackClick(detail: string, properties: EventProperties = {}): void {
|
||||
sensors.track("Click", { ...commonProperties({ pageCode: routePageCode(), pageName: document.title }), event_detail: detail, ...properties });
|
||||
}
|
||||
|
||||
/** 创建当前页面公共属性。 */
|
||||
function commonProperties(context: PageAnalyticsContext): EventProperties {
|
||||
const url = new URL(location.href);
|
||||
const connection = (navigator as Navigator & { connection?: { effectiveType?: string } }).connection;
|
||||
return {
|
||||
page_code: context.pageCode,
|
||||
page_name: context.pageName,
|
||||
target_code: context.targetCode,
|
||||
scene: context.scene,
|
||||
start_time: pageStartTime,
|
||||
pixel_ratio: String(window.devicePixelRatio || 1),
|
||||
domain: url.host,
|
||||
url_args: url.search,
|
||||
win_height: window.innerHeight,
|
||||
win_width: window.innerWidth,
|
||||
network: connection?.effectiveType,
|
||||
utm_source: url.searchParams.get("utm_source") || undefined,
|
||||
utm_campaign: url.searchParams.get("utm_campaign") || undefined,
|
||||
utm_adgroup: url.searchParams.get("utm_adgroup") || undefined,
|
||||
flow_channel: flowChannel(document.referrer),
|
||||
social_media_channel: socialChannel(document.referrer),
|
||||
};
|
||||
}
|
||||
|
||||
/** 获取或创建匿名访客。 */
|
||||
function ensureVisitor(): { code: string; isNew: boolean } {
|
||||
const existing = localStorage.getItem(VISITOR_KEY);
|
||||
if (existing) return { code: existing, isNew: false };
|
||||
const code = crypto.randomUUID();
|
||||
localStorage.setItem(VISITOR_KEY, code);
|
||||
return { code, isNew: true };
|
||||
}
|
||||
|
||||
/** 获取或创建三十分钟有效的会话。 */
|
||||
function ensureSession(): { code: string; isFirst: boolean } {
|
||||
const now = Date.now();
|
||||
const previousTime = Number(sessionStorage.getItem(SESSION_TIME_KEY) || 0);
|
||||
let code = sessionStorage.getItem(SESSION_KEY);
|
||||
let isFirst = sessionStorage.getItem(`${SESSION_KEY}_visited`) !== "1";
|
||||
if (!code || now - previousTime > SESSION_TIMEOUT) {
|
||||
code = crypto.randomUUID();
|
||||
sessionStorage.setItem(SESSION_KEY, code);
|
||||
sessionStorage.removeItem(`${SESSION_KEY}_visited`);
|
||||
isFirst = true;
|
||||
}
|
||||
sessionStorage.setItem(SESSION_TIME_KEY, String(now));
|
||||
return { code, isFirst };
|
||||
}
|
||||
|
||||
/** 标记当前会话已产生页面访问。 */
|
||||
function markSessionVisited(): void {
|
||||
sessionStorage.setItem(`${SESSION_KEY}_visited`, "1");
|
||||
sessionStorage.setItem(SESSION_TIME_KEY, String(Date.now()));
|
||||
}
|
||||
|
||||
/** 获取首次落地页。 */
|
||||
function landing(): URL {
|
||||
const stored = sessionStorage.getItem(LANDING_KEY);
|
||||
if (stored) return new URL(stored);
|
||||
sessionStorage.setItem(LANDING_KEY, location.href);
|
||||
return new URL(location.href);
|
||||
}
|
||||
|
||||
/** 判断流量渠道。 */
|
||||
function flowChannel(referrer: string): string {
|
||||
if (!referrer) return "DIRECT";
|
||||
const host = new URL(referrer).hostname.toLowerCase();
|
||||
if (/google|bing|yahoo|baidu|yandex/.test(host)) return "ORGANIC_SEARCH";
|
||||
if (/facebook|instagram|linkedin|twitter|x\.com|youtube|tiktok/.test(host)) return "SOCIAL";
|
||||
return "REFERRAL";
|
||||
}
|
||||
|
||||
/** 判断社媒来源。 */
|
||||
function socialChannel(referrer: string): string | undefined {
|
||||
const match = referrer.toLowerCase().match(/facebook|instagram|linkedin|twitter|youtube|tiktok/);
|
||||
return match?.[0];
|
||||
}
|
||||
|
||||
/** 根据当前路径识别页面类型。 */
|
||||
export function routePageCode(): string {
|
||||
const paths = location.pathname.split("/").filter(Boolean);
|
||||
if (!paths.length) return "HOME";
|
||||
const mapping: Record<string, string> = { products: "PRODUCT", news: "NEWS", cases: "CASE", help: "HELP" };
|
||||
return mapping[paths[0]] ? `${mapping[paths[0]]}_${paths[1] ? "DETAIL" : "CATEGORY"}` : "CUSTOM_PAGE";
|
||||
}
|
||||
+105
-9
@@ -2,8 +2,9 @@ import React, { useEffect, useState } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { ArrowRight, ChevronRight, Mail, Menu, Search } from "lucide-react";
|
||||
import "./styles.css";
|
||||
import { initializeAnalytics, routePageCode, trackInquirySubmitted, trackPageLeave, trackPageView } from "./analytics";
|
||||
|
||||
const API = "http://localhost:8082/api/site/v1";
|
||||
const API = import.meta.env.VITE_SITE_API_BASE || "/api/site/v1";
|
||||
type ContentType = "NEWS" | "CASE" | "HELP";
|
||||
type Item = {
|
||||
productCode?: string;
|
||||
@@ -13,7 +14,7 @@ type Item = {
|
||||
slug: string;
|
||||
summary?: string;
|
||||
model?: string;
|
||||
publishTime?: string;
|
||||
publishTime?: number;
|
||||
coverMediaUrl?: string;
|
||||
};
|
||||
type InquiryField = {
|
||||
@@ -35,6 +36,17 @@ type InquiryFormData = {
|
||||
successMessage: string;
|
||||
fields: InquiryField[];
|
||||
};
|
||||
type SeoData = {
|
||||
title: string;
|
||||
description?: string;
|
||||
keywords?: string;
|
||||
canonicalUrl?: string;
|
||||
robots?: string;
|
||||
ogTitle?: string;
|
||||
ogDescription?: string;
|
||||
ogImageUrl?: string;
|
||||
structuredData?: string;
|
||||
};
|
||||
async function post(path: string, body: unknown) {
|
||||
const r = await fetch(API + path, {
|
||||
method: "POST",
|
||||
@@ -45,6 +57,53 @@ async function post(path: string, body: unknown) {
|
||||
throw new Error((await r.json()).message || "Unable to load content");
|
||||
return r.json();
|
||||
}
|
||||
function setMeta(name: string, content?: string) {
|
||||
const selector = `meta[name="${name}"]`;
|
||||
let element = document.head.querySelector<HTMLMetaElement>(selector);
|
||||
if (!content) { element?.remove(); return; }
|
||||
if (!element) { element = document.createElement("meta"); element.name = name; document.head.appendChild(element); }
|
||||
element.content = content;
|
||||
}
|
||||
function setProperty(property: string, content?: string) {
|
||||
const selector = `meta[property="${property}"]`;
|
||||
let element = document.head.querySelector<HTMLMetaElement>(selector);
|
||||
if (!content) { element?.remove(); return; }
|
||||
if (!element) { element = document.createElement("meta"); element.setAttribute("property", property); document.head.appendChild(element); }
|
||||
element.content = content;
|
||||
}
|
||||
function applySeo(data?: SeoData) {
|
||||
const canonicalValue = data?.canonicalUrl || `${location.origin}${location.pathname}`;
|
||||
const canonical = new URL(canonicalValue, location.origin).href;
|
||||
if (data?.title) document.title = data.title;
|
||||
setMeta("description", data?.description);
|
||||
setMeta("keywords", data?.keywords);
|
||||
setMeta("robots", data?.robots || "index,follow");
|
||||
let link = document.head.querySelector<HTMLLinkElement>('link[rel="canonical"]');
|
||||
if (!link) { link = document.createElement("link"); link.rel = "canonical"; document.head.appendChild(link); }
|
||||
link.href = canonical;
|
||||
setProperty("og:title", data?.ogTitle || data?.title);
|
||||
setProperty("og:description", data?.ogDescription || data?.description);
|
||||
setProperty("og:image", data?.ogImageUrl ? new URL(data.ogImageUrl, location.origin).href : undefined);
|
||||
setProperty("og:url", canonical);
|
||||
let structuredData = document.head.querySelector<HTMLScriptElement>('script[data-shoplix-seo="json-ld"]');
|
||||
structuredData?.remove();
|
||||
if (data?.structuredData) {
|
||||
structuredData = document.createElement("script"); structuredData.type = "application/ld+json";
|
||||
structuredData.dataset.shoplixSeo = "json-ld"; structuredData.text = data.structuredData;
|
||||
document.head.appendChild(structuredData);
|
||||
}
|
||||
}
|
||||
function usePageSeo(pageType: string, targetCode = "") {
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
applySeo();
|
||||
if (!pageType) return () => { active = false; };
|
||||
post("/seo/detail", { pageType, targetCode })
|
||||
.then((data: SeoData) => { if (active) applySeo(data); })
|
||||
.catch(() => undefined);
|
||||
return () => { active = false; };
|
||||
}, [pageType, targetCode]);
|
||||
}
|
||||
const nav = [
|
||||
["Products", "/products"],
|
||||
["Cases", "/cases"],
|
||||
@@ -62,13 +121,49 @@ function route() {
|
||||
}
|
||||
function App() {
|
||||
const r = route();
|
||||
useEffect(() => {
|
||||
initializeAnalytics();
|
||||
const context = { pageCode: routePageCode(), pageName: document.title, scene: r.kind };
|
||||
trackPageView(context);
|
||||
const leave = () => trackPageLeave(context);
|
||||
window.addEventListener("pagehide", leave, { once: true });
|
||||
return () => window.removeEventListener("pagehide", leave);
|
||||
}, [r.kind, r.slug]);
|
||||
const runtime = <CustomCodeRuntime />;
|
||||
if (r.kind === "home") return <>{runtime}<DecoratedPage pageType={r.previewPage || "HOME"} fallback={<><Header /><main><Home /></main><Footer /></>} /></>;
|
||||
if (r.kind === "products") return <>{runtime}<DecoratedPage pageType={r.previewPage || (r.slug ? "PRODUCT_DETAIL" : "PRODUCT_CATEGORY")} fallback={<><Header /><main><Collection title="Products" type="products" slug={r.slug} /></main><Footer /></>} /></>;
|
||||
if (r.kind === "news") return <>{runtime}<DecoratedPage pageType={r.previewPage || (r.slug ? "NEWS_DETAIL" : "NEWS_CATEGORY")} fallback={<><Header /><main><Collection title="News" type="NEWS" slug={r.slug} /></main><Footer /></>} /></>;
|
||||
if (r.kind === "cases") return <>{runtime}<DecoratedPage pageType={r.previewPage || (r.slug ? "CASE_DETAIL" : "CASE_CATEGORY")} fallback={<><Header /><main><Collection title="Case Studies" type="CASE" slug={r.slug} /></main><Footer /></>} /></>;
|
||||
if (r.kind === "help") return <>{runtime}<DecoratedPage pageType={r.previewPage || (r.slug ? "HELP_DETAIL" : "HELP_CATEGORY")} fallback={<><Header /><main><Collection title="Help Center" type="HELP" slug={r.slug} /></main><Footer /></>} /></>;
|
||||
return <>{runtime}<DecoratedPage pageType={r.previewPage || (r.slug === "about-us" ? "ABOUT_US" : "CUSTOM_PAGE")} fallback={<><Header /><main><Page slug={r.slug!} /></main><Footer /></>} /></>;
|
||||
const seoRuntime = <SeoRuntime current={r} />;
|
||||
if (r.kind === "home") return <>{runtime}{seoRuntime}<DecoratedPage pageType={r.previewPage || "HOME"} fallback={<><Header /><main><Home /></main><Footer /></>} /></>;
|
||||
if (r.kind === "products") return <>{runtime}{seoRuntime}<DecoratedPage pageType={r.previewPage || (r.slug ? "PRODUCT_DETAIL" : "PRODUCT_CATEGORY")} fallback={<><Header /><main><Collection title="Products" type="products" slug={r.slug} /></main><Footer /></>} /></>;
|
||||
if (r.kind === "news") return <>{runtime}{seoRuntime}<DecoratedPage pageType={r.previewPage || (r.slug ? "NEWS_DETAIL" : "NEWS_CATEGORY")} fallback={<><Header /><main><Collection title="News" type="NEWS" slug={r.slug} /></main><Footer /></>} /></>;
|
||||
if (r.kind === "cases") return <>{runtime}{seoRuntime}<DecoratedPage pageType={r.previewPage || (r.slug ? "CASE_DETAIL" : "CASE_CATEGORY")} fallback={<><Header /><main><Collection title="Case Studies" type="CASE" slug={r.slug} /></main><Footer /></>} /></>;
|
||||
if (r.kind === "help") return <>{runtime}{seoRuntime}<DecoratedPage pageType={r.previewPage || (r.slug ? "HELP_DETAIL" : "HELP_CATEGORY")} fallback={<><Header /><main><Collection title="Help Center" type="HELP" slug={r.slug} /></main><Footer /></>} /></>;
|
||||
return <>{runtime}{seoRuntime}<DecoratedPage pageType={r.previewPage || (r.slug === "about-us" ? "ABOUT_US" : "CUSTOM_PAGE")} fallback={<><Header /><main><Page slug={r.slug!} /></main><Footer /></>} /></>;
|
||||
}
|
||||
function SeoRuntime({ current }: { current: ReturnType<typeof route> }) {
|
||||
const [target, setTarget] = useState({ pageType: "", targetCode: "" });
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
const listType = current.kind === "home" ? "HOME"
|
||||
: current.kind === "products" && !current.slug ? "PRODUCT_LIST"
|
||||
: current.kind === "news" && !current.slug ? "NEWS_LIST"
|
||||
: current.kind === "cases" && !current.slug ? "CASE_LIST"
|
||||
: current.kind === "help" && !current.slug ? "HELP_CATEGORY_LIST" : "";
|
||||
if (listType) { setTarget({ pageType: listType, targetCode: "" }); return () => { active = false; }; }
|
||||
setTarget({ pageType: "", targetCode: "" });
|
||||
if (["products", "news", "cases", "help"].includes(current.kind) && current.slug) {
|
||||
const product = current.kind === "products";
|
||||
const contentType = current.kind === "cases" ? "CASE" : current.kind.toUpperCase();
|
||||
post(product ? "/products/detail" : "/contents/detail", product ? { slug: current.slug } : { contentType, slug: current.slug })
|
||||
.then(data => { if (active) setTarget({ pageType: product ? "PRODUCT_DETAIL" : `${contentType}_DETAIL`, targetCode: data.productCode || data.contentCode || "" }); })
|
||||
.catch(() => undefined);
|
||||
} else if (current.kind === "page" && current.slug) {
|
||||
post("/pages/detail", { slug: current.slug })
|
||||
.then(data => { if (active) setTarget({ pageType: data.pageType === "SYSTEM_PAGE" ? "SYSTEM_PAGE" : "CUSTOM_PAGE", targetCode: data.pageCode || "" }); })
|
||||
.catch(() => undefined);
|
||||
}
|
||||
return () => { active = false; };
|
||||
}, [current.kind, current.slug]);
|
||||
usePageSeo(target.pageType, target.targetCode);
|
||||
return null;
|
||||
}
|
||||
function CustomCodeRuntime() {
|
||||
useEffect(() => { let nodes: HTMLElement[] = []; post("/custom-codes/list", { siteCode: "SIT0000000000001" }).then(data => { (data.items || []).forEach((item: { content: string; position: string }) => { const container = item.position === "HEAD" ? document.head : document.body; const wrapper = document.createElement("div"); wrapper.innerHTML = item.content; Array.from(wrapper.children).forEach(child => { let node: HTMLElement = child as HTMLElement; if (child.tagName === "SCRIPT") { const script = document.createElement("script"); Array.from(child.attributes).forEach(attribute => script.setAttribute(attribute.name, attribute.value)); script.text = child.textContent || ""; node = script; } container.insertBefore(node, item.position === "BODY_START" ? container.firstChild : null); nodes.push(node); }); }); }).catch(() => undefined); return () => nodes.forEach(node => node.remove()); }, []);
|
||||
@@ -281,7 +376,7 @@ function Collection({
|
||||
</div>
|
||||
<div>
|
||||
<small>
|
||||
{item.model || item.publishTime?.slice(0, 10) || "INSIGHT"}
|
||||
{item.model || (item.publishTime ? new Date(item.publishTime).toLocaleDateString("en-CA") : "INSIGHT")}
|
||||
</small>
|
||||
<h2>{item.productName || item.title}</h2>
|
||||
<p>
|
||||
@@ -398,6 +493,7 @@ function InquiryForm({
|
||||
})),
|
||||
landingUrl: sessionStorage.getItem("landingUrl") || location.href,
|
||||
});
|
||||
trackInquirySubmitted(result.inquiryCode, scene);
|
||||
setNotice(result.successMessage);
|
||||
} catch (err) {
|
||||
setNotice(
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"root":["./src/main.tsx","./src/vite-env.d.ts"],"version":"5.7.3"}
|
||||
{"root":["./src/analytics.ts","./src/main.tsx","./src/vite-env.d.ts"],"version":"5.7.3"}
|
||||
Reference in new issue
Block a user