package controllers import ( "encoding/json" "fmt" "io" "math/rand" "strconv" "strings" "time" "server/models" "github.com/beego/beego/v2/client/orm" beego "github.com/beego/beego/v2/server/web" "server/pkg/identity" ) type BackendCrmContractController struct { beego.Controller } type contractSummary struct { HardwareAmount float64 `json:"hardware_amount"` SoftwareAmount float64 `json:"software_amount"` OtherAmount float64 `json:"other_amount"` TotalAmount float64 `json:"total_amount"` TotalCost float64 `json:"total_cost"` TotalProfit float64 `json:"total_profit"` } type contractPayload struct { ContractNo string `json:"contract_no"` ContractName string `json:"contract_name"` ContractCategory string `json:"contract_category"` OurRole *int8 `json:"our_role"` PartyCount int8 `json:"party_count"` ProjectID uint64 `json:"project_id"` ProjectName string `json:"project_name"` OwnerUserID string `json:"owner_user_id"` OwnerUserName string `json:"owner_user_name"` SignDate string `json:"sign_date"` EffectiveDate string `json:"effective_date"` ExpireDate string `json:"expire_date"` Parties json.RawMessage `json:"parties"` Products json.RawMessage `json:"products"` Step int8 `json:"step"` Status int8 `json:"status"` Remark string `json:"remark"` } type contractResp struct { models.TenantCrmContract Parties json.RawMessage `json:"parties"` Products json.RawMessage `json:"products"` Summary *contractSummary `json:"summary"` } func (c *BackendCrmContractController) 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")) ourRole := strings.TrimSpace(c.GetString("our_role")) category := strings.TrimSpace(c.GetString("contract_category")) projectType := strings.TrimSpace(c.GetString("project_type")) projectID := strings.TrimSpace(c.GetString("project_id")) status := strings.TrimSpace(c.GetString("status")) tenantID := pipelineTenantID(claims) cond := orm.NewCondition().And("tenant_id", tenantID).And("delete_time__isnull", true) cond = crmApplyOwnerScope(cond, claims) if keyword != "" { kw := orm.NewCondition(). Or("contract_name__contains", keyword). Or("contract_no__contains", keyword). Or("project_name__contains", keyword). Or("owner_user_name__contains", keyword). Or("parties__contains", keyword) cond = cond.AndCond(kw) } if ourRole != "" { cond = cond.And("our_role", ourRole) } if category != "" { cond = cond.And("contract_category", category) } if status != "" { cond = cond.And("status", status) } switch projectType { case "project": cond = cond.And("project_id__gt", 0) case "headless": cond = cond.And("project_id__isnull", true) } if projectID != "" { if pid, err := strconv.ParseUint(projectID, 10, 64); err == nil && pid > 0 { cond = cond.And("project_id", pid) } } period := strings.TrimSpace(c.GetString("period")) rangeStart := strings.TrimSpace(c.GetString("start_date")) rangeEnd := strings.TrimSpace(c.GetString("end_date")) if period != "" && period != "custom" { rangeStart, rangeEnd = periodRange(period) } if rangeStart != "" { cond = cond.AndCond(orm.NewCondition().Or("sign_date__isnull", true).Or("sign_date__gte", rangeStart)) } if rangeEnd != "" { cond = cond.AndCond(orm.NewCondition().Or("sign_date__isnull", true).Or("sign_date__lte", rangeEnd)) } qs := models.Orm.QueryTable(new(models.TenantCrmContract)).SetCond(cond) total, _ := qs.Count() var list []models.TenantCrmContract if total > 0 { if _, err := qs.OrderBy("-sign_date", "-id").Offset((page - 1) * pageSize).Limit(pageSize).All(&list); err != nil { pipelineErr(&c.Controller, 500, 500, "查询失败: "+err.Error()) return } } if len(list) > 0 { contractIDs := make([]uint64, 0, len(list)) for i := range list { contractIDs = append(contractIDs, list[i].ID) } overdues := paybackOverdueDateByContracts(tenantID, contractIDs) for i := range list { list[i].PaybackOverdueDate = overdues[list[i].ID] } } items := make([]contractResp, 0, len(list)) for i := range list { items = append(items, buildContractResp(&list[i])) } pipelineOk(&c.Controller, map[string]interface{}{ "list": items, "total": total, "page": page, "pageSize": pageSize, }) } func (c *BackendCrmContractController) Stats() { claims, err := pipelineClaims(&c.Controller) if err != nil { code := identity.Status(err) pipelineErr(&c.Controller, code, code, err.Error()) return } tenantID := pipelineTenantID(claims) period := strings.TrimSpace(c.GetString("period")) start := strings.TrimSpace(c.GetString("start_date")) end := strings.TrimSpace(c.GetString("end_date")) if period != "" && period != "custom" { start, end = periodRange(period) } table := new(models.TenantCrmContract).TableName() where := "tenant_id = ? AND delete_time IS NULL AND status <> 3 AND our_role <> 0" args := []interface{}{tenantID} if start != "" { where += " AND (sign_date IS NULL OR sign_date >= ?)" args = append(args, start) } if end != "" { where += " AND (sign_date IS NULL OR sign_date <= ?)" args = append(args, end) } raw := "SELECT COUNT(*) AS total, IFNULL(SUM(total_amount),0) AS total_amount, " + "IFNULL(SUM(total_cost),0) AS total_cost, " + "IFNULL(SUM(CASE WHEN our_role <> 1 THEN total_profit ELSE 0 END),0) AS total_profit " + "FROM " + table + " WHERE " + where var rows []orm.Params if _, err := models.Orm.Raw(raw, args...).Values(&rows); err != nil || len(rows) == 0 { pipelineOk(&c.Controller, map[string]interface{}{ "total": 0, "total_amount": 0, "total_cost": 0, "total_profit": 0, }) return } r := rows[0] pipelineOk(&c.Controller, map[string]interface{}{ "total": toInt64(r["total"]), "total_amount": toFloat64(r["total_amount"]), "total_cost": toFloat64(r["total_cost"]), "total_profit": toFloat64(r["total_profit"]), }) } func periodRange(period string) (string, string) { now := time.Now() loc := now.Location() y, m, _ := now.Date() switch period { case "quarter": q := (int(m) - 1) / 3 start := time.Date(y, time.Month(q*3+1), 1, 0, 0, 0, 0, loc) end := start.AddDate(0, 3, 0).Add(-time.Nanosecond) return start.Format("2006-01-02"), end.Format("2006-01-02") case "year": start := time.Date(y, 1, 1, 0, 0, 0, 0, loc) end := start.AddDate(1, 0, 0).Add(-time.Nanosecond) return start.Format("2006-01-02"), end.Format("2006-01-02") default: start := time.Date(y, m, 1, 0, 0, 0, 0, loc) end := start.AddDate(0, 1, 0).Add(-time.Nanosecond) return start.Format("2006-01-02"), end.Format("2006-01-02") } } func (c *BackendCrmContractController) 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 row models.TenantCrmContract if err := models.Orm.QueryTable(new(models.TenantCrmContract)). Filter("id", id).Filter("tenant_id", pipelineTenantID(claims)). Filter("delete_time__isnull", true).One(&row); err != nil { pipelineErr(&c.Controller, 404, 404, "合同未找到") return } if !canAccessCrmRecord(claims, row.OwnerUserID, row.CreateUserID) { pipelineErr(&c.Controller, 403, 403, "无权查看该合同数据") return } if od := paybackOverdueDateByContracts(pipelineTenantID(claims), []uint64{row.ID}); od[row.ID] != "" { row.PaybackOverdueDate = od[row.ID] } pipelineOk(&c.Controller, buildContractResp(&row)) } func (c *BackendCrmContractController) 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 contractPayload if err := json.Unmarshal(raw, &p); err != nil { pipelineErr(&c.Controller, 400, 400, "参数错误") return } if strings.TrimSpace(p.ContractName) == "" { pipelineErr(&c.Controller, 400, 400, "合同名称不能为空") return } tenantID := pipelineTenantID(claims) now := time.Now() ourRole := int8(2) if p.OurRole != nil { ourRole = *p.OurRole } row := models.TenantCrmContract{ TenantID: tenantID, ContractNo: strings.TrimSpace(p.ContractNo), ContractName: strings.TrimSpace(p.ContractName), OurRole: normalizeOurRole(ourRole), PartyCount: pickInt8(p.PartyCount, 2, 4), OwnerUserID: firstNonEmpty(p.OwnerUserID, pipelineUID(claims)), OwnerUserName: firstNonEmpty(p.OwnerUserName, resolveUserName(claims)), SignDate: parsePipelineDate(p.SignDate), EffectiveDate: parsePipelineDate(p.EffectiveDate), ExpireDate: parsePipelineDate(p.ExpireDate), Status: pickInt8(p.Status, 1, 5), Step: pickInt8(p.Step, 1, 2), Remark: p.Remark, CreateUserID: pipelineUID(claims), CreateTime: now, UpdateTime: now, } if strings.TrimSpace(p.ContractCategory) != "" { row.ContractCategory = strings.TrimSpace(p.ContractCategory) } if row.ContractNo == "" { row.ContractNo = genContractNo(tenantID) } if p.ProjectID > 0 { projID, projName, ok := c.resolveProject(tenantID, p.ProjectID) if !ok { pipelineErr(&c.Controller, 400, 400, "关联项目不存在") return } row.ProjectID = &projID row.ProjectName = projName } parties, err := normalizeContractJSON(p.Parties) if err != nil { pipelineErr(&c.Controller, 400, 400, "参与方数据格式错误") return } row.Parties = parties products, err := normalizeContractJSON(p.Products) if err != nil { pipelineErr(&c.Controller, 400, 400, "产品清单数据格式错误") return } row.Products = products projID := uint64(0) if row.ProjectID != nil { projID = *row.ProjectID } if synced, serr := SyncContractProducts(tenantID, pipelineUID(claims), projID, row.ProjectName, json.RawMessage(products)); serr == nil { row.Products = string(synced) } applyContractAmounts(&row) if crmContractDuplicated(tenantID, row.ContractName, row.Parties) { pipelineErr(&c.Controller, 409, 409, "已存在同名且签约方相同的合同(可能由其他同事创建),如需继续跟进请联系管理员转移") return } if _, err := models.Orm.Insert(&row); err != nil { pipelineErr(&c.Controller, 500, 500, "创建失败: "+err.Error()) return } syncContractPartyContacts(tenantID, row.Parties) crmWriteLog(tenantID, 6, row.ID, "create", "创建合同:"+row.ContractName, claims) pipelineOk(&c.Controller, map[string]interface{}{"id": row.ID}) } func (c *BackendCrmContractController) 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 contractPayload if err := json.Unmarshal(raw, &p); err != nil { pipelineErr(&c.Controller, 400, 400, "参数错误") return } tenantID := pipelineTenantID(claims) var row models.TenantCrmContract if err := models.Orm.QueryTable(new(models.TenantCrmContract)). Filter("id", id).Filter("tenant_id", tenantID). Filter("delete_time__isnull", true).One(&row); err != nil { pipelineErr(&c.Controller, 404, 404, "合同未找到") return } if !canAccessCrmRecord(claims, row.OwnerUserID, row.CreateUserID) { pipelineErr(&c.Controller, 403, 403, "无权操作该合同数据") return } if strings.TrimSpace(p.ContractName) == "" { pipelineErr(&c.Controller, 400, 400, "合同名称不能为空") return } row.ContractName = strings.TrimSpace(p.ContractName) if no := strings.TrimSpace(p.ContractNo); no != "" { row.ContractNo = no } if strings.TrimSpace(p.ContractCategory) != "" { row.ContractCategory = strings.TrimSpace(p.ContractCategory) } if p.OurRole != nil { row.OurRole = normalizeOurRole(*p.OurRole) } if p.PartyCount != 0 { row.PartyCount = p.PartyCount } if p.ProjectID > 0 { projID, projName, ok := c.resolveProject(tenantID, p.ProjectID) if !ok { pipelineErr(&c.Controller, 400, 400, "关联项目不存在") return } row.ProjectID = &projID row.ProjectName = projName } else { row.ProjectID = nil row.ProjectName = "" } if strings.TrimSpace(p.OwnerUserID) != "" { row.OwnerUserID = strings.TrimSpace(p.OwnerUserID) } if strings.TrimSpace(p.OwnerUserName) != "" { row.OwnerUserName = strings.TrimSpace(p.OwnerUserName) } row.SignDate = parsePipelineDate(p.SignDate) row.EffectiveDate = parsePipelineDate(p.EffectiveDate) row.ExpireDate = parsePipelineDate(p.ExpireDate) if p.Parties != nil { parties, err := normalizeContractJSON(p.Parties) if err != nil { pipelineErr(&c.Controller, 400, 400, "参与方数据格式错误") return } row.Parties = parties } if p.Products != nil { products, err := normalizeContractJSON(p.Products) if err != nil { pipelineErr(&c.Controller, 400, 400, "产品清单数据格式错误") return } row.Products = products projID := uint64(0) if row.ProjectID != nil { projID = *row.ProjectID } if synced, serr := SyncContractProducts(tenantID, pipelineUID(claims), projID, row.ProjectName, json.RawMessage(products)); serr == nil { row.Products = string(synced) } } applyContractAmounts(&row) if p.Step != 0 { row.Step = p.Step } row.Remark = p.Remark row.UpdateTime = time.Now() if _, err := models.Orm.Update(&row); err != nil { pipelineErr(&c.Controller, 500, 500, "更新失败: "+err.Error()) return } syncContractPartyContacts(tenantID, row.Parties) crmWriteLog(tenantID, 6, row.ID, "update", "更新合同:"+row.ContractName, claims) pipelineOk(&c.Controller, map[string]interface{}{"id": row.ID}) } func (c *BackendCrmContractController) 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 row models.TenantCrmContract if err := models.Orm.QueryTable(new(models.TenantCrmContract)). Filter("id", id).Filter("tenant_id", tenantID). Filter("delete_time__isnull", true).One(&row); err != nil { pipelineErr(&c.Controller, 404, 404, "合同未找到") return } if !canAccessCrmRecord(claims, row.OwnerUserID, row.CreateUserID) { pipelineErr(&c.Controller, 403, 403, "无权操作该合同数据") return } if !canDeleteCrmRecord(claims, row.CreateUserID) { pipelineErr(&c.Controller, 403, 403, "只有创建人、租户管理员或平台管理员可以删除该合同") return } now := time.Now() _, err = models.Orm.QueryTable(new(models.TenantCrmContract)). 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 (c *BackendCrmContractController) 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"` } if err := json.Unmarshal(raw, &p); err != nil { pipelineErr(&c.Controller, 400, 400, "参数错误") return } if p.Status < 2 || p.Status > 5 { pipelineErr(&c.Controller, 400, 400, "无效的状态值") return } tenantID := pipelineTenantID(claims) var row models.TenantCrmContract if err := models.Orm.QueryTable(new(models.TenantCrmContract)). Filter("id", id).Filter("tenant_id", tenantID). Filter("delete_time__isnull", true).One(&row); err != nil { pipelineErr(&c.Controller, 404, 404, "合同未找到") return } if !canAccessCrmRecord(claims, row.OwnerUserID, row.CreateUserID) { pipelineErr(&c.Controller, 403, 403, "无权操作该合同数据") return } if row.Status == p.Status { pipelineOk(&c.Controller, map[string]interface{}{"id": row.ID, "status": row.Status}) return } if _, err := models.Orm.QueryTable(new(models.TenantCrmContract)). 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 } crmWriteLog(tenantID, 6, row.ID, "status", fmt.Sprintf("合同状态流转:%s → %s", contractStatusName(row.Status), contractStatusName(p.Status)), claims) pipelineOk(&c.Controller, map[string]interface{}{"id": row.ID, "status": p.Status}) } func contractStatusName(s int8) string { switch s { case 1: return "草稿" case 2: return "已完成" case 3: return "已作废" case 4: return "履约中" case 5: return "异常" default: return "未知" } } func buildContractResp(row *models.TenantCrmContract) contractResp { parties := json.RawMessage("[]") if strings.TrimSpace(row.Parties) != "" { parties = json.RawMessage(row.Parties) } products := json.RawMessage("[]") if strings.TrimSpace(row.Products) != "" { products = json.RawMessage(row.Products) } if strings.TrimSpace(row.Products) != "" && string(products) != "[]" { applyContractAmounts(row) } return contractResp{ TenantCrmContract: *row, Parties: parties, Products: products, Summary: &contractSummary{ HardwareAmount: row.HardwareAmount, SoftwareAmount: row.SoftwareAmount, OtherAmount: row.OtherAmount, TotalAmount: row.TotalAmount, TotalCost: row.TotalCost, TotalProfit: row.TotalProfit, }, } } func syncContractPartyContacts(tenantID, partiesJSON string) { partiesJSON = strings.TrimSpace(partiesJSON) if models.Orm == nil || partiesJSON == "" || partiesJSON == "[]" { return } var parties []struct { RefType int `json:"ref_type"` RefID uint64 `json:"ref_id"` SignerName string `json:"signer_name"` SignerPhone string `json:"signer_phone"` } if err := json.Unmarshal([]byte(partiesJSON), &parties); err != nil { return } for _, p := range parties { if p.RefID == 0 || (p.RefType != 1 && p.RefType != 2) { continue } name := strings.TrimSpace(p.SignerName) if name == "" { continue } companyType := crmContactCompanyType(p.RefType) if !crmContactCompanyExists(tenantID, companyType, p.RefID) { continue } crmEnsureCompanyContact(tenantID, companyType, p.RefID, name, strings.TrimSpace(p.SignerPhone)) } } func (c *BackendCrmContractController) resolveProject(tenantID string, projectID uint64) (uint64, string, bool) { var proj models.TenantCrmProject if err := models.Orm.QueryTable(new(models.TenantCrmProject)). Filter("id", projectID).Filter("tenant_id", tenantID). Filter("delete_time__isnull", true).One(&proj); err != nil { return 0, "", false } return proj.ID, proj.ProjectName, true } func normalizeContractJSON(raw json.RawMessage) (string, error) { if len(raw) == 0 || strings.TrimSpace(string(raw)) == "" || strings.TrimSpace(string(raw)) == "null" { return "[]", nil } var arr []map[string]interface{} if err := json.Unmarshal(raw, &arr); err != nil { return "", err } out, err := json.Marshal(arr) if err != nil { return "", err } return string(out), nil } func contractTreeSellTotal(nodes []interface{}, unitPrice float64) float64 { var sum float64 for _, n := range nodes { m, ok := n.(map[string]interface{}) if !ok { continue } if kids, ok := m["children"].([]interface{}); ok && len(kids) > 0 { sum += contractTreeSellTotal(kids, unitPrice) continue } sum += round2(toFloat64(m["man_days"]) * unitPrice) } return round2(sum) } func applyContractAmounts(row *models.TenantCrmContract) { var items []map[string]interface{} if strings.TrimSpace(row.Products) != "" { _ = json.Unmarshal([]byte(row.Products), &items) } var hardware, software, other, cost float64 for _, item := range items { if fmt.Sprintf("%v", item["line_type"]) == "dev" { qty := toFloat64(item["quantity"]) if qty <= 0 { qty = 1 } total := toFloat64(item["dev_total_price"]) if total <= 0 { if tree, ok := item["dev_tree"].([]interface{}); ok { total = contractTreeSellTotal(tree, toFloat64(item["dev_unit_price"])) } } costPrice := toFloat64(item["cost_price"]) if costPrice <= 0 { costPrice = total } price := toFloat64(item["price"]) if price <= 0 { price = total } software = round2(software + round2(qty*price)) cost = round2(cost + round2(qty*costPrice)) continue } qty := toFloat64(item["quantity"]) price := toFloat64(item["price"]) costPrice := toFloat64(item["cost_price"]) amount := round2(qty * price) cost = round2(cost + round2(qty*costPrice)) cat := fmt.Sprintf("%v", item["category"]) switch { case cat == "1" || strings.Contains(cat, "硬件"): hardware = round2(hardware + amount) case cat == "2" || strings.Contains(cat, "软件"): software = round2(software + amount) default: other = round2(other + amount) } } row.HardwareAmount = hardware row.SoftwareAmount = software row.OtherAmount = other row.TotalAmount = round2(hardware + software + other) row.TotalCost = cost row.TotalProfit = round2(row.TotalAmount - cost) } func contractReceivedAmount(tenantID string, contractID uint64) float64 { if contractID == 0 { return 0 } var rows []orm.Params sql := "SELECT IFNULL(SUM(received_amount),0) AS received FROM " + new(models.TenantCrmPayback).TableName() + " WHERE tenant_id = ? AND contract_id = ? AND delete_time IS NULL" if _, err := models.Orm.Raw(sql, tenantID, contractID).Values(&rows); err != nil || len(rows) == 0 { return 0 } return toFloat64(rows[0]["received"]) } func crmContractDuplicated(tenantID, name, partiesJSON string) bool { name = strings.TrimSpace(name) if name == "" || strings.TrimSpace(tenantID) == "" || models.Orm == nil { return false } sig := contractPartiesSignature(partiesJSON) var rows []models.TenantCrmContract _, err := models.Orm.QueryTable(new(models.TenantCrmContract)). Filter("tenant_id", tenantID). Filter("delete_time__isnull", true). Filter("contract_name", name). All(&rows, "id", "parties") if err != nil { return false } for i := range rows { if contractPartiesSignature(rows[i].Parties) == sig { return true } } return false } func contractPartiesSignature(partiesJSON string) string { if strings.TrimSpace(partiesJSON) == "" { return "" } var parties []map[string]interface{} if err := json.Unmarshal([]byte(partiesJSON), &parties); err != nil { return "" } str := func(v interface{}) string { if v == nil { return "" } return strings.TrimSpace(fmt.Sprintf("%v", v)) } byRole := make(map[string]string, len(parties)) for _, p := range parties { role := str(p["role"]) if role == "" { continue } subject := str(p["ref_id"]) if subject == "" || subject == "0" { subject = str(p["ref_name"]) } byRole[role] = str(p["ref_type"]) + "|" + subject } var sb strings.Builder for _, role := range []string{"party_a", "party_b", "party_c", "party_d"} { if v, ok := byRole[role]; ok { sb.WriteString(role) sb.WriteString(":") sb.WriteString(v) sb.WriteString(";") } } return sb.String() } func genContractNo(tenantID string) string { for i := 0; i < 5; i++ { no := fmt.Sprintf("HT-%s-%04d", time.Now().Format("20060102"), rand.Intn(10000)) count, _ := models.Orm.QueryTable(new(models.TenantCrmContract)). Filter("tenant_id", tenantID).Filter("contract_no", no). Filter("delete_time__isnull", true).Count() if count == 0 { return no } } return fmt.Sprintf("HT-%s-%d", time.Now().Format("20060102"), time.Now().UnixNano()%100000) } func normalizeOurRole(v int8) int8 { if v == 0 { return 0 } return pickInt8(v, 2, 4) } func pickInt8(v, def, max int8) int8 { if v >= 1 && v <= max { return v } return def } func round2(n float64) float64 { return float64(int64((n+1e-9)*100+0.5)) / 100 } func toInt64(v interface{}) int64 { switch n := v.(type) { case int64: return n case []byte: x, _ := strconv.ParseInt(strings.TrimSpace(string(n)), 10, 64) return x case string: x, _ := strconv.ParseInt(strings.TrimSpace(n), 10, 64) return x } return 0 } func toFloat64(v interface{}) float64 { switch n := v.(type) { case float64: return n case int64: return float64(n) case []byte: x, _ := strconv.ParseFloat(strings.TrimSpace(string(n)), 64) return x case string: x, _ := strconv.ParseFloat(strings.TrimSpace(n), 64) return x } return 0 }