Files
yunzerwebsiteallinone/go/controllers/backend_crm_contact.go
T
2026-11-16 17:22:50 +08:00

649 lines
17 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package controllers
import (
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
"time"
"server/models"
"server/pkg/identity"
"server/pkg/jwtutil"
"github.com/beego/beego/v2/client/orm"
beego "github.com/beego/beego/v2/server/web"
)
type BackendCrmContactController struct {
beego.Controller
}
type crmContactDTO struct {
ID uint64 `json:"id"`
RelatedType int `json:"related_type"`
RelatedID uint64 `json:"related_id"`
RelatedName string `json:"related_name"`
ContactName string `json:"contact_name"`
Gender int8 `json:"gender"`
Mobile string `json:"mobile"`
Mobiles string `json:"mobiles"`
Phone string `json:"phone"`
Email string `json:"email"`
Wechat string `json:"wechat"`
QQ string `json:"qq"`
Dingtalk string `json:"dingtalk"`
Department string `json:"department"`
Position string `json:"position"`
HomeAddress string `json:"home_address"`
IsPrimary int8 `json:"is_primary"`
Remark string `json:"remark"`
Status int8 `json:"status"`
CreateTime time.Time `json:"create_time"`
UpdateTime time.Time `json:"update_time"`
}
func buildMobiles(mobile string) string {
mobile = strings.TrimSpace(mobile)
if mobile == "" {
return ""
}
arr := []string{mobile}
b, err := json.Marshal(arr)
if err != nil {
return ""
}
return string(b)
}
func buildMobilesFromList(mobiles []string) string {
cleaned := make([]string, 0, len(mobiles))
seen := map[string]bool{}
for _, m := range mobiles {
m = strings.TrimSpace(m)
if m == "" || seen[m] {
continue
}
seen[m] = true
cleaned = append(cleaned, m)
if len(cleaned) >= 5 {
break
}
}
if len(cleaned) == 0 {
return ""
}
b, err := json.Marshal(cleaned)
if err != nil {
return ""
}
return string(b)
}
func normalizeMobiles(mobiles []string, mobile string) string {
if len(mobiles) == 0 {
return buildMobiles(mobile)
}
return buildMobilesFromList(mobiles)
}
func splitMobiles(mobiles string) []string {
mobiles = strings.TrimSpace(mobiles)
if mobiles == "" {
return nil
}
var arr []string
if err := json.Unmarshal([]byte(mobiles), &arr); err == nil {
out := make([]string, 0, len(arr))
for _, m := range arr {
if m = strings.TrimSpace(m); m != "" {
out = append(out, m)
}
}
return out
}
parts := strings.FieldsFunc(mobiles, func(r rune) bool {
switch r {
case ',', ',', '、', ';', ';', ' ', '/', '|':
return true
}
return false
})
out := make([]string, 0, len(parts))
for _, p := range parts {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
func mobilesFromPayload(raw json.RawMessage, fallback string) string {
if len(raw) > 0 {
text := strings.TrimSpace(string(raw))
if text != "" && text != "null" {
var arr []string
if err := json.Unmarshal(raw, &arr); err == nil {
return buildMobilesFromList(arr)
}
var s string
if err := json.Unmarshal(raw, &s); err == nil {
if strings.TrimSpace(s) == "" {
return ""
}
return buildMobilesFromList(splitMobiles(s))
}
}
}
return buildMobiles(fallback)
}
func firstMobile(mobiles string) string {
mobiles = strings.TrimSpace(mobiles)
if mobiles == "" {
return ""
}
var arr []string
if err := json.Unmarshal([]byte(mobiles), &arr); err == nil {
for _, m := range arr {
if strings.TrimSpace(m) != "" {
return strings.TrimSpace(m)
}
}
return ""
}
return mobiles
}
func crmContactCompanyType(relatedType int) string {
if relatedType == 2 {
return "supplier"
}
return "customer"
}
func crmContactRelatedType(companyType string) int {
if companyType == "supplier" {
return 2
}
return 1
}
func crmContactAtoi(s string) int {
n, _ := strconv.Atoi(strings.TrimSpace(s))
return n
}
func (c *BackendCrmContactController) contactClaims() (*jwtutil.Claims, error) {
return identity.Claims(c.Ctx.Request.Header.Get("Authorization"), identity.EndBackend)
}
func (c *BackendCrmContactController) crmContactJsonErr(httpStatus, bizCode int, msg string) {
c.Ctx.Output.SetStatus(httpStatus)
c.Data["json"] = map[string]interface{}{"code": bizCode, "msg": msg}
_ = c.ServeJSON()
}
func (c *BackendCrmContactController) crmContactOk(data interface{}) {
c.Data["json"] = map[string]interface{}{"code": 200, "msg": "success", "data": data}
_ = c.ServeJSON()
}
func toCrmContactDTO(row models.ErpCompanyContact, names map[string]string) crmContactDTO {
relatedType := crmContactRelatedType(row.CompanyType)
key := fmt.Sprintf("%s:%d", row.CompanyType, row.CompanyID)
return crmContactDTO{
ID: row.ID,
RelatedType: relatedType,
RelatedID: row.CompanyID,
RelatedName: names[key],
ContactName: row.Name,
Gender: row.Gender,
Mobile: firstMobile(row.Mobiles),
Mobiles: row.Mobiles,
Phone: row.Phone,
Email: row.Email,
Wechat: row.Wechat,
QQ: row.QQ,
Dingtalk: row.Dingtalk,
Department: row.Department,
Position: row.Position,
HomeAddress: row.HomeAddress,
IsPrimary: row.IsPrimary,
Remark: row.Remark,
Status: row.Status,
CreateTime: row.CreateTime,
UpdateTime: row.UpdateTime,
}
}
func loadRelatedNames(tenantID string, rows []models.ErpCompanyContact) map[string]string {
names := map[string]string{}
if len(rows) == 0 || models.Orm == nil {
return names
}
customerIDs := make([]uint64, 0)
supplierIDs := make([]uint64, 0)
for _, r := range rows {
if r.CompanyType == "supplier" {
supplierIDs = append(supplierIDs, r.CompanyID)
} else {
customerIDs = append(customerIDs, r.CompanyID)
}
}
if len(customerIDs) > 0 {
var list []models.TenantCrmCustomer
if _, err := models.Orm.QueryTable(new(models.TenantCrmCustomer)).
Filter("tenant_id", tenantID).
Filter("id__in", customerIDs).
All(&list); err == nil {
for _, r := range list {
names[fmt.Sprintf("customer:%d", r.ID)] = r.CustomerName
}
}
}
if len(supplierIDs) > 0 {
var list []models.TenantCrmSupplier
if _, err := models.Orm.QueryTable(new(models.TenantCrmSupplier)).
Filter("tenant_id", tenantID).
Filter("id__in", supplierIDs).
All(&list); err == nil {
for _, r := range list {
names[fmt.Sprintf("supplier:%d", r.ID)] = r.SupplierName
}
}
}
return names
}
func clearOtherPrimary(tenantID, companyType string, companyID, excludeID uint64) {
if models.Orm == nil || companyID == 0 {
return
}
qs := models.Orm.QueryTable(new(models.ErpCompanyContact)).
Filter("tenant_id", tenantID).
Filter("company_type", companyType).
Filter("company_id", companyID).
Filter("delete_time__isnull", true).
Exclude("id", excludeID)
_, _ = qs.Update(map[string]interface{}{"is_primary": 0})
}
func isMobileNumber(phone string) bool {
digits := strings.Map(func(r rune) rune {
if r >= '0' && r <= '9' {
return r
}
return -1
}, phone)
return len(digits) == 11 && digits[0] == '1'
}
func crmContactCompanyExists(tenantID, companyType string, companyID uint64) bool {
if models.Orm == nil || companyID == 0 {
return false
}
if companyType == "supplier" {
cnt, err := models.Orm.QueryTable(new(models.TenantCrmSupplier)).
Filter("id", companyID).Filter("tenant_id", tenantID).
Filter("delete_time__isnull", true).Count()
return err == nil && cnt > 0
}
cnt, err := models.Orm.QueryTable(new(models.TenantCrmCustomer)).
Filter("id", companyID).Filter("tenant_id", tenantID).
Filter("delete_time__isnull", true).Count()
return err == nil && cnt > 0
}
func contactPhoneMatched(row models.ErpCompanyContact, phone string) bool {
if strings.TrimSpace(row.Phone) == phone {
return true
}
var mobiles []string
if err := json.Unmarshal([]byte(strings.TrimSpace(row.Mobiles)), &mobiles); err == nil {
for _, m := range mobiles {
if strings.TrimSpace(m) == phone {
return true
}
}
}
return false
}
func crmEnsureCompanyContact(tenantID, companyType string, companyID uint64, name, phone string) {
if models.Orm == nil || companyID == 0 {
return
}
name = strings.TrimSpace(name)
phone = strings.TrimSpace(phone)
if name == "" {
return
}
var rows []models.ErpCompanyContact
if _, err := models.Orm.QueryTable(new(models.ErpCompanyContact)).
Filter("tenant_id", tenantID).
Filter("company_type", companyType).
Filter("company_id", companyID).
Filter("delete_time__isnull", true).
All(&rows); err != nil && err != orm.ErrNoRows {
return
}
for i := range rows {
row := rows[i]
sameName := strings.EqualFold(strings.TrimSpace(row.Name), name)
samePhone := phone != "" && contactPhoneMatched(row, phone)
if !sameName && !samePhone {
continue
}
if phone != "" && strings.TrimSpace(row.Mobiles) == "" && strings.TrimSpace(row.Phone) == "" {
up := map[string]interface{}{"update_time": time.Now()}
if isMobileNumber(phone) {
up["mobiles"] = buildMobiles(phone)
} else {
up["phone"] = phone
}
_, _ = models.Orm.QueryTable(new(models.ErpCompanyContact)).
Filter("id", row.ID).Update(up)
}
return
}
now := time.Now()
contact := models.ErpCompanyContact{
TenantID: tenantID,
CompanyType: companyType,
CompanyID: companyID,
Name: name,
Status: 1,
Remark: "由合同签约信息自动写入,可在联系人中补全其他资料",
CreateTime: now,
UpdateTime: now,
}
if len(rows) == 0 {
contact.IsPrimary = 1
}
if phone != "" {
if isMobileNumber(phone) {
contact.Mobiles = buildMobiles(phone)
} else {
contact.Phone = phone
}
}
_, _ = models.Orm.Insert(&contact)
}
func (c *BackendCrmContactController) List() {
claims, err := c.contactClaims()
if err != nil {
code := identity.Status(err)
c.crmContactJsonErr(code, code, err.Error())
return
}
page, _ := c.GetInt("page", 1)
pageSize, _ := c.GetInt("pageSize", 20)
keyword := strings.TrimSpace(c.GetString("keyword"))
relatedTypeStr := strings.TrimSpace(c.GetString("related_type"))
relatedIDStr := strings.TrimSpace(c.GetString("related_id"))
primaryStr := strings.TrimSpace(c.GetString("is_primary"))
if page < 1 {
page = 1
}
if pageSize < 1 || pageSize > 100 {
pageSize = 20
}
tenantID := fmt.Sprintf("%d", claims.TenantId)
cond := orm.NewCondition().
And("tenant_id", tenantID).
And("delete_time__isnull", true)
if relatedTypeStr != "" {
cond = cond.And("company_type", crmContactCompanyType(crmContactAtoi(relatedTypeStr)))
}
if relatedIDStr != "" && relatedIDStr != "0" {
cond = cond.And("company_id", relatedIDStr)
}
if primaryStr != "" {
cond = cond.And("is_primary", crmContactAtoi(primaryStr))
}
if keyword != "" {
kw := orm.NewCondition().
Or("name__contains", keyword).
Or("mobiles__contains", keyword).
Or("phone__contains", keyword).
Or("email__contains", keyword)
cond = cond.AndCond(kw)
}
qs := models.Orm.QueryTable(new(models.ErpCompanyContact)).SetCond(cond)
total, _ := qs.Count()
var rows []models.ErpCompanyContact
if total > 0 {
_, _ = qs.OrderBy("-is_primary", "-update_time").
Offset((page - 1) * pageSize).
Limit(pageSize).
All(&rows)
}
names := loadRelatedNames(tenantID, rows)
list := make([]crmContactDTO, 0, len(rows))
for _, r := range rows {
list = append(list, toCrmContactDTO(r, names))
}
c.crmContactOk(map[string]interface{}{
"list": list,
"total": total,
"page": page,
"pageSize": pageSize,
})
}
func (c *BackendCrmContactController) Add() {
claims, err := c.contactClaims()
if err != nil {
code := identity.Status(err)
c.crmContactJsonErr(code, code, err.Error())
return
}
var p struct {
RelatedType int `json:"related_type"`
RelatedID uint64 `json:"related_id"`
ContactName string `json:"contact_name"`
Gender int8 `json:"gender"`
Mobile string `json:"mobile"`
Mobiles []string `json:"mobiles"`
Phone string `json:"phone"`
Email string `json:"email"`
Wechat string `json:"wechat"`
QQ string `json:"qq"`
Dingtalk string `json:"dingtalk"`
Department string `json:"department"`
Position string `json:"position"`
HomeAddress string `json:"home_address"`
IsPrimary int8 `json:"is_primary"`
Status int8 `json:"status"`
Remark string `json:"remark"`
}
raw, _ := io.ReadAll(c.Ctx.Request.Body)
if err := json.Unmarshal(raw, &p); err != nil {
c.crmContactJsonErr(400, 400, "参数错误")
return
}
if strings.TrimSpace(p.ContactName) == "" {
c.crmContactJsonErr(400, 400, "联系人姓名不能为空")
return
}
if p.RelatedID == 0 {
c.crmContactJsonErr(400, 400, "请选择关联对象")
return
}
companyType := crmContactCompanyType(p.RelatedType)
now := time.Now()
contact := models.ErpCompanyContact{
TenantID: fmt.Sprintf("%d", claims.TenantId),
CompanyType: companyType,
CompanyID: p.RelatedID,
Name: strings.TrimSpace(p.ContactName),
Gender: p.Gender,
Phone: strings.TrimSpace(p.Phone),
Mobiles: normalizeMobiles(p.Mobiles, p.Mobile),
Email: strings.TrimSpace(p.Email),
Wechat: strings.TrimSpace(p.Wechat),
QQ: strings.TrimSpace(p.QQ),
Dingtalk: strings.TrimSpace(p.Dingtalk),
Department: strings.TrimSpace(p.Department),
Position: strings.TrimSpace(p.Position),
HomeAddress: strings.TrimSpace(p.HomeAddress),
IsPrimary: p.IsPrimary,
Status: 1,
Remark: p.Remark,
CreateTime: now,
UpdateTime: now,
}
if p.Status == 0 {
contact.Status = 1
} else {
contact.Status = p.Status
}
id, err := models.Orm.Insert(&contact)
if err != nil {
c.crmContactJsonErr(500, 500, "新增失败: "+err.Error())
return
}
if p.IsPrimary == 1 {
clearOtherPrimary(fmt.Sprintf("%d", claims.TenantId), companyType, p.RelatedID, uint64(id))
}
c.crmContactOk(map[string]interface{}{"id": id})
}
func (c *BackendCrmContactController) Edit() {
claims, err := c.contactClaims()
if err != nil {
code := identity.Status(err)
c.crmContactJsonErr(code, code, err.Error())
return
}
var p struct {
ID uint64 `json:"id"`
RelatedType int `json:"related_type"`
RelatedID uint64 `json:"related_id"`
ContactName string `json:"contact_name"`
Gender int8 `json:"gender"`
Mobile string `json:"mobile"`
Mobiles []string `json:"mobiles"`
Phone string `json:"phone"`
Email string `json:"email"`
Wechat string `json:"wechat"`
QQ string `json:"qq"`
Dingtalk string `json:"dingtalk"`
Department string `json:"department"`
Position string `json:"position"`
HomeAddress string `json:"home_address"`
IsPrimary int8 `json:"is_primary"`
Status int8 `json:"status"`
Remark string `json:"remark"`
}
raw, _ := io.ReadAll(c.Ctx.Request.Body)
if err := json.Unmarshal(raw, &p); err != nil {
c.crmContactJsonErr(400, 400, "参数错误")
return
}
if p.ID == 0 {
c.crmContactJsonErr(400, 400, "缺少ID")
return
}
if strings.TrimSpace(p.ContactName) == "" {
c.crmContactJsonErr(400, 400, "联系人姓名不能为空")
return
}
tenantID := fmt.Sprintf("%d", claims.TenantId)
var contact models.ErpCompanyContact
if err := models.Orm.QueryTable(new(models.ErpCompanyContact)).
Filter("id", p.ID).
Filter("tenant_id", tenantID).
Filter("delete_time__isnull", true).
One(&contact); err != nil {
c.crmContactJsonErr(404, 404, "联系人未找到")
return
}
companyType := contact.CompanyType
companyID := contact.CompanyID
if p.RelatedID > 0 {
companyType = crmContactCompanyType(p.RelatedType)
companyID = p.RelatedID
}
contact.CompanyType = companyType
contact.CompanyID = companyID
contact.Name = strings.TrimSpace(p.ContactName)
contact.Gender = p.Gender
contact.Phone = strings.TrimSpace(p.Phone)
contact.Mobiles = normalizeMobiles(p.Mobiles, p.Mobile)
contact.Email = strings.TrimSpace(p.Email)
contact.Wechat = strings.TrimSpace(p.Wechat)
contact.QQ = strings.TrimSpace(p.QQ)
contact.Dingtalk = strings.TrimSpace(p.Dingtalk)
contact.Department = strings.TrimSpace(p.Department)
contact.Position = strings.TrimSpace(p.Position)
contact.HomeAddress = strings.TrimSpace(p.HomeAddress)
contact.IsPrimary = p.IsPrimary
contact.Status = p.Status
contact.Remark = p.Remark
contact.UpdateTime = time.Now()
if _, err := models.Orm.Update(&contact); err != nil {
c.crmContactJsonErr(500, 500, "更新失败: "+err.Error())
return
}
if p.IsPrimary == 1 {
clearOtherPrimary(tenantID, companyType, companyID, contact.ID)
}
c.crmContactOk(map[string]interface{}{"id": contact.ID})
}
func (c *BackendCrmContactController) Delete() {
claims, err := c.contactClaims()
if err != nil {
code := identity.Status(err)
c.crmContactJsonErr(code, code, err.Error())
return
}
var p struct {
ID uint64 `json:"id"`
}
raw, _ := io.ReadAll(c.Ctx.Request.Body)
if err := json.Unmarshal(raw, &p); err != nil {
c.crmContactJsonErr(400, 400, "参数错误")
return
}
if p.ID == 0 {
c.crmContactJsonErr(400, 400, "缺少ID")
return
}
now := time.Now()
num, err := models.Orm.QueryTable(new(models.ErpCompanyContact)).
Filter("id", p.ID).
Filter("tenant_id", fmt.Sprintf("%d", claims.TenantId)).
Filter("delete_time__isnull", true).
Update(map[string]interface{}{
"delete_time": now,
"update_time": now,
})
if err != nil {
c.crmContactJsonErr(500, 500, "删除失败: "+err.Error())
return
}
if num == 0 {
c.crmContactJsonErr(404, 404, "联系人未找到")
return
}
c.crmContactOk(nil)
}