feat: 落地 CRM Phase0 客户/产品(表结构、CRUD、Excel导入与菜单)

This commit is contained in:
2026-10-22 17:40:31 +08:00
parent a9e91801fe
commit dd6ab6de82
39 changed files with 3196 additions and 7 deletions
@@ -0,0 +1,81 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.controller;
import jakarta.validation.Valid;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
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.customer.model.dto.CreateCrmCustomerDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.CrmCustomerFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.UpdateCrmCustomerDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.vo.CrmCustomerVO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.service.CrmCustomerService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmImportResultVO;
/**
* 客户管理接口。
*/
@RestController
@RequestMapping("/api/crm/customer")
public class CrmCustomerController {
private final CrmCustomerService crmCustomerService;
public CrmCustomerController(CrmCustomerService crmCustomerService) {
this.crmCustomerService = crmCustomerService;
}
@PostMapping("/create")
@RequirePermission(value = "crm:customer:create", description = "创建客户")
public ApiResponse<CrmCustomerVO> create(@Valid @RequestBody CreateCrmCustomerDTO dto) {
return ApiResponse.success("创建成功", crmCustomerService.create(dto));
}
@PutMapping("/update/{id}")
@RequirePermission(value = "crm:customer:update", description = "更新客户")
public ApiResponse<CrmCustomerVO> update(@PathVariable Long id, @Valid @RequestBody UpdateCrmCustomerDTO dto) {
return ApiResponse.success("更新成功", crmCustomerService.update(id, dto));
}
@DeleteMapping("/delete/{id}")
@RequirePermission(value = "crm:customer:delete", description = "删除客户")
public ApiResponse<Void> delete(@PathVariable Long id) {
crmCustomerService.delete(id);
return ApiResponse.success("删除成功");
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:customer:read", description = "客户详情")
public ApiResponse<CrmCustomerVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", crmCustomerService.get(id));
}
@PostMapping("/list")
@RequirePermission(value = "crm:customer:read", description = "客户列表")
public ApiResponse<PageResultVO<CrmCustomerVO>> list(
@Valid @RequestBody PageQueryDTO<CrmCustomerFilterDTO> query) {
return ApiResponse.success("获取成功", crmCustomerService.page(query));
}
@GetMapping("/import/template")
@RequirePermission(value = "crm:customer:import", description = "下载客户导入模板")
public ResponseEntity<byte[]> importTemplate() {
byte[] bytes = crmCustomerService.importTemplate();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=crm-customer-import.xlsx")
.contentType(MediaType.parseMediaType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(bytes);
}
@PostMapping("/import")
@RequirePermission(value = "crm:customer:import", description = "导入客户")
public ApiResponse<CrmImportResultVO> importExcel(@RequestParam("file") MultipartFile file) {
return ApiResponse.success("导入完成", crmCustomerService.importExcel(file));
}
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.po.CrmCustomerPO;
/**
* 客户 Mapper。
*/
@Mapper
public interface CrmCustomerMapper extends BaseMapper<CrmCustomerPO> {
}
@@ -0,0 +1,49 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
/**
* 创建客户。
*/
@Data
public class CreateCrmCustomerDTO {
@NotBlank(message = "客户名称不能为空")
@Size(max = 200)
private String name;
@Size(max = 200)
private String nameEn;
@Size(max = 64)
private String country;
@Size(max = 500)
private String address;
@Size(max = 100)
private String contactName;
@Size(max = 100)
private String email;
@Size(max = 50)
private String phone;
@Size(max = 3)
private String currency;
@Size(max = 200)
private String paymentTerms;
/** lead/following/won/paused */
@Size(max = 32)
private String status;
private Long ownerUserId;
@Size(max = 1000)
private String remark;
}
@@ -0,0 +1,16 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto;
import lombok.Data;
/**
* 客户列表筛选。
*/
@Data
public class CrmCustomerFilterDTO {
private String keyword;
private String status;
private String country;
private Long ownerUserId;
/** true 时仅看我负责的 */
private Boolean onlyMine;
}
@@ -0,0 +1,48 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
/**
* 更新客户。
*/
@Data
public class UpdateCrmCustomerDTO {
@NotBlank(message = "客户名称不能为空")
@Size(max = 200)
private String name;
@Size(max = 200)
private String nameEn;
@Size(max = 64)
private String country;
@Size(max = 500)
private String address;
@Size(max = 100)
private String contactName;
@Size(max = 100)
private String email;
@Size(max = 50)
private String phone;
@Size(max = 3)
private String currency;
@Size(max = 200)
private String paymentTerms;
@Size(max = 32)
private String status;
private Long ownerUserId;
@Size(max = 1000)
private String remark;
}
@@ -0,0 +1,76 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 客户实体。
*/
@Data
@TableName("crm_customer")
public class CrmCustomerPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("name")
private String name;
@TableField("name_en")
private String nameEn;
@TableField("country")
private String country;
@TableField("address")
private String address;
@TableField("contact_name")
private String contactName;
@TableField("email")
private String email;
@TableField("phone")
private String phone;
@TableField("currency")
private String currency;
@TableField("payment_terms")
private String paymentTerms;
/** lead / following / won / paused */
@TableField("status")
private String status;
@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,28 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 客户视图。
*/
@Data
public class CrmCustomerVO {
private Long id;
private Long companyId;
private String name;
private String nameEn;
private String country;
private String address;
private String contactName;
private String email;
private String phone;
private String currency;
private String paymentTerms;
private String status;
private Long ownerUserId;
private String remark;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.service;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.CreateCrmCustomerDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.CrmCustomerFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.UpdateCrmCustomerDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.vo.CrmCustomerVO;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmImportResultVO;
/**
* 客户用例。
*/
public interface CrmCustomerService {
CrmCustomerVO create(CreateCrmCustomerDTO dto);
CrmCustomerVO update(Long id, UpdateCrmCustomerDTO dto);
void delete(Long id);
CrmCustomerVO get(Long id);
PageResultVO<CrmCustomerVO> page(PageQueryDTO<CrmCustomerFilterDTO> query);
byte[] importTemplate();
CrmImportResultVO importExcel(MultipartFile file);
}
@@ -0,0 +1,237 @@
package top.xyquan.ecomdmbbackend.modules.crm.customer.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.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
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.dto.CreateCrmCustomerDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.CrmCustomerFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.dto.UpdateCrmCustomerDTO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.po.CrmCustomerPO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.model.vo.CrmCustomerVO;
import top.xyquan.ecomdmbbackend.modules.crm.customer.service.CrmCustomerService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmExcelSupport;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmImportResultVO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.List;
import java.util.Locale;
import java.util.Set;
/**
* 客户用例实现:公司隔离、软删、Excel 导入。
*/
@Service
public class CrmCustomerServiceImpl extends ServiceImpl<CrmCustomerMapper, CrmCustomerPO>
implements CrmCustomerService {
private static final Set<String> STATUSES = Set.of("lead", "following", "won", "paused");
private static final String[] IMPORT_HEADERS = {
"公司名*", "国家", "联系人", "邮箱", "电话", "币种", "备注"
};
private final CurrentUserContext currentUserContext;
private final CrmExcelSupport crmExcelSupport;
public CrmCustomerServiceImpl(CurrentUserContext currentUserContext, CrmExcelSupport crmExcelSupport) {
this.currentUserContext = currentUserContext;
this.crmExcelSupport = crmExcelSupport;
}
@Override
@Transactional
public CrmCustomerVO create(CreateCrmCustomerDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmCustomerPO po = new CrmCustomerPO();
BeanCopyUtils.copyProperties(dto, po);
normalize(po);
po.setCompanyId(companyId);
po.setCreateBy(userId);
po.setUpdateBy(userId);
if (po.getOwnerUserId() == null) {
po.setOwnerUserId(userId);
}
try {
this.save(po);
} catch (DuplicateKeyException e) {
throw new BusinessException("同国家下客户名称已存在");
}
return toVo(po);
}
@Override
@Transactional
public CrmCustomerVO update(Long id, UpdateCrmCustomerDTO dto) {
CrmCustomerPO existing = requireOwned(id);
BeanCopyUtils.copyProperties(dto, existing);
normalize(existing);
existing.setUpdateBy(currentUserContext.getCurrentUserId());
try {
this.updateById(existing);
} catch (DuplicateKeyException e) {
throw new BusinessException("同国家下客户名称已存在");
}
return toVo(this.getById(id));
}
@Override
@Transactional
public void delete(Long id) {
requireOwned(id);
Long userId = currentUserContext.getCurrentUserId();
this.lambdaUpdate()
.eq(CrmCustomerPO::getId, id)
.set(CrmCustomerPO::getDeleteBy, userId)
.update();
this.removeById(id);
}
@Override
public CrmCustomerVO get(Long id) {
return toVo(requireOwned(id));
}
@Override
public PageResultVO<CrmCustomerVO> page(PageQueryDTO<CrmCustomerFilterDTO> query) {
Long companyId = requireCompanyId();
CrmCustomerFilterDTO filters = query.getFilters() != null ? query.getFilters() : new CrmCustomerFilterDTO();
LambdaQueryWrapper<CrmCustomerPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CrmCustomerPO::getCompanyId, companyId);
if (StringUtils.hasText(filters.getKeyword())) {
String kw = filters.getKeyword().trim();
wrapper.and(w -> w.like(CrmCustomerPO::getName, kw)
.or().like(CrmCustomerPO::getNameEn, kw)
.or().like(CrmCustomerPO::getContactName, kw)
.or().like(CrmCustomerPO::getEmail, kw));
}
if (StringUtils.hasText(filters.getStatus())) {
wrapper.eq(CrmCustomerPO::getStatus, filters.getStatus().trim());
}
if (StringUtils.hasText(filters.getCountry())) {
wrapper.eq(CrmCustomerPO::getCountry, filters.getCountry().trim());
}
if (Boolean.TRUE.equals(filters.getOnlyMine())) {
wrapper.eq(CrmCustomerPO::getOwnerUserId, currentUserContext.getCurrentUserId());
} else if (filters.getOwnerUserId() != null) {
wrapper.eq(CrmCustomerPO::getOwnerUserId, filters.getOwnerUserId());
}
wrapper.orderByDesc(CrmCustomerPO::getId);
IPage<CrmCustomerPO> page = this.page(new Page<>(query.getPage(), query.getPageSize()), wrapper);
List<CrmCustomerVO> records = page.getRecords().stream().map(this::toVo).toList();
return PageResultVO.create(records, page.getTotal(), query.getPage(), query.getPageSize());
}
@Override
public byte[] importTemplate() {
return crmExcelSupport.buildTemplate("客户导入", IMPORT_HEADERS);
}
@Override
@Transactional
public CrmImportResultVO importExcel(MultipartFile file) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmImportResultVO result = new CrmImportResultVO();
List<CrmExcelSupport.RowContext> rows = crmExcelSupport.parseRows(file, IMPORT_HEADERS.length, r -> r);
for (CrmExcelSupport.RowContext row : rows) {
try {
String name = row.str(0);
if (!StringUtils.hasText(name)) {
throw new BusinessException("公司名不能为空");
}
CrmCustomerPO po = new CrmCustomerPO();
po.setCompanyId(companyId);
po.setName(name.trim());
po.setCountry(row.str(1));
po.setContactName(row.str(2));
po.setEmail(row.str(3));
po.setPhone(row.str(4));
po.setCurrency(row.str(5));
po.setRemark(row.str(6));
po.setOwnerUserId(userId);
po.setCreateBy(userId);
po.setUpdateBy(userId);
normalize(po);
// 同名同国:更新
LambdaQueryWrapper<CrmCustomerPO> exists = new LambdaQueryWrapper<>();
exists.eq(CrmCustomerPO::getCompanyId, companyId)
.eq(CrmCustomerPO::getName, po.getName())
.eq(po.getCountry() != null, CrmCustomerPO::getCountry, po.getCountry())
.isNull(po.getCountry() == null, CrmCustomerPO::getCountry);
CrmCustomerPO old = this.getOne(exists, false);
if (old != null) {
po.setId(old.getId());
this.updateById(po);
} else {
this.save(po);
}
result.setSuccessCount(result.getSuccessCount() + 1);
} catch (Exception e) {
result.setFailCount(result.getFailCount() + 1);
String msg = e instanceof BusinessException be ? be.getMessage() : e.getMessage();
result.getErrors().add(new CrmImportResultVO.RowError(row.rowNum(), msg));
}
}
return result;
}
private void normalize(CrmCustomerPO po) {
if (!StringUtils.hasText(po.getCurrency())) {
po.setCurrency("USD");
} else {
po.setCurrency(po.getCurrency().trim().toUpperCase(Locale.ROOT));
}
if (!StringUtils.hasText(po.getStatus())) {
po.setStatus("lead");
} else {
String s = po.getStatus().trim().toLowerCase(Locale.ROOT);
if (!STATUSES.contains(s)) {
throw new BusinessException("客户状态不合法");
}
po.setStatus(s);
}
if (po.getName() != null) {
po.setName(po.getName().trim());
}
if (po.getCountry() != null) {
po.setCountry(po.getCountry().trim());
if (po.getCountry().isEmpty()) {
po.setCountry(null);
}
}
}
private CrmCustomerPO requireOwned(Long id) {
Long companyId = requireCompanyId();
CrmCustomerPO 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;
}
private CrmCustomerVO toVo(CrmCustomerPO po) {
CrmCustomerVO vo = new CrmCustomerVO();
BeanCopyUtils.copyProperties(po, vo);
return vo;
}
}
@@ -0,0 +1,81 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.controller;
import jakarta.validation.Valid;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
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.product.model.dto.CreateCrmProductDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.CrmProductFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.UpdateCrmProductDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.vo.CrmProductVO;
import top.xyquan.ecomdmbbackend.modules.crm.product.service.CrmProductService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmImportResultVO;
/**
* 产品管理接口。
*/
@RestController
@RequestMapping("/api/crm/product")
public class CrmProductController {
private final CrmProductService crmProductService;
public CrmProductController(CrmProductService crmProductService) {
this.crmProductService = crmProductService;
}
@PostMapping("/create")
@RequirePermission(value = "crm:product:create", description = "创建产品")
public ApiResponse<CrmProductVO> create(@Valid @RequestBody CreateCrmProductDTO dto) {
return ApiResponse.success("创建成功", crmProductService.create(dto));
}
@PutMapping("/update/{id}")
@RequirePermission(value = "crm:product:update", description = "更新产品")
public ApiResponse<CrmProductVO> update(@PathVariable Long id, @Valid @RequestBody UpdateCrmProductDTO dto) {
return ApiResponse.success("更新成功", crmProductService.update(id, dto));
}
@DeleteMapping("/delete/{id}")
@RequirePermission(value = "crm:product:delete", description = "删除产品")
public ApiResponse<Void> delete(@PathVariable Long id) {
crmProductService.delete(id);
return ApiResponse.success("删除成功");
}
@GetMapping("/{id}")
@RequirePermission(value = "crm:product:read", description = "产品详情")
public ApiResponse<CrmProductVO> get(@PathVariable Long id) {
return ApiResponse.success("获取成功", crmProductService.get(id));
}
@PostMapping("/list")
@RequirePermission(value = "crm:product:read", description = "产品列表")
public ApiResponse<PageResultVO<CrmProductVO>> list(
@Valid @RequestBody PageQueryDTO<CrmProductFilterDTO> query) {
return ApiResponse.success("获取成功", crmProductService.page(query));
}
@GetMapping("/import/template")
@RequirePermission(value = "crm:product:import", description = "下载产品导入模板")
public ResponseEntity<byte[]> importTemplate() {
byte[] bytes = crmProductService.importTemplate();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=crm-product-import.xlsx")
.contentType(MediaType.parseMediaType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(bytes);
}
@PostMapping("/import")
@RequirePermission(value = "crm:product:import", description = "导入产品")
public ApiResponse<CrmImportResultVO> importExcel(@RequestParam("file") MultipartFile file) {
return ApiResponse.success("导入完成", crmProductService.importExcel(file));
}
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.po.CrmProductPO;
/**
* 产品 Mapper。
*/
@Mapper
public interface CrmProductMapper extends BaseMapper<CrmProductPO> {
}
@@ -0,0 +1,48 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.math.BigDecimal;
/**
* 创建产品。
*/
@Data
public class CreateCrmProductDTO {
@NotBlank(message = "产品编码不能为空")
@Size(max = 64)
private String code;
@Size(max = 200)
private String nameZh;
@NotBlank(message = "英文名不能为空")
@Size(max = 200)
private String nameEn;
@Size(max = 500)
private String spec;
@Size(max = 32)
private String unit;
private BigDecimal unitPrice;
@Size(max = 3)
private String currency;
@Size(max = 32)
private String hsCode;
private BigDecimal grossWeightKg;
private BigDecimal netWeightKg;
private BigDecimal volumeCbm;
private Integer status;
@Size(max = 500)
private String remark;
}
@@ -0,0 +1,12 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.model.dto;
import lombok.Data;
/**
* 产品列表筛选。
*/
@Data
public class CrmProductFilterDTO {
private String keyword;
private Integer status;
}
@@ -0,0 +1,48 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.math.BigDecimal;
/**
* 更新产品。
*/
@Data
public class UpdateCrmProductDTO {
@NotBlank(message = "产品编码不能为空")
@Size(max = 64)
private String code;
@Size(max = 200)
private String nameZh;
@NotBlank(message = "英文名不能为空")
@Size(max = 200)
private String nameEn;
@Size(max = 500)
private String spec;
@Size(max = 32)
private String unit;
private BigDecimal unitPrice;
@Size(max = 3)
private String currency;
@Size(max = 32)
private String hsCode;
private BigDecimal grossWeightKg;
private BigDecimal netWeightKg;
private BigDecimal volumeCbm;
private Integer status;
@Size(max = 500)
private String remark;
}
@@ -0,0 +1,79 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 产品实体。
*/
@Data
@TableName("crm_product")
public class CrmProductPO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("company_id")
private Long companyId;
@TableField("code")
private String code;
@TableField("name_zh")
private String nameZh;
@TableField("name_en")
private String nameEn;
@TableField("spec")
private String spec;
@TableField("unit")
private String unit;
@TableField("unit_price")
private BigDecimal unitPrice;
@TableField("currency")
private String currency;
@TableField("hs_code")
private String hsCode;
@TableField("gross_weight_kg")
private BigDecimal grossWeightKg;
@TableField("net_weight_kg")
private BigDecimal netWeightKg;
@TableField("volume_cbm")
private BigDecimal volumeCbm;
@TableField("status")
private Integer status;
@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,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.model.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 产品视图。
*/
@Data
public class CrmProductVO {
private Long id;
private Long companyId;
private String code;
private String nameZh;
private String nameEn;
private String spec;
private String unit;
private BigDecimal unitPrice;
private String currency;
private String hsCode;
private BigDecimal grossWeightKg;
private BigDecimal netWeightKg;
private BigDecimal volumeCbm;
private Integer status;
private String remark;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
@@ -0,0 +1,30 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.service;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.CreateCrmProductDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.CrmProductFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.UpdateCrmProductDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.vo.CrmProductVO;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmImportResultVO;
/**
* 产品用例。
*/
public interface CrmProductService {
CrmProductVO create(CreateCrmProductDTO dto);
CrmProductVO update(Long id, UpdateCrmProductDTO dto);
void delete(Long id);
CrmProductVO get(Long id);
PageResultVO<CrmProductVO> page(PageQueryDTO<CrmProductFilterDTO> query);
byte[] importTemplate();
CrmImportResultVO importExcel(MultipartFile file);
}
@@ -0,0 +1,214 @@
package top.xyquan.ecomdmbbackend.modules.crm.product.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.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
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.product.mapper.CrmProductMapper;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.CreateCrmProductDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.CrmProductFilterDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.dto.UpdateCrmProductDTO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.po.CrmProductPO;
import top.xyquan.ecomdmbbackend.modules.crm.product.model.vo.CrmProductVO;
import top.xyquan.ecomdmbbackend.modules.crm.product.service.CrmProductService;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmExcelSupport;
import top.xyquan.ecomdmbbackend.modules.crm.support.CrmImportResultVO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.List;
import java.util.Locale;
/**
* 产品用例实现:编码 upsert、Excel 导入。
*/
@Service
public class CrmProductServiceImpl extends ServiceImpl<CrmProductMapper, CrmProductPO>
implements CrmProductService {
private static final String[] IMPORT_HEADERS = {
"编码*", "中文名", "英文名*", "单位", "单价", "币种", "HS"
};
private final CurrentUserContext currentUserContext;
private final CrmExcelSupport crmExcelSupport;
public CrmProductServiceImpl(CurrentUserContext currentUserContext, CrmExcelSupport crmExcelSupport) {
this.currentUserContext = currentUserContext;
this.crmExcelSupport = crmExcelSupport;
}
@Override
@Transactional
public CrmProductVO create(CreateCrmProductDTO dto) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmProductPO po = new CrmProductPO();
BeanCopyUtils.copyProperties(dto, po);
normalize(po);
po.setCompanyId(companyId);
po.setCreateBy(userId);
po.setUpdateBy(userId);
try {
this.save(po);
} catch (DuplicateKeyException e) {
throw new BusinessException("产品编码已存在");
}
return toVo(po);
}
@Override
@Transactional
public CrmProductVO update(Long id, UpdateCrmProductDTO dto) {
CrmProductPO existing = requireOwned(id);
BeanCopyUtils.copyProperties(dto, existing);
normalize(existing);
existing.setUpdateBy(currentUserContext.getCurrentUserId());
try {
this.updateById(existing);
} catch (DuplicateKeyException e) {
throw new BusinessException("产品编码已存在");
}
return toVo(this.getById(id));
}
@Override
@Transactional
public void delete(Long id) {
requireOwned(id);
Long userId = currentUserContext.getCurrentUserId();
this.lambdaUpdate()
.eq(CrmProductPO::getId, id)
.set(CrmProductPO::getDeleteBy, userId)
.update();
this.removeById(id);
}
@Override
public CrmProductVO get(Long id) {
return toVo(requireOwned(id));
}
@Override
public PageResultVO<CrmProductVO> page(PageQueryDTO<CrmProductFilterDTO> query) {
Long companyId = requireCompanyId();
CrmProductFilterDTO filters = query.getFilters() != null ? query.getFilters() : new CrmProductFilterDTO();
LambdaQueryWrapper<CrmProductPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(CrmProductPO::getCompanyId, companyId);
if (StringUtils.hasText(filters.getKeyword())) {
String kw = filters.getKeyword().trim();
wrapper.and(w -> w.like(CrmProductPO::getCode, kw)
.or().like(CrmProductPO::getNameZh, kw)
.or().like(CrmProductPO::getNameEn, kw)
.or().like(CrmProductPO::getHsCode, kw));
}
if (filters.getStatus() != null) {
wrapper.eq(CrmProductPO::getStatus, filters.getStatus());
}
wrapper.orderByDesc(CrmProductPO::getId);
IPage<CrmProductPO> page = this.page(new Page<>(query.getPage(), query.getPageSize()), wrapper);
List<CrmProductVO> records = page.getRecords().stream().map(this::toVo).toList();
return PageResultVO.create(records, page.getTotal(), query.getPage(), query.getPageSize());
}
@Override
public byte[] importTemplate() {
return crmExcelSupport.buildTemplate("产品导入", IMPORT_HEADERS);
}
@Override
@Transactional
public CrmImportResultVO importExcel(MultipartFile file) {
Long companyId = requireCompanyId();
Long userId = currentUserContext.getCurrentUserId();
CrmImportResultVO result = new CrmImportResultVO();
List<CrmExcelSupport.RowContext> rows = crmExcelSupport.parseRows(file, IMPORT_HEADERS.length, r -> r);
for (CrmExcelSupport.RowContext row : rows) {
try {
String code = row.str(0);
String nameEn = row.str(2);
if (!StringUtils.hasText(code)) {
throw new BusinessException("编码不能为空");
}
if (!StringUtils.hasText(nameEn)) {
throw new BusinessException("英文名不能为空");
}
CrmProductPO po = new CrmProductPO();
po.setCompanyId(companyId);
po.setCode(code.trim());
po.setNameZh(row.str(1));
po.setNameEn(nameEn.trim());
po.setUnit(row.str(3));
po.setUnitPrice(row.decimal(4));
po.setCurrency(row.str(5));
po.setHsCode(row.str(6));
po.setCreateBy(userId);
po.setUpdateBy(userId);
normalize(po);
LambdaQueryWrapper<CrmProductPO> exists = new LambdaQueryWrapper<>();
exists.eq(CrmProductPO::getCompanyId, companyId).eq(CrmProductPO::getCode, po.getCode());
CrmProductPO old = this.getOne(exists, false);
if (old != null) {
po.setId(old.getId());
this.updateById(po);
} else {
this.save(po);
}
result.setSuccessCount(result.getSuccessCount() + 1);
} catch (Exception e) {
result.setFailCount(result.getFailCount() + 1);
String msg = e instanceof BusinessException be ? be.getMessage() : e.getMessage();
result.getErrors().add(new CrmImportResultVO.RowError(row.rowNum(), msg));
}
}
return result;
}
private void normalize(CrmProductPO po) {
if (po.getCode() != null) {
po.setCode(po.getCode().trim());
}
if (!StringUtils.hasText(po.getUnit())) {
po.setUnit("PCS");
}
if (!StringUtils.hasText(po.getCurrency())) {
po.setCurrency("USD");
} else {
po.setCurrency(po.getCurrency().trim().toUpperCase(Locale.ROOT));
}
if (po.getStatus() == null) {
po.setStatus(1);
}
}
private CrmProductPO requireOwned(Long id) {
Long companyId = requireCompanyId();
CrmProductPO 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;
}
private CrmProductVO toVo(CrmProductPO po) {
CrmProductVO vo = new CrmProductVO();
BeanCopyUtils.copyProperties(po, vo);
return vo;
}
}
@@ -0,0 +1,168 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
/**
* CRM Excel 模板生成与行解析(POI)。
*/
@Component
public class CrmExcelSupport {
public static final int MAX_IMPORT_ROWS = 2000;
public byte[] buildTemplate(String sheetName, String[] headers) {
try (Workbook wb = new XSSFWorkbook(); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
Sheet sheet = wb.createSheet(sheetName);
Row header = sheet.createRow(0);
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setBold(true);
style.setFont(font);
for (int i = 0; i < headers.length; i++) {
Cell cell = header.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(style);
sheet.setColumnWidth(i, 18 * 256);
}
wb.write(out);
return out.toByteArray();
} catch (Exception e) {
throw new BusinessException("生成导入模板失败");
}
}
public <T> List<T> parseRows(MultipartFile file, int expectedCols, Function<RowContext, T> mapper) {
if (file == null || file.isEmpty()) {
throw new BusinessException("请上传 Excel 文件");
}
String name = file.getOriginalFilename();
if (name == null || !(name.endsWith(".xlsx") || name.endsWith(".xls"))) {
throw new BusinessException("仅支持 .xlsx / .xls 文件");
}
try (InputStream in = file.getInputStream(); Workbook wb = WorkbookFactory.create(in)) {
Sheet sheet = wb.getSheetAt(0);
if (sheet == null) {
throw new BusinessException("Excel 无工作表");
}
Iterator<Row> it = sheet.iterator();
if (!it.hasNext()) {
throw new BusinessException("Excel 为空");
}
it.next(); // skip header
List<T> rows = new ArrayList<>();
int dataCount = 0;
while (it.hasNext()) {
Row row = it.next();
if (isBlankRow(row, expectedCols)) {
continue;
}
dataCount++;
if (dataCount > MAX_IMPORT_ROWS) {
throw new BusinessException("单次最多导入 " + MAX_IMPORT_ROWS + " 行");
}
rows.add(mapper.apply(new RowContext(row)));
}
if (rows.isEmpty()) {
throw new BusinessException("没有可导入的数据行");
}
return rows;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException("解析 Excel 失败:" + e.getMessage());
}
}
private boolean isBlankRow(Row row, int cols) {
for (int i = 0; i < cols; i++) {
if (StringUtils.hasText(cellString(row, i))) {
return false;
}
}
return true;
}
public static String cellString(Row row, int idx) {
Cell cell = row.getCell(idx, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (cell == null) {
return null;
}
return switch (cell.getCellType()) {
case STRING -> trimToNull(cell.getStringCellValue());
case NUMERIC -> {
if (DateUtil.isCellDateFormatted(cell)) {
yield cell.getLocalDateTimeCellValue() != null
? cell.getLocalDateTimeCellValue().toLocalDate().toString()
: null;
}
double n = cell.getNumericCellValue();
if (n == Math.rint(n) && Math.abs(n) < 1e15) {
yield String.valueOf((long) n);
}
yield BigDecimal.valueOf(n).stripTrailingZeros().toPlainString();
}
case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
case FORMULA -> {
try {
yield trimToNull(cell.getStringCellValue());
} catch (Exception ex) {
yield BigDecimal.valueOf(cell.getNumericCellValue()).stripTrailingZeros().toPlainString();
}
}
default -> null;
};
}
public static BigDecimal cellDecimal(Row row, int idx) {
String s = cellString(row, idx);
if (!StringUtils.hasText(s)) {
return null;
}
try {
return new BigDecimal(s.trim());
} catch (Exception e) {
throw new BusinessException("第 " + (row.getRowNum() + 1) + " 行数字格式错误");
}
}
private static String trimToNull(String s) {
if (s == null) {
return null;
}
String t = s.trim();
return t.isEmpty() ? null : t;
}
public static final class RowContext {
private final Row row;
public RowContext(Row row) {
this.row = row;
}
public int rowNum() {
return row.getRowNum() + 1;
}
public String str(int idx) {
return cellString(row, idx);
}
public BigDecimal decimal(int idx) {
return cellDecimal(row, idx);
}
}
}
@@ -0,0 +1,29 @@
package top.xyquan.ecomdmbbackend.modules.crm.support;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* Excel 导入结果。
*/
@Data
public class CrmImportResultVO {
private int successCount;
private int failCount;
private List<RowError> errors = new ArrayList<>();
@Data
public static class RowError {
private int rowNum;
private String message;
public RowError() {}
public RowError(int rowNum, String message) {
this.rowNum = rowNum;
this.message = message;
}
}
}
@@ -0,0 +1,365 @@
-- CRM 外贸出口域表结构(由 sql/design/crm/crm_design.sql 落地)
-- 规划:docs/外贸出口CRM雏形规划.md
-- ----------------------------------------
-- 发号器
-- ----------------------------------------
CREATE TABLE `crm_seq` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`biz_type` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '业务:quote/shipment/document',
`year` smallint UNSIGNED NOT NULL COMMENT '年份',
`next_val` int UNSIGNED NOT NULL DEFAULT 1 COMMENT '下一流水号',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_crm_seq_company_biz_year` (`company_id`, `biz_type`, `year`) USING BTREE,
CONSTRAINT `fk_crm_seq_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-单号发号器';
-- ----------------------------------------
-- 本公司出口抬头(卖方资料)
-- ----------------------------------------
CREATE TABLE `crm_company_profile` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID(一公司一行)',
`legal_name_zh` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '中文法定名称',
`legal_name_en` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '英文名称(单证卖方)',
`address_zh` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '中文地址',
`address_en` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '英文地址',
`country` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '国家/地区',
`phone` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '电话',
`email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '邮箱',
`tax_no` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '税号/统一社会信用代码',
`bank_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '开户行',
`bank_account` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '银行账号',
`bank_swift` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'SWIFT/BIC',
`bank_address` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '银行地址',
`default_currency` char(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'USD' COMMENT '默认币种',
`default_incoterm` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '默认贸易术语 FOB/CIF…',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_crm_company_profile_company` (`company_id`) USING BTREE,
CONSTRAINT `fk_crm_company_profile_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_company_profile_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_company_profile_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-本公司出口抬头';
-- ----------------------------------------
-- 客户
-- ----------------------------------------
CREATE TABLE `crm_customer` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '客户ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
`name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '客户公司名',
`name_en` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '英文名(单证买方可覆盖)',
`country` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '国家/地区',
`address` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '地址',
`contact_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '联系人',
`email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '邮箱',
`phone` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '电话',
`currency` char(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'USD' COMMENT '偏好币种',
`payment_terms` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '付款条款备注',
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'lead' COMMENT 'lead/following/won/paused',
`owner_user_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '负责人用户ID',
`remark` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
`delete_time` timestamp NULL DEFAULT NULL COMMENT '删除时间(软删)',
`delete_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '删除人',
-- 未删时 = name\\0country;已删为 NULL(唯一索引允许多 NULL,可复用同名)
`active_name_country` varchar(280) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci
GENERATED ALWAYS AS (IF(`delete_time` IS NULL, CONCAT(`name`, CHAR(31), IFNULL(`country`, '')), NULL)) STORED COMMENT '软删友好唯一键',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_crm_customer_company_active_name_country` (`company_id`, `active_name_country`) USING BTREE,
INDEX `idx_crm_customer_company_status` (`company_id`, `status`, `id`) USING BTREE,
INDEX `idx_crm_customer_company_owner` (`company_id`, `owner_user_id`) USING BTREE,
INDEX `idx_crm_customer_company_name` (`company_id`, `name`) USING BTREE,
INDEX `idx_crm_customer_delete_time` (`delete_time`) USING BTREE,
CONSTRAINT `fk_crm_customer_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_customer_owner` FOREIGN KEY (`owner_user_id`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_customer_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_customer_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_customer_deleter` FOREIGN KEY (`delete_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-客户';
-- ----------------------------------------
-- 产品
-- ----------------------------------------
CREATE TABLE `crm_product` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '产品ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
`code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'SKU/编码(公司内未删唯一)',
`name_zh` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '中文名',
`name_en` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '英文名(单证主用)',
`spec` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '规格',
`unit` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'PCS' COMMENT '单位',
`unit_price` decimal(18, 4) NULL DEFAULT NULL COMMENT '参考单价',
`currency` char(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'USD' COMMENT '币种',
`hs_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'HS Code',
`gross_weight_kg` decimal(18, 3) NULL DEFAULT NULL COMMENT '参考毛重 kg/单位',
`net_weight_kg` decimal(18, 3) NULL DEFAULT NULL COMMENT '参考净重 kg/单位',
`volume_cbm` decimal(18, 4) NULL DEFAULT NULL COMMENT '参考体积 m³/单位',
`status` tinyint UNSIGNED NOT NULL DEFAULT 1 COMMENT '0禁用 1启用',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
`delete_time` timestamp NULL DEFAULT NULL COMMENT '删除时间(软删)',
`delete_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '删除人',
`active_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci
GENERATED ALWAYS AS (IF(`delete_time` IS NULL, `code`, NULL)) STORED COMMENT '软删友好唯一键',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_crm_product_company_active_code` (`company_id`, `active_code`) USING BTREE,
INDEX `idx_crm_product_company_status` (`company_id`, `status`, `id`) USING BTREE,
INDEX `idx_crm_product_delete_time` (`delete_time`) USING BTREE,
CONSTRAINT `fk_crm_product_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_product_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_product_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_product_deleter` FOREIGN KEY (`delete_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-产品';
-- ----------------------------------------
-- 报价
-- ----------------------------------------
CREATE TABLE `crm_quote` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '报价ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
`quote_no` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '报价号 Qyyyy######',
`customer_id` bigint UNSIGNED NOT NULL COMMENT '客户ID',
`quote_date` date NOT NULL COMMENT '报价日期',
`valid_until` date NULL DEFAULT NULL COMMENT '有效期至',
`currency` char(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'USD' COMMENT '币种',
`incoterm` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '贸易术语',
`payment_terms` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '付款条款',
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'draft' COMMENT 'draft/sent/accepted/rejected/expired',
`total_amount` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '合计金额',
`owner_user_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '负责人',
`remark` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
`delete_time` timestamp NULL DEFAULT NULL COMMENT '删除时间',
`delete_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '删除人',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_crm_quote_company_no` (`company_id`, `quote_no`) USING BTREE,
INDEX `idx_crm_quote_company_status` (`company_id`, `status`, `id`) USING BTREE,
INDEX `idx_crm_quote_customer` (`customer_id`) USING BTREE,
INDEX `idx_crm_quote_delete_time` (`delete_time`) USING BTREE,
CONSTRAINT `fk_crm_quote_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_customer` FOREIGN KEY (`customer_id`) REFERENCES `crm_customer` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_owner` FOREIGN KEY (`owner_user_id`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_deleter` FOREIGN KEY (`delete_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-报价单';
CREATE TABLE `crm_quote_item` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '行ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID(冗余)',
`quote_id` bigint UNSIGNED NOT NULL COMMENT '报价ID',
`line_no` int UNSIGNED NOT NULL DEFAULT 1 COMMENT '行号',
`product_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '产品ID(可空,允许临时品名)',
`product_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '编码快照',
`name_en` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '英文品名快照',
`name_zh` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '中文品名快照',
`spec` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '规格快照',
`unit` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'PCS' COMMENT '单位',
`qty` decimal(18, 3) NOT NULL DEFAULT 0 COMMENT '数量',
`unit_price` decimal(18, 4) NOT NULL DEFAULT 0 COMMENT '单价',
`amount` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '金额',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '行备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_crm_quote_item_quote` (`quote_id`, `line_no`) USING BTREE,
INDEX `idx_crm_quote_item_product` (`product_id`) USING BTREE,
CONSTRAINT `fk_crm_quote_item_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_item_quote` FOREIGN KEY (`quote_id`) REFERENCES `crm_quote` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_quote_item_product` FOREIGN KEY (`product_id`) REFERENCES `crm_product` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-报价行';
-- ----------------------------------------
-- 出货
-- ----------------------------------------
CREATE TABLE `crm_shipment` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '出货ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
`shipment_no` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '出货号 SHyyyy######',
`quote_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '来源报价(可空)',
`customer_id` bigint UNSIGNED NOT NULL COMMENT '客户ID',
`plan_ship_date` date NULL DEFAULT NULL COMMENT '计划出货日',
`actual_ship_date` date NULL DEFAULT NULL COMMENT '实际出货日',
`destination_port` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '目的港',
`transport_mode` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '运输方式 sea/air/express…',
`container_type` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '柜型 20GP/40HQ…',
`currency` char(3) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'USD' COMMENT '币种(CI)',
`incoterm` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '贸易术语',
`payment_terms` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '付款条款',
`status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'draft' COMMENT 'draft/ready/shipped/closed',
`total_amount` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '发票合计',
`total_packages` int UNSIGNED NULL DEFAULT NULL COMMENT '总箱数',
`total_gross_kg` decimal(18, 3) NULL DEFAULT NULL COMMENT '总毛重',
`total_net_kg` decimal(18, 3) NULL DEFAULT NULL COMMENT '总净重',
`total_cbm` decimal(18, 4) NULL DEFAULT NULL COMMENT '总体积',
`owner_user_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '负责人',
`remark` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
`delete_time` timestamp NULL DEFAULT NULL COMMENT '删除时间',
`delete_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '删除人',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_crm_shipment_company_no` (`company_id`, `shipment_no`) USING BTREE,
INDEX `idx_crm_shipment_company_status` (`company_id`, `status`, `id`) USING BTREE,
INDEX `idx_crm_shipment_quote` (`quote_id`) USING BTREE,
INDEX `idx_crm_shipment_customer` (`customer_id`) USING BTREE,
INDEX `idx_crm_shipment_delete_time` (`delete_time`) USING BTREE,
CONSTRAINT `fk_crm_shipment_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_quote` FOREIGN KEY (`quote_id`) REFERENCES `crm_quote` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_customer` FOREIGN KEY (`customer_id`) REFERENCES `crm_customer` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_owner` FOREIGN KEY (`owner_user_id`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_deleter` FOREIGN KEY (`delete_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-出货单';
CREATE TABLE `crm_shipment_item` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '行ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID(冗余)',
`shipment_id` bigint UNSIGNED NOT NULL COMMENT '出货ID',
`line_no` int UNSIGNED NOT NULL DEFAULT 1 COMMENT '行号',
`product_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '产品ID',
`product_code` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '编码快照',
`name_en` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '英文品名',
`name_zh` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '中文品名',
`spec` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '规格',
`hs_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'HS Code',
`unit` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'PCS' COMMENT '单位',
`qty` decimal(18, 3) NOT NULL DEFAULT 0 COMMENT '数量',
`unit_price` decimal(18, 4) NOT NULL DEFAULT 0 COMMENT '单价',
`amount` decimal(18, 2) NOT NULL DEFAULT 0.00 COMMENT '金额',
`packages` int UNSIGNED NULL DEFAULT NULL COMMENT '箱数',
`qty_per_package` decimal(18, 3) NULL DEFAULT NULL COMMENT '每箱数量',
`gross_weight_kg` decimal(18, 3) NULL DEFAULT NULL COMMENT '毛重 kg',
`net_weight_kg` decimal(18, 3) NULL DEFAULT NULL COMMENT '净重 kg',
`volume_cbm` decimal(18, 4) NULL DEFAULT NULL COMMENT '体积 m³',
`origin_country` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '原产地',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '行备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_crm_shipment_item_shipment` (`shipment_id`, `line_no`) USING BTREE,
INDEX `idx_crm_shipment_item_product` (`product_id`) USING BTREE,
CONSTRAINT `fk_crm_shipment_item_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_item_shipment` FOREIGN KEY (`shipment_id`) REFERENCES `crm_shipment` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_shipment_item_product` FOREIGN KEY (`product_id`) REFERENCES `crm_product` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-出货行';
-- ----------------------------------------
-- 单证元数据(文件落 sys_file)
-- ----------------------------------------
CREATE TABLE `crm_document` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '单证ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`doc_type` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'pi/ci/pl',
`doc_no` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '单证号(可空,默认同业务单号)',
`ref_type` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'quote/shipment',
`ref_id` bigint UNSIGNED NOT NULL COMMENT '业务单ID',
`file_id` bigint UNSIGNED NOT NULL COMMENT 'sys_file.id',
`is_latest` tinyint UNSIGNED NOT NULL DEFAULT 1 COMMENT '是否最新版本 1是 0否',
`version_no` int UNSIGNED NOT NULL DEFAULT 1 COMMENT '版本号',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_crm_document_ref` (`company_id`, `ref_type`, `ref_id`, `doc_type`, `is_latest`) USING BTREE,
INDEX `idx_crm_document_file` (`file_id`) USING BTREE,
CONSTRAINT `fk_crm_document_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_document_file` FOREIGN KEY (`file_id`) REFERENCES `sys_file` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `fk_crm_document_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-单证记录';
-- ----------------------------------------
-- 邮件(方案 A)
-- ----------------------------------------
CREATE TABLE `crm_mail_account` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '显示名',
`from_email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '发件邮箱',
`smtp_host` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'SMTP 主机',
`smtp_port` int UNSIGNED NOT NULL DEFAULT 465 COMMENT 'SMTP 端口',
`smtp_ssl` tinyint UNSIGNED NOT NULL DEFAULT 1 COMMENT '是否 SSL/TLS',
`username` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '登录用户名',
`password_cipher` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '密码密文',
`enabled` tinyint UNSIGNED NOT NULL DEFAULT 1 COMMENT '是否启用',
`is_default` tinyint UNSIGNED NOT NULL DEFAULT 0 COMMENT '是否默认发件',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_crm_mail_account_company` (`company_id`, `enabled`) USING BTREE,
CONSTRAINT `fk_crm_mail_account_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_account_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_account_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-发件账户';
CREATE TABLE `crm_mail_template` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '模板ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '模板名称',
`scene` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'outreach' COMMENT 'outreach/quote_followup/shipment_notice',
`subject` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '主题(支持变量)',
`body_html` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '正文 HTML(支持变量)',
`enabled` tinyint UNSIGNED NOT NULL DEFAULT 1 COMMENT '是否启用',
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人',
`delete_time` timestamp NULL DEFAULT NULL COMMENT '删除时间',
`delete_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '删除人',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_crm_mail_template_company_scene` (`company_id`, `scene`, `enabled`) USING BTREE,
CONSTRAINT `fk_crm_mail_template_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_template_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_template_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_template_deleter` FOREIGN KEY (`delete_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-邮件模板';
CREATE TABLE `crm_mail_log` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '日志ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
`account_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '发件账户',
`template_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '模板ID',
`customer_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '关联客户',
`ref_type` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT 'quote/shipment 等',
`ref_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '业务单ID',
`to_email` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '收件人',
`cc_email` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '抄送',
`subject` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '实际主题',
`body_html` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT '实际正文',
`status` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'pending' COMMENT 'pending/success/failed',
`error_message` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '失败原因',
`sent_at` timestamp NULL DEFAULT NULL COMMENT '发送时间',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '操作人',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_crm_mail_log_company_time` (`company_id`, `create_time` DESC) USING BTREE,
INDEX `idx_crm_mail_log_customer` (`customer_id`) USING BTREE,
CONSTRAINT `fk_crm_mail_log_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_log_account` FOREIGN KEY (`account_id`) REFERENCES `crm_mail_account` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_log_template` FOREIGN KEY (`template_id`) REFERENCES `crm_mail_template` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_log_customer` FOREIGN KEY (`customer_id`) REFERENCES `crm_customer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_crm_mail_log_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'CRM-邮件发送记录';
@@ -0,0 +1,76 @@
-- CRM 菜单与权限种子(幂等,已有库也可跑)
-- ------------------------------------------------
-- CRM 外贸业务(Phase0:客户 / 产品)
-- ID 分段: 6000 crm
-- ------------------------------------------------
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6000, NULL, 'crm', '外贸业务', 'module', 1, '客户报价出货单证', 30
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6000 OR `code` = 'crm');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6100, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:customer', '客户', 'module', 1, '', 10
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6100 OR `code` = 'crm:customer');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6101, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:customer' LIMIT 1), 'crm:customer:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6101 OR `code` = 'crm:customer:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6102, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:customer' LIMIT 1), 'crm:customer:create', '创建', 'api', 1, '', 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6102 OR `code` = 'crm:customer:create');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6103, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:customer' LIMIT 1), 'crm:customer:update', '更新', 'api', 1, '', 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6103 OR `code` = 'crm:customer:update');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6104, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:customer' LIMIT 1), 'crm:customer:delete', '删除', 'api', 1, '', 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6104 OR `code` = 'crm:customer:delete');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6105, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:customer' LIMIT 1), 'crm:customer:import', '导入', 'api', 1, '', 5
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6105 OR `code` = 'crm:customer:import');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6200, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:product', '产品', 'module', 1, '', 20
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6200 OR `code` = 'crm:product');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6201, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:product' LIMIT 1), 'crm:product:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6201 OR `code` = 'crm:product:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6202, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:product' LIMIT 1), 'crm:product:create', '创建', 'api', 1, '', 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6202 OR `code` = 'crm:product:create');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6203, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:product' LIMIT 1), 'crm:product:update', '更新', 'api', 1, '', 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6203 OR `code` = 'crm:product:update');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6204, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:product' LIMIT 1), 'crm:product:delete', '删除', 'api', 1, '', 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6204 OR `code` = 'crm:product:delete');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6205, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:product' LIMIT 1), 'crm:product:import', '导入', 'api', 1, '', 5
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6205 OR `code` = 'crm:product:import');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14100, NULL, 0, 'CrmCatalog', '外贸业务', '/crm', '', '', 'lucide:ship', 'catalog', 1, 1, 0, 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14101, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmCustomer', '客户', '/crm/customer', '/crm/customer/index', '', 'lucide:users', 'menu', 1, 1, 1, 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14101 OR `route_name` = 'CrmCustomer');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14102, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmProduct', '产品', '/crm/product', '/crm/product/index', '', 'lucide:package', 'menu', 1, 1, 1, 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14102 OR `route_name` = 'CrmProduct');
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:customer:%' WHERE m.route_name = 'CrmCustomer';
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:product:%' WHERE m.route_name = 'CrmProduct';
@@ -1,9 +1,9 @@
-- ========================================
-- 系统基础数据初始化(权限多级树 + 菜单)
-- 权限码约定:域 → 资源 → 动作,如 sys / sys:permission / sys:permission:create
-- 根域: sys org open agent
-- 叶子 api: create / update / delete / read / assign 等动作
-- ID 分段: 1000 sys / 2000 org / 5000 open / 5500 agent
-- 根域: sys org crm open agent
-- 叶子 api: create / update / delete / read / assign / import 等动作
-- ID 分段: 1000 sys / 2000 org / 5000 open / 5500 agent / 6000 crm
-- 由 SysInitDataService 在空库时执行;按 code/name NOT EXISTS 幂等
-- ========================================
@@ -488,3 +488,78 @@ SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'agent:c
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 = 'agent:llm-settings' WHERE m.route_name = 'AgentLlmSettings';
-- ------------------------------------------------
-- CRM 外贸业务(Phase0:客户 / 产品)
-- ID 分段: 6000 crm
-- ------------------------------------------------
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6000, NULL, 'crm', '外贸业务', 'module', 1, '客户报价出货单证', 30
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6000 OR `code` = 'crm');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6100, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:customer', '客户', 'module', 1, '', 10
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6100 OR `code` = 'crm:customer');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6101, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:customer' LIMIT 1), 'crm:customer:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6101 OR `code` = 'crm:customer:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6102, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:customer' LIMIT 1), 'crm:customer:create', '创建', 'api', 1, '', 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6102 OR `code` = 'crm:customer:create');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6103, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:customer' LIMIT 1), 'crm:customer:update', '更新', 'api', 1, '', 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6103 OR `code` = 'crm:customer:update');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6104, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:customer' LIMIT 1), 'crm:customer:delete', '删除', 'api', 1, '', 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6104 OR `code` = 'crm:customer:delete');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6105, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:customer' LIMIT 1), 'crm:customer:import', '导入', 'api', 1, '', 5
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6105 OR `code` = 'crm:customer:import');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6200, (SELECT id FROM `sys_permission` WHERE `code` = 'crm' LIMIT 1), 'crm:product', '产品', 'module', 1, '', 20
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6200 OR `code` = 'crm:product');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6201, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:product' LIMIT 1), 'crm:product:read', '查看', 'api', 1, '', 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6201 OR `code` = 'crm:product:read');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6202, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:product' LIMIT 1), 'crm:product:create', '创建', 'api', 1, '', 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6202 OR `code` = 'crm:product:create');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6203, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:product' LIMIT 1), 'crm:product:update', '更新', 'api', 1, '', 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6203 OR `code` = 'crm:product:update');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6204, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:product' LIMIT 1), 'crm:product:delete', '删除', 'api', 1, '', 4
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6204 OR `code` = 'crm:product:delete');
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
SELECT 6205, (SELECT id FROM `sys_permission` WHERE `code` = 'crm:product' LIMIT 1), 'crm:product:import', '导入', 'api', 1, '', 5
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 6205 OR `code` = 'crm:product:import');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14100, NULL, 0, 'CrmCatalog', '外贸业务', '/crm', '', '', 'lucide:ship', 'catalog', 1, 1, 0, 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14101, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmCustomer', '客户', '/crm/customer', '/crm/customer/index', '', 'lucide:users', 'menu', 1, 1, 1, 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14101 OR `route_name` = 'CrmCustomer');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14102, (SELECT id FROM `sys_menu` WHERE `id` = 14100 OR `route_name` = 'CrmCatalog' LIMIT 1), 0, 'CrmProduct', '产品', '/crm/product', '/crm/product/index', '', 'lucide:package', 'menu', 1, 1, 1, 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14102 OR `route_name` = 'CrmProduct');
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:customer:%' WHERE m.route_name = 'CrmCustomer';
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:product:%' WHERE m.route_name = 'CrmProduct';