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

1096 lines
34 KiB
Go

package controllers
import (
"encoding/json"
"io"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"server/models"
"server/pkg/identity"
"server/pkg/jwtutil"
"server/services"
"github.com/beego/beego/v2/client/orm"
beego "github.com/beego/beego/v2/server/web"
)
type BackendCrmProjectController struct {
beego.Controller
}
const crmProjectStatusDone = "3"
func projectStatusName(s int8) string {
switch s {
case 1:
return "未开始"
case 2:
return "进行中"
case 3:
return "已完成"
case 4:
return "已暂停"
case 5:
return "异常"
}
return "未知"
}
type projectPayload struct {
ProjectName string `json:"project_name"`
ProjectNo string `json:"project_no"`
ProjectType int8 `json:"project_type"`
CustomerID uint64 `json:"customer_id"`
CustomerRefType int8 `json:"customer_ref_type"`
CustomerName string `json:"customer_name"`
SupplierID uint64 `json:"supplier_id"`
SupplierRefType int8 `json:"supplier_ref_type"`
SupplierName string `json:"supplier_name"`
SupplierIndustry string `json:"supplier_industry"`
OwnerUserID string `json:"owner_user_id"`
OwnerUserName string `json:"owner_user_name"`
Industry string `json:"industry"`
UpstreamAmount float64 `json:"upstream_amount"`
DownstreamAmount float64 `json:"downstream_amount"`
Amount float64 `json:"amount"`
Status int8 `json:"status"`
Reason string `json:"reason"`
StartDate string `json:"start_date"`
EndDate string `json:"end_date"`
UpstreamContact string `json:"upstream_contact"`
UpstreamPhone string `json:"upstream_phone"`
DownstreamContact string `json:"downstream_contact"`
DownstreamPhone string `json:"downstream_phone"`
ContactPerson string `json:"contact_person"`
ContactPosition string `json:"contact_position"`
ContactPhone string `json:"contact_phone"`
Address string `json:"address"`
Remark string `json:"remark"`
Products string `json:"products"`
}
func normalizeProjectFields(p *projectPayload) (pt int8, upstream, downstream float64, upContact, upPhone, downContact, downPhone string) {
pt = p.ProjectType
if pt != 2 && pt != 3 {
pt = 1
}
upstream = p.UpstreamAmount
if upstream == 0 && p.Amount != 0 {
upstream = p.Amount
}
upContact = strings.TrimSpace(firstNonEmpty(p.UpstreamContact, p.ContactPerson))
upPhone = strings.TrimSpace(firstNonEmpty(p.UpstreamPhone, p.ContactPhone))
if pt == 2 || pt == 3 {
downstream = p.DownstreamAmount
downContact = strings.TrimSpace(p.DownstreamContact)
downPhone = strings.TrimSpace(p.DownstreamPhone)
}
return
}
func resolveProjectCustomer(tenantID string, refType int8, refID uint64, name string) (*uint64, int8, string) {
name = strings.TrimSpace(name)
if refID == 0 {
return nil, 0, name
}
if refType == 2 {
var sup models.TenantCrmSupplier
if err := models.Orm.QueryTable(new(models.TenantCrmSupplier)).
Filter("id", refID).Filter("tenant_id", tenantID).
Filter("delete_time__isnull", true).One(&sup); err != nil {
return nil, 0, name
}
id := sup.ID
if strings.TrimSpace(sup.SupplierName) != "" {
name = sup.SupplierName
}
return &id, 2, name
}
var cus models.TenantCrmCustomer
if err := models.Orm.QueryTable(new(models.TenantCrmCustomer)).
Filter("id", refID).Filter("tenant_id", tenantID).
Filter("delete_time__isnull", true).One(&cus); err != nil {
return nil, 0, name
}
id := cus.ID
if strings.TrimSpace(cus.CustomerName) != "" {
name = cus.CustomerName
}
return &id, 1, name
}
func resolveProjectSupplier(tenantID string, refType int8, refID uint64, name string) (*uint64, int8, string) {
name = strings.TrimSpace(name)
if refID == 0 {
return nil, 0, name
}
switch refType {
case 2:
var sup models.TenantCrmSupplier
if err := models.Orm.QueryTable(new(models.TenantCrmSupplier)).
Filter("id", refID).Filter("tenant_id", tenantID).
Filter("delete_time__isnull", true).One(&sup); err != nil {
return nil, 0, name
}
id := sup.ID
if strings.TrimSpace(sup.SupplierName) != "" {
name = sup.SupplierName
}
return &id, 2, name
case 1:
var cus models.TenantCrmCustomer
if err := models.Orm.QueryTable(new(models.TenantCrmCustomer)).
Filter("id", refID).Filter("tenant_id", tenantID).
Filter("delete_time__isnull", true).One(&cus); err != nil {
return nil, 0, name
}
id := cus.ID
if strings.TrimSpace(cus.CustomerName) != "" {
name = cus.CustomerName
}
return &id, 1, name
}
return nil, 0, name
}
func attachProjectContractPeriod(tenantID string, list []models.TenantCrmProject) {
if len(list) == 0 {
return
}
idx := make(map[uint64]int, len(list))
ids := make([]uint64, 0, len(list))
for i := range list {
idx[list[i].ID] = i
ids = append(ids, list[i].ID)
}
var rows []models.TenantCrmContract
_, err := models.Orm.QueryTable(new(models.TenantCrmContract)).
Filter("tenant_id", tenantID).Filter("delete_time__isnull", true).
Filter("project_id__in", ids).
All(&rows, "project_id", "sign_date", "effective_date", "expire_date")
if err != nil {
return
}
for i := range rows {
ct := rows[i]
if ct.ProjectID == nil {
continue
}
pos, ok := idx[*ct.ProjectID]
if !ok {
continue
}
start := ct.EffectiveDate
if start == nil {
start = ct.SignDate
}
if start != nil && (list[pos].ContractStartDate == nil || start.Before(*list[pos].ContractStartDate)) {
list[pos].ContractStartDate = start
}
if ct.ExpireDate != nil && (list[pos].ContractEndDate == nil || ct.ExpireDate.After(*list[pos].ContractEndDate)) {
list[pos].ContractEndDate = ct.ExpireDate
}
}
}
func crmProjectNameDuplicated(tenantID, name string, customerID *uint64, customerRefType int8) bool {
name = strings.TrimSpace(name)
if name == "" || strings.TrimSpace(tenantID) == "" || models.Orm == nil {
return false
}
cond := orm.NewCondition().
And("tenant_id", tenantID).
And("delete_time__isnull", true).
And("project_name", name)
if customerID != nil && *customerID > 0 {
cond = cond.And("customer_id", *customerID)
if customerRefType == 2 {
cond = cond.And("customer_ref_type", 2)
} else {
cond = cond.And("customer_ref_type__in", []int{0, 1})
}
} else {
cond = cond.AndCond(orm.NewCondition().Or("customer_id__isnull", true).Or("customer_id", 0))
}
cnt, err := models.Orm.QueryTable(new(models.TenantCrmProject)).SetCond(cond).Count()
return err == nil && cnt > 0
}
func (c *BackendCrmProjectController) List() {
claims, err := pipelineClaims(&c.Controller)
if err != nil {
code := identity.Status(err)
pipelineErr(&c.Controller, code, code, err.Error())
return
}
page, _ := c.GetInt("page", 1)
pageSize, _ := c.GetInt("pageSize", 20)
if page < 1 {
page = 1
}
if pageSize < 1 || pageSize > 100 {
pageSize = 20
}
keyword := strings.TrimSpace(c.GetString("keyword"))
status := strings.TrimSpace(c.GetString("status"))
ownerID := strings.TrimSpace(c.GetString("owner_user_id"))
year := strings.TrimSpace(c.GetString("year"))
tenantID := pipelineTenantID(claims)
buildCond := func() *orm.Condition {
cond := orm.NewCondition().And("tenant_id", tenantID).And("delete_time__isnull", true)
cond = crmApplyOwnerScope(cond, claims)
if keyword != "" {
kw := orm.NewCondition().
Or("project_name__contains", keyword).
Or("project_no__contains", keyword).
Or("customer_name__contains", keyword).
Or("supplier_name__contains", keyword)
cond = cond.AndCond(kw)
}
if status != "" {
cond = cond.And("status", status)
}
if ownerID != "" {
cond = cond.And("owner_user_id", ownerID)
}
return cond
}
projectQuery := func(cond *orm.Condition) orm.QuerySeter {
return models.Orm.QueryTable(new(models.TenantCrmProject)).SetCond(cond)
}
total, _ := projectQuery(buildCond()).Count()
years := []int{}
var list []models.TenantCrmProject
if total > 0 {
if _, err := projectQuery(buildCond()).All(&list); err != nil {
pipelineErr(&c.Controller, 500, 500, "查询失败: "+err.Error())
return
}
attachProjectContractPeriod(tenantID, list)
startOf := func(p *models.TenantCrmProject) time.Time {
if p.ContractStartDate != nil {
return *p.ContractStartDate
}
if p.StartDate != nil {
return *p.StartDate
}
return time.Time{}
}
yearSet := make(map[int]struct{})
for i := range list {
if d := startOf(&list[i]); !d.IsZero() {
yearSet[d.Year()] = struct{}{}
}
}
years = make([]int, 0, len(yearSet))
for y := range yearSet {
years = append(years, y)
}
sort.Sort(sort.Reverse(sort.IntSlice(years)))
if year != "" {
if want, err := strconv.Atoi(year); err == nil && want > 0 {
kept := make([]models.TenantCrmProject, 0, len(list))
for i := range list {
if d := startOf(&list[i]); !d.IsZero() && d.Year() == want {
kept = append(kept, list[i])
}
}
list = kept
total = int64(len(list))
}
}
sort.SliceStable(list, func(i, j int) bool {
ti, tj := startOf(&list[i]), startOf(&list[j])
if ti.IsZero() != tj.IsZero() {
return !ti.IsZero()
}
if !ti.Equal(tj) {
return ti.After(tj)
}
return list[i].ID > list[j].ID
})
offset := (page - 1) * pageSize
if offset > len(list) {
offset = len(list)
}
end := offset + pageSize
if end > len(list) {
end = len(list)
}
list = list[offset:end]
}
attachBusinessName(tenantID, list)
pipelineOk(&c.Controller, map[string]interface{}{
"list": list, "total": total, "years": years,
"page": page, "pageSize": pageSize,
})
}
func (c *BackendCrmProjectController) Detail() {
claims, err := pipelineClaims(&c.Controller)
if err != nil {
code := identity.Status(err)
pipelineErr(&c.Controller, code, code, err.Error())
return
}
id, _ := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
if id == 0 {
pipelineErr(&c.Controller, 400, 400, "无效的ID")
return
}
var proj models.TenantCrmProject
err = models.Orm.QueryTable(new(models.TenantCrmProject)).
Filter("id", id).Filter("tenant_id", pipelineTenantID(claims)).
Filter("delete_time__isnull", true).One(&proj)
if err != nil {
pipelineErr(&c.Controller, 404, 404, "项目未找到")
return
}
tmp := []models.TenantCrmProject{proj}
attachBusinessName(pipelineTenantID(claims), tmp)
attachProjectContractPeriod(pipelineTenantID(claims), tmp)
proj.BusinessName = tmp[0].BusinessName
proj.ContractStartDate = tmp[0].ContractStartDate
proj.ContractEndDate = tmp[0].ContractEndDate
if proj.DocCategoryID == 0 {
if cid, err := services.EnsureCrmProjectDocCategory(claims.TenantId, proj.ID, proj.ProjectName, 0); err == nil && cid > 0 {
proj.DocCategoryID = cid
}
}
pipelineOk(&c.Controller, proj)
}
func (c *BackendCrmProjectController) Create() {
claims, err := pipelineClaims(&c.Controller)
if err != nil {
code := identity.Status(err)
pipelineErr(&c.Controller, code, code, err.Error())
return
}
raw, _ := io.ReadAll(c.Ctx.Request.Body)
var p projectPayload
if err := json.Unmarshal(raw, &p); err != nil {
pipelineErr(&c.Controller, 400, 400, "参数错误")
return
}
if strings.TrimSpace(p.ProjectName) == "" {
pipelineErr(&c.Controller, 400, 400, "项目名称不能为空")
return
}
tenantID := pipelineTenantID(claims)
custIDVal, custRefType, customerName := resolveProjectCustomer(tenantID, p.CustomerRefType, p.CustomerID, p.CustomerName)
status := p.Status
if status == 0 {
status = 1
}
pt, upstream, downstream, upContact, upPhone, downContact, downPhone := normalizeProjectFields(&p)
supplierID, supplierRefType, supplierName := resolveProjectSupplier(tenantID, p.SupplierRefType, p.SupplierID, p.SupplierName)
if pt == 1 {
supplierID, supplierRefType, supplierName = nil, 0, ""
}
now := time.Now()
proj := models.TenantCrmProject{
TenantID: tenantID,
ProjectName: strings.TrimSpace(p.ProjectName),
ProjectNo: strings.TrimSpace(p.ProjectNo),
ProjectType: pt,
CustomerID: custIDVal,
CustomerRefType: custRefType,
CustomerName: customerName,
SupplierID: supplierID,
SupplierRefType: supplierRefType,
SupplierName: supplierName,
SupplierIndustry: strings.TrimSpace(p.SupplierIndustry),
OwnerUserID: firstNonEmpty(p.OwnerUserID, pipelineUID(claims)),
OwnerUserName: firstNonEmpty(p.OwnerUserName, resolveUserName(claims)),
Industry: strings.TrimSpace(p.Industry),
UpstreamAmount: upstream,
DownstreamAmount: downstream,
Amount: upstream,
Status: status,
StartDate: parsePipelineDate(p.StartDate),
EndDate: parsePipelineDate(p.EndDate),
UpstreamContact: upContact,
UpstreamPhone: upPhone,
DownstreamContact: downContact,
DownstreamPhone: downPhone,
ContactPerson: upContact,
ContactPhone: upPhone,
Address: strings.TrimSpace(p.Address),
Remark: p.Remark,
Products: p.Products,
CreateUserID: pipelineUID(claims),
CreateTime: now,
UpdateTime: now,
}
if crmProjectNameDuplicated(tenantID, proj.ProjectName, proj.CustomerID, proj.CustomerRefType) {
pipelineErr(&c.Controller, 409, 409, "该客户下已存在同名项目(可能由其他同事创建),如需继续跟进请联系管理员转移")
return
}
id, err := models.Orm.Insert(&proj)
if err != nil {
pipelineErr(&c.Controller, 500, 500, "创建失败: "+err.Error())
return
}
if strings.TrimSpace(p.Products) != "" {
var items []crmProductItem
if json.Unmarshal([]byte(p.Products), &items) == nil {
if _, _, serr := SyncProjectProducts(tenantID, uint64(id), proj.ProjectName, items); serr != nil {
_ = serr
}
}
}
if cid, err := services.EnsureCrmProjectDocCategory(claims.TenantId, uint64(id), proj.ProjectName, 0); err == nil {
proj.DocCategoryID = cid
}
crmWriteLog(tenantID, 3, uint64(id), "create", "创建项目:"+proj.ProjectName, claims)
pipelineOk(&c.Controller, map[string]interface{}{"id": id, "doc_category_id": proj.DocCategoryID})
}
func (c *BackendCrmProjectController) Update() {
claims, err := pipelineClaims(&c.Controller)
if err != nil {
code := identity.Status(err)
pipelineErr(&c.Controller, code, code, err.Error())
return
}
id, _ := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
if id == 0 {
pipelineErr(&c.Controller, 400, 400, "无效的ID")
return
}
raw, _ := io.ReadAll(c.Ctx.Request.Body)
var p projectPayload
if err := json.Unmarshal(raw, &p); err != nil {
pipelineErr(&c.Controller, 400, 400, "参数错误")
return
}
tenantID := pipelineTenantID(claims)
var proj models.TenantCrmProject
if err := models.Orm.QueryTable(new(models.TenantCrmProject)).
Filter("id", id).Filter("tenant_id", tenantID).
Filter("delete_time__isnull", true).One(&proj); err != nil {
pipelineErr(&c.Controller, 404, 404, "项目未找到")
return
}
if !canAccessCrmRecord(claims, proj.OwnerUserID, proj.CreateUserID) {
pipelineErr(&c.Controller, 403, 403, "无权操作该项目数据")
return
}
if strings.TrimSpace(p.ProjectName) == "" {
pipelineErr(&c.Controller, 400, 400, "项目名称不能为空")
return
}
proj.ProjectName = strings.TrimSpace(p.ProjectName)
proj.ProjectNo = strings.TrimSpace(p.ProjectNo)
if p.CustomerID > 0 {
cid, cref, cname := resolveProjectCustomer(tenantID, p.CustomerRefType, p.CustomerID, p.CustomerName)
proj.CustomerID = cid
proj.CustomerRefType = cref
proj.CustomerName = cname
} else if strings.TrimSpace(p.CustomerName) != "" {
proj.CustomerName = strings.TrimSpace(p.CustomerName)
}
if strings.TrimSpace(p.OwnerUserID) != "" {
proj.OwnerUserID = strings.TrimSpace(p.OwnerUserID)
}
if strings.TrimSpace(p.OwnerUserName) != "" {
proj.OwnerUserName = strings.TrimSpace(p.OwnerUserName)
}
proj.Industry = strings.TrimSpace(p.Industry)
pt, upstream, downstream, upContact, upPhone, downContact, downPhone := normalizeProjectFields(&p)
supplierID, supplierRefType, supplierName := resolveProjectSupplier(tenantID, p.SupplierRefType, p.SupplierID, p.SupplierName)
if pt == 1 {
supplierID, supplierRefType, supplierName = nil, 0, ""
}
proj.ProjectType = pt
proj.SupplierID = supplierID
proj.SupplierRefType = supplierRefType
proj.SupplierName = supplierName
proj.SupplierIndustry = strings.TrimSpace(p.SupplierIndustry)
proj.UpstreamAmount = upstream
proj.DownstreamAmount = downstream
proj.Amount = upstream
proj.UpstreamContact = upContact
proj.UpstreamPhone = upPhone
proj.DownstreamContact = downContact
proj.DownstreamPhone = downPhone
proj.ContactPerson = upContact
proj.ContactPhone = upPhone
prevStatus := proj.Status
if p.Status != 0 {
proj.Status = p.Status
}
proj.StartDate = parsePipelineDate(p.StartDate)
proj.EndDate = parsePipelineDate(p.EndDate)
proj.Address = strings.TrimSpace(p.Address)
proj.Remark = p.Remark
proj.Products = p.Products
proj.UpdateTime = time.Now()
statusChanged := p.Status != 0 && p.Status != prevStatus
reason := strings.TrimSpace(p.Reason)
if p.Status == 5 && prevStatus != 5 && reason == "" {
pipelineErr(&c.Controller, 400, 400, "请填写项目异常原因")
return
}
if _, err := models.Orm.Update(&proj); err != nil {
pipelineErr(&c.Controller, 500, 500, "更新失败: "+err.Error())
return
}
if strings.TrimSpace(p.Products) != "" {
var items []crmProductItem
if json.Unmarshal([]byte(p.Products), &items) == nil {
_, _, _ = SyncProjectProducts(tenantID, proj.ID, proj.ProjectName, items)
}
}
if proj.DocCategoryID > 0 {
_ = services.RenameCrmProjectDocCategory(claims.TenantId, proj.DocCategoryID, proj.ProjectName)
}
if statusChanged {
logText := "项目状态:" + projectStatusName(prevStatus) + " → " + projectStatusName(proj.Status)
if proj.Status == 5 && reason != "" {
logText += ";异常原因:" + reason
}
crmWriteLog(tenantID, 3, proj.ID, "status", logText, claims)
}
crmWriteLog(tenantID, 3, proj.ID, "update", "更新项目:"+proj.ProjectName, claims)
pipelineOk(&c.Controller, map[string]interface{}{"id": proj.ID})
}
func (c *BackendCrmProjectController) Delete() {
claims, err := pipelineClaims(&c.Controller)
if err != nil {
code := identity.Status(err)
pipelineErr(&c.Controller, code, code, err.Error())
return
}
id, _ := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
if id == 0 {
pipelineErr(&c.Controller, 400, 400, "无效的ID")
return
}
tenantID := pipelineTenantID(claims)
var proj models.TenantCrmProject
if err := models.Orm.QueryTable(new(models.TenantCrmProject)).
Filter("id", id).Filter("tenant_id", tenantID).
Filter("delete_time__isnull", true).One(&proj); err != nil {
pipelineErr(&c.Controller, 404, 404, "项目未找到")
return
}
if !canAccessCrmRecord(claims, proj.OwnerUserID, proj.CreateUserID) {
pipelineErr(&c.Controller, 403, 403, "无权操作该项目数据")
return
}
if !canDeleteCrmRecord(claims, proj.CreateUserID) {
pipelineErr(&c.Controller, 403, 403, "只有创建人、租户管理员或平台管理员可以删除该项目")
return
}
now := time.Now()
_, err = models.Orm.QueryTable(new(models.TenantCrmProject)).
Filter("id", id).Filter("tenant_id", tenantID).
Update(map[string]interface{}{"delete_time": now, "update_time": now})
if err != nil {
pipelineErr(&c.Controller, 500, 500, "删除失败: "+err.Error())
return
}
pipelineOk(&c.Controller, nil)
}
func contactIDsJSON(ids []uint64) string {
if len(ids) == 0 {
return ""
}
b, err := json.Marshal(ids)
if err != nil {
return ""
}
return string(b)
}
func filterCompanyContactIDs(tenantID string, companyType string, companyID *uint64, ids []uint64) []uint64 {
if companyID == nil || *companyID == 0 || len(ids) == 0 {
return nil
}
var rows []models.ErpCompanyContact
_, _ = 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)
allowed := make(map[uint64]bool, len(rows))
for _, r := range rows {
allowed[r.ID] = true
}
out := make([]uint64, 0, len(ids))
seen := make(map[uint64]bool, len(ids))
for _, id := range ids {
if id > 0 && allowed[id] && !seen[id] {
out = append(out, id)
seen[id] = true
}
}
return out
}
func (c *BackendCrmProjectController) SaveContacts() {
claims, err := pipelineClaims(&c.Controller)
if err != nil {
code := identity.Status(err)
pipelineErr(&c.Controller, code, code, err.Error())
return
}
id, _ := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
if id == 0 {
pipelineErr(&c.Controller, 400, 400, "无效的ID")
return
}
raw, _ := io.ReadAll(c.Ctx.Request.Body)
var p struct {
UpstreamContactIDs []uint64 `json:"upstream_contact_ids"`
DownstreamContactIDs []uint64 `json:"downstream_contact_ids"`
}
if err := json.Unmarshal(raw, &p); err != nil {
pipelineErr(&c.Controller, 400, 400, "参数错误")
return
}
tenantID := pipelineTenantID(claims)
var proj models.TenantCrmProject
if err := models.Orm.QueryTable(new(models.TenantCrmProject)).
Filter("id", id).Filter("tenant_id", tenantID).
Filter("delete_time__isnull", true).One(&proj); err != nil {
pipelineErr(&c.Controller, 404, 404, "项目未找到")
return
}
if !canAccessCrmRecord(claims, proj.OwnerUserID, proj.CreateUserID) {
pipelineErr(&c.Controller, 403, 403, "无权操作该项目数据")
return
}
pt := proj.ProjectType
if pt != 2 && pt != 3 {
pt = 1
}
upCompanyType := "customer"
if proj.CustomerRefType == 2 {
upCompanyType = "supplier"
}
upIDs := filterCompanyContactIDs(tenantID, upCompanyType, proj.CustomerID, p.UpstreamContactIDs)
var downIDs []uint64
if pt != 1 && proj.SupplierID != nil && *proj.SupplierID > 0 {
companyType := "supplier"
if proj.SupplierRefType == 1 {
companyType = "customer"
}
downIDs = filterCompanyContactIDs(tenantID, companyType, proj.SupplierID, p.DownstreamContactIDs)
}
now := time.Now()
_, err = models.Orm.QueryTable(new(models.TenantCrmProject)).
Filter("id", proj.ID).Filter("tenant_id", tenantID).
Update(map[string]interface{}{
"upstream_contact_ids": contactIDsJSON(upIDs),
"downstream_contact_ids": contactIDsJSON(downIDs),
"update_time": now,
})
if err != nil {
pipelineErr(&c.Controller, 500, 500, "保存项目联系人失败: "+err.Error())
return
}
crmWriteLog(tenantID, 3, proj.ID, "update", "更新项目联系人:"+proj.ProjectName, claims)
pipelineOk(&c.Controller, map[string]interface{}{
"upstream_contact_ids": upIDs,
"downstream_contact_ids": downIDs,
})
}
func (c *BackendCrmProjectController) ChangeStatus() {
claims, err := pipelineClaims(&c.Controller)
if err != nil {
code := identity.Status(err)
pipelineErr(&c.Controller, code, code, err.Error())
return
}
id, _ := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
if id == 0 {
pipelineErr(&c.Controller, 400, 400, "无效的ID")
return
}
raw, _ := io.ReadAll(c.Ctx.Request.Body)
var p struct {
Status int8 `json:"status"`
Reason string `json:"reason"`
}
if err := json.Unmarshal(raw, &p); err != nil {
pipelineErr(&c.Controller, 400, 400, "参数错误")
return
}
if p.Status < 1 || p.Status > 5 {
pipelineErr(&c.Controller, 400, 400, "无效的状态值")
return
}
reason := strings.TrimSpace(p.Reason)
if p.Status == 5 && reason == "" {
pipelineErr(&c.Controller, 400, 400, "请填写项目异常原因")
return
}
tenantID := pipelineTenantID(claims)
var proj models.TenantCrmProject
if err := models.Orm.QueryTable(new(models.TenantCrmProject)).
Filter("id", id).Filter("tenant_id", tenantID).
Filter("delete_time__isnull", true).One(&proj); err != nil {
pipelineErr(&c.Controller, 404, 404, "项目未找到")
return
}
if !canAccessCrmRecord(claims, proj.OwnerUserID, proj.CreateUserID) {
pipelineErr(&c.Controller, 403, 403, "无权操作该项目数据")
return
}
if proj.Status == p.Status {
pipelineOk(&c.Controller, map[string]interface{}{"id": proj.ID, "status": proj.Status})
return
}
if _, err := models.Orm.QueryTable(new(models.TenantCrmProject)).
Filter("id", id).Filter("tenant_id", tenantID).
Update(map[string]interface{}{"status": p.Status, "update_time": time.Now()}); err != nil {
pipelineErr(&c.Controller, 500, 500, "状态更新失败: "+err.Error())
return
}
logText := "项目状态流转:" + projectStatusName(proj.Status) + " → " + projectStatusName(p.Status)
if p.Status == 5 {
logText += ";异常原因:" + reason
}
crmWriteLog(tenantID, 3, proj.ID, "status", logText, claims)
pipelineOk(&c.Controller, map[string]interface{}{"id": proj.ID, "status": p.Status})
}
type projectDocItem struct {
models.OaDoc
FolderName string `json:"folder_name"`
}
func (c *BackendCrmProjectController) projectDocContext(claims *jwtutil.Claims) (*models.TenantCrmProject, uint64, bool) {
id, _ := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
if id == 0 {
pipelineErr(&c.Controller, 400, 400, "无效的ID")
return nil, 0, false
}
var proj models.TenantCrmProject
if err := models.Orm.QueryTable(new(models.TenantCrmProject)).
Filter("id", id).Filter("tenant_id", pipelineTenantID(claims)).
Filter("delete_time__isnull", true).One(&proj); err != nil {
pipelineErr(&c.Controller, 404, 404, "项目未找到")
return nil, 0, false
}
cid, err := services.EnsureCrmProjectDocCategory(claims.TenantId, proj.ID, proj.ProjectName, proj.DocCategoryID)
if err != nil || cid == 0 {
pipelineErr(&c.Controller, 500, 500, "项目文档文件夹准备失败")
return nil, 0, false
}
proj.DocCategoryID = cid
return &proj, cid, true
}
func (c *BackendCrmProjectController) DocList() {
claims, err := pipelineClaims(&c.Controller)
if err != nil {
code := identity.Status(err)
pipelineErr(&c.Controller, code, code, err.Error())
return
}
proj, cid, ok := c.projectDocContext(claims)
if !ok {
return
}
page, _ := c.GetInt("page", 1)
pageSize, _ := c.GetInt("pageSize", 20)
if page < 1 {
page = 1
}
if pageSize < 1 || pageSize > 200 {
pageSize = 20
}
actor := services.NewOaDocActor(claims.TenantId, uint64(claims.UserID))
filterCategory := cid
if v, _ := c.GetUint64("category_id"); v > 0 && services.CrmProjectDocCategoryInScope(actor, cid, v) {
filterCategory = v
}
list, total, err := services.OaDocList(actor, services.OaDocListParams{
Actor: actor,
Scope: models.DocScopeShared,
Keyword: strings.TrimSpace(c.GetString("keyword")),
CategoryID: filterCategory,
Status: -1,
DocType: -1,
Star: -1,
Page: page,
PageSize: pageSize,
})
if err != nil {
pipelineErr(&c.Controller, 500, 500, "查询失败: "+err.Error())
return
}
nameMap := services.CrmProjectDocCategoryNameMap(claims.TenantId)
items := make([]projectDocItem, 0, len(list))
for _, d := range list {
folder := nameMap[d.CategoryID]
if folder == "" {
folder = proj.ProjectName
}
items = append(items, projectDocItem{OaDoc: d, FolderName: folder})
}
folders, err := services.CrmProjectDocFolderTree(actor, cid)
if err != nil {
folders = []*services.ProjectDocFolder{}
}
pipelineOk(&c.Controller, map[string]interface{}{
"category_id": cid,
"category_name": proj.ProjectName,
"folders": folders,
"list": items,
"total": total,
"page": page,
"pageSize": pageSize,
})
}
func (c *BackendCrmProjectController) DocUpload() {
claims, err := pipelineClaims(&c.Controller)
if err != nil {
code := identity.Status(err)
pipelineErr(&c.Controller, code, code, err.Error())
return
}
proj, cid, ok := c.projectDocContext(claims)
if !ok {
return
}
var p struct {
FileID uint64 `json:"file_id"`
FileName string `json:"file_name"`
FileURL string `json:"file_url"`
FileSize int64 `json:"file_size"`
Ext string `json:"ext"`
Title string `json:"title"`
Summary string `json:"summary"`
CategoryID uint64 `json:"category_id"`
}
raw, _ := io.ReadAll(c.Ctx.Request.Body)
if err := json.Unmarshal(raw, &p); err != nil {
pipelineErr(&c.Controller, 400, 400, "参数错误")
return
}
fileName := strings.TrimSpace(p.FileName)
fileURL := strings.TrimSpace(p.FileURL)
if fileName == "" || fileURL == "" {
pipelineErr(&c.Controller, 400, 400, "文件信息不完整")
return
}
ext := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(p.Ext), "."))
if ext == "" {
ext = strings.ToLower(strings.TrimPrefix(filepath.Ext(fileName), "."))
}
var size uint64
if p.FileSize > 0 {
size = uint64(p.FileSize)
}
operatorName := resolveUserName(claims)
actor := services.NewOaDocActor(claims.TenantId, uint64(claims.UserID))
targetCategory := cid
if p.CategoryID > 0 {
if !services.CrmProjectDocCategoryInScope(actor, cid, p.CategoryID) {
pipelineErr(&c.Controller, 403, 403, "只能上传到项目自己的文件夹内")
return
}
targetCategory = p.CategoryID
}
doc, err := services.OaDocCreate(actor, operatorName, services.OaDocSaveParams{
SetCategory: true,
CategoryID: targetCategory,
SetVisibility: true,
Visibility: models.DocVisibilityPublic,
Title: strings.TrimSpace(p.Title),
FileID: p.FileID,
FileURL: fileURL,
FileName: fileName,
Ext: ext,
Size: size,
Summary: strings.TrimSpace(p.Summary),
Status: models.DocStatusPublish,
OwnerID: uint64(claims.UserID),
OwnerName: operatorName,
})
if err != nil {
pipelineErr(&c.Controller, 400, 400, "同步文档库失败: "+err.Error())
return
}
now := time.Now()
var fileIDPtr *uint64
if doc.FileID > 0 {
fid := doc.FileID
fileIDPtr = &fid
}
_, _ = models.Orm.Insert(&models.TenantCrmAttach{
TenantID: pipelineTenantID(claims),
RelatedType: 3,
RelatedID: proj.ID,
FileID: fileIDPtr,
FileName: doc.FileName,
FileURL: doc.FileURL,
FileSize: int64(doc.Size),
UploaderID: pipelineUID(claims),
UploaderName: operatorName,
CreateTime: now,
UpdateTime: now,
})
crmWriteLog(pipelineTenantID(claims), 3, proj.ID, "doc", "上传项目文档:"+doc.Title, claims)
pipelineOk(&c.Controller, doc)
}
func (c *BackendCrmProjectController) DocDelete() {
claims, err := pipelineClaims(&c.Controller)
if err != nil {
code := identity.Status(err)
pipelineErr(&c.Controller, code, code, err.Error())
return
}
proj, cid, ok := c.projectDocContext(claims)
if !ok {
return
}
var p struct {
DocID uint64 `json:"doc_id"`
}
raw, _ := io.ReadAll(c.Ctx.Request.Body)
if err := json.Unmarshal(raw, &p); err != nil || p.DocID == 0 {
pipelineErr(&c.Controller, 400, 400, "参数错误")
return
}
actor := services.NewOaDocActor(claims.TenantId, uint64(claims.UserID))
doc, err := services.OaDocGet(actor, p.DocID)
if err != nil {
pipelineErr(&c.Controller, 404, 404, "文档不存在")
return
}
if !services.CrmProjectDocCategoryInScope(actor, cid, doc.CategoryID) {
pipelineErr(&c.Controller, 403, 403, "该文档不属于当前项目")
return
}
if _, err := services.OaDocDelete(actor, []uint64{doc.ID}); err != nil {
pipelineErr(&c.Controller, 400, 400, err.Error())
return
}
now := time.Now()
q := models.Orm.QueryTable(new(models.TenantCrmAttach)).
Filter("tenant_id", pipelineTenantID(claims)).
Filter("related_type", 3).
Filter("related_id", proj.ID).
Filter("delete_time__isnull", true)
if doc.FileID > 0 {
q = q.Filter("file_id", doc.FileID)
} else {
q = q.Filter("file_name", doc.FileName).Filter("file_url", doc.FileURL)
}
_, _ = q.Update(map[string]interface{}{"delete_time": now, "update_time": now})
crmWriteLog(pipelineTenantID(claims), 3, proj.ID, "doc", "删除项目文档:"+doc.Title, claims)
pipelineOk(&c.Controller, nil)
}
func (c *BackendCrmProjectController) DocFolderCreate() {
claims, err := pipelineClaims(&c.Controller)
if err != nil {
code := identity.Status(err)
pipelineErr(&c.Controller, code, code, err.Error())
return
}
proj, cid, ok := c.projectDocContext(claims)
if !ok {
return
}
var p struct {
Name string `json:"name"`
ParentID uint64 `json:"parent_id"`
}
raw, _ := io.ReadAll(c.Ctx.Request.Body)
if err := json.Unmarshal(raw, &p); err != nil {
pipelineErr(&c.Controller, 400, 400, "参数错误")
return
}
name := strings.TrimSpace(p.Name)
if name == "" {
pipelineErr(&c.Controller, 400, 400, "请输入文件夹名称")
return
}
parentID := p.ParentID
if parentID == 0 {
parentID = cid
}
actor := services.NewOaDocActor(claims.TenantId, uint64(claims.UserID))
if !services.CrmProjectDocCategoryInScope(actor, cid, parentID) {
pipelineErr(&c.Controller, 403, 403, "只能在项目文件夹内创建子文件夹")
return
}
item, err := services.OaDocCategoryCreate(actor, models.DocScopeShared, parentID, name, "项目文档:"+proj.ProjectName, 0)
if err != nil {
pipelineErr(&c.Controller, 400, 400, err.Error())
return
}
crmWriteLog(pipelineTenantID(claims), 3, proj.ID, "doc-folder", "新建项目文档文件夹:"+item.Name, claims)
pipelineOk(&c.Controller, item)
}
func (c *BackendCrmProjectController) DocFolderDelete() {
claims, err := pipelineClaims(&c.Controller)
if err != nil {
code := identity.Status(err)
pipelineErr(&c.Controller, code, code, err.Error())
return
}
proj, cid, ok := c.projectDocContext(claims)
if !ok {
return
}
var p struct {
FolderID uint64 `json:"folder_id"`
}
raw, _ := io.ReadAll(c.Ctx.Request.Body)
if err := json.Unmarshal(raw, &p); err != nil || p.FolderID == 0 {
pipelineErr(&c.Controller, 400, 400, "参数错误")
return
}
if p.FolderID == cid {
pipelineErr(&c.Controller, 400, 400, "项目根文件夹不可删除")
return
}
actor := services.NewOaDocActor(claims.TenantId, uint64(claims.UserID))
if !services.CrmProjectDocCategoryInScope(actor, cid, p.FolderID) {
pipelineErr(&c.Controller, 403, 403, "该文件夹不属于当前项目")
return
}
var folder models.OaDocCategory
if err := models.Orm.QueryTable(new(models.OaDocCategory)).
Filter("tid", claims.TenantId).Filter("id", p.FolderID).
Filter("is_deleted", 0).One(&folder); err != nil {
pipelineErr(&c.Controller, 404, 404, "文件夹不存在")
return
}
if err := services.OaDocCategoryDelete(actor, p.FolderID); err != nil {
pipelineErr(&c.Controller, 400, 400, err.Error())
return
}
crmWriteLog(pipelineTenantID(claims), 3, proj.ID, "doc-folder", "删除项目文档文件夹:"+folder.Name, claims)
pipelineOk(&c.Controller, nil)
}