Compare commits

...
2 Commits
82 changed files with 5701 additions and 9 deletions
+5
View File
@@ -129,6 +129,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- CRM 动态 SMTP 发信(按公司账户建 Session,不用全局 MailSender) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Spring AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -33,7 +33,6 @@ import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
@@ -0,0 +1,80 @@
package top.xyquan.ecomdmbbackend.modules.crm.document.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.modules.crm.document.mapper.CrmDocumentMapper;
import top.xyquan.ecomdmbbackend.modules.crm.document.model.po.CrmDocumentPO;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmGeneratedFileService;
import top.xyquan.ecomdmbbackend.modules.sys.file.model.po.SysFilePO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
/**
* 单证版本落库:标记旧版非最新,写入新 crm_document。
*/
@Service
public class CrmDocumentService {
private final CrmDocumentMapper documentMapper;
private final CrmGeneratedFileService generatedFileService;
private final CurrentUserContext currentUserContext;
public CrmDocumentService(CrmDocumentMapper documentMapper,
CrmGeneratedFileService generatedFileService,
CurrentUserContext currentUserContext) {
this.documentMapper = documentMapper;
this.generatedFileService = generatedFileService;
this.currentUserContext = currentUserContext;
}
@Transactional
public CrmDocumentPO savePdf(Long companyId, String docType, String docNo,
String refType, Long refId,
String filename, byte[] pdf) {
SysFilePO file = generatedFileService.saveBytes(companyId, filename, "application/pdf", pdf);
documentMapper.update(null, new LambdaUpdateWrapper<CrmDocumentPO>()
.eq(CrmDocumentPO::getCompanyId, companyId)
.eq(CrmDocumentPO::getRefType, refType)
.eq(CrmDocumentPO::getRefId, refId)
.eq(CrmDocumentPO::getDocType, docType)
.eq(CrmDocumentPO::getIsLatest, 1)
.set(CrmDocumentPO::getIsLatest, 0));
int nextVersion = 1;
CrmDocumentPO last = documentMapper.selectOne(new LambdaQueryWrapper<CrmDocumentPO>()
.eq(CrmDocumentPO::getCompanyId, companyId)
.eq(CrmDocumentPO::getRefType, refType)
.eq(CrmDocumentPO::getRefId, refId)
.eq(CrmDocumentPO::getDocType, docType)
.orderByDesc(CrmDocumentPO::getVersionNo)
.last("LIMIT 1"));
if (last != null && last.getVersionNo() != null) {
nextVersion = last.getVersionNo() + 1;
}
CrmDocumentPO doc = new CrmDocumentPO();
doc.setCompanyId(companyId);
doc.setDocType(docType);
doc.setDocNo(docNo);
doc.setRefType(refType);
doc.setRefId(refId);
doc.setFileId(file.getId());
doc.setIsLatest(1);
doc.setVersionNo(nextVersion);
doc.setCreateBy(currentUserContext.getCurrentUserId());
documentMapper.insert(doc);
return doc;
}
public CrmDocumentPO findLatest(Long companyId, String refType, Long refId, String docType) {
return documentMapper.selectOne(new LambdaQueryWrapper<CrmDocumentPO>()
.eq(CrmDocumentPO::getCompanyId, companyId)
.eq(CrmDocumentPO::getRefType, refType)
.eq(CrmDocumentPO::getRefId, refId)
.eq(CrmDocumentPO::getDocType, docType)
.eq(CrmDocumentPO::getIsLatest, 1)
.last("LIMIT 1"));
}
}
@@ -0,0 +1,62 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto.CreateCrmMailAccountDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto.UpdateCrmMailAccountDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.vo.CrmMailAccountVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.service.CrmMailAccountService;
import java.util.List;
/** 发件账户管理。 */
@RestController
@RequestMapping("/api/crm/mail-account")
public class CrmMailAccountController {
private final CrmMailAccountService mailAccountService;
public CrmMailAccountController(CrmMailAccountService mailAccountService) {
this.mailAccountService = mailAccountService;
}
@PostMapping("/create")
@RequirePermission(value = "crm:mail-account:create", description = "创建发件账户")
public ApiResponse<CrmMailAccountVO> create(@Valid @RequestBody CreateCrmMailAccountDTO dto) {
return ApiResponse.success("创建成功", mailAccountService.create(dto));
}
@PutMapping("/update/{id}")
@RequirePermission(value = "crm:mail-account:update", description = "更新发件账户")
public ApiResponse<CrmMailAccountVO> update(
@PathVariable Long id, @Valid @RequestBody UpdateCrmMailAccountDTO dto) {
return ApiResponse.success("更新成功", mailAccountService.update(id, dto));
}
@DeleteMapping("/delete/{id}")
@RequirePermission(value = "crm:mail-account:delete", description = "删除发件账户")
public ApiResponse<Void> delete(@PathVariable Long id) {
mailAccountService.delete(id);
return ApiResponse.success("删除成功");
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:mail-account:read", description = "发件账户详情")
public ApiResponse<CrmMailAccountVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", mailAccountService.get(id));
}
@GetMapping("/list")
@RequirePermission(value = "crm:mail-account:read", description = "发件账户列表")
public ApiResponse<List<CrmMailAccountVO>> list() {
return ApiResponse.success("获取成功", mailAccountService.listAll());
}
@GetMapping("/options")
@RequirePermission(value = "crm:mail:send", description = "启用发件账户选项")
public ApiResponse<List<CrmMailAccountVO>> options() {
return ApiResponse.success("获取成功", mailAccountService.listEnabled());
}
}
@@ -0,0 +1,10 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.po.CrmMailAccountPO;
/** 发件账户 Mapper。 */
@Mapper
public interface CrmMailAccountMapper extends BaseMapper<CrmMailAccountPO> {
}
@@ -0,0 +1,43 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
/** 创建发件账户。 */
@Data
public class CreateCrmMailAccountDTO {
@NotBlank
@Size(max = 100)
private String name;
@NotBlank
@Email
@Size(max = 100)
private String fromEmail;
@NotBlank
@Size(max = 200)
private String smtpHost;
@NotNull
private Integer smtpPort;
/** 1=SSL/TLS,0=STARTTLS */
private Integer smtpSsl;
@NotBlank
@Size(max = 200)
private String username;
@NotBlank
@Size(max = 200)
private String password;
private Integer enabled;
private Integer isDefault;
}
@@ -0,0 +1,42 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
/** 更新发件账户;password 空则保留原密文。 */
@Data
public class UpdateCrmMailAccountDTO {
@NotBlank
@Size(max = 100)
private String name;
@NotBlank
@Email
@Size(max = 100)
private String fromEmail;
@NotBlank
@Size(max = 200)
private String smtpHost;
@NotNull
private Integer smtpPort;
private Integer smtpSsl;
@NotBlank
@Size(max = 200)
private String username;
/** 留空表示不改密码 */
@Size(max = 200)
private String password;
private Integer enabled;
private Integer isDefault;
}
@@ -0,0 +1,43 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
/** 公司 SMTP 发件账户。 */
@Data
@TableName("crm_mail_account")
public class CrmMailAccountPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("name")
private String name;
@TableField("from_email")
private String fromEmail;
@TableField("smtp_host")
private String smtpHost;
@TableField("smtp_port")
private Integer smtpPort;
@TableField("smtp_ssl")
private Integer smtpSsl;
@TableField("username")
private String username;
@TableField("password_cipher")
private String passwordCipher;
@TableField("enabled")
private Integer enabled;
@TableField("is_default")
private Integer isDefault;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField("create_by")
private Long createBy;
@TableField("update_by")
private Long updateBy;
}
@@ -0,0 +1,23 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/** 发件账户视图(不含密码)。 */
@Data
public class CrmMailAccountVO {
private Long id;
private Long companyId;
private String name;
private String fromEmail;
private String smtpHost;
private Integer smtpPort;
private Integer smtpSsl;
private String username;
private Integer enabled;
private Integer isDefault;
private Boolean passwordSet;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.service;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto.CreateCrmMailAccountDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto.UpdateCrmMailAccountDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.po.CrmMailAccountPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.vo.CrmMailAccountVO;
import java.util.List;
/** 发件账户用例。 */
public interface CrmMailAccountService {
CrmMailAccountVO create(CreateCrmMailAccountDTO dto);
CrmMailAccountVO update(Long id, UpdateCrmMailAccountDTO dto);
void delete(Long id);
CrmMailAccountVO get(Long id);
List<CrmMailAccountVO> listAll();
/** 启用账户下拉(发信用)。 */
List<CrmMailAccountVO> listEnabled();
/** 解析发件账户:指定 id,否则取默认启用账户。 */
CrmMailAccountPO requireForSend(Long companyId, Long accountId);
String decryptPassword(CrmMailAccountPO account);
}
@@ -0,0 +1,196 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.account.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.mapper.CrmMailAccountMapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto.CreateCrmMailAccountDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.dto.UpdateCrmMailAccountDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.po.CrmMailAccountPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.vo.CrmMailAccountVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.service.CrmMailAccountService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmSecretCrypto;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.List;
/**
* 发件账户:密码入库加密;VO 不回传明文。
*/
@Service
public class CrmMailAccountServiceImpl extends ServiceImpl<CrmMailAccountMapper, CrmMailAccountPO>
implements CrmMailAccountService {
private final CrmSecretCrypto secretCrypto;
private final CurrentUserContext currentUserContext;
public CrmMailAccountServiceImpl(CrmSecretCrypto secretCrypto,
CurrentUserContext currentUserContext) {
this.secretCrypto = secretCrypto;
this.currentUserContext = currentUserContext;
}
@Override
@Transactional
public CrmMailAccountVO create(CreateCrmMailAccountDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmMailAccountPO po = new CrmMailAccountPO();
po.setCompanyId(companyId);
applyFields(po, dto.getName(), dto.getFromEmail(), dto.getSmtpHost(), dto.getSmtpPort(),
dto.getSmtpSsl(), dto.getUsername(), dto.getEnabled(), dto.getIsDefault());
po.setPasswordCipher(secretCrypto.encrypt(dto.getPassword()));
po.setCreateBy(userId);
po.setUpdateBy(userId);
this.save(po);
if (Integer.valueOf(1).equals(po.getIsDefault())) {
clearOtherDefaults(companyId, po.getId());
}
return toVo(po);
}
@Override
@Transactional
public CrmMailAccountVO update(Long id, UpdateCrmMailAccountDTO dto) {
CrmMailAccountPO po = requireOwned(id);
applyFields(po, dto.getName(), dto.getFromEmail(), dto.getSmtpHost(), dto.getSmtpPort(),
dto.getSmtpSsl(), dto.getUsername(), dto.getEnabled(), dto.getIsDefault());
if (StringUtils.hasText(dto.getPassword())) {
po.setPasswordCipher(secretCrypto.encrypt(dto.getPassword().trim()));
}
po.setUpdateBy(currentUserContext.getCurrentUserId());
this.updateById(po);
if (Integer.valueOf(1).equals(po.getIsDefault())) {
clearOtherDefaults(po.getCompanyId(), po.getId());
}
return toVo(po);
}
@Override
@Transactional
public void delete(Long id) {
requireOwned(id);
this.removeById(id);
}
@Override
public CrmMailAccountVO get(Long id) {
return toVo(requireOwned(id));
}
@Override
public List<CrmMailAccountVO> listAll() {
Long companyId = requireCompanyId();
return this.list(new LambdaQueryWrapper<CrmMailAccountPO>()
.eq(CrmMailAccountPO::getCompanyId, companyId)
.orderByDesc(CrmMailAccountPO::getIsDefault)
.orderByDesc(CrmMailAccountPO::getId))
.stream().map(this::toVo).toList();
}
@Override
public List<CrmMailAccountVO> listEnabled() {
Long companyId = requireCompanyId();
return this.list(new LambdaQueryWrapper<CrmMailAccountPO>()
.eq(CrmMailAccountPO::getCompanyId, companyId)
.eq(CrmMailAccountPO::getEnabled, 1)
.orderByDesc(CrmMailAccountPO::getIsDefault)
.orderByDesc(CrmMailAccountPO::getId))
.stream().map(this::toVo).toList();
}
@Override
public CrmMailAccountPO requireForSend(Long companyId, Long accountId) {
CrmMailAccountPO account;
if (accountId != null) {
account = this.getById(accountId);
if (account == null || !companyId.equals(account.getCompanyId())) {
throw new BusinessException("发件账户不存在");
}
} else {
account = this.getOne(new LambdaQueryWrapper<CrmMailAccountPO>()
.eq(CrmMailAccountPO::getCompanyId, companyId)
.eq(CrmMailAccountPO::getEnabled, 1)
.eq(CrmMailAccountPO::getIsDefault, 1)
.last("LIMIT 1"));
if (account == null) {
account = this.getOne(new LambdaQueryWrapper<CrmMailAccountPO>()
.eq(CrmMailAccountPO::getCompanyId, companyId)
.eq(CrmMailAccountPO::getEnabled, 1)
.orderByDesc(CrmMailAccountPO::getId)
.last("LIMIT 1"));
}
}
if (account == null) {
throw new BusinessException("请先配置启用的发件账户");
}
if (!Integer.valueOf(1).equals(account.getEnabled())) {
throw new BusinessException("发件账户未启用");
}
return account;
}
@Override
public String decryptPassword(CrmMailAccountPO account) {
return secretCrypto.decrypt(account.getPasswordCipher());
}
private void clearOtherDefaults(Long companyId, Long keepId) {
this.update(null, new LambdaUpdateWrapper<CrmMailAccountPO>()
.eq(CrmMailAccountPO::getCompanyId, companyId)
.ne(CrmMailAccountPO::getId, keepId)
.eq(CrmMailAccountPO::getIsDefault, 1)
.set(CrmMailAccountPO::getIsDefault, 0));
}
private void applyFields(CrmMailAccountPO po, String name, String fromEmail, String host,
Integer port, Integer ssl, String username, Integer enabled, Integer isDefault) {
po.setName(name.trim());
po.setFromEmail(fromEmail.trim());
po.setSmtpHost(host.trim());
po.setSmtpPort(port != null && port > 0 ? port : 465);
po.setSmtpSsl(ssl == null || ssl == 1 ? 1 : 0);
po.setUsername(username.trim());
po.setEnabled(enabled == null || enabled == 1 ? 1 : 0);
po.setIsDefault(isDefault != null && isDefault == 1 ? 1 : 0);
}
private CrmMailAccountVO toVo(CrmMailAccountPO po) {
CrmMailAccountVO vo = new CrmMailAccountVO();
vo.setId(po.getId());
vo.setCompanyId(po.getCompanyId());
vo.setName(po.getName());
vo.setFromEmail(po.getFromEmail());
vo.setSmtpHost(po.getSmtpHost());
vo.setSmtpPort(po.getSmtpPort());
vo.setSmtpSsl(po.getSmtpSsl());
vo.setUsername(po.getUsername());
vo.setEnabled(po.getEnabled());
vo.setIsDefault(po.getIsDefault());
vo.setPasswordSet(StringUtils.hasText(po.getPasswordCipher()));
vo.setCreateTime(po.getCreateTime());
vo.setUpdateTime(po.getUpdateTime());
return vo;
}
private CrmMailAccountPO requireOwned(Long id) {
Long companyId = requireCompanyId();
CrmMailAccountPO po = this.getById(id);
if (po == null || !companyId.equals(po.getCompanyId())) {
throw new BusinessException("发件账户不存在");
}
return po;
}
private Long requireCompanyId() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("请先选择公司");
}
return companyId;
}
}
@@ -0,0 +1,36 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.dto.CrmMailLogFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo.CrmMailLogVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.service.CrmMailLogService;
/** 邮件发送记录。 */
@RestController
@RequestMapping("/api/crm/mail-log")
public class CrmMailLogController {
private final CrmMailLogService mailLogService;
public CrmMailLogController(CrmMailLogService mailLogService) {
this.mailLogService = mailLogService;
}
@PostMapping("/list")
@RequirePermission(value = "crm:mail-log:read", description = "发送记录列表")
public ApiResponse<PageResultVO<CrmMailLogVO>> list(
@Valid @RequestBody PageQueryDTO<CrmMailLogFilterDTO> query) {
return ApiResponse.success("获取成功", mailLogService.page(query));
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:mail-log:read", description = "发送记录详情")
public ApiResponse<CrmMailLogVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", mailLogService.get(id));
}
}
@@ -0,0 +1,10 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.po.CrmMailLogPO;
/** 发送记录 Mapper。 */
@Mapper
public interface CrmMailLogMapper extends BaseMapper<CrmMailLogPO> {
}
@@ -0,0 +1,13 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.dto;
import lombok.Data;
/** 发送记录筛选。 */
@Data
public class CrmMailLogFilterDTO {
private String keyword;
private String status;
private Long customerId;
private String refType;
private Long refId;
}
@@ -0,0 +1,45 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
/** 邮件发送记录。 */
@Data
@TableName("crm_mail_log")
public class CrmMailLogPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("account_id")
private Long accountId;
@TableField("template_id")
private Long templateId;
@TableField("customer_id")
private Long customerId;
@TableField("ref_type")
private String refType;
@TableField("ref_id")
private Long refId;
@TableField("to_email")
private String toEmail;
@TableField("cc_email")
private String ccEmail;
@TableField("subject")
private String subject;
@TableField("body_html")
private String bodyHtml;
@TableField("status")
private String status;
@TableField("error_message")
private String errorMessage;
@TableField("sent_at")
private LocalDateTime sentAt;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField("create_by")
private Long createBy;
}
@@ -0,0 +1,29 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/** 发送记录视图。 */
@Data
public class CrmMailLogVO {
private Long id;
private Long companyId;
private Long accountId;
private String accountName;
private Long templateId;
private String templateName;
private Long customerId;
private String customerName;
private String refType;
private Long refId;
private String toEmail;
private String ccEmail;
private String subject;
private String bodyHtml;
private String status;
private String errorMessage;
private LocalDateTime sentAt;
private LocalDateTime createTime;
private Long createBy;
}
@@ -0,0 +1,17 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.service;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.dto.CrmMailLogFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.po.CrmMailLogPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo.CrmMailLogVO;
/** 发送记录查询与落库。 */
public interface CrmMailLogService {
PageResultVO<CrmMailLogVO> page(PageQueryDTO<CrmMailLogFilterDTO> query);
CrmMailLogVO get(Long id);
void insertLog(CrmMailLogPO log);
}
@@ -0,0 +1,183 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.log.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
import top.xyquan.ecomdmbbackend.modules.crm.customer.mapper.CrmCustomerMapper;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.po.CrmCustomerPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.mapper.CrmMailAccountMapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.po.CrmMailAccountPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.mapper.CrmMailLogMapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.dto.CrmMailLogFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.po.CrmMailLogPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo.CrmMailLogVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.service.CrmMailLogService;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.mapper.CrmMailTemplateMapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.po.CrmMailTemplatePO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.*;
import java.util.stream.Collectors;
/** 发送记录:只读列表 + 写入。 */
@Service
public class CrmMailLogServiceImpl extends ServiceImpl<CrmMailLogMapper, CrmMailLogPO>
implements CrmMailLogService {
private final CrmCustomerMapper customerMapper;
private final CrmMailAccountMapper accountMapper;
private final CrmMailTemplateMapper templateMapper;
private final CurrentUserContext currentUserContext;
public CrmMailLogServiceImpl(CrmCustomerMapper customerMapper,
CrmMailAccountMapper accountMapper,
CrmMailTemplateMapper templateMapper,
CurrentUserContext currentUserContext) {
this.customerMapper = customerMapper;
this.accountMapper = accountMapper;
this.templateMapper = templateMapper;
this.currentUserContext = currentUserContext;
}
@Override
public PageResultVO<CrmMailLogVO> page(PageQueryDTO<CrmMailLogFilterDTO> query) {
Long companyId = requireCompanyId();
CrmMailLogFilterDTO filters =
query.getFilters() != null ? query.getFilters() : new CrmMailLogFilterDTO();
LambdaQueryWrapper<CrmMailLogPO> w = new LambdaQueryWrapper<>();
w.eq(CrmMailLogPO::getCompanyId, companyId);
if (StringUtils.hasText(filters.getStatus())) {
w.eq(CrmMailLogPO::getStatus, filters.getStatus().trim());
}
if (filters.getCustomerId() != null) {
w.eq(CrmMailLogPO::getCustomerId, filters.getCustomerId());
}
if (StringUtils.hasText(filters.getRefType())) {
w.eq(CrmMailLogPO::getRefType, filters.getRefType().trim());
}
if (filters.getRefId() != null) {
w.eq(CrmMailLogPO::getRefId, filters.getRefId());
}
if (StringUtils.hasText(filters.getKeyword())) {
String kw = filters.getKeyword().trim();
w.and(x -> x.like(CrmMailLogPO::getToEmail, kw)
.or().like(CrmMailLogPO::getSubject, kw));
}
w.orderByDesc(CrmMailLogPO::getId);
IPage<CrmMailLogPO> page = this.page(new Page<>(query.getPage(), query.getPageSize()), w);
Set<Long> customerIds = page.getRecords().stream()
.map(CrmMailLogPO::getCustomerId).filter(Objects::nonNull).collect(Collectors.toSet());
Set<Long> accountIds = page.getRecords().stream()
.map(CrmMailLogPO::getAccountId).filter(Objects::nonNull).collect(Collectors.toSet());
Set<Long> templateIds = page.getRecords().stream()
.map(CrmMailLogPO::getTemplateId).filter(Objects::nonNull).collect(Collectors.toSet());
Map<Long, String> customers = loadCustomerNames(companyId, customerIds);
Map<Long, String> accounts = loadAccountNames(companyId, accountIds);
Map<Long, String> templates = loadTemplateNames(companyId, templateIds);
List<CrmMailLogVO> records = page.getRecords().stream().map(log -> {
CrmMailLogVO vo = toVo(log);
if (log.getCustomerId() != null) {
vo.setCustomerName(customers.get(log.getCustomerId()));
}
if (log.getAccountId() != null) {
vo.setAccountName(accounts.get(log.getAccountId()));
}
if (log.getTemplateId() != null) {
vo.setTemplateName(templates.get(log.getTemplateId()));
}
return vo;
}).toList();
return PageResultVO.create(records, page.getTotal(), query.getPage(), query.getPageSize());
}
@Override
public CrmMailLogVO get(Long id) {
Long companyId = requireCompanyId();
CrmMailLogPO log = this.getById(id);
if (log == null || !companyId.equals(log.getCompanyId())) {
throw new BusinessException("发送记录不存在");
}
CrmMailLogVO vo = toVo(log);
if (log.getCustomerId() != null) {
CrmCustomerPO c = customerMapper.selectById(log.getCustomerId());
if (c != null) {
vo.setCustomerName(c.getName());
}
}
if (log.getAccountId() != null) {
CrmMailAccountPO a = accountMapper.selectById(log.getAccountId());
if (a != null) {
vo.setAccountName(a.getName());
}
}
if (log.getTemplateId() != null) {
CrmMailTemplatePO t = templateMapper.selectById(log.getTemplateId());
if (t != null) {
vo.setTemplateName(t.getName());
}
}
return vo;
}
@Override
public void insertLog(CrmMailLogPO log) {
this.baseMapper.insert(log);
}
private CrmMailLogVO toVo(CrmMailLogPO po) {
CrmMailLogVO vo = new CrmMailLogVO();
BeanCopyUtils.copyProperties(po, vo);
return vo;
}
private Map<Long, String> loadCustomerNames(Long companyId, Set<Long> ids) {
if (ids.isEmpty()) {
return Map.of();
}
return customerMapper.selectList(new LambdaQueryWrapper<CrmCustomerPO>()
.eq(CrmCustomerPO::getCompanyId, companyId)
.in(CrmCustomerPO::getId, ids))
.stream()
.collect(Collectors.toMap(CrmCustomerPO::getId, CrmCustomerPO::getName, (a, b) -> a));
}
private Map<Long, String> loadAccountNames(Long companyId, Set<Long> ids) {
if (ids.isEmpty()) {
return Map.of();
}
return accountMapper.selectList(new LambdaQueryWrapper<CrmMailAccountPO>()
.eq(CrmMailAccountPO::getCompanyId, companyId)
.in(CrmMailAccountPO::getId, ids))
.stream()
.collect(Collectors.toMap(CrmMailAccountPO::getId, CrmMailAccountPO::getName, (a, b) -> a));
}
private Map<Long, String> loadTemplateNames(Long companyId, Set<Long> ids) {
if (ids.isEmpty()) {
return Map.of();
}
return templateMapper.selectList(new LambdaQueryWrapper<CrmMailTemplatePO>()
.eq(CrmMailTemplatePO::getCompanyId, companyId)
.in(CrmMailTemplatePO::getId, ids))
.stream()
.collect(Collectors.toMap(CrmMailTemplatePO::getId, CrmMailTemplatePO::getName, (a, b) -> a));
}
private Long requireCompanyId() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("请先选择公司");
}
return companyId;
}
}
@@ -0,0 +1,35 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.send.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo.CrmMailLogVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto.CrmMailPreviewDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto.CrmMailSendDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.vo.CrmMailPreviewVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.service.CrmMailSendService;
/** 手发邮件:预览与确认发送。 */
@RestController
@RequestMapping("/api/crm/mail")
public class CrmMailSendController {
private final CrmMailSendService mailSendService;
public CrmMailSendController(CrmMailSendService mailSendService) {
this.mailSendService = mailSendService;
}
@PostMapping("/preview")
@RequirePermission(value = "crm:mail:send", description = "预览邮件")
public ApiResponse<CrmMailPreviewVO> preview(@Valid @RequestBody CrmMailPreviewDTO dto) {
return ApiResponse.success("预览成功", mailSendService.preview(dto));
}
@PostMapping("/send")
@RequirePermission(value = "crm:mail:send", description = "发送邮件")
public ApiResponse<CrmMailLogVO> send(@Valid @RequestBody CrmMailSendDTO dto) {
return ApiResponse.success("发送成功", mailSendService.send(dto));
}
}
@@ -0,0 +1,20 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
/** 预览:模板 + 客户/业务单上下文。 */
@Data
public class CrmMailPreviewDTO {
@NotNull(message = "模板不能为空")
private Long templateId;
@NotNull(message = "客户不能为空")
private Long customerId;
/** quote / shipment,可空 */
private String refType;
private Long refId;
}
@@ -0,0 +1,39 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
/** 确认发送:用户可改主题/正文后再发。 */
@Data
public class CrmMailSendDTO {
/** 空则用默认发件账户 */
private Long accountId;
private Long templateId;
@NotNull(message = "客户不能为空")
private Long customerId;
private String refType;
private Long refId;
@NotBlank
@Email
@Size(max = 200)
private String toEmail;
@Size(max = 500)
private String ccEmail;
@NotBlank
@Size(max = 500)
private String subject;
@NotBlank
private String bodyHtml;
}
@@ -0,0 +1,18 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.vo;
import lombok.Data;
import java.util.Map;
/** 预览结果(已替换变量)。 */
@Data
public class CrmMailPreviewVO {
private Long templateId;
private String templateName;
private String scene;
private Long customerId;
private String toEmail;
private String subject;
private String bodyHtml;
private Map<String, String> variables;
}
@@ -0,0 +1,14 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.send.service;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo.CrmMailLogVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto.CrmMailPreviewDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto.CrmMailSendDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.vo.CrmMailPreviewVO;
/** 手发邮件:预览变量 → 确认发送 → 写日志。 */
public interface CrmMailSendService {
CrmMailPreviewVO preview(CrmMailPreviewDTO dto);
CrmMailLogVO send(CrmMailSendDTO dto);
}
@@ -0,0 +1,276 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.send.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.crm.customer.mapper.CrmCustomerMapper;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.po.CrmCustomerPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.model.po.CrmMailAccountPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.account.service.CrmMailAccountService;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.po.CrmMailLogPO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.model.vo.CrmMailLogVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.log.service.CrmMailLogService;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto.CrmMailPreviewDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.dto.CrmMailSendDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.model.vo.CrmMailPreviewVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.send.service.CrmMailSendService;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.po.CrmMailTemplatePO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.service.CrmMailTemplateService;
import top.xyquan.ecomdmbbackend.modules.crm.profile.model.vo.CrmCompanyProfileVO;
import top.xyquan.ecomdmbbackend.modules.crm.profile.service.CrmCompanyProfileService;
import top.xyquan.ecomdmbbackend.modules.crm.quote.mapper.CrmQuoteMapper;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.po.CrmQuotePO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.mapper.CrmShipmentMapper;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po.CrmShipmentPO;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmMailVariableRenderer;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmSmtpClient;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
/**
* 邮件发送编排:拼变量 → SMTP → 落 crm_mail_log(成功/失败均记)。
*/
@Service
public class CrmMailSendServiceImpl implements CrmMailSendService {
private final CrmMailTemplateService templateService;
private final CrmMailAccountService accountService;
private final CrmMailLogService mailLogService;
private final CrmCustomerMapper customerMapper;
private final CrmQuoteMapper quoteMapper;
private final CrmShipmentMapper shipmentMapper;
private final CrmCompanyProfileService profileService;
private final CrmMailVariableRenderer variableRenderer;
private final CrmSmtpClient smtpClient;
private final CurrentUserContext currentUserContext;
public CrmMailSendServiceImpl(CrmMailTemplateService templateService,
CrmMailAccountService accountService,
CrmMailLogService mailLogService,
CrmCustomerMapper customerMapper,
CrmQuoteMapper quoteMapper,
CrmShipmentMapper shipmentMapper,
CrmCompanyProfileService profileService,
CrmMailVariableRenderer variableRenderer,
CrmSmtpClient smtpClient,
CurrentUserContext currentUserContext) {
this.templateService = templateService;
this.accountService = accountService;
this.mailLogService = mailLogService;
this.customerMapper = customerMapper;
this.quoteMapper = quoteMapper;
this.shipmentMapper = shipmentMapper;
this.profileService = profileService;
this.variableRenderer = variableRenderer;
this.smtpClient = smtpClient;
this.currentUserContext = currentUserContext;
}
@Override
public CrmMailPreviewVO preview(CrmMailPreviewDTO dto) {
Long companyId = requireCompanyId();
CrmMailTemplatePO template = templateService.requireOwned(companyId, dto.getTemplateId());
CrmCustomerPO customer = requireCustomer(companyId, dto.getCustomerId());
Map<String, String> vars = buildVariables(companyId, customer, dto.getRefType(), dto.getRefId());
CrmMailPreviewVO vo = new CrmMailPreviewVO();
vo.setTemplateId(template.getId());
vo.setTemplateName(template.getName());
vo.setScene(template.getScene());
vo.setCustomerId(customer.getId());
vo.setToEmail(customer.getEmail());
vo.setSubject(variableRenderer.render(template.getSubject(), vars));
vo.setBodyHtml(variableRenderer.render(template.getBodyHtml(), vars));
vo.setVariables(vars);
return vo;
}
@Override
@Transactional
public CrmMailLogVO send(CrmMailSendDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
requireCustomer(companyId, dto.getCustomerId());
if (dto.getTemplateId() != null) {
templateService.requireOwned(companyId, dto.getTemplateId());
}
validateRef(companyId, dto.getCustomerId(), dto.getRefType(), dto.getRefId());
CrmMailAccountPO account = accountService.requireForSend(companyId, dto.getAccountId());
String password = accountService.decryptPassword(account);
CrmMailLogPO log = new CrmMailLogPO();
log.setCompanyId(companyId);
log.setAccountId(account.getId());
log.setTemplateId(dto.getTemplateId());
log.setCustomerId(dto.getCustomerId());
log.setRefType(trimToNull(dto.getRefType()));
log.setRefId(dto.getRefId());
log.setToEmail(dto.getToEmail().trim());
log.setCcEmail(trimToNull(dto.getCcEmail()));
log.setSubject(dto.getSubject().trim());
log.setBodyHtml(dto.getBodyHtml());
log.setCreateBy(userId);
try {
smtpClient.send(
new CrmSmtpClient.SmtpAccount(
account.getName(),
account.getFromEmail(),
account.getSmtpHost(),
account.getSmtpPort(),
Integer.valueOf(1).equals(account.getSmtpSsl()),
account.getUsername(),
password),
log.getToEmail(),
log.getCcEmail(),
log.getSubject(),
log.getBodyHtml());
log.setStatus("success");
log.setSentAt(LocalDateTime.now());
} catch (Exception e) {
log.setStatus("failed");
String msg = e.getMessage();
if (msg != null && msg.length() > 1000) {
msg = msg.substring(0, 1000);
}
log.setErrorMessage(msg);
mailLogService.insertLog(log);
throw new BusinessException("发送失败: " + e.getMessage());
}
mailLogService.insertLog(log);
return mailLogService.get(log.getId());
}
private Map<String, String> buildVariables(Long companyId, CrmCustomerPO customer,
String refType, Long refId) {
Map<String, String> vars = new LinkedHashMap<>();
vars.put("customerName", nz(firstNonBlank(customer.getNameEn(), customer.getName())));
vars.put("contactName", nz(customer.getContactName()));
vars.put("customerEmail", nz(customer.getEmail()));
vars.put("customerCountry", nz(customer.getCountry()));
vars.put("customerPhone", nz(customer.getPhone()));
CrmCompanyProfileVO profile = profileService.getCurrent();
vars.put("companyName", nz(firstNonBlank(profile.getLegalNameEn(), profile.getLegalNameZh())));
vars.put("companyEmail", nz(profile.getEmail()));
vars.put("companyPhone", nz(profile.getPhone()));
vars.put("quoteNo", "");
vars.put("quoteDate", "");
vars.put("totalAmount", "");
vars.put("currency", nz(customer.getCurrency()));
vars.put("incoterm", "");
vars.put("shipmentNo", "");
vars.put("destinationPort", "");
vars.put("planShipDate", "");
if (!StringUtils.hasText(refType) || refId == null) {
return vars;
}
String type = refType.trim().toLowerCase(Locale.ROOT);
if ("quote".equals(type)) {
CrmQuotePO quote = quoteMapper.selectById(refId);
if (quote == null || !companyId.equals(quote.getCompanyId())) {
throw new BusinessException("报价不存在");
}
if (!customer.getId().equals(quote.getCustomerId())) {
throw new BusinessException("报价与客户不匹配");
}
vars.put("quoteNo", nz(quote.getQuoteNo()));
vars.put("quoteDate", quote.getQuoteDate() != null ? quote.getQuoteDate().toString() : "");
vars.put("totalAmount", quote.getTotalAmount() != null ? quote.getTotalAmount().toPlainString() : "");
vars.put("currency", nz(quote.getCurrency()));
vars.put("incoterm", nz(quote.getIncoterm()));
} else if ("shipment".equals(type)) {
CrmShipmentPO ship = shipmentMapper.selectById(refId);
if (ship == null || !companyId.equals(ship.getCompanyId())) {
throw new BusinessException("出货单不存在");
}
if (!customer.getId().equals(ship.getCustomerId())) {
throw new BusinessException("出货与客户不匹配");
}
vars.put("shipmentNo", nz(ship.getShipmentNo()));
vars.put("destinationPort", nz(ship.getDestinationPort()));
vars.put("planShipDate",
ship.getPlanShipDate() != null ? ship.getPlanShipDate().toString() : "");
vars.put("totalAmount", ship.getTotalAmount() != null ? ship.getTotalAmount().toPlainString() : "");
vars.put("currency", nz(ship.getCurrency()));
vars.put("incoterm", nz(ship.getIncoterm()));
if (ship.getQuoteId() != null) {
CrmQuotePO quote = quoteMapper.selectById(ship.getQuoteId());
if (quote != null) {
vars.put("quoteNo", nz(quote.getQuoteNo()));
}
}
}
return vars;
}
private void validateRef(Long companyId, Long customerId, String refType, Long refId) {
if (!StringUtils.hasText(refType) && refId == null) {
return;
}
if (!StringUtils.hasText(refType) || refId == null) {
throw new BusinessException("关联业务单类型与 ID 需同时提供");
}
String type = refType.trim().toLowerCase(Locale.ROOT);
if ("quote".equals(type)) {
CrmQuotePO quote = quoteMapper.selectById(refId);
if (quote == null || !companyId.equals(quote.getCompanyId())
|| !customerId.equals(quote.getCustomerId())) {
throw new BusinessException("关联报价无效");
}
} else if ("shipment".equals(type)) {
CrmShipmentPO ship = shipmentMapper.selectById(refId);
if (ship == null || !companyId.equals(ship.getCompanyId())
|| !customerId.equals(ship.getCustomerId())) {
throw new BusinessException("关联出货无效");
}
} else {
throw new BusinessException("不支持的关联类型: " + refType);
}
}
private CrmCustomerPO requireCustomer(Long companyId, Long customerId) {
CrmCustomerPO customer = customerMapper.selectById(customerId);
if (customer == null || !companyId.equals(customer.getCompanyId())) {
throw new BusinessException("客户不存在");
}
return customer;
}
private Long requireCompanyId() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("请先选择公司");
}
return companyId;
}
private static String nz(String s) {
return s == null ? "" : s;
}
private static String trimToNull(String s) {
if (!StringUtils.hasText(s)) {
return null;
}
return s.trim();
}
private static String firstNonBlank(String a, String b) {
if (StringUtils.hasText(a)) {
return a.trim();
}
if (StringUtils.hasText(b)) {
return b.trim();
}
return "";
}
}
@@ -0,0 +1,67 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.CreateCrmMailTemplateDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.CrmMailTemplateFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.UpdateCrmMailTemplateDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.vo.CrmMailTemplateVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.service.CrmMailTemplateService;
import java.util.List;
/** 邮件模板管理。 */
@RestController
@RequestMapping("/api/crm/mail-template")
public class CrmMailTemplateController {
private final CrmMailTemplateService mailTemplateService;
public CrmMailTemplateController(CrmMailTemplateService mailTemplateService) {
this.mailTemplateService = mailTemplateService;
}
@PostMapping("/create")
@RequirePermission(value = "crm:mail-template:create", description = "创建邮件模板")
public ApiResponse<CrmMailTemplateVO> create(@Valid @RequestBody CreateCrmMailTemplateDTO dto) {
return ApiResponse.success("创建成功", mailTemplateService.create(dto));
}
@PutMapping("/update/{id}")
@RequirePermission(value = "crm:mail-template:update", description = "更新邮件模板")
public ApiResponse<CrmMailTemplateVO> update(
@PathVariable Long id, @Valid @RequestBody UpdateCrmMailTemplateDTO dto) {
return ApiResponse.success("更新成功", mailTemplateService.update(id, dto));
}
@DeleteMapping("/delete/{id}")
@RequirePermission(value = "crm:mail-template:delete", description = "删除邮件模板")
public ApiResponse<Void> delete(@PathVariable Long id) {
mailTemplateService.delete(id);
return ApiResponse.success("删除成功");
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:mail-template:read", description = "邮件模板详情")
public ApiResponse<CrmMailTemplateVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", mailTemplateService.get(id));
}
@PostMapping("/list")
@RequirePermission(value = "crm:mail-template:read", description = "邮件模板列表")
public ApiResponse<PageResultVO<CrmMailTemplateVO>> list(
@Valid @RequestBody PageQueryDTO<CrmMailTemplateFilterDTO> query) {
return ApiResponse.success("获取成功", mailTemplateService.page(query));
}
@GetMapping("/options")
@RequirePermission(value = "crm:mail:send", description = "启用模板选项")
public ApiResponse<List<CrmMailTemplateVO>> options(
@RequestParam(required = false) String scene) {
return ApiResponse.success("获取成功", mailTemplateService.listEnabled(scene));
}
}
@@ -0,0 +1,10 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.po.CrmMailTemplatePO;
/** 邮件模板 Mapper。 */
@Mapper
public interface CrmMailTemplateMapper extends BaseMapper<CrmMailTemplatePO> {
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
/** 创建邮件模板。 */
@Data
public class CreateCrmMailTemplateDTO {
@NotBlank
@Size(max = 100)
private String name;
@NotBlank
@Size(max = 32)
private String scene;
@NotBlank
@Size(max = 500)
private String subject;
@NotBlank
private String bodyHtml;
private Integer enabled;
@Size(max = 500)
private String remark;
}
@@ -0,0 +1,11 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto;
import lombok.Data;
/** 模板列表筛选。 */
@Data
public class CrmMailTemplateFilterDTO {
private String keyword;
private String scene;
private Integer enabled;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
/** 更新邮件模板。 */
@Data
public class UpdateCrmMailTemplateDTO {
@NotBlank
@Size(max = 100)
private String name;
@NotBlank
@Size(max = 32)
private String scene;
@NotBlank
@Size(max = 500)
private String subject;
@NotBlank
private String bodyHtml;
private Integer enabled;
@Size(max = 500)
private String remark;
}
@@ -0,0 +1,42 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
/** 邮件模板。 */
@Data
@TableName("crm_mail_template")
public class CrmMailTemplatePO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("name")
private String name;
@TableField("scene")
private String scene;
@TableField("subject")
private String subject;
@TableField("body_html")
private String bodyHtml;
@TableField("enabled")
private Integer enabled;
@TableField("remark")
private String remark;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField("create_by")
private Long createBy;
@TableField("update_by")
private Long updateBy;
@TableLogic
@TableField("delete_time")
private LocalDateTime deleteTime;
@TableField("delete_by")
private Long deleteBy;
}
@@ -0,0 +1,20 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/** 邮件模板视图。 */
@Data
public class CrmMailTemplateVO {
private Long id;
private Long companyId;
private String name;
private String scene;
private String subject;
private String bodyHtml;
private Integer enabled;
private String remark;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.service;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.CreateCrmMailTemplateDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.CrmMailTemplateFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.UpdateCrmMailTemplateDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.po.CrmMailTemplatePO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.vo.CrmMailTemplateVO;
import java.util.List;
/** 邮件模板用例。 */
public interface CrmMailTemplateService {
CrmMailTemplateVO create(CreateCrmMailTemplateDTO dto);
CrmMailTemplateVO update(Long id, UpdateCrmMailTemplateDTO dto);
void delete(Long id);
CrmMailTemplateVO get(Long id);
PageResultVO<CrmMailTemplateVO> page(PageQueryDTO<CrmMailTemplateFilterDTO> query);
/** 启用模板下拉(发信用)。 */
List<CrmMailTemplateVO> listEnabled(String scene);
CrmMailTemplatePO requireOwned(Long companyId, Long id);
}
@@ -0,0 +1,157 @@
package top.xyquan.ecomdmbbackend.modules.crm.mail.template.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.mapper.CrmMailTemplateMapper;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.CreateCrmMailTemplateDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.CrmMailTemplateFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.dto.UpdateCrmMailTemplateDTO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.po.CrmMailTemplatePO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.model.vo.CrmMailTemplateVO;
import top.xyquan.ecomdmbbackend.modules.crm.mail.template.service.CrmMailTemplateService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.List;
import java.util.Locale;
import java.util.Set;
/** 邮件模板 CRUD。 */
@Service
public class CrmMailTemplateServiceImpl extends ServiceImpl<CrmMailTemplateMapper, CrmMailTemplatePO>
implements CrmMailTemplateService {
private static final Set<String> SCENES = Set.of("outreach", "quote_followup", "shipment_notice");
private final CurrentUserContext currentUserContext;
public CrmMailTemplateServiceImpl(CurrentUserContext currentUserContext) {
this.currentUserContext = currentUserContext;
}
@Override
@Transactional
public CrmMailTemplateVO create(CreateCrmMailTemplateDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmMailTemplatePO po = new CrmMailTemplatePO();
po.setCompanyId(companyId);
apply(po, dto.getName(), dto.getScene(), dto.getSubject(), dto.getBodyHtml(),
dto.getEnabled(), dto.getRemark());
po.setCreateBy(userId);
po.setUpdateBy(userId);
this.save(po);
return toVo(po);
}
@Override
@Transactional
public CrmMailTemplateVO update(Long id, UpdateCrmMailTemplateDTO dto) {
CrmMailTemplatePO po = requireOwnedLocal(id);
apply(po, dto.getName(), dto.getScene(), dto.getSubject(), dto.getBodyHtml(),
dto.getEnabled(), dto.getRemark());
po.setUpdateBy(currentUserContext.getCurrentUserId());
this.updateById(po);
return toVo(po);
}
@Override
@Transactional
public void delete(Long id) {
CrmMailTemplatePO po = requireOwnedLocal(id);
po.setDeleteBy(currentUserContext.getCurrentUserId());
this.updateById(po);
this.removeById(id);
}
@Override
public CrmMailTemplateVO get(Long id) {
return toVo(requireOwnedLocal(id));
}
@Override
public PageResultVO<CrmMailTemplateVO> page(PageQueryDTO<CrmMailTemplateFilterDTO> query) {
Long companyId = requireCompanyId();
CrmMailTemplateFilterDTO filters =
query.getFilters() != null ? query.getFilters() : new CrmMailTemplateFilterDTO();
LambdaQueryWrapper<CrmMailTemplatePO> w = new LambdaQueryWrapper<>();
w.eq(CrmMailTemplatePO::getCompanyId, companyId);
if (StringUtils.hasText(filters.getScene())) {
w.eq(CrmMailTemplatePO::getScene, filters.getScene().trim());
}
if (filters.getEnabled() != null) {
w.eq(CrmMailTemplatePO::getEnabled, filters.getEnabled());
}
if (StringUtils.hasText(filters.getKeyword())) {
String kw = filters.getKeyword().trim();
w.and(x -> x.like(CrmMailTemplatePO::getName, kw)
.or().like(CrmMailTemplatePO::getSubject, kw));
}
w.orderByDesc(CrmMailTemplatePO::getId);
IPage<CrmMailTemplatePO> page = this.page(new Page<>(query.getPage(), query.getPageSize()), w);
List<CrmMailTemplateVO> records = page.getRecords().stream().map(this::toVo).toList();
return PageResultVO.create(records, page.getTotal(), query.getPage(), query.getPageSize());
}
@Override
public List<CrmMailTemplateVO> listEnabled(String scene) {
Long companyId = requireCompanyId();
LambdaQueryWrapper<CrmMailTemplatePO> w = new LambdaQueryWrapper<>();
w.eq(CrmMailTemplatePO::getCompanyId, companyId)
.eq(CrmMailTemplatePO::getEnabled, 1);
if (StringUtils.hasText(scene)) {
w.eq(CrmMailTemplatePO::getScene, scene.trim());
}
w.orderByDesc(CrmMailTemplatePO::getId);
return this.list(w).stream().map(this::toVo).toList();
}
@Override
public CrmMailTemplatePO requireOwned(Long companyId, Long id) {
CrmMailTemplatePO po = this.getById(id);
if (po == null || !companyId.equals(po.getCompanyId())) {
throw new BusinessException("邮件模板不存在");
}
return po;
}
private void apply(CrmMailTemplatePO po, String name, String scene, String subject,
String bodyHtml, Integer enabled, String remark) {
String sceneNorm = scene.trim().toLowerCase(Locale.ROOT);
if (!SCENES.contains(sceneNorm)) {
throw new BusinessException("场景不合法,可用: outreach / quote_followup / shipment_notice");
}
po.setName(name.trim());
po.setScene(sceneNorm);
po.setSubject(subject.trim());
po.setBodyHtml(bodyHtml);
po.setEnabled(enabled == null || enabled == 1 ? 1 : 0);
po.setRemark(StringUtils.hasText(remark) ? remark.trim() : null);
}
private CrmMailTemplateVO toVo(CrmMailTemplatePO po) {
CrmMailTemplateVO vo = new CrmMailTemplateVO();
BeanCopyUtils.copyProperties(po, vo);
return vo;
}
private CrmMailTemplatePO requireOwnedLocal(Long id) {
return requireOwned(requireCompanyId(), id);
}
private Long requireCompanyId() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("请先选择公司");
}
return companyId;
}
}
@@ -0,0 +1,84 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.ChangeCrmShipmentStatusDTO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.CreateCrmShipmentDTO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.CrmShipmentFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.UpdateCrmShipmentDTO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.vo.CrmShipmentVO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.service.CrmShipmentService;
/** 出货管理。 */
@RestController
@RequestMapping("/api/crm/shipment")
public class CrmShipmentController {
private final CrmShipmentService crmShipmentService;
public CrmShipmentController(CrmShipmentService crmShipmentService) {
this.crmShipmentService = crmShipmentService;
}
@PostMapping("/create")
@RequirePermission(value = "crm:shipment:create", description = "创建出货")
public ApiResponse<CrmShipmentVO> create(@Valid @RequestBody CreateCrmShipmentDTO dto) {
return ApiResponse.success("创建成功", crmShipmentService.create(dto));
}
@PostMapping("/from-quote/{quoteId}")
@RequirePermission(value = "crm:shipment:create", description = "从报价生成出货")
public ApiResponse<CrmShipmentVO> createFromQuote(@PathVariable Long quoteId) {
return ApiResponse.success("已生成出货", crmShipmentService.createFromQuote(quoteId));
}
@PutMapping("/update/{id}")
@RequirePermission(value = "crm:shipment:update", description = "更新出货")
public ApiResponse<CrmShipmentVO> update(
@PathVariable Long id, @Valid @RequestBody UpdateCrmShipmentDTO dto) {
return ApiResponse.success("更新成功", crmShipmentService.update(id, dto));
}
@DeleteMapping("/delete/{id}")
@RequirePermission(value = "crm:shipment:delete", description = "删除出货")
public ApiResponse<Void> delete(@PathVariable Long id) {
crmShipmentService.delete(id);
return ApiResponse.success("删除成功");
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:shipment:read", description = "出货详情")
public ApiResponse<CrmShipmentVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", crmShipmentService.get(id));
}
@PostMapping("/list")
@RequirePermission(value = "crm:shipment:read", description = "出货列表")
public ApiResponse<PageResultVO<CrmShipmentVO>> list(
@Valid @RequestBody PageQueryDTO<CrmShipmentFilterDTO> query) {
return ApiResponse.success("获取成功", crmShipmentService.page(query));
}
@PostMapping("/{id}/status")
@RequirePermission(value = "crm:shipment:status", description = "变更出货状态")
public ApiResponse<CrmShipmentVO> changeStatus(
@PathVariable Long id, @Valid @RequestBody ChangeCrmShipmentStatusDTO dto) {
return ApiResponse.success("状态已更新", crmShipmentService.changeStatus(id, dto));
}
@PostMapping("/{id}/export-ci")
@RequirePermission(value = "crm:shipment:export", description = "导出商业发票 CI")
public ApiResponse<CrmShipmentVO> exportCi(@PathVariable Long id) {
return ApiResponse.success("CI 已生成", crmShipmentService.exportCi(id));
}
@PostMapping("/{id}/export-pl")
@RequirePermission(value = "crm:shipment:export", description = "导出装箱单 PL")
public ApiResponse<CrmShipmentVO> exportPl(@PathVariable Long id) {
return ApiResponse.success("PL 已生成", crmShipmentService.exportPl(id));
}
}
@@ -0,0 +1,10 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po.CrmShipmentItemPO;
/** 出货行 Mapper。 */
@Mapper
public interface CrmShipmentItemMapper extends BaseMapper<CrmShipmentItemPO> {
}
@@ -0,0 +1,10 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po.CrmShipmentPO;
/** 出货单 Mapper。 */
@Mapper
public interface CrmShipmentMapper extends BaseMapper<CrmShipmentPO> {
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/** 变更出货状态。 */
@Data
public class ChangeCrmShipmentStatusDTO {
@NotBlank(message = "目标状态不能为空")
private String status;
}
@@ -0,0 +1,51 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.time.LocalDate;
import java.util.List;
/** 手动创建出货(可不关联报价)。 */
@Data
public class CreateCrmShipmentDTO {
private Long quoteId;
@NotNull(message = "客户不能为空")
private Long customerId;
private LocalDate planShipDate;
private LocalDate actualShipDate;
@Size(max = 100)
private String destinationPort;
@Size(max = 32)
private String transportMode;
@Size(max = 32)
private String containerType;
@Size(max = 3)
private String currency;
@Size(max = 16)
private String incoterm;
@Size(max = 200)
private String paymentTerms;
private Long ownerUserId;
@Size(max = 1000)
private String remark;
@NotEmpty(message = "至少一行明细")
@Valid
private List<CrmShipmentItemDTO> items;
}
@@ -0,0 +1,13 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto;
import lombok.Data;
/** 出货列表筛选。 */
@Data
public class CrmShipmentFilterDTO {
private String keyword;
private String status;
private Long customerId;
private Long quoteId;
private Boolean onlyMine;
}
@@ -0,0 +1,56 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.math.BigDecimal;
/** 出货行入参。 */
@Data
public class CrmShipmentItemDTO {
private Long productId;
@Size(max = 64)
private String productCode;
@NotBlank(message = "英文品名不能为空")
@Size(max = 200)
private String nameEn;
@Size(max = 200)
private String nameZh;
@Size(max = 500)
private String spec;
@Size(max = 32)
private String hsCode;
@Size(max = 32)
private String unit;
@NotNull(message = "数量不能为空")
private BigDecimal qty;
@NotNull(message = "单价不能为空")
private BigDecimal unitPrice;
private Integer packages;
private BigDecimal qtyPerPackage;
private BigDecimal grossWeightKg;
private BigDecimal netWeightKg;
private BigDecimal volumeCbm;
@Size(max = 64)
private String originCountry;
@Size(max = 500)
private String remark;
}
@@ -0,0 +1,49 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.time.LocalDate;
import java.util.List;
/** 更新出货(草稿/待出货可改)。 */
@Data
public class UpdateCrmShipmentDTO {
@NotNull(message = "客户不能为空")
private Long customerId;
private LocalDate planShipDate;
private LocalDate actualShipDate;
@Size(max = 100)
private String destinationPort;
@Size(max = 32)
private String transportMode;
@Size(max = 32)
private String containerType;
@Size(max = 3)
private String currency;
@Size(max = 16)
private String incoterm;
@Size(max = 200)
private String paymentTerms;
private Long ownerUserId;
@Size(max = 1000)
private String remark;
@NotEmpty(message = "至少一行明细")
@Valid
private List<CrmShipmentItemDTO> items;
}
@@ -0,0 +1,60 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/** 出货行(含箱规/重量/体积快照)。 */
@Data
@TableName("crm_shipment_item")
public class CrmShipmentItemPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("shipment_id")
private Long shipmentId;
@TableField("line_no")
private Integer lineNo;
@TableField("product_id")
private Long productId;
@TableField("product_code")
private String productCode;
@TableField("name_en")
private String nameEn;
@TableField("name_zh")
private String nameZh;
@TableField("spec")
private String spec;
@TableField("hs_code")
private String hsCode;
@TableField("unit")
private String unit;
@TableField("qty")
private BigDecimal qty;
@TableField("unit_price")
private BigDecimal unitPrice;
@TableField("amount")
private BigDecimal amount;
@TableField("packages")
private Integer packages;
@TableField("qty_per_package")
private BigDecimal qtyPerPackage;
@TableField("gross_weight_kg")
private BigDecimal grossWeightKg;
@TableField("net_weight_kg")
private BigDecimal netWeightKg;
@TableField("volume_cbm")
private BigDecimal volumeCbm;
@TableField("origin_country")
private String originCountry;
@TableField("remark")
private String remark;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
@@ -0,0 +1,70 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/** 出货单头。 */
@Data
@TableName("crm_shipment")
public class CrmShipmentPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("shipment_no")
private String shipmentNo;
@TableField("quote_id")
private Long quoteId;
@TableField("customer_id")
private Long customerId;
@TableField("plan_ship_date")
private LocalDate planShipDate;
@TableField("actual_ship_date")
private LocalDate actualShipDate;
@TableField("destination_port")
private String destinationPort;
@TableField("transport_mode")
private String transportMode;
@TableField("container_type")
private String containerType;
@TableField("currency")
private String currency;
@TableField("incoterm")
private String incoterm;
@TableField("payment_terms")
private String paymentTerms;
@TableField("status")
private String status;
@TableField("total_amount")
private BigDecimal totalAmount;
@TableField("total_packages")
private Integer totalPackages;
@TableField("total_gross_kg")
private BigDecimal totalGrossKg;
@TableField("total_net_kg")
private BigDecimal totalNetKg;
@TableField("total_cbm")
private BigDecimal totalCbm;
@TableField("owner_user_id")
private Long ownerUserId;
@TableField("remark")
private String remark;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField("create_by")
private Long createBy;
@TableField("update_by")
private Long updateBy;
@TableLogic
@TableField("delete_time")
private LocalDateTime deleteTime;
@TableField("delete_by")
private Long deleteBy;
}
@@ -0,0 +1,29 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.vo;
import lombok.Data;
import java.math.BigDecimal;
/** 出货行视图。 */
@Data
public class CrmShipmentItemVO {
private Long id;
private Integer lineNo;
private Long productId;
private String productCode;
private String nameEn;
private String nameZh;
private String spec;
private String hsCode;
private String unit;
private BigDecimal qty;
private BigDecimal unitPrice;
private BigDecimal amount;
private Integer packages;
private BigDecimal qtyPerPackage;
private BigDecimal grossWeightKg;
private BigDecimal netWeightKg;
private BigDecimal volumeCbm;
private String originCountry;
private String remark;
}
@@ -0,0 +1,43 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.model.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/** 出货视图。 */
@Data
public class CrmShipmentVO {
private Long id;
private Long companyId;
private String shipmentNo;
private Long quoteId;
private String quoteNo;
private Long customerId;
private String customerName;
private LocalDate planShipDate;
private LocalDate actualShipDate;
private String destinationPort;
private String transportMode;
private String containerType;
private String currency;
private String incoterm;
private String paymentTerms;
private String status;
private BigDecimal totalAmount;
private Integer totalPackages;
private BigDecimal totalGrossKg;
private BigDecimal totalNetKg;
private BigDecimal totalCbm;
private Long ownerUserId;
private String remark;
private LocalDateTime createTime;
private LocalDateTime updateTime;
private List<CrmShipmentItemVO> items;
private Long latestCiFileId;
private String latestCiAccessUrl;
private Long latestPlFileId;
private String latestPlAccessUrl;
}
@@ -0,0 +1,32 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.service;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.ChangeCrmShipmentStatusDTO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.CreateCrmShipmentDTO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.CrmShipmentFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.UpdateCrmShipmentDTO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.vo.CrmShipmentVO;
/** 出货用例:CRUD、从报价生成、导出 CI/PL。 */
public interface CrmShipmentService {
CrmShipmentVO create(CreateCrmShipmentDTO dto);
/** 从已接受报价生成出货草稿(带入客户与行项目)。 */
CrmShipmentVO createFromQuote(Long quoteId);
CrmShipmentVO update(Long id, UpdateCrmShipmentDTO dto);
void delete(Long id);
CrmShipmentVO get(Long id);
PageResultVO<CrmShipmentVO> page(PageQueryDTO<CrmShipmentFilterDTO> query);
CrmShipmentVO changeStatus(Long id, ChangeCrmShipmentStatusDTO dto);
CrmShipmentVO exportCi(Long id);
CrmShipmentVO exportPl(Long id);
}
@@ -0,0 +1,668 @@
package top.xyquan.ecomdmbbackend.modules.crm.shipment.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
import top.xyquan.ecomdmbbackend.modules.crm.customer.mapper.CrmCustomerMapper;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.po.CrmCustomerPO;
import top.xyquan.ecomdmbbackend.modules.crm.document.model.po.CrmDocumentPO;
import top.xyquan.ecomdmbbackend.modules.crm.document.service.CrmDocumentService;
import top.xyquan.ecomdmbbackend.modules.crm.product.mapper.CrmProductMapper;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.po.CrmProductPO;
import top.xyquan.ecomdmbbackend.modules.crm.profile.model.vo.CrmCompanyProfileVO;
import top.xyquan.ecomdmbbackend.modules.crm.profile.service.CrmCompanyProfileService;
import top.xyquan.ecomdmbbackend.modules.crm.quote.mapper.CrmQuoteItemMapper;
import top.xyquan.ecomdmbbackend.modules.crm.quote.mapper.CrmQuoteMapper;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.po.CrmQuoteItemPO;
import top.xyquan.ecomdmbbackend.modules.crm.quote.model.po.CrmQuotePO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.mapper.CrmShipmentItemMapper;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.mapper.CrmShipmentMapper;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.dto.*;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po.CrmShipmentItemPO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.po.CrmShipmentPO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.vo.CrmShipmentItemVO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.model.vo.CrmShipmentVO;
import top.xyquan.ecomdmbbackend.modules.crm.shipment.service.CrmShipmentService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmDocPdfRenderer;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmSeqService;
import top.xyquan.ecomdmbbackend.modules.sys.file.service.SysFileService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
/**
* 出货:草稿可改删;从已接受报价生成;导出 CI/PL。
*/
@Service
public class CrmShipmentServiceImpl extends ServiceImpl<CrmShipmentMapper, CrmShipmentPO>
implements CrmShipmentService {
private static final Set<String> STATUSES = Set.of("draft", "ready", "shipped", "closed");
private static final Set<String> EDITABLE = Set.of("draft", "ready");
private final CrmShipmentItemMapper shipmentItemMapper;
private final CrmCustomerMapper customerMapper;
private final CrmProductMapper productMapper;
private final CrmQuoteMapper quoteMapper;
private final CrmQuoteItemMapper quoteItemMapper;
private final CrmSeqService crmSeqService;
private final CrmCompanyProfileService profileService;
private final CrmDocPdfRenderer docPdfRenderer;
private final CrmDocumentService documentService;
private final SysFileService sysFileService;
private final CurrentUserContext currentUserContext;
public CrmShipmentServiceImpl(CrmShipmentItemMapper shipmentItemMapper,
CrmCustomerMapper customerMapper,
CrmProductMapper productMapper,
CrmQuoteMapper quoteMapper,
CrmQuoteItemMapper quoteItemMapper,
CrmSeqService crmSeqService,
CrmCompanyProfileService profileService,
CrmDocPdfRenderer docPdfRenderer,
CrmDocumentService documentService,
SysFileService sysFileService,
CurrentUserContext currentUserContext) {
this.shipmentItemMapper = shipmentItemMapper;
this.customerMapper = customerMapper;
this.productMapper = productMapper;
this.quoteMapper = quoteMapper;
this.quoteItemMapper = quoteItemMapper;
this.crmSeqService = crmSeqService;
this.profileService = profileService;
this.docPdfRenderer = docPdfRenderer;
this.documentService = documentService;
this.sysFileService = sysFileService;
this.currentUserContext = currentUserContext;
}
@Override
@Transactional
public CrmShipmentVO create(CreateCrmShipmentDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
requireCustomer(companyId, dto.getCustomerId());
if (dto.getQuoteId() != null) {
requireQuote(companyId, dto.getQuoteId());
}
CrmShipmentPO ship = new CrmShipmentPO();
ship.setCompanyId(companyId);
ship.setShipmentNo(crmSeqService.nextShipmentNo(companyId));
ship.setQuoteId(dto.getQuoteId());
applyHeader(ship, dto.getCustomerId(), dto.getPlanShipDate(), dto.getActualShipDate(),
dto.getDestinationPort(), dto.getTransportMode(), dto.getContainerType(),
dto.getCurrency(), dto.getIncoterm(), dto.getPaymentTerms(),
dto.getOwnerUserId() != null ? dto.getOwnerUserId() : userId,
dto.getRemark());
ship.setStatus("draft");
ship.setCreateBy(userId);
ship.setUpdateBy(userId);
List<CrmShipmentItemPO> items = buildItems(companyId, dto.getItems());
applyTotals(ship, items);
this.save(ship);
persistItems(ship.getId(), companyId, items);
return get(ship.getId());
}
@Override
@Transactional
public CrmShipmentVO createFromQuote(Long quoteId) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmQuotePO quote = requireQuote(companyId, quoteId);
if (!"accepted".equals(quote.getStatus())) {
throw new BusinessException("仅已接受的报价可生成出货");
}
List<CrmQuoteItemPO> quoteItems = quoteItemMapper.selectList(new LambdaQueryWrapper<CrmQuoteItemPO>()
.eq(CrmQuoteItemPO::getQuoteId, quoteId)
.orderByAsc(CrmQuoteItemPO::getLineNo));
if (quoteItems.isEmpty()) {
throw new BusinessException("报价无明细,无法生成出货");
}
CrmShipmentPO ship = new CrmShipmentPO();
ship.setCompanyId(companyId);
ship.setShipmentNo(crmSeqService.nextShipmentNo(companyId));
ship.setQuoteId(quoteId);
ship.setCustomerId(quote.getCustomerId());
ship.setPlanShipDate(LocalDate.now());
ship.setCurrency(normalizeCurrency(quote.getCurrency()));
ship.setIncoterm(quote.getIncoterm());
ship.setPaymentTerms(quote.getPaymentTerms());
ship.setStatus("draft");
ship.setOwnerUserId(quote.getOwnerUserId() != null ? quote.getOwnerUserId() : userId);
ship.setRemark(quote.getRemark());
ship.setCreateBy(userId);
ship.setUpdateBy(userId);
List<CrmShipmentItemPO> items = new ArrayList<>();
int lineNo = 1;
for (CrmQuoteItemPO qi : quoteItems) {
CrmShipmentItemPO item = new CrmShipmentItemPO();
item.setCompanyId(companyId);
item.setLineNo(lineNo++);
item.setProductId(qi.getProductId());
item.setProductCode(qi.getProductCode());
item.setNameEn(qi.getNameEn());
item.setNameZh(qi.getNameZh());
item.setSpec(qi.getSpec());
item.setUnit(qi.getUnit());
item.setQty(qi.getQty());
item.setUnitPrice(qi.getUnitPrice());
item.setAmount(qi.getAmount());
item.setRemark(qi.getRemark());
enrichFromProduct(companyId, item);
items.add(item);
}
applyTotals(ship, items);
this.save(ship);
persistItems(ship.getId(), companyId, items);
return get(ship.getId());
}
@Override
@Transactional
public CrmShipmentVO update(Long id, UpdateCrmShipmentDTO dto) {
CrmShipmentPO ship = requireOwned(id);
if (!EDITABLE.contains(ship.getStatus())) {
throw new BusinessException("当前状态不可编辑");
}
Long companyId = ship.getCompanyId();
requireCustomer(companyId, dto.getCustomerId());
applyHeader(ship, dto.getCustomerId(), dto.getPlanShipDate(), dto.getActualShipDate(),
dto.getDestinationPort(), dto.getTransportMode(), dto.getContainerType(),
dto.getCurrency(), dto.getIncoterm(), dto.getPaymentTerms(),
dto.getOwnerUserId() != null ? dto.getOwnerUserId() : ship.getOwnerUserId(),
dto.getRemark());
ship.setUpdateBy(currentUserContext.getCurrentUserId());
List<CrmShipmentItemPO> items = buildItems(companyId, dto.getItems());
applyTotals(ship, items);
this.updateById(ship);
shipmentItemMapper.delete(new LambdaQueryWrapper<CrmShipmentItemPO>()
.eq(CrmShipmentItemPO::getShipmentId, id));
persistItems(id, companyId, items);
return get(id);
}
@Override
@Transactional
public void delete(Long id) {
CrmShipmentPO ship = requireOwned(id);
if (!"draft".equals(ship.getStatus())) {
throw new BusinessException("仅草稿出货可删除");
}
Long userId = currentUserContext.getCurrentUserId();
this.lambdaUpdate()
.eq(CrmShipmentPO::getId, id)
.set(CrmShipmentPO::getDeleteBy, userId)
.update();
this.removeById(id);
}
@Override
public CrmShipmentVO get(Long id) {
return toDetailVo(requireOwned(id));
}
@Override
public PageResultVO<CrmShipmentVO> page(PageQueryDTO<CrmShipmentFilterDTO> query) {
Long companyId = requireCompanyId();
CrmShipmentFilterDTO filters = query.getFilters() != null ? query.getFilters() : new CrmShipmentFilterDTO();
LambdaQueryWrapper<CrmShipmentPO> w = new LambdaQueryWrapper<>();
w.eq(CrmShipmentPO::getCompanyId, companyId);
if (StringUtils.hasText(filters.getStatus())) {
w.eq(CrmShipmentPO::getStatus, filters.getStatus().trim());
}
if (filters.getCustomerId() != null) {
w.eq(CrmShipmentPO::getCustomerId, filters.getCustomerId());
}
if (filters.getQuoteId() != null) {
w.eq(CrmShipmentPO::getQuoteId, filters.getQuoteId());
}
if (Boolean.TRUE.equals(filters.getOnlyMine())) {
w.eq(CrmShipmentPO::getOwnerUserId, currentUserContext.getCurrentUserId());
}
if (StringUtils.hasText(filters.getKeyword())) {
String kw = filters.getKeyword().trim();
w.and(x -> x.like(CrmShipmentPO::getShipmentNo, kw)
.or().like(CrmShipmentPO::getDestinationPort, kw)
.or().like(CrmShipmentPO::getRemark, kw));
}
w.orderByDesc(CrmShipmentPO::getId);
IPage<CrmShipmentPO> page = this.page(new Page<>(query.getPage(), query.getPageSize()), w);
Set<Long> customerIds = page.getRecords().stream().map(CrmShipmentPO::getCustomerId).collect(Collectors.toSet());
Set<Long> quoteIds = page.getRecords().stream()
.map(CrmShipmentPO::getQuoteId).filter(Objects::nonNull).collect(Collectors.toSet());
Map<Long, String> customerNames = loadCustomerNames(companyId, customerIds);
Map<Long, String> quoteNos = loadQuoteNos(companyId, quoteIds);
List<CrmShipmentVO> records = page.getRecords().stream().map(s -> {
CrmShipmentVO vo = toBriefVo(s);
vo.setCustomerName(customerNames.get(s.getCustomerId()));
if (s.getQuoteId() != null) {
vo.setQuoteNo(quoteNos.get(s.getQuoteId()));
}
return vo;
}).toList();
return PageResultVO.create(records, page.getTotal(), query.getPage(), query.getPageSize());
}
@Override
@Transactional
public CrmShipmentVO changeStatus(Long id, ChangeCrmShipmentStatusDTO dto) {
CrmShipmentPO ship = requireOwned(id);
String target = dto.getStatus().trim().toLowerCase(Locale.ROOT);
if (!STATUSES.contains(target)) {
throw new BusinessException("目标状态不合法");
}
if (!isAllowedTransition(ship.getStatus(), target)) {
throw new BusinessException("不允许从 " + ship.getStatus() + " 变更为 " + target);
}
ship.setStatus(target);
if ("shipped".equals(target) && ship.getActualShipDate() == null) {
ship.setActualShipDate(LocalDate.now());
}
ship.setUpdateBy(currentUserContext.getCurrentUserId());
this.updateById(ship);
return get(id);
}
@Override
@Transactional
public CrmShipmentVO exportCi(Long id) {
CrmShipmentPO ship = requireOwned(id);
List<CrmShipmentItemPO> items = listItems(id);
if (items.isEmpty()) {
throw new BusinessException("出货无明细,无法导出 CI");
}
Long companyId = ship.getCompanyId();
CrmCustomerPO customer = requireCustomer(companyId, ship.getCustomerId());
CrmCompanyProfileVO profile = profileService.getCurrent();
LocalDate docDate = ship.getActualShipDate() != null
? ship.getActualShipDate()
: (ship.getPlanShipDate() != null ? ship.getPlanShipDate() : LocalDate.now());
CrmDocPdfRenderer.Party seller = partyFromProfile(profile);
CrmDocPdfRenderer.Party buyer = partyFromCustomer(customer);
List<CrmDocPdfRenderer.InvoiceLine> lines = new ArrayList<>();
for (CrmShipmentItemPO item : items) {
lines.add(new CrmDocPdfRenderer.InvoiceLine(
item.getLineNo(),
item.getProductCode(),
item.getNameEn(),
item.getSpec(),
item.getHsCode(),
item.getUnit(),
item.getQty(),
item.getUnitPrice(),
item.getAmount()));
}
String docNo = ship.getShipmentNo() + "-CI";
CrmDocPdfRenderer.InvoiceModel model = new CrmDocPdfRenderer.InvoiceModel(
"COMMERCIAL INVOICE",
docNo,
docDate.toString(),
ship.getCurrency(),
ship.getIncoterm(),
ship.getPaymentTerms(),
ship.getDestinationPort(),
ship.getTransportMode(),
ship.getContainerType(),
ship.getRemark(),
seller,
buyer,
lines,
ship.getTotalAmount());
byte[] pdf = docPdfRenderer.renderCommercialInvoice(model);
documentService.savePdf(companyId, "ci", docNo, "shipment", id,
"CI-" + ship.getShipmentNo() + ".pdf", pdf);
return get(id);
}
@Override
@Transactional
public CrmShipmentVO exportPl(Long id) {
CrmShipmentPO ship = requireOwned(id);
List<CrmShipmentItemPO> items = listItems(id);
if (items.isEmpty()) {
throw new BusinessException("出货无明细,无法导出 PL");
}
Long companyId = ship.getCompanyId();
CrmCustomerPO customer = requireCustomer(companyId, ship.getCustomerId());
CrmCompanyProfileVO profile = profileService.getCurrent();
LocalDate docDate = ship.getActualShipDate() != null
? ship.getActualShipDate()
: (ship.getPlanShipDate() != null ? ship.getPlanShipDate() : LocalDate.now());
List<CrmDocPdfRenderer.PackLine> lines = new ArrayList<>();
for (CrmShipmentItemPO item : items) {
lines.add(new CrmDocPdfRenderer.PackLine(
item.getLineNo(),
item.getProductCode(),
item.getNameEn(),
item.getSpec(),
item.getUnit(),
item.getQty(),
item.getPackages(),
item.getQtyPerPackage(),
item.getGrossWeightKg(),
item.getNetWeightKg(),
item.getVolumeCbm(),
item.getOriginCountry()));
}
String docNo = ship.getShipmentNo() + "-PL";
CrmDocPdfRenderer.PackingModel model = new CrmDocPdfRenderer.PackingModel(
"PACKING LIST",
docNo,
docDate.toString(),
ship.getDestinationPort(),
ship.getTransportMode(),
ship.getContainerType(),
ship.getRemark(),
partyFromProfile(profile),
partyFromCustomer(customer),
lines,
ship.getTotalPackages(),
ship.getTotalGrossKg(),
ship.getTotalNetKg(),
ship.getTotalCbm());
byte[] pdf = docPdfRenderer.renderPackingList(model);
documentService.savePdf(companyId, "pl", docNo, "shipment", id,
"PL-" + ship.getShipmentNo() + ".pdf", pdf);
return get(id);
}
private void applyHeader(CrmShipmentPO ship, Long customerId,
LocalDate planShipDate, LocalDate actualShipDate,
String destinationPort, String transportMode, String containerType,
String currency, String incoterm, String paymentTerms,
Long ownerUserId, String remark) {
ship.setCustomerId(customerId);
ship.setPlanShipDate(planShipDate);
ship.setActualShipDate(actualShipDate);
ship.setDestinationPort(trimToNull(destinationPort));
ship.setTransportMode(trimToNull(transportMode));
ship.setContainerType(trimToNull(containerType));
ship.setCurrency(normalizeCurrency(currency));
ship.setIncoterm(trimToNull(incoterm));
ship.setPaymentTerms(trimToNull(paymentTerms));
ship.setOwnerUserId(ownerUserId);
ship.setRemark(trimToNull(remark));
}
private boolean isAllowedTransition(String from, String to) {
if (from.equals(to)) {
return true;
}
return switch (from) {
case "draft" -> Set.of("ready", "closed").contains(to);
case "ready" -> Set.of("shipped", "draft", "closed").contains(to);
case "shipped" -> "closed".equals(to);
case "closed" -> false;
default -> false;
};
}
private List<CrmShipmentItemPO> buildItems(Long companyId, List<CrmShipmentItemDTO> dtos) {
List<CrmShipmentItemPO> items = new ArrayList<>();
int lineNo = 1;
for (CrmShipmentItemDTO dto : dtos) {
if (dto.getQty() == null || dto.getQty().compareTo(BigDecimal.ZERO) <= 0) {
throw new BusinessException("第 " + lineNo + " 行数量须大于 0");
}
if (dto.getUnitPrice() == null || dto.getUnitPrice().compareTo(BigDecimal.ZERO) < 0) {
throw new BusinessException("第 " + lineNo + " 行单价不能为负");
}
CrmShipmentItemPO item = new CrmShipmentItemPO();
item.setCompanyId(companyId);
item.setLineNo(lineNo++);
item.setProductId(dto.getProductId());
item.setProductCode(trimToNull(dto.getProductCode()));
item.setNameEn(dto.getNameEn().trim());
item.setNameZh(trimToNull(dto.getNameZh()));
item.setSpec(trimToNull(dto.getSpec()));
item.setHsCode(trimToNull(dto.getHsCode()));
item.setUnit(StringUtils.hasText(dto.getUnit()) ? dto.getUnit().trim() : "PCS");
item.setQty(dto.getQty());
item.setUnitPrice(dto.getUnitPrice());
item.setAmount(dto.getQty().multiply(dto.getUnitPrice()).setScale(2, RoundingMode.HALF_UP));
item.setPackages(dto.getPackages());
item.setQtyPerPackage(dto.getQtyPerPackage());
item.setGrossWeightKg(dto.getGrossWeightKg());
item.setNetWeightKg(dto.getNetWeightKg());
item.setVolumeCbm(dto.getVolumeCbm());
item.setOriginCountry(trimToNull(dto.getOriginCountry()));
item.setRemark(trimToNull(dto.getRemark()));
enrichFromProduct(companyId, item);
items.add(item);
}
return items;
}
/** 缺省字段从产品补全(不覆盖已填值)。 */
private void enrichFromProduct(Long companyId, CrmShipmentItemPO item) {
if (item.getProductId() == null) {
return;
}
CrmProductPO product = productMapper.selectById(item.getProductId());
if (product == null || !companyId.equals(product.getCompanyId())) {
throw new BusinessException("产品不存在: " + item.getProductId());
}
if (!StringUtils.hasText(item.getProductCode())) {
item.setProductCode(product.getCode());
}
if (!StringUtils.hasText(item.getNameZh())) {
item.setNameZh(product.getNameZh());
}
if (!StringUtils.hasText(item.getSpec())) {
item.setSpec(product.getSpec());
}
if (!StringUtils.hasText(item.getHsCode())) {
item.setHsCode(product.getHsCode());
}
if (item.getGrossWeightKg() == null && product.getGrossWeightKg() != null && item.getQty() != null) {
item.setGrossWeightKg(product.getGrossWeightKg().multiply(item.getQty()).setScale(3, RoundingMode.HALF_UP));
}
if (item.getNetWeightKg() == null && product.getNetWeightKg() != null && item.getQty() != null) {
item.setNetWeightKg(product.getNetWeightKg().multiply(item.getQty()).setScale(3, RoundingMode.HALF_UP));
}
if (item.getVolumeCbm() == null && product.getVolumeCbm() != null && item.getQty() != null) {
item.setVolumeCbm(product.getVolumeCbm().multiply(item.getQty()).setScale(4, RoundingMode.HALF_UP));
}
}
private void applyTotals(CrmShipmentPO ship, List<CrmShipmentItemPO> items) {
ship.setTotalAmount(items.stream()
.map(CrmShipmentItemPO::getAmount)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add)
.setScale(2, RoundingMode.HALF_UP));
int pkgs = items.stream()
.map(CrmShipmentItemPO::getPackages)
.filter(Objects::nonNull)
.mapToInt(Integer::intValue)
.sum();
ship.setTotalPackages(pkgs > 0 ? pkgs : null);
ship.setTotalGrossKg(sumDecimal(items.stream().map(CrmShipmentItemPO::getGrossWeightKg), 3));
ship.setTotalNetKg(sumDecimal(items.stream().map(CrmShipmentItemPO::getNetWeightKg), 3));
ship.setTotalCbm(sumDecimal(items.stream().map(CrmShipmentItemPO::getVolumeCbm), 4));
}
private static BigDecimal sumDecimal(java.util.stream.Stream<BigDecimal> stream, int scale) {
BigDecimal sum = stream.filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
if (sum.compareTo(BigDecimal.ZERO) == 0) {
return null;
}
return sum.setScale(scale, RoundingMode.HALF_UP);
}
private void persistItems(Long shipmentId, Long companyId, List<CrmShipmentItemPO> items) {
for (CrmShipmentItemPO item : items) {
item.setId(null);
item.setShipmentId(shipmentId);
item.setCompanyId(companyId);
shipmentItemMapper.insert(item);
}
}
private List<CrmShipmentItemPO> listItems(Long shipmentId) {
return shipmentItemMapper.selectList(new LambdaQueryWrapper<CrmShipmentItemPO>()
.eq(CrmShipmentItemPO::getShipmentId, shipmentId)
.orderByAsc(CrmShipmentItemPO::getLineNo));
}
private CrmShipmentVO toDetailVo(CrmShipmentPO ship) {
CrmShipmentVO vo = toBriefVo(ship);
CrmCustomerPO customer = customerMapper.selectById(ship.getCustomerId());
if (customer != null) {
vo.setCustomerName(customer.getName());
}
if (ship.getQuoteId() != null) {
CrmQuotePO quote = quoteMapper.selectById(ship.getQuoteId());
if (quote != null) {
vo.setQuoteNo(quote.getQuoteNo());
}
}
vo.setItems(listItems(ship.getId()).stream().map(item -> {
CrmShipmentItemVO iv = new CrmShipmentItemVO();
BeanCopyUtils.copyProperties(item, iv);
return iv;
}).toList());
CrmDocumentPO ci = documentService.findLatest(ship.getCompanyId(), "shipment", ship.getId(), "ci");
if (ci != null) {
vo.setLatestCiFileId(ci.getFileId());
vo.setLatestCiAccessUrl(sysFileService.resolveAccessUrl(ci.getFileId()));
}
CrmDocumentPO pl = documentService.findLatest(ship.getCompanyId(), "shipment", ship.getId(), "pl");
if (pl != null) {
vo.setLatestPlFileId(pl.getFileId());
vo.setLatestPlAccessUrl(sysFileService.resolveAccessUrl(pl.getFileId()));
}
return vo;
}
private CrmShipmentVO toBriefVo(CrmShipmentPO ship) {
CrmShipmentVO vo = new CrmShipmentVO();
BeanCopyUtils.copyProperties(ship, vo);
return vo;
}
private Map<Long, String> loadCustomerNames(Long companyId, Set<Long> ids) {
if (ids == null || ids.isEmpty()) {
return Map.of();
}
return customerMapper.selectList(new LambdaQueryWrapper<CrmCustomerPO>()
.eq(CrmCustomerPO::getCompanyId, companyId)
.in(CrmCustomerPO::getId, ids))
.stream()
.collect(Collectors.toMap(CrmCustomerPO::getId, CrmCustomerPO::getName, (a, b) -> a));
}
private Map<Long, String> loadQuoteNos(Long companyId, Set<Long> ids) {
if (ids == null || ids.isEmpty()) {
return Map.of();
}
return quoteMapper.selectList(new LambdaQueryWrapper<CrmQuotePO>()
.eq(CrmQuotePO::getCompanyId, companyId)
.in(CrmQuotePO::getId, ids))
.stream()
.collect(Collectors.toMap(CrmQuotePO::getId, CrmQuotePO::getQuoteNo, (a, b) -> a));
}
private CrmDocPdfRenderer.Party partyFromProfile(CrmCompanyProfileVO profile) {
return new CrmDocPdfRenderer.Party(
firstNonBlank(profile.getLegalNameEn(), profile.getLegalNameZh()),
firstNonBlank(profile.getAddressEn(), profile.getAddressZh()),
profile.getCountry(),
profile.getPhone(),
profile.getEmail());
}
private CrmDocPdfRenderer.Party partyFromCustomer(CrmCustomerPO customer) {
return new CrmDocPdfRenderer.Party(
firstNonBlank(customer.getNameEn(), customer.getName()),
customer.getAddress(),
customer.getCountry(),
customer.getPhone(),
customer.getEmail());
}
private CrmCustomerPO requireCustomer(Long companyId, Long customerId) {
CrmCustomerPO customer = customerMapper.selectById(customerId);
if (customer == null || !companyId.equals(customer.getCompanyId())) {
throw new BusinessException("客户不存在");
}
return customer;
}
private CrmQuotePO requireQuote(Long companyId, Long quoteId) {
CrmQuotePO quote = quoteMapper.selectById(quoteId);
if (quote == null || !companyId.equals(quote.getCompanyId())) {
throw new BusinessException("报价不存在");
}
return quote;
}
private CrmShipmentPO requireOwned(Long id) {
Long companyId = requireCompanyId();
CrmShipmentPO ship = this.getById(id);
if (ship == null || !companyId.equals(ship.getCompanyId())) {
throw new BusinessException("出货单不存在");
}
return ship;
}
private Long requireCompanyId() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new BusinessException("请先选择公司");
}
return companyId;
}
private static String normalizeCurrency(String currency) {
if (!StringUtils.hasText(currency)) {
return "USD";
}
return currency.trim().toUpperCase(Locale.ROOT);
}
private static String trimToNull(String s) {
if (!StringUtils.hasText(s)) {
return null;
}
return s.trim();
}
private static String firstNonBlank(String a, String b) {
if (StringUtils.hasText(a)) {
return a.trim();
}
if (StringUtils.hasText(b)) {
return b.trim();
}
return "";
}
}
@@ -0,0 +1,217 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
/**
* 出货单证 CI / PL PDF(英文排版)。
*/
@Component
public class CrmDocPdfRenderer {
public record Party(String name, String address, String country, String phone, String email) {
}
public record InvoiceLine(int lineNo, String code, String nameEn, String spec, String hsCode,
String unit, BigDecimal qty, BigDecimal unitPrice, BigDecimal amount) {
}
public record PackLine(int lineNo, String code, String nameEn, String spec,
String unit, BigDecimal qty, Integer packages, BigDecimal qtyPerPackage,
BigDecimal grossKg, BigDecimal netKg, BigDecimal cbm, String origin) {
}
public record InvoiceModel(
String title,
String docNo,
String docDate,
String currency,
String incoterm,
String paymentTerms,
String destinationPort,
String transportMode,
String containerType,
String remark,
Party seller,
Party buyer,
List<InvoiceLine> lines,
BigDecimal totalAmount
) {
}
public record PackingModel(
String title,
String docNo,
String docDate,
String destinationPort,
String transportMode,
String containerType,
String remark,
Party seller,
Party buyer,
List<PackLine> lines,
Integer totalPackages,
BigDecimal totalGrossKg,
BigDecimal totalNetKg,
BigDecimal totalCbm
) {
}
public byte[] renderCommercialInvoice(InvoiceModel model) {
return toPdf(buildCiHtml(model));
}
public byte[] renderPackingList(PackingModel model) {
return toPdf(buildPlHtml(model));
}
private byte[] toPdf(String html) {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.useFastMode();
builder.withHtmlContent(html, null);
builder.toStream(out);
builder.run();
return out.toByteArray();
} catch (Exception e) {
throw new BusinessException("生成 PDF 失败: " + e.getMessage());
}
}
private String buildCiHtml(InvoiceModel m) {
StringBuilder rows = new StringBuilder();
for (InvoiceLine line : m.lines()) {
rows.append("<tr>")
.append("<td>").append(line.lineNo()).append("</td>")
.append("<td>").append(esc(line.code())).append("</td>")
.append("<td>").append(esc(line.nameEn())).append("</td>")
.append("<td>").append(esc(line.spec())).append("</td>")
.append("<td>").append(esc(line.hsCode())).append("</td>")
.append("<td>").append(esc(line.unit())).append("</td>")
.append("<td class='num'>").append(fmt(line.qty(), 3)).append("</td>")
.append("<td class='num'>").append(fmt(line.unitPrice(), 4)).append("</td>")
.append("<td class='num'>").append(fmt(line.amount(), 2)).append("</td>")
.append("</tr>");
}
Party s = nz(m.seller());
Party b = nz(m.buyer());
StringBuilder html = new StringBuilder();
html.append(commonHead(m.title()))
.append(metaRow("No.", m.docNo(), "Date", m.docDate()))
.append(metaRow("Currency", m.currency(), "Incoterm", dash(m.incoterm())))
.append(metaRow("Payment", dash(m.paymentTerms()), "Dest. Port", dash(m.destinationPort())))
.append(metaRow("Transport", dash(m.transportMode()), "Container", dash(m.containerType())))
.append("</table>")
.append(partyBoxes(s, b))
.append("<table class=\"items\"><thead><tr>")
.append("<th>#</th><th>Code</th><th>Description</th><th>Spec</th><th>HS</th>")
.append("<th>Unit</th><th>Qty</th><th>Unit Price</th><th>Amount</th>")
.append("</tr></thead><tbody>").append(rows).append("</tbody></table>")
.append("<div class=\"total\">Total ").append(esc(m.currency())).append(" ")
.append(fmt(m.totalAmount(), 2)).append("</div>")
.append("<p class=\"muted\">Remark: ").append(esc(dash(m.remark()))).append("</p>")
.append("</body></html>");
return html.toString();
}
private String buildPlHtml(PackingModel m) {
StringBuilder rows = new StringBuilder();
for (PackLine line : m.lines()) {
rows.append("<tr>")
.append("<td>").append(line.lineNo()).append("</td>")
.append("<td>").append(esc(line.code())).append("</td>")
.append("<td>").append(esc(line.nameEn())).append("</td>")
.append("<td>").append(esc(line.spec())).append("</td>")
.append("<td>").append(esc(line.unit())).append("</td>")
.append("<td class='num'>").append(fmt(line.qty(), 3)).append("</td>")
.append("<td class='num'>").append(line.packages() == null ? "-" : line.packages()).append("</td>")
.append("<td class='num'>").append(fmt(line.qtyPerPackage(), 3)).append("</td>")
.append("<td class='num'>").append(fmt(line.grossKg(), 3)).append("</td>")
.append("<td class='num'>").append(fmt(line.netKg(), 3)).append("</td>")
.append("<td class='num'>").append(fmt(line.cbm(), 4)).append("</td>")
.append("<td>").append(esc(line.origin())).append("</td>")
.append("</tr>");
}
Party s = nz(m.seller());
Party b = nz(m.buyer());
StringBuilder html = new StringBuilder();
html.append(commonHead(m.title()))
.append(metaRow("No.", m.docNo(), "Date", m.docDate()))
.append(metaRow("Dest. Port", dash(m.destinationPort()), "Transport", dash(m.transportMode())))
.append(metaRow("Container", dash(m.containerType()), "", ""))
.append("</table>")
.append(partyBoxes(s, b))
.append("<table class=\"items\"><thead><tr>")
.append("<th>#</th><th>Code</th><th>Description</th><th>Spec</th><th>Unit</th>")
.append("<th>Qty</th><th>Pkgs</th><th>Qty/Pkg</th><th>G.W.</th><th>N.W.</th><th>CBM</th><th>Origin</th>")
.append("</tr></thead><tbody>").append(rows).append("</tbody></table>")
.append("<div class=\"total\">Pkgs: ").append(m.totalPackages() == null ? "-" : m.totalPackages())
.append(" &nbsp; G.W.: ").append(fmt(m.totalGrossKg(), 3))
.append(" kg &nbsp; N.W.: ").append(fmt(m.totalNetKg(), 3))
.append(" kg &nbsp; CBM: ").append(fmt(m.totalCbm(), 4)).append("</div>")
.append("<p class=\"muted\">Remark: ").append(esc(dash(m.remark()))).append("</p>")
.append("</body></html>");
return html.toString();
}
private static String commonHead(String title) {
return "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"/><style>"
+ "@page { size: A4; margin: 16mm; }"
+ "body { font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #222; }"
+ "h1 { font-size: 16px; margin: 0 0 8px 0; }"
+ ".meta td { padding: 2px 8px 2px 0; vertical-align: top; }"
+ ".box { border: 1px solid #ccc; padding: 8px; width: 48%; }"
+ ".row { width: 100%; margin-bottom: 10px; }"
+ ".row td { vertical-align: top; }"
+ "table.items { width: 100%; border-collapse: collapse; margin-top: 8px; }"
+ "table.items th, table.items td { border: 1px solid #999; padding: 4px 5px; }"
+ "table.items th { background: #f2f2f2; text-align: left; }"
+ ".num { text-align: right; white-space: nowrap; }"
+ ".total { margin-top: 10px; text-align: right; font-size: 12px; font-weight: bold; }"
+ ".muted { color: #666; font-size: 9px; }"
+ "</style></head><body><h1>" + esc(title) + "</h1><table class=\"meta\">";
}
private static String metaRow(String k1, String v1, String k2, String v2) {
return "<tr><td><b>" + esc(k1) + "</b></td><td>" + esc(dash(v1)) + "</td>"
+ "<td><b>" + esc(k2) + "</b></td><td>" + esc(dash(v2)) + "</td></tr>";
}
private static String partyBoxes(Party s, Party b) {
return "<table class=\"row\"><tr>"
+ "<td class=\"box\"><b>Seller</b><br/>" + esc(s.name()) + "<br/>" + esc(s.address())
+ "<br/>" + esc(s.country()) + "<br/>" + esc(s.phone()) + " " + esc(s.email()) + "</td>"
+ "<td style=\"width:4%\"></td>"
+ "<td class=\"box\"><b>Buyer</b><br/>" + esc(b.name()) + "<br/>" + esc(b.address())
+ "<br/>" + esc(b.country()) + "<br/>" + esc(b.phone()) + " " + esc(b.email()) + "</td>"
+ "</tr></table>";
}
private static Party nz(Party p) {
return p != null ? p : new Party("", "", "", "", "");
}
private static String fmt(BigDecimal v, int scale) {
if (v == null) {
return "-";
}
return v.setScale(scale, RoundingMode.HALF_UP).toPlainString();
}
private static String dash(String s) {
return s == null || s.isBlank() ? "-" : s;
}
private static String esc(String s) {
if (s == null) {
return "";
}
return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
}
}
@@ -0,0 +1,32 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 邮件模板变量替换:{{key}} → 上下文值。
*/
@Component
public class CrmMailVariableRenderer {
private static final Pattern VAR = Pattern.compile("\\{\\{\\s*([a-zA-Z0-9_]+)\\s*}}");
public String render(String template, Map<String, String> vars) {
if (!StringUtils.hasText(template)) {
return "";
}
Matcher m = VAR.matcher(template);
StringBuilder sb = new StringBuilder();
while (m.find()) {
String key = m.group(1);
String value = vars.getOrDefault(key, "");
m.appendReplacement(sb, Matcher.quoteReplacement(value == null ? "" : value));
}
m.appendTail(sb);
return sb.toString();
}
}
@@ -0,0 +1,70 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
/**
* CRM 敏感字段 AES-GCM(SMTP 密码等);密钥由 jwt.secret 派生。
*/
@Component
public class CrmSecretCrypto {
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
private static final int GCM_IV_LENGTH = 12;
private static final int GCM_TAG_LENGTH = 128;
private final String jwtSecret;
public CrmSecretCrypto(@Value("${jwt.secret}") String jwtSecret) {
this.jwtSecret = jwtSecret;
}
public String encrypt(String plain) {
try {
byte[] iv = new byte[GCM_IV_LENGTH];
new SecureRandom().nextBytes(iv);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
byte[] cipherBytes = cipher.doFinal(plain.getBytes(StandardCharsets.UTF_8));
ByteBuffer buffer = ByteBuffer.allocate(iv.length + cipherBytes.length);
buffer.put(iv);
buffer.put(cipherBytes);
return Base64.getEncoder().encodeToString(buffer.array());
} catch (Exception e) {
throw new BusinessException("加密失败");
}
}
public String decrypt(String token) {
try {
byte[] all = Base64.getDecoder().decode(token);
ByteBuffer buffer = ByteBuffer.wrap(all);
byte[] iv = new byte[GCM_IV_LENGTH];
buffer.get(iv);
byte[] cipherBytes = new byte[buffer.remaining()];
buffer.get(cipherBytes);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
return new String(cipher.doFinal(cipherBytes), StandardCharsets.UTF_8);
} catch (Exception e) {
throw new BusinessException("解密失败,请检查 jwt.secret 是否变更");
}
}
private SecretKey secretKey() throws Exception {
byte[] digest = MessageDigest.getInstance("SHA-256")
.digest(jwtSecret.getBytes(StandardCharsets.UTF_8));
return new SecretKeySpec(digest, "AES");
}
}
@@ -0,0 +1,72 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import jakarta.mail.Authenticator;
import jakarta.mail.Message;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import java.util.Properties;
/**
* 按账户动态建 SMTP Session 发送;不持有全局 MailSender。
*/
@Component
public class CrmSmtpClient {
public void send(SmtpAccount account, String to, String cc, String subject, String bodyHtml) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", account.host());
props.put("mail.smtp.port", String.valueOf(account.port()));
props.put("mail.smtp.auth", "true");
if (account.ssl()) {
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.port", String.valueOf(account.port()));
} else {
props.put("mail.smtp.starttls.enable", "true");
}
props.put("mail.smtp.connectiontimeout", "15000");
props.put("mail.smtp.timeout", "30000");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(account.username(), account.password());
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(account.fromEmail(), account.fromName()));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
if (StringUtils.hasText(cc)) {
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
}
message.setSubject(subject, "UTF-8");
message.setContent(bodyHtml, "text/html; charset=UTF-8");
Transport.send(message);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException("邮件发送失败: " + e.getMessage());
}
}
/** SMTP 发件参数(明文密码仅在内存短暂使用)。 */
public record SmtpAccount(
String fromName,
String fromEmail,
String host,
int port,
boolean ssl,
String username,
String password
) {
}
}
@@ -0,0 +1,36 @@
-- CRM Phase2 出货菜单权限(幂等)
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6500, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:shipment', '出货', 'module', 1, '', 40
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6500 OR `code` = 'crm:shipment');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6501, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6501 OR `code` = 'crm:shipment:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6502, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:create', '创建', 'api', 1, '', 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6502 OR `code` = 'crm:shipment:create');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6503, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:update', '更新', 'api', 1, '', 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6503 OR `code` = 'crm:shipment:update');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6504, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:delete', '删除', 'api', 1, '', 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6504 OR `code` = 'crm:shipment:delete');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6505, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:status', '改状态', 'api', 1, '', 5
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6505 OR `code` = 'crm:shipment:status');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6506, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:export', '导出CI/PL', 'api', 1, '', 6
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6506 OR `code` = 'crm:shipment:export');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14105, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmShipment', '出货', '/crm/shipment', '/crm/shipment/index', '', 'lucide:ship', 'menu', 1, 1, 1, 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14105 OR `route_name` = 'CrmShipment');
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'crm:shipment:%' WHERE m.route_name = 'CrmShipment';
@@ -0,0 +1,84 @@
-- CRM Phase3 邮件方案 A 菜单权限(幂等)
-- 发件账户
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6600, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:mail-account', '发件账户', 'module', 1, '', 50
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6600 OR `code` = 'crm:mail-account');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6601, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-account' LIMIT 1), 'crm:mail-account:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6601 OR `code` = 'crm:mail-account:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6602, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-account' LIMIT 1), 'crm:mail-account:create', '创建', 'api', 1, '', 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6602 OR `code` = 'crm:mail-account:create');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6603, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-account' LIMIT 1), 'crm:mail-account:update', '更新', 'api', 1, '', 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6603 OR `code` = 'crm:mail-account:update');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6604, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-account' LIMIT 1), 'crm:mail-account:delete', '删除', 'api', 1, '', 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6604 OR `code` = 'crm:mail-account:delete');
-- 邮件模板
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6700, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:mail-template', '邮件模板', 'module', 1, '', 60
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6700 OR `code` = 'crm:mail-template');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6701, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-template' LIMIT 1), 'crm:mail-template:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6701 OR `code` = 'crm:mail-template:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6702, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-template' LIMIT 1), 'crm:mail-template:create', '创建', 'api', 1, '', 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6702 OR `code` = 'crm:mail-template:create');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6703, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-template' LIMIT 1), 'crm:mail-template:update', '更新', 'api', 1, '', 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6703 OR `code` = 'crm:mail-template:update');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6704, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-template' LIMIT 1), 'crm:mail-template:delete', '删除', 'api', 1, '', 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6704 OR `code` = 'crm:mail-template:delete');
-- 手发
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6750, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:mail:send', '发送邮件', 'api', 1, '', 65
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6750 OR `code` = 'crm:mail:send');
-- 发送记录
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6800, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:mail-log', '发送记录', 'module', 1, '', 70
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6800 OR `code` = 'crm:mail-log');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6801, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-log' LIMIT 1), 'crm:mail-log:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6801 OR `code` = 'crm:mail-log:read');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14106, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmMailAccount', '发件账户', '/crm/mail-account', '/crm/mail-account/index', '', 'lucide:mailbox', 'menu', 1, 1, 0, 5
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14106 OR `route_name` = 'CrmMailAccount');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14107, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmMailTemplate', '邮件模板', '/crm/mail-template', '/crm/mail-template/index', '', 'lucide:mail', 'menu', 1, 1, 1, 6
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14107 OR `route_name` = 'CrmMailTemplate');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14108, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmMailLog', '发送记录', '/crm/mail-log', '/crm/mail-log/index', '', 'lucide:scroll-text', 'menu', 1, 1, 0, 7
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14108 OR `route_name` = 'CrmMailLog');
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'crm:mail-account:%' WHERE m.route_name = 'CrmMailAccount';
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'crm:mail-template:%' WHERE m.route_name = 'CrmMailTemplate';
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'crm:mail:send' WHERE m.route_name = 'CrmMailTemplate';
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'crm:mail-log:read' WHERE m.route_name = 'CrmMailLog';
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'crm:mail:send' WHERE m.route_name IN ('CrmCustomer', 'CrmQuote');
@@ -621,3 +621,125 @@ SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'crm:
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'crm:profile:%' WHERE m.route_name = 'CrmProfile';
-- ------------------------------------------------
-- CRM Phase2:出货
-- ------------------------------------------------
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6500, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:shipment', '出货', 'module', 1, '', 40
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6500 OR `code` = 'crm:shipment');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6501, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6501 OR `code` = 'crm:shipment:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6502, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:create', '创建', 'api', 1, '', 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6502 OR `code` = 'crm:shipment:create');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6503, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:update', '更新', 'api', 1, '', 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6503 OR `code` = 'crm:shipment:update');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6504, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:delete', '删除', 'api', 1, '', 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6504 OR `code` = 'crm:shipment:delete');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6505, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:status', '改状态', 'api', 1, '', 5
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6505 OR `code` = 'crm:shipment:status');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6506, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:shipment' LIMIT 1), 'crm:shipment:export', '导出CI/PL', 'api', 1, '', 6
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6506 OR `code` = 'crm:shipment:export');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14105, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmShipment', '出货', '/crm/shipment', '/crm/shipment/index', '', 'lucide:ship', 'menu', 1, 1, 1, 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14105 OR `route_name` = 'CrmShipment');
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'crm:shipment:%' WHERE m.route_name = 'CrmShipment';
-- ------------------------------------------------
-- CRM Phase3:邮件方案 A
-- ------------------------------------------------
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6600, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:mail-account', '发件账户', 'module', 1, '', 50
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6600 OR `code` = 'crm:mail-account');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6601, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-account' LIMIT 1), 'crm:mail-account:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6601 OR `code` = 'crm:mail-account:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6602, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-account' LIMIT 1), 'crm:mail-account:create', '创建', 'api', 1, '', 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6602 OR `code` = 'crm:mail-account:create');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6603, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-account' LIMIT 1), 'crm:mail-account:update', '更新', 'api', 1, '', 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6603 OR `code` = 'crm:mail-account:update');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6604, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-account' LIMIT 1), 'crm:mail-account:delete', '删除', 'api', 1, '', 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6604 OR `code` = 'crm:mail-account:delete');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6700, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:mail-template', '邮件模板', 'module', 1, '', 60
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6700 OR `code` = 'crm:mail-template');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6701, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-template' LIMIT 1), 'crm:mail-template:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6701 OR `code` = 'crm:mail-template:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6702, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-template' LIMIT 1), 'crm:mail-template:create', '创建', 'api', 1, '', 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6702 OR `code` = 'crm:mail-template:create');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6703, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-template' LIMIT 1), 'crm:mail-template:update', '更新', 'api', 1, '', 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6703 OR `code` = 'crm:mail-template:update');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6704, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-template' LIMIT 1), 'crm:mail-template:delete', '删除', 'api', 1, '', 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6704 OR `code` = 'crm:mail-template:delete');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6750, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:mail:send', '发送邮件', 'api', 1, '', 65
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6750 OR `code` = 'crm:mail:send');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6800, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:mail-log', '发送记录', 'module', 1, '', 70
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6800 OR `code` = 'crm:mail-log');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6801, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:mail-log' LIMIT 1), 'crm:mail-log:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6801 OR `code` = 'crm:mail-log:read');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14106, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmMailAccount', '发件账户', '/crm/mail-account', '/crm/mail-account/index', '', 'lucide:mailbox', 'menu', 1, 1, 0, 5
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14106 OR `route_name` = 'CrmMailAccount');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14107, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmMailTemplate', '邮件模板', '/crm/mail-template', '/crm/mail-template/index', '', 'lucide:mail', 'menu', 1, 1, 1, 6
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14107 OR `route_name` = 'CrmMailTemplate');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14108, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmMailLog', '发送记录', '/crm/mail-log', '/crm/mail-log/index', '', 'lucide:scroll-text', 'menu', 1, 1, 0, 7
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14108 OR `route_name` = 'CrmMailLog');
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'crm:mail-account:%' WHERE m.route_name = 'CrmMailAccount';
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'crm:mail-template:%' WHERE m.route_name = 'CrmMailTemplate';
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'crm:mail:send' WHERE m.route_name = 'CrmMailTemplate';
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'crm:mail-log:read' WHERE m.route_name = 'CrmMailLog';
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'crm:mail:send' WHERE m.route_name IN ('CrmCustomer', 'CrmQuote');
@@ -0,0 +1,38 @@
import type { CrmMailAccountDTO, CrmMailAccountVO } from './types';
import { requestClient } from '#/api/request';
export async function getCrmMailAccountListApi() {
return requestClient.get<CrmMailAccountVO.Info[]>('/crm/mail-account/list');
}
export async function getCrmMailAccountOptionsApi() {
return requestClient.get<CrmMailAccountVO.Info[]>(
'/crm/mail-account/options',
);
}
export async function getCrmMailAccountApi(id: number) {
return requestClient.get<CrmMailAccountVO.Info>(`/crm/mail-account/${id}`);
}
export async function createCrmMailAccountApi(data: CrmMailAccountDTO.Create) {
return requestClient.post<CrmMailAccountVO.Info>(
'/crm/mail-account/create',
data,
);
}
export async function updateCrmMailAccountApi(
id: number,
data: CrmMailAccountDTO.Update,
) {
return requestClient.put<CrmMailAccountVO.Info>(
`/crm/mail-account/update/${id}`,
data,
);
}
export async function deleteCrmMailAccountApi(id: number) {
return requestClient.delete(`/crm/mail-account/delete/${id}`);
}
@@ -0,0 +1,2 @@
export * from './apis';
export * from './types';
@@ -0,0 +1,44 @@
/** 发件账户 */
export namespace CrmMailAccountVO {
export interface Info {
id: number;
companyId?: number;
name: string;
fromEmail: string;
smtpHost: string;
smtpPort: number;
smtpSsl?: number;
username: string;
enabled?: number;
isDefault?: number;
passwordSet?: boolean;
createTime?: string;
updateTime?: string;
}
}
export namespace CrmMailAccountDTO {
export interface Create {
name: string;
fromEmail: string;
smtpHost: string;
smtpPort: number;
smtpSsl?: number;
username: string;
password: string;
enabled?: number;
isDefault?: number;
}
export interface Update {
name: string;
fromEmail: string;
smtpHost: string;
smtpPort: number;
smtpSsl?: number;
username: string;
password?: string;
enabled?: number;
isDefault?: number;
}
}
@@ -0,0 +1,18 @@
import type { CrmMailLogDTO, CrmMailLogVO } from './types';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import { requestClient } from '#/api/request';
export async function getCrmMailLogPageApi(
params: PageQueryDTO<CrmMailLogDTO.Filters>,
) {
return requestClient.post<PageResultVO<CrmMailLogVO.Info>>(
'/crm/mail-log/list',
params,
);
}
export async function getCrmMailLogApi(id: number) {
return requestClient.get<CrmMailLogVO.Info>(`/crm/mail-log/${id}`);
}
@@ -0,0 +1,2 @@
export * from './apis';
export * from './types';
@@ -0,0 +1,34 @@
/** 发送记录 */
export namespace CrmMailLogVO {
export interface Info {
id: number;
companyId?: number;
accountId?: number;
accountName?: string;
templateId?: number;
templateName?: string;
customerId?: number;
customerName?: string;
refType?: string;
refId?: number;
toEmail: string;
ccEmail?: string;
subject: string;
bodyHtml?: string;
status: string;
errorMessage?: string;
sentAt?: string;
createTime?: string;
createBy?: number;
}
}
export namespace CrmMailLogDTO {
export interface Filters {
keyword?: string;
status?: string;
customerId?: number;
refType?: string;
refId?: number;
}
}
@@ -0,0 +1,12 @@
import type { CrmMailLogVO } from '../log';
import type { CrmMailSendDTO, CrmMailSendVO } from './types';
import { requestClient } from '#/api/request';
export async function previewCrmMailApi(data: CrmMailSendDTO.Preview) {
return requestClient.post<CrmMailSendVO.Preview>('/crm/mail/preview', data);
}
export async function sendCrmMailApi(data: CrmMailSendDTO.Send) {
return requestClient.post<CrmMailLogVO.Info>('/crm/mail/send', data);
}
@@ -0,0 +1,2 @@
export * from './apis';
export * from './types';
@@ -0,0 +1,34 @@
/** 手发邮件 */
export namespace CrmMailSendVO {
export interface Preview {
templateId: number;
templateName?: string;
scene?: string;
customerId: number;
toEmail?: string;
subject: string;
bodyHtml: string;
variables?: Record<string, string>;
}
}
export namespace CrmMailSendDTO {
export interface Preview {
templateId: number;
customerId: number;
refType?: string;
refId?: number;
}
export interface Send {
accountId?: number;
templateId?: number;
customerId: number;
refType?: string;
refId?: number;
toEmail: string;
ccEmail?: string;
subject: string;
bodyHtml: string;
}
}
@@ -0,0 +1,48 @@
import type { CrmMailTemplateDTO, CrmMailTemplateVO } from './types';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import { requestClient } from '#/api/request';
export async function getCrmMailTemplatePageApi(
params: PageQueryDTO<CrmMailTemplateDTO.Filters>,
) {
return requestClient.post<PageResultVO<CrmMailTemplateVO.Info>>(
'/crm/mail-template/list',
params,
);
}
export async function getCrmMailTemplateOptionsApi(scene?: string) {
return requestClient.get<CrmMailTemplateVO.Info[]>(
'/crm/mail-template/options',
{ params: { scene } },
);
}
export async function getCrmMailTemplateApi(id: number) {
return requestClient.get<CrmMailTemplateVO.Info>(`/crm/mail-template/${id}`);
}
export async function createCrmMailTemplateApi(
data: CrmMailTemplateDTO.Create,
) {
return requestClient.post<CrmMailTemplateVO.Info>(
'/crm/mail-template/create',
data,
);
}
export async function updateCrmMailTemplateApi(
id: number,
data: CrmMailTemplateDTO.Update,
) {
return requestClient.put<CrmMailTemplateVO.Info>(
`/crm/mail-template/update/${id}`,
data,
);
}
export async function deleteCrmMailTemplateApi(id: number) {
return requestClient.delete(`/crm/mail-template/delete/${id}`);
}
@@ -0,0 +1,2 @@
export * from './apis';
export * from './types';
@@ -0,0 +1,34 @@
/** 邮件模板 */
export namespace CrmMailTemplateVO {
export interface Info {
id: number;
companyId?: number;
name: string;
scene: string;
subject: string;
bodyHtml: string;
enabled?: number;
remark?: string;
createTime?: string;
updateTime?: string;
}
}
export namespace CrmMailTemplateDTO {
export interface Create {
name: string;
scene: string;
subject: string;
bodyHtml: string;
enabled?: number;
remark?: string;
}
export type Update = Create;
export interface Filters {
keyword?: string;
scene?: string;
enabled?: number;
}
}
@@ -0,0 +1,60 @@
import type { CrmShipmentDTO, CrmShipmentVO } from './types';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import { requestClient } from '#/api/request';
export async function getCrmShipmentPageApi(
params: PageQueryDTO<CrmShipmentDTO.Filters>,
) {
return requestClient.post<PageResultVO<CrmShipmentVO.Info>>(
'/crm/shipment/list',
params,
);
}
export async function getCrmShipmentApi(id: number) {
return requestClient.get<CrmShipmentVO.Info>(`/crm/shipment/${id}`);
}
export async function createCrmShipmentApi(data: CrmShipmentDTO.Create) {
return requestClient.post<CrmShipmentVO.Info>('/crm/shipment/create', data);
}
export async function createCrmShipmentFromQuoteApi(quoteId: number) {
return requestClient.post<CrmShipmentVO.Info>(
`/crm/shipment/from-quote/${quoteId}`,
);
}
export async function updateCrmShipmentApi(
id: number,
data: CrmShipmentDTO.Update,
) {
return requestClient.put<CrmShipmentVO.Info>(
`/crm/shipment/update/${id}`,
data,
);
}
export async function deleteCrmShipmentApi(id: number) {
return requestClient.delete(`/crm/shipment/delete/${id}`);
}
export async function changeCrmShipmentStatusApi(
id: number,
data: CrmShipmentDTO.ChangeStatus,
) {
return requestClient.post<CrmShipmentVO.Info>(
`/crm/shipment/${id}/status`,
data,
);
}
export async function exportCrmShipmentCiApi(id: number) {
return requestClient.post<CrmShipmentVO.Info>(`/crm/shipment/${id}/export-ci`);
}
export async function exportCrmShipmentPlApi(id: number) {
return requestClient.post<CrmShipmentVO.Info>(`/crm/shipment/${id}/export-pl`);
}
@@ -0,0 +1,2 @@
export * from './apis';
export * from './types';
@@ -0,0 +1,2 @@
export * from './types.dto';
export * from './types.vo';
@@ -0,0 +1,51 @@
/** 出货 DTO */
export namespace CrmShipmentDTO {
export interface Item {
productId?: number;
productCode?: string;
nameEn: string;
nameZh?: string;
spec?: string;
hsCode?: string;
unit?: string;
qty: number;
unitPrice: number;
packages?: number;
qtyPerPackage?: number;
grossWeightKg?: number;
netWeightKg?: number;
volumeCbm?: number;
originCountry?: string;
remark?: string;
}
export interface Create {
quoteId?: number;
customerId: number;
planShipDate?: string;
actualShipDate?: string;
destinationPort?: string;
transportMode?: string;
containerType?: string;
currency?: string;
incoterm?: string;
paymentTerms?: string;
ownerUserId?: number;
remark?: string;
items: Item[];
}
export type Update = Omit<Create, 'quoteId'>;
export interface Filters {
keyword?: string;
status?: string;
customerId?: number;
quoteId?: number;
onlyMine?: boolean;
}
export interface ChangeStatus {
status: string;
}
}
@@ -0,0 +1,57 @@
/** 出货 VO */
export namespace CrmShipmentVO {
export interface Item {
id?: number;
lineNo?: number;
productId?: number;
productCode?: string;
nameEn: string;
nameZh?: string;
spec?: string;
hsCode?: string;
unit?: string;
qty: number;
unitPrice: number;
amount?: number;
packages?: number;
qtyPerPackage?: number;
grossWeightKg?: number;
netWeightKg?: number;
volumeCbm?: number;
originCountry?: string;
remark?: string;
}
export interface Info {
id: number;
companyId?: number;
shipmentNo: string;
quoteId?: number;
quoteNo?: string;
customerId: number;
customerName?: string;
planShipDate?: string;
actualShipDate?: string;
destinationPort?: string;
transportMode?: string;
containerType?: string;
currency?: string;
incoterm?: string;
paymentTerms?: string;
status: string;
totalAmount?: number;
totalPackages?: number;
totalGrossKg?: number;
totalNetKg?: number;
totalCbm?: number;
ownerUserId?: number;
remark?: string;
createTime?: string;
updateTime?: string;
items?: Item[];
latestCiFileId?: number;
latestCiAccessUrl?: string;
latestPlFileId?: number;
latestPlAccessUrl?: string;
}
}
@@ -23,6 +23,7 @@ import {
} from '#/composables/use-vxe-action-column';
import { exportByGet } from '#/utils/export';
import SendMailModal from '../mail/components/SendMailModal.vue';
import CustomerModal from './components/CustomerModal.vue';
defineOptions({ name: 'CrmCustomer' });
@@ -33,6 +34,7 @@ const UploadIcon = createIconifyIcon('lucide:upload');
const loading = ref(false);
const modalRef = ref<InstanceType<typeof CustomerModal>>();
const mailModalRef = ref<InstanceType<typeof SendMailModal>>();
const searchForm = ref({ keyword: '', status: undefined as string | undefined });
const statusMap: Record<string, { color: string; label: string }> = {
@@ -47,6 +49,7 @@ const actionCodes = [
'crm:customer:update',
'crm:customer:delete',
'crm:customer:import',
'crm:mail:send',
];
const showActionColumn = useActionColumnVisible(actionCodes);
@@ -71,7 +74,7 @@ const actionColumn: NonNullable<
VxeGridProps<CrmCustomerVO.Info>['columns']
>[number] = {
title: '操作',
width: 160,
width: 200,
fixed: 'right',
slots: { default: 'action' },
};
@@ -220,6 +223,22 @@ async function handleImport(file: File) {
编辑
</Button>
</PermissionGate>
<PermissionGate code="crm:mail:send">
<Button
type="link"
size="small"
:disabled="!row.email"
@click="
mailModalRef?.open({
customerId: row.id,
toEmail: row.email,
scene: 'outreach',
})
"
>
发邮件
</Button>
</PermissionGate>
<PermissionGate code="crm:customer:delete">
<Popconfirm title="确认删除该客户?" @confirm="handleDelete(row)">
<Button type="link" size="small" danger>删除</Button>
@@ -229,5 +248,6 @@ async function handleImport(file: File) {
</template>
</Grid>
<CustomerModal ref="modalRef" @success="gridApi.reload()" />
<SendMailModal ref="mailModalRef" />
</Page>
</template>
@@ -0,0 +1,167 @@
<script lang="ts" setup>
import type { CrmMailAccountDTO, CrmMailAccountVO } from '#/api/crm/mail/account';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Form, Input, InputNumber, Switch, message } from 'ant-design-vue';
import {
createCrmMailAccountApi,
updateCrmMailAccountApi,
} from '#/api/crm/mail/account';
const emit = defineEmits<{ success: [] }>();
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[560px]',
onCancel() {
modalApi.close();
},
onConfirm() {
handleSubmit();
},
});
const formRef = ref();
const isEdit = ref(false);
const editingId = ref<number>();
const form = ref({
name: '',
fromEmail: '',
smtpHost: '',
smtpPort: 465,
smtpSsl: true,
username: '',
password: '',
enabled: true,
isDefault: false,
});
const rules = {
name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
fromEmail: [{ required: true, message: '请输入发件邮箱', trigger: 'blur' }],
smtpHost: [{ required: true, message: '请输入 SMTP 主机', trigger: 'blur' }],
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
};
async function open(edit = false, row?: CrmMailAccountVO.Info) {
isEdit.value = edit;
editingId.value = row?.id;
if (edit && row) {
form.value = {
name: row.name,
fromEmail: row.fromEmail,
smtpHost: row.smtpHost,
smtpPort: row.smtpPort ?? 465,
smtpSsl: row.smtpSsl !== 0,
username: row.username,
password: '',
enabled: row.enabled !== 0,
isDefault: row.isDefault === 1,
};
modalApi.setState({ title: `编辑发件账户 ${row.name}` });
} else {
form.value = {
name: '',
fromEmail: '',
smtpHost: '',
smtpPort: 465,
smtpSsl: true,
username: '',
password: '',
enabled: true,
isDefault: false,
};
modalApi.setState({ title: '新建发件账户' });
}
modalApi.open();
}
async function handleSubmit() {
try {
await formRef.value?.validate();
} catch {
return;
}
if (!isEdit.value && !form.value.password) {
message.error('请填写 SMTP 密码');
return;
}
modalApi.setState({ confirmLoading: true });
try {
const payload: CrmMailAccountDTO.Create = {
name: form.value.name,
fromEmail: form.value.fromEmail,
smtpHost: form.value.smtpHost,
smtpPort: form.value.smtpPort,
smtpSsl: form.value.smtpSsl ? 1 : 0,
username: form.value.username,
password: form.value.password,
enabled: form.value.enabled ? 1 : 0,
isDefault: form.value.isDefault ? 1 : 0,
};
if (isEdit.value && editingId.value) {
await updateCrmMailAccountApi(editingId.value, {
...payload,
password: form.value.password || undefined,
});
message.success('更新成功');
} else {
await createCrmMailAccountApi(payload);
message.success('创建成功');
}
modalApi.close();
emit('success');
} finally {
modalApi.setState({ confirmLoading: false });
}
}
defineExpose({ open });
</script>
<template>
<Modal>
<Form
ref="formRef"
:model="form"
:rules="rules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 16 }"
>
<Form.Item label="显示名" name="name">
<Input v-model:value="form.name" placeholder="如 业务邮箱" />
</Form.Item>
<Form.Item label="发件邮箱" name="fromEmail">
<Input v-model:value="form.fromEmail" />
</Form.Item>
<Form.Item label="SMTP 主机" name="smtpHost">
<Input v-model:value="form.smtpHost" placeholder="smtp.example.com" />
</Form.Item>
<Form.Item label="端口">
<InputNumber v-model:value="form.smtpPort" :min="1" class="w-full" />
</Form.Item>
<Form.Item label="SSL/TLS">
<Switch v-model:checked="form.smtpSsl" />
</Form.Item>
<Form.Item label="用户名" name="username">
<Input v-model:value="form.username" />
</Form.Item>
<Form.Item :label="isEdit ? '密码(留空不改)' : '密码'">
<Input.Password
v-model:value="form.password"
:placeholder="isEdit ? '不修改请留空' : 'SMTP 密码'"
/>
</Form.Item>
<Form.Item label="启用">
<Switch v-model:checked="form.enabled" />
</Form.Item>
<Form.Item label="默认发件">
<Switch v-model:checked="form.isDefault" />
</Form.Item>
</Form>
</Modal>
</template>
@@ -0,0 +1,145 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { CrmMailAccountVO } from '#/api/crm/mail/account';
import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, Popconfirm, Space, Tag, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteCrmMailAccountApi,
getCrmMailAccountListApi,
} from '#/api/crm/mail/account';
import { PermissionGate } from '#/components/permission';
import {
syncVxeGridColumns,
useActionColumnVisible,
} from '#/composables/use-vxe-action-column';
import MailAccountModal from './components/MailAccountModal.vue';
defineOptions({ name: 'CrmMailAccount' });
const PlusIcon = createIconifyIcon('lucide:plus');
const modalRef = ref<InstanceType<typeof MailAccountModal>>();
const rows = ref<CrmMailAccountVO.Info[]>([]);
const actionCodes = [
'crm:mail-account:create',
'crm:mail-account:update',
'crm:mail-account:delete',
];
const showActionColumn = useActionColumnVisible(actionCodes);
const baseColumns: VxeGridProps<CrmMailAccountVO.Info>['columns'] = [
{ type: 'seq', title: '序号', minWidth: 60 },
{ field: 'name', title: '名称', minWidth: 140 },
{ field: 'fromEmail', title: '发件邮箱', minWidth: 180 },
{ field: 'smtpHost', title: 'SMTP', minWidth: 160 },
{ field: 'smtpPort', title: '端口', minWidth: 70 },
{
field: 'enabled',
title: '启用',
minWidth: 80,
slots: { default: 'enabled' },
},
{
field: 'isDefault',
title: '默认',
minWidth: 80,
slots: { default: 'isDefault' },
},
];
const actionColumn: NonNullable<
VxeGridProps<CrmMailAccountVO.Info>['columns']
>[number] = {
title: '操作',
width: 140,
fixed: 'right',
slots: { default: 'action' },
};
const tableColumns = computed(() =>
showActionColumn.value
? [...(baseColumns ?? []), actionColumn]
: (baseColumns ?? []),
);
const gridOptions: VxeGridProps<CrmMailAccountVO.Info> = {
columns: tableColumns.value,
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
pagerConfig: { enabled: false },
proxyConfig: {
ajax: {
query: async () => {
rows.value = (await getCrmMailAccountListApi()) ?? [];
return { items: rows.value, total: rows.value.length };
},
},
},
};
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });
syncVxeGridColumns(gridApi, tableColumns);
async function handleDelete(row: CrmMailAccountVO.Info) {
await deleteCrmMailAccountApi(row.id);
message.success('已删除');
gridApi.reload();
}
onMounted(() => gridApi.reload());
</script>
<template>
<Page
auto-content-height
title="发件账户"
description="公司级 SMTP,密码加密存储,不回显明文"
>
<Grid>
<template #toolbar-tools>
<PermissionGate code="crm:mail-account:create">
<Button type="primary" @click="modalRef?.open(false)">
<PlusIcon class="size-4" />
新建
</Button>
</PermissionGate>
</template>
<template #enabled="{ row }">
<Tag :color="row.enabled === 1 ? 'success' : 'default'">
{{ row.enabled === 1 ? '是' : '否' }}
</Tag>
</template>
<template #isDefault="{ row }">
<Tag v-if="row.isDefault === 1" color="processing">默认</Tag>
<span v-else>-</span>
</template>
<template #action="{ row }">
<Space>
<PermissionGate code="crm:mail-account:update">
<Button type="link" size="small" @click="modalRef?.open(true, row)">
编辑
</Button>
</PermissionGate>
<PermissionGate code="crm:mail-account:delete">
<Popconfirm title="确认删除?" @confirm="handleDelete(row)">
<Button type="link" size="small" danger>删除</Button>
</Popconfirm>
</PermissionGate>
</Space>
</template>
</Grid>
<MailAccountModal ref="modalRef" @success="gridApi.reload()" />
</Page>
</template>
@@ -0,0 +1,147 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { CrmMailLogDTO, CrmMailLogVO } from '#/api/crm/mail/log';
import type { PageQueryDTO } from '#/types/common';
import { h, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, Modal, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getCrmMailLogApi, getCrmMailLogPageApi } from '#/api/crm/mail/log';
defineOptions({ name: 'CrmMailLog' });
const searchForm = ref({
keyword: '',
status: undefined as string | undefined,
});
const statusMap: Record<string, { color: string; label: string }> = {
pending: { color: 'default', label: '待发' },
success: { color: 'success', label: '成功' },
failed: { color: 'error', label: '失败' },
};
const columns: VxeGridProps<CrmMailLogVO.Info>['columns'] = [
{ type: 'seq', title: '序号', minWidth: 60 },
{ field: 'createTime', title: '时间', minWidth: 160 },
{ field: 'toEmail', title: '收件人', minWidth: 180 },
{ field: 'subject', title: '主题', minWidth: 200 },
{ field: 'customerName', title: '客户', minWidth: 140 },
{ field: 'templateName', title: '模板', minWidth: 120 },
{ field: 'accountName', title: '发件账户', minWidth: 120 },
{
field: 'status',
title: '状态',
minWidth: 90,
slots: { default: 'status' },
},
{
title: '操作',
width: 90,
fixed: 'right',
slots: { default: 'action' },
},
];
const gridOptions: VxeGridProps<CrmMailLogVO.Info> = {
columns,
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
toolbarConfig: { custom: true, refresh: true, zoom: true },
pagerConfig: { enabled: true, pageSizes: [10, 20, 50, 100] },
proxyConfig: {
ajax: {
query: async ({ page }) => {
const params: PageQueryDTO<CrmMailLogDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
keyword: searchForm.value.keyword || undefined,
status: searchForm.value.status,
},
};
const data = await getCrmMailLogPageApi(params);
return { items: data.records, total: data.total };
},
},
},
};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: {
schema: [
{
component: 'Input',
fieldName: 'keyword',
label: '关键词',
componentProps: { placeholder: '收件人/主题' },
},
{
component: 'Select',
fieldName: 'status',
label: '状态',
componentProps: {
allowClear: true,
options: Object.entries(statusMap).map(([value, v]) => ({
value,
label: v.label,
})),
},
},
],
handleSubmit: async (values: Record<string, any>) => {
searchForm.value.keyword = values.keyword ?? '';
searchForm.value.status = values.status;
gridApi.reload();
},
},
});
async function showDetail(row: CrmMailLogVO.Info) {
const detail = await getCrmMailLogApi(row.id);
Modal.info({
title: detail.subject,
width: 720,
content: h('div', { class: 'space-y-2 text-sm' }, [
h('div', `收件:${detail.toEmail}`),
detail.ccEmail ? h('div', `抄送:${detail.ccEmail}`) : null,
detail.errorMessage
? h(
'div',
{ style: 'color:#cf1322' },
`失败:${detail.errorMessage}`,
)
: null,
h('div', {
style:
'border:1px solid #eee;padding:12px;max-height:360px;overflow:auto',
innerHTML: detail.bodyHtml || '',
}),
]),
});
}
</script>
<template>
<Page auto-content-height>
<Grid>
<template #status="{ row }">
<Tag :color="statusMap[row.status]?.color ?? 'default'">
{{ statusMap[row.status]?.label ?? row.status }}
</Tag>
</template>
<template #action="{ row }">
<Button type="link" size="small" @click="showDetail(row)">详情</Button>
</template>
</Grid>
</Page>
</template>
@@ -0,0 +1,153 @@
<script lang="ts" setup>
import type {
CrmMailTemplateDTO,
CrmMailTemplateVO,
} from '#/api/crm/mail/template';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Form, Input, Select, Switch, message } from 'ant-design-vue';
import {
createCrmMailTemplateApi,
getCrmMailTemplateApi,
updateCrmMailTemplateApi,
} from '#/api/crm/mail/template';
const emit = defineEmits<{ success: [] }>();
const sceneOptions = [
{ value: 'outreach', label: '开发信' },
{ value: 'quote_followup', label: '报价跟进' },
{ value: 'shipment_notice', label: '出货通知' },
];
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[720px]',
onCancel() {
modalApi.close();
},
onConfirm() {
handleSubmit();
},
});
const formRef = ref();
const isEdit = ref(false);
const editingId = ref<number>();
const form = ref({
name: '',
scene: 'outreach',
subject: '',
bodyHtml: '',
enabled: true,
remark: '',
});
const rules = {
name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
scene: [{ required: true, message: '请选择场景', trigger: 'change' }],
subject: [{ required: true, message: '请输入主题', trigger: 'blur' }],
bodyHtml: [{ required: true, message: '请输入正文', trigger: 'blur' }],
};
async function open(edit = false, id?: number) {
isEdit.value = edit;
editingId.value = id;
if (edit && id) {
const detail = await getCrmMailTemplateApi(id);
form.value = {
name: detail.name,
scene: detail.scene,
subject: detail.subject,
bodyHtml: detail.bodyHtml,
enabled: detail.enabled !== 0,
remark: detail.remark ?? '',
};
modalApi.setState({ title: `编辑模板 ${detail.name}` });
} else {
form.value = {
name: '',
scene: 'outreach',
subject: 'Hello {{contactName}}',
bodyHtml:
'<p>Dear {{contactName}},</p><p>We are {{companyName}}.</p><p>Best regards</p>',
enabled: true,
remark: '',
};
modalApi.setState({ title: '新建邮件模板' });
}
modalApi.open();
}
async function handleSubmit() {
try {
await formRef.value?.validate();
} catch {
return;
}
modalApi.setState({ confirmLoading: true });
try {
const payload: CrmMailTemplateDTO.Create = {
name: form.value.name,
scene: form.value.scene,
subject: form.value.subject,
bodyHtml: form.value.bodyHtml,
enabled: form.value.enabled ? 1 : 0,
remark: form.value.remark || undefined,
};
if (isEdit.value && editingId.value) {
await updateCrmMailTemplateApi(editingId.value, payload);
message.success('更新成功');
} else {
await createCrmMailTemplateApi(payload);
message.success('创建成功');
}
modalApi.close();
emit('success');
} finally {
modalApi.setState({ confirmLoading: false });
}
}
defineExpose({ open });
</script>
<template>
<Modal>
<Form
ref="formRef"
:model="form"
:rules="rules"
:label-col="{ span: 4 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="名称" name="name">
<Input v-model:value="form.name" />
</Form.Item>
<Form.Item label="场景" name="scene">
<Select v-model:value="form.scene" :options="sceneOptions" />
</Form.Item>
<Form.Item label="主题" name="subject">
<Input v-model:value="form.subject" />
</Form.Item>
<Form.Item label="正文 HTML" name="bodyHtml">
<Input.TextArea v-model:value="form.bodyHtml" :rows="10" />
</Form.Item>
<Form.Item label="启用">
<Switch v-model:checked="form.enabled" />
</Form.Item>
<Form.Item label="备注">
<Input v-model:value="form.remark" />
</Form.Item>
</Form>
<div class="text-muted-foreground px-2 text-xs">
变量示例:&#123;&#123;customerName&#125;&#125; &#123;&#123;contactName&#125;&#125;
&#123;&#123;quoteNo&#125;&#125; &#123;&#123;companyName&#125;&#125;
&#123;&#123;shipmentNo&#125;&#125;
</div>
</Modal>
</template>
@@ -0,0 +1,192 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type {
CrmMailTemplateDTO,
CrmMailTemplateVO,
} from '#/api/crm/mail/template';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, Popconfirm, Space, Tag, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteCrmMailTemplateApi,
getCrmMailTemplatePageApi,
} from '#/api/crm/mail/template';
import { PermissionGate } from '#/components/permission';
import {
syncVxeGridColumns,
useActionColumnVisible,
} from '#/composables/use-vxe-action-column';
import MailTemplateModal from './components/MailTemplateModal.vue';
defineOptions({ name: 'CrmMailTemplate' });
const PlusIcon = createIconifyIcon('lucide:plus');
const modalRef = ref<InstanceType<typeof MailTemplateModal>>();
const searchForm = ref({
keyword: '',
scene: undefined as string | undefined,
});
const sceneMap: Record<string, string> = {
outreach: '开发信',
quote_followup: '报价跟进',
shipment_notice: '出货通知',
};
const actionCodes = [
'crm:mail-template:create',
'crm:mail-template:update',
'crm:mail-template:delete',
];
const showActionColumn = useActionColumnVisible(actionCodes);
const baseColumns: VxeGridProps<CrmMailTemplateVO.Info>['columns'] = [
{ type: 'seq', title: '序号', minWidth: 60 },
{ field: 'name', title: '名称', minWidth: 160 },
{
field: 'scene',
title: '场景',
minWidth: 110,
slots: { default: 'scene' },
},
{ field: 'subject', title: '主题', minWidth: 220 },
{
field: 'enabled',
title: '启用',
minWidth: 80,
slots: { default: 'enabled' },
},
{ field: 'updateTime', title: '更新时间', minWidth: 160 },
];
const actionColumn: NonNullable<
VxeGridProps<CrmMailTemplateVO.Info>['columns']
>[number] = {
title: '操作',
width: 140,
fixed: 'right',
slots: { default: 'action' },
};
const tableColumns = computed(() =>
showActionColumn.value
? [...(baseColumns ?? []), actionColumn]
: (baseColumns ?? []),
);
const gridOptions: VxeGridProps<CrmMailTemplateVO.Info> = {
columns: tableColumns.value,
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
toolbarConfig: { custom: true, refresh: true, zoom: true },
pagerConfig: { enabled: true, pageSizes: [10, 20, 50] },
proxyConfig: {
ajax: {
query: async ({ page }) => {
const params: PageQueryDTO<CrmMailTemplateDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
keyword: searchForm.value.keyword || undefined,
scene: searchForm.value.scene,
},
};
const data = await getCrmMailTemplatePageApi(params);
return { items: data.records, total: data.total };
},
},
},
};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: {
schema: [
{
component: 'Input',
fieldName: 'keyword',
label: '关键词',
componentProps: { placeholder: '名称/主题' },
},
{
component: 'Select',
fieldName: 'scene',
label: '场景',
componentProps: {
allowClear: true,
options: Object.entries(sceneMap).map(([value, label]) => ({
value,
label,
})),
},
},
],
handleSubmit: async (values: Record<string, any>) => {
searchForm.value.keyword = values.keyword ?? '';
searchForm.value.scene = values.scene;
gridApi.reload();
},
},
});
syncVxeGridColumns(gridApi, tableColumns);
async function handleDelete(row: CrmMailTemplateVO.Info) {
await deleteCrmMailTemplateApi(row.id);
message.success('已删除');
gridApi.reload();
}
</script>
<template>
<Page auto-content-height>
<Grid>
<template #toolbar-tools>
<PermissionGate code="crm:mail-template:create">
<Button type="primary" @click="modalRef?.open(false)">
<PlusIcon class="size-4" />
新建模板
</Button>
</PermissionGate>
</template>
<template #scene="{ row }">
{{ sceneMap[row.scene] ?? row.scene }}
</template>
<template #enabled="{ row }">
<Tag :color="row.enabled === 1 ? 'success' : 'default'">
{{ row.enabled === 1 ? '是' : '否' }}
</Tag>
</template>
<template #action="{ row }">
<Space>
<PermissionGate code="crm:mail-template:update">
<Button
type="link"
size="small"
@click="modalRef?.open(true, row.id)"
>
编辑
</Button>
</PermissionGate>
<PermissionGate code="crm:mail-template:delete">
<Popconfirm title="确认删除?" @confirm="handleDelete(row)">
<Button type="link" size="small" danger>删除</Button>
</Popconfirm>
</PermissionGate>
</Space>
</template>
</Grid>
<MailTemplateModal ref="modalRef" @success="gridApi.reload()" />
</Page>
</template>
@@ -0,0 +1,186 @@
<script lang="ts" setup>
import type { CrmMailAccountVO } from '#/api/crm/mail/account';
import type { CrmMailTemplateVO } from '#/api/crm/mail/template';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Form, Input, Select, message } from 'ant-design-vue';
import { getCrmMailAccountOptionsApi } from '#/api/crm/mail/account';
import { previewCrmMailApi, sendCrmMailApi } from '#/api/crm/mail/send';
import { getCrmMailTemplateOptionsApi } from '#/api/crm/mail/template';
const emit = defineEmits<{ success: [] }>();
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[760px]',
onCancel() {
modalApi.close();
},
onConfirm() {
handleSend();
},
});
const formRef = ref();
const accounts = ref<CrmMailAccountVO.Info[]>([]);
const templates = ref<CrmMailTemplateVO.Info[]>([]);
const ctx = ref({
customerId: 0,
refType: undefined as string | undefined,
refId: undefined as number | undefined,
defaultTo: '',
scene: undefined as string | undefined,
});
const form = ref({
accountId: undefined as number | undefined,
templateId: undefined as number | undefined,
toEmail: '',
ccEmail: '',
subject: '',
bodyHtml: '',
});
const rules = {
templateId: [{ required: true, message: '请选择模板', trigger: 'change' }],
toEmail: [{ required: true, message: '请填写收件人', trigger: 'blur' }],
subject: [{ required: true, message: '请填写主题', trigger: 'blur' }],
bodyHtml: [{ required: true, message: '请填写正文', trigger: 'blur' }],
};
async function open(opts: {
customerId: number;
toEmail?: string;
refType?: string;
refId?: number;
scene?: string;
}) {
ctx.value = {
customerId: opts.customerId,
refType: opts.refType,
refId: opts.refId,
defaultTo: opts.toEmail ?? '',
scene: opts.scene,
};
const [acc, tpl] = await Promise.all([
getCrmMailAccountOptionsApi(),
getCrmMailTemplateOptionsApi(opts.scene),
]);
accounts.value = acc ?? [];
templates.value = tpl ?? [];
const defaultAcc = accounts.value.find((a) => a.isDefault === 1);
form.value = {
accountId: defaultAcc?.id ?? accounts.value[0]?.id,
templateId: templates.value[0]?.id,
toEmail: opts.toEmail ?? '',
ccEmail: '',
subject: '',
bodyHtml: '',
};
modalApi.setState({ title: '发送邮件' });
modalApi.open();
if (form.value.templateId) {
await handlePreview();
}
}
async function handlePreview() {
if (!form.value.templateId || !ctx.value.customerId) {
return;
}
const preview = await previewCrmMailApi({
templateId: form.value.templateId,
customerId: ctx.value.customerId,
refType: ctx.value.refType,
refId: ctx.value.refId,
});
form.value.subject = preview.subject;
form.value.bodyHtml = preview.bodyHtml;
if (!form.value.toEmail) {
form.value.toEmail = preview.toEmail || ctx.value.defaultTo || '';
}
}
async function handleSend() {
try {
await formRef.value?.validate();
} catch {
return;
}
modalApi.setState({ confirmLoading: true });
try {
await sendCrmMailApi({
accountId: form.value.accountId,
templateId: form.value.templateId,
customerId: ctx.value.customerId,
refType: ctx.value.refType,
refId: ctx.value.refId,
toEmail: form.value.toEmail,
ccEmail: form.value.ccEmail || undefined,
subject: form.value.subject,
bodyHtml: form.value.bodyHtml,
});
message.success('发送成功');
modalApi.close();
emit('success');
} finally {
modalApi.setState({ confirmLoading: false });
}
}
defineExpose({ open });
</script>
<template>
<Modal>
<Form
ref="formRef"
:model="form"
:rules="rules"
:label-col="{ span: 4 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="发件账户">
<Select
v-model:value="form.accountId"
allow-clear
:options="
accounts.map((a) => ({
value: a.id,
label: `${a.name} <${a.fromEmail}>`,
}))
"
placeholder="默认账户"
/>
</Form.Item>
<Form.Item label="模板" name="templateId">
<Select
v-model:value="form.templateId"
:options="
templates.map((t) => ({
value: t.id,
label: `${t.name} (${t.scene})`,
}))
"
@change="handlePreview"
/>
</Form.Item>
<Form.Item label="收件人" name="toEmail">
<Input v-model:value="form.toEmail" />
</Form.Item>
<Form.Item label="抄送">
<Input v-model:value="form.ccEmail" placeholder="可选,逗号分隔" />
</Form.Item>
<Form.Item label="主题" name="subject">
<Input v-model:value="form.subject" />
</Form.Item>
<Form.Item label="正文" name="bodyHtml">
<Input.TextArea v-model:value="form.bodyHtml" :rows="10" />
</Form.Item>
</Form>
</Modal>
</template>
@@ -19,6 +19,7 @@ import {
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { createCrmShipmentFromQuoteApi } from '#/api/crm/shipment';
import {
changeCrmQuoteStatusApi,
deleteCrmQuoteApi,
@@ -31,6 +32,7 @@ import {
useActionColumnVisible,
} from '#/composables/use-vxe-action-column';
import SendMailModal from '../mail/components/SendMailModal.vue';
import QuoteModal from './components/QuoteModal.vue';
defineOptions({ name: 'CrmQuote' });
@@ -38,6 +40,7 @@ defineOptions({ name: 'CrmQuote' });
const PlusIcon = createIconifyIcon('lucide:plus');
const loading = ref(false);
const modalRef = ref<InstanceType<typeof QuoteModal>>();
const mailModalRef = ref<InstanceType<typeof SendMailModal>>();
const searchForm = ref({
keyword: '',
status: undefined as string | undefined,
@@ -57,6 +60,8 @@ const actionCodes = [
'crm:quote:delete',
'crm:quote:status',
'crm:quote:export',
'crm:shipment:create',
'crm:mail:send',
];
const showActionColumn = useActionColumnVisible(actionCodes);
@@ -80,7 +85,7 @@ const actionColumn: NonNullable<
VxeGridProps<CrmQuoteVO.Info>['columns']
>[number] = {
title: '操作',
width: 280,
width: 380,
fixed: 'right',
slots: { default: 'action' },
};
@@ -177,6 +182,12 @@ async function handleExportPi(row: CrmQuoteVO.Info) {
gridApi.reload();
}
async function handleCreateShipment(row: CrmQuoteVO.Info) {
const ship = await createCrmShipmentFromQuoteApi(row.id);
message.success(`已生成出货 ${ship.shipmentNo}`);
gridApi.reload();
}
function statusActions(row: CrmQuoteVO.Info) {
const s = row.status;
const actions: Array<{ key: string; label: string }> = [];
@@ -228,6 +239,32 @@ function statusActions(row: CrmQuoteVO.Info) {
导出PI
</Button>
</PermissionGate>
<PermissionGate code="crm:mail:send">
<Button
type="link"
size="small"
@click="
mailModalRef?.open({
customerId: row.customerId,
refType: 'quote',
refId: row.id,
scene: 'quote_followup',
})
"
>
发邮件
</Button>
</PermissionGate>
<PermissionGate code="crm:shipment:create">
<Button
v-if="row.status === 'accepted'"
type="link"
size="small"
@click="handleCreateShipment(row)"
>
生成出货
</Button>
</PermissionGate>
<PermissionGate code="crm:quote:status">
<Dropdown v-if="statusActions(row).length">
<Button type="link" size="small">状态</Button>
@@ -261,5 +298,6 @@ function statusActions(row: CrmQuoteVO.Info) {
</template>
</Grid>
<QuoteModal ref="modalRef" @success="gridApi.reload()" />
<SendMailModal ref="mailModalRef" />
</Page>
</template>
@@ -0,0 +1,429 @@
<script lang="ts" setup>
import type { CrmCustomerVO } from '#/api/crm/customer';
import type { CrmProductVO } from '#/api/crm/product';
import type { CrmShipmentDTO, CrmShipmentVO } from '#/api/crm/shipment';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import {
Button,
DatePicker,
Form,
Input,
InputNumber,
message,
Select,
Space,
Table,
} from 'ant-design-vue';
import dayjs, { type Dayjs } from 'dayjs';
import { getCrmCustomerPageApi } from '#/api/crm/customer';
import { getCrmProductPageApi } from '#/api/crm/product';
import {
createCrmShipmentApi,
getCrmShipmentApi,
updateCrmShipmentApi,
} from '#/api/crm/shipment';
const emit = defineEmits<{ success: [] }>();
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[1100px]',
onCancel() {
modalApi.close();
},
onConfirm() {
handleSubmit();
},
});
const formRef = ref();
const isEdit = ref(false);
const editingId = ref<number>();
const customers = ref<CrmCustomerVO.Info[]>([]);
const products = ref<CrmProductVO.Info[]>([]);
interface LineRow extends CrmShipmentDTO.Item {
_key: string;
}
const formData = ref({
customerId: undefined as number | undefined,
planShipDate: dayjs() as Dayjs | undefined,
actualShipDate: undefined as Dayjs | undefined,
destinationPort: '',
transportMode: '',
containerType: '',
currency: 'USD',
incoterm: '',
paymentTerms: '',
remark: '',
});
const items = ref<LineRow[]>([]);
const totalAmount = computed(() =>
items.value.reduce((sum, row) => {
const qty = Number(row.qty) || 0;
const price = Number(row.unitPrice) || 0;
return sum + qty * price;
}, 0),
);
const rules = {
customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
};
async function loadOptions() {
const [c, p] = await Promise.all([
getCrmCustomerPageApi({ page: 1, pageSize: 200, filters: {} }),
getCrmProductPageApi({
page: 1,
pageSize: 200,
filters: { status: 1 },
}),
]);
customers.value = c.records ?? [];
products.value = p.records ?? [];
}
function emptyLine(): LineRow {
return {
_key: `${Date.now()}-${Math.random()}`,
nameEn: '',
unit: 'PCS',
qty: 1,
unitPrice: 0,
};
}
function mapItems(list: CrmShipmentVO.Item[] | undefined): LineRow[] {
return (list ?? []).map((it) => ({
_key: `${it.id ?? Date.now()}-${Math.random()}`,
productId: it.productId,
productCode: it.productCode,
nameEn: it.nameEn,
nameZh: it.nameZh,
spec: it.spec,
hsCode: it.hsCode,
unit: it.unit ?? 'PCS',
qty: Number(it.qty) || 0,
unitPrice: Number(it.unitPrice) || 0,
packages: it.packages,
qtyPerPackage: it.qtyPerPackage,
grossWeightKg: it.grossWeightKg,
netWeightKg: it.netWeightKg,
volumeCbm: it.volumeCbm,
originCountry: it.originCountry,
remark: it.remark,
}));
}
async function open(edit = false, id?: number) {
await loadOptions();
isEdit.value = edit;
editingId.value = id;
if (edit && id) {
const detail = await getCrmShipmentApi(id);
formData.value = {
customerId: detail.customerId,
planShipDate: detail.planShipDate ? dayjs(detail.planShipDate) : dayjs(),
actualShipDate: detail.actualShipDate
? dayjs(detail.actualShipDate)
: undefined,
destinationPort: detail.destinationPort ?? '',
transportMode: detail.transportMode ?? '',
containerType: detail.containerType ?? '',
currency: detail.currency ?? 'USD',
incoterm: detail.incoterm ?? '',
paymentTerms: detail.paymentTerms ?? '',
remark: detail.remark ?? '',
};
items.value = mapItems(detail.items);
modalApi.setState({ title: `编辑出货 ${detail.shipmentNo}` });
} else {
formData.value = {
customerId: undefined,
planShipDate: dayjs(),
actualShipDate: undefined,
destinationPort: '',
transportMode: '',
containerType: '',
currency: 'USD',
incoterm: '',
paymentTerms: '',
remark: '',
};
items.value = [emptyLine()];
modalApi.setState({ title: '新建出货' });
}
modalApi.open();
}
function addLine() {
items.value.push(emptyLine());
}
function removeLine(key: string) {
if (items.value.length <= 1) {
message.warning('至少保留一行');
return;
}
items.value = items.value.filter((x) => x._key !== key);
}
function onPickProduct(row: LineRow, productId: number) {
const p = products.value.find((x) => x.id === productId);
if (!p) return;
row.productId = p.id;
row.productCode = p.code;
row.nameEn = p.nameEn;
row.nameZh = p.nameZh;
row.spec = p.spec;
row.hsCode = p.hsCode;
row.unit = p.unit || 'PCS';
row.unitPrice = Number(p.unitPrice) || 0;
const qty = Number(row.qty) || 1;
if (p.grossWeightKg != null) {
row.grossWeightKg = Number(p.grossWeightKg) * qty;
}
if (p.netWeightKg != null) {
row.netWeightKg = Number(p.netWeightKg) * qty;
}
if (p.volumeCbm != null) {
row.volumeCbm = Number(p.volumeCbm) * qty;
}
}
function buildPayload(): CrmShipmentDTO.Create {
return {
customerId: formData.value.customerId!,
planShipDate: formData.value.planShipDate?.format('YYYY-MM-DD'),
actualShipDate: formData.value.actualShipDate?.format('YYYY-MM-DD'),
destinationPort: formData.value.destinationPort || undefined,
transportMode: formData.value.transportMode || undefined,
containerType: formData.value.containerType || undefined,
currency: formData.value.currency,
incoterm: formData.value.incoterm || undefined,
paymentTerms: formData.value.paymentTerms || undefined,
remark: formData.value.remark || undefined,
items: items.value.map((row) => ({
productId: row.productId,
productCode: row.productCode,
nameEn: row.nameEn,
nameZh: row.nameZh,
spec: row.spec,
hsCode: row.hsCode,
unit: row.unit,
qty: Number(row.qty),
unitPrice: Number(row.unitPrice),
packages: row.packages,
qtyPerPackage: row.qtyPerPackage,
grossWeightKg: row.grossWeightKg,
netWeightKg: row.netWeightKg,
volumeCbm: row.volumeCbm,
originCountry: row.originCountry,
remark: row.remark,
})),
};
}
async function handleSubmit() {
try {
await formRef.value?.validate();
} catch {
return;
}
if (items.value.some((x) => !x.nameEn?.trim())) {
message.error('请填写每行英文品名');
return;
}
modalApi.setState({ confirmLoading: true });
try {
const payload = buildPayload();
if (isEdit.value && editingId.value) {
await updateCrmShipmentApi(editingId.value, payload);
message.success('更新成功');
} else {
await createCrmShipmentApi(payload);
message.success('创建成功');
}
modalApi.close();
emit('success');
} finally {
modalApi.setState({ confirmLoading: false });
}
}
const columns = [
{ title: '产品', key: 'product', width: 140 },
{ title: '英文品名', key: 'nameEn', width: 140 },
{ title: 'HS', key: 'hsCode', width: 90 },
{ title: '数量', key: 'qty', width: 90 },
{ title: '单价', key: 'unitPrice', width: 100 },
{ title: '箱数', key: 'packages', width: 80 },
{ title: '毛重', key: 'grossWeightKg', width: 90 },
{ title: '净重', key: 'netWeightKg', width: 90 },
{ title: 'CBM', key: 'volumeCbm', width: 90 },
{ title: '', key: 'action', width: 50 },
];
defineExpose({ open });
</script>
<template>
<Modal>
<Form
ref="formRef"
:model="formData"
:rules="rules"
:label-col="{ span: 4 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="客户" name="customerId">
<Select
v-model:value="formData.customerId"
show-search
option-filter-prop="label"
:options="
customers.map((c) => ({
value: c.id,
label: `${c.name}${c.country ? ` (${c.country})` : ''}`,
}))
"
placeholder="选择客户"
/>
</Form.Item>
<Form.Item label="计划出货日">
<DatePicker v-model:value="formData.planShipDate" class="w-full" />
</Form.Item>
<Form.Item label="实际出货日">
<DatePicker v-model:value="formData.actualShipDate" class="w-full" />
</Form.Item>
<Form.Item label="目的港">
<Input v-model:value="formData.destinationPort" />
</Form.Item>
<Form.Item label="运输方式">
<Input
v-model:value="formData.transportMode"
placeholder="sea / air / express"
/>
</Form.Item>
<Form.Item label="柜型">
<Input
v-model:value="formData.containerType"
placeholder="20GP / 40HQ"
/>
</Form.Item>
<Form.Item label="币种">
<Input v-model:value="formData.currency" />
</Form.Item>
<Form.Item label="贸易术语">
<Input v-model:value="formData.incoterm" placeholder="FOB / CIF" />
</Form.Item>
<Form.Item label="付款条款">
<Input v-model:value="formData.paymentTerms" />
</Form.Item>
<Form.Item label="备注">
<Input.TextArea v-model:value="formData.remark" :rows="2" />
</Form.Item>
</Form>
<div class="mb-2 flex items-center justify-between">
<div class="font-medium">明细 / 箱规</div>
<Space>
<span>合计:{{ totalAmount.toFixed(2) }} {{ formData.currency }}</span>
<Button size="small" @click="addLine">加行</Button>
</Space>
</div>
<Table
size="small"
:pagination="false"
:columns="columns"
:data-source="items"
:row-key="(r: LineRow) => r._key"
:scroll="{ x: 1000 }"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'product'">
<Select
class="w-full"
allow-clear
show-search
option-filter-prop="label"
:value="record.productId"
:options="
products.map((p) => ({
value: p.id,
label: `${p.code} ${p.nameEn}`,
}))
"
@change="(v: any) => v && onPickProduct(record, v)"
/>
</template>
<template v-else-if="column.key === 'nameEn'">
<Input v-model:value="record.nameEn" />
</template>
<template v-else-if="column.key === 'hsCode'">
<Input v-model:value="record.hsCode" />
</template>
<template v-else-if="column.key === 'qty'">
<InputNumber v-model:value="record.qty" :min="0" class="w-full" />
</template>
<template v-else-if="column.key === 'unitPrice'">
<InputNumber
v-model:value="record.unitPrice"
:min="0"
:precision="4"
class="w-full"
/>
</template>
<template v-else-if="column.key === 'packages'">
<InputNumber
v-model:value="record.packages"
:min="0"
class="w-full"
/>
</template>
<template v-else-if="column.key === 'grossWeightKg'">
<InputNumber
v-model:value="record.grossWeightKg"
:min="0"
:precision="3"
class="w-full"
/>
</template>
<template v-else-if="column.key === 'netWeightKg'">
<InputNumber
v-model:value="record.netWeightKg"
:min="0"
:precision="3"
class="w-full"
/>
</template>
<template v-else-if="column.key === 'volumeCbm'">
<InputNumber
v-model:value="record.volumeCbm"
:min="0"
:precision="4"
class="w-full"
/>
</template>
<template v-else-if="column.key === 'action'">
<Button
type="link"
danger
size="small"
@click="removeLine(record._key)"
>
删
</Button>
</template>
</template>
</Table>
</Modal>
</template>
@@ -0,0 +1,284 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { CrmShipmentDTO, CrmShipmentVO } from '#/api/crm/shipment';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import {
Button,
Dropdown,
Menu,
message,
Popconfirm,
Space,
Tag,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
changeCrmShipmentStatusApi,
deleteCrmShipmentApi,
exportCrmShipmentCiApi,
exportCrmShipmentPlApi,
getCrmShipmentPageApi,
} from '#/api/crm/shipment';
import { PermissionGate } from '#/components/permission';
import {
syncVxeGridColumns,
useActionColumnVisible,
} from '#/composables/use-vxe-action-column';
import ShipmentModal from './components/ShipmentModal.vue';
defineOptions({ name: 'CrmShipment' });
const PlusIcon = createIconifyIcon('lucide:plus');
const loading = ref(false);
const modalRef = ref<InstanceType<typeof ShipmentModal>>();
const searchForm = ref({
keyword: '',
status: undefined as string | undefined,
});
const statusMap: Record<string, { color: string; label: string }> = {
draft: { color: 'default', label: '草稿' },
ready: { color: 'processing', label: '待出货' },
shipped: { color: 'success', label: '已出货' },
closed: { color: 'warning', label: '已关闭' },
};
const actionCodes = [
'crm:shipment:create',
'crm:shipment:update',
'crm:shipment:delete',
'crm:shipment:status',
'crm:shipment:export',
];
const showActionColumn = useActionColumnVisible(actionCodes);
const baseColumns: VxeGridProps<CrmShipmentVO.Info>['columns'] = [
{ type: 'seq', title: '序号', minWidth: 60 },
{ field: 'shipmentNo', title: '出货号', minWidth: 140 },
{ field: 'quoteNo', title: '来源报价', minWidth: 130 },
{ field: 'customerName', title: '客户', minWidth: 150 },
{ field: 'planShipDate', title: '计划日', minWidth: 110 },
{ field: 'destinationPort', title: '目的港', minWidth: 120 },
{ field: 'currency', title: '币种', minWidth: 70 },
{ field: 'totalAmount', title: '合计', minWidth: 100 },
{
field: 'status',
title: '状态',
minWidth: 90,
slots: { default: 'status' },
},
{ field: 'createTime', title: '创建时间', minWidth: 160 },
];
const actionColumn: NonNullable<
VxeGridProps<CrmShipmentVO.Info>['columns']
>[number] = {
title: '操作',
width: 320,
fixed: 'right',
slots: { default: 'action' },
};
const tableColumns = computed(() =>
showActionColumn.value
? [...(baseColumns ?? []), actionColumn]
: (baseColumns ?? []),
);
const gridOptions: VxeGridProps<CrmShipmentVO.Info> = {
columns: tableColumns.value,
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
toolbarConfig: { custom: true, refresh: true, zoom: true },
pagerConfig: { enabled: true, pageSizes: [10, 20, 50, 100] },
proxyConfig: {
ajax: {
query: async ({ page }) => {
loading.value = true;
try {
const params: PageQueryDTO<CrmShipmentDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
keyword: searchForm.value.keyword || undefined,
status: searchForm.value.status,
},
};
const data = await getCrmShipmentPageApi(params);
return { items: data.records, total: data.total };
} finally {
loading.value = false;
}
},
},
},
};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: {
schema: [
{
component: 'Input',
fieldName: 'keyword',
label: '关键词',
componentProps: { placeholder: '出货号/目的港/备注' },
},
{
component: 'Select',
fieldName: 'status',
label: '状态',
componentProps: {
allowClear: true,
options: Object.entries(statusMap).map(([value, v]) => ({
value,
label: v.label,
})),
},
},
],
handleSubmit: async (values: Record<string, any>) => {
searchForm.value.keyword = values.keyword ?? '';
searchForm.value.status = values.status;
gridApi.reload();
},
},
});
syncVxeGridColumns(gridApi, tableColumns);
async function handleDelete(row: CrmShipmentVO.Info) {
await deleteCrmShipmentApi(row.id);
message.success('已删除');
gridApi.reload();
}
async function handleStatus(row: CrmShipmentVO.Info, status: string) {
await changeCrmShipmentStatusApi(row.id, { status });
message.success('状态已更新');
gridApi.reload();
}
async function handleExportCi(row: CrmShipmentVO.Info) {
const detail = await exportCrmShipmentCiApi(row.id);
message.success('CI 已生成');
if (detail.latestCiAccessUrl) {
window.open(detail.latestCiAccessUrl, '_blank');
}
gridApi.reload();
}
async function handleExportPl(row: CrmShipmentVO.Info) {
const detail = await exportCrmShipmentPlApi(row.id);
message.success('PL 已生成');
if (detail.latestPlAccessUrl) {
window.open(detail.latestPlAccessUrl, '_blank');
}
gridApi.reload();
}
function canEdit(row: CrmShipmentVO.Info) {
return row.status === 'draft' || row.status === 'ready';
}
function statusActions(row: CrmShipmentVO.Info) {
const s = row.status;
const actions: Array<{ key: string; label: string }> = [];
if (s === 'draft') {
actions.push({ key: 'ready', label: '标记待出货' });
actions.push({ key: 'closed', label: '关闭' });
} else if (s === 'ready') {
actions.push({ key: 'shipped', label: '标记已出货' });
actions.push({ key: 'draft', label: '退回草稿' });
actions.push({ key: 'closed', label: '关闭' });
} else if (s === 'shipped') {
actions.push({ key: 'closed', label: '关闭' });
}
return actions;
}
</script>
<template>
<Page auto-content-height>
<Grid>
<template #toolbar-tools>
<PermissionGate code="crm:shipment:create">
<Button type="primary" @click="modalRef?.open(false)">
<PlusIcon class="size-4" />
新建出货
</Button>
</PermissionGate>
</template>
<template #status="{ row }">
<Tag :color="statusMap[row.status]?.color ?? 'default'">
{{ statusMap[row.status]?.label ?? row.status }}
</Tag>
</template>
<template #action="{ row }">
<Space wrap>
<PermissionGate code="crm:shipment:update">
<Button
type="link"
size="small"
:disabled="!canEdit(row)"
@click="modalRef?.open(true, row.id)"
>
编辑
</Button>
</PermissionGate>
<PermissionGate code="crm:shipment:export">
<Button type="link" size="small" @click="handleExportCi(row)">
CI
</Button>
</PermissionGate>
<PermissionGate code="crm:shipment:export">
<Button type="link" size="small" @click="handleExportPl(row)">
PL
</Button>
</PermissionGate>
<PermissionGate code="crm:shipment:status">
<Dropdown v-if="statusActions(row).length">
<Button type="link" size="small">状态</Button>
<template #overlay>
<Menu
@click="
({ key }: { key: string | number }) =>
handleStatus(row, String(key))
"
>
<Menu.Item
v-for="a in statusActions(row)"
:key="a.key"
>
{{ a.label }}
</Menu.Item>
</Menu>
</template>
</Dropdown>
</PermissionGate>
<PermissionGate code="crm:shipment:delete">
<Popconfirm
v-if="row.status === 'draft'"
title="确认删除该出货?"
@confirm="handleDelete(row)"
>
<Button type="link" size="small" danger>删除</Button>
</Popconfirm>
</PermissionGate>
</Space>
</template>
</Grid>
<ShipmentModal ref="modalRef" @success="gridApi.reload()" />
</Page>
</template>
+10 -6
View File
@@ -241,17 +241,19 @@ modules/crm/
### Phase 2 — 出货与 CI/PL
- [ ] 从「已接受报价」生成出货;出货行可改箱规重量
- [ ] 一键生成 CI、PL;下载;历史版本可查
- [x] 从「已接受报价」生成出货;出货行可改箱规重量
- [x] 一键生成 CI、PL;下载;历史版本经 `crm_document`(is_latest)可查
**验收**:演示「报价接受 → 出货 → 下载 CI+PL」全程不重复手抄品名数量。
**验收**:演示「报价接受 → 出货 → 下载 CI+PL」全程不重复手抄品名数量。
**种子**:`V5__crm_shipment_menu_seed.sql`;公司菜单/权限需勾选「出货」。
### Phase 3 — 邮件方案 A
- [ ] 发件账户、模板 CRUD
- [ ] 客户/报价页手动发送 + 发送记录
- [x] 发件账户、模板 CRUD(SMTP 密码 AES-GCM,jwt.secret 派生)
- [x] 客户/报价页手动发送 + 发送记录
**验收**:选模板改两处变量后发送成功,同事能在发送记录里看到。
**验收**:选模板改两处变量后发送成功,同事能在发送记录里看到。
**种子**:`V6__crm_mail_menu_seed.sql`;公司菜单/权限需勾选「发件账户」「邮件模板」「发送记录」及 `crm:mail:send`。
### Phase 4 — 打磨(可穿插)
@@ -286,3 +288,5 @@ modules/crm/
| 2026-10-22 | 初稿:确认外贸出口、小团队、CI+PL+PI、邮件方案 A、Excel 导入 |
| 2026-10-22 | 落地约定:表设计 `sql/design/crm/`;Flyway `db/migration/V2__crm_schema.sql`(`sql/migration` 已弃用)。软删 + 生成列唯一;单号 Q/SH+年+6 位;默认币种 USD;V2 一次建齐全部 crm_*,Phase0 只实现客户/产品 |
| 2026-10-22 | Phase1:报价+状态+PI PDF+单证资料;菜单种子 V4 |
| 2026-10-23 | Phase2:出货 CRUD、从已接受报价生成、CI/PL PDF;菜单种子 V5 |
| 2026-10-24 | Phase3:发件账户/模板/手发/发送记录;菜单种子 V6 |