business.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. package proj
  2. import (
  3. "context"
  4. platDao "dashoo.cn/micro/app/dao/plat"
  5. "dashoo.cn/micro/app/dao/work"
  6. "github.com/gogf/gf/container/garray"
  7. "os"
  8. contractDao "dashoo.cn/micro/app/dao/contract"
  9. custDao "dashoo.cn/micro/app/dao/cust"
  10. projDao "dashoo.cn/micro/app/dao/proj"
  11. contractModel "dashoo.cn/micro/app/model/contract"
  12. model "dashoo.cn/micro/app/model/proj"
  13. workflowModel "dashoo.cn/micro/app/model/workflow"
  14. workflowService "dashoo.cn/micro/app/service/workflow"
  15. "dashoo.cn/opms_libary/plugin/dingtalk"
  16. "fmt"
  17. "strconv"
  18. "strings"
  19. "dashoo.cn/micro/app/service"
  20. "dashoo.cn/opms_libary/multipart"
  21. "dashoo.cn/opms_libary/myerrors"
  22. "dashoo.cn/opms_libary/plugin/dingtalk/message"
  23. "dashoo.cn/opms_libary/utils"
  24. "github.com/gogf/gf/database/gdb"
  25. "github.com/gogf/gf/frame/g"
  26. "github.com/gogf/gf/os/gtime"
  27. "github.com/gogf/gf/util/gconv"
  28. "github.com/shopspring/decimal"
  29. )
  30. type businessService struct {
  31. *service.ContextService
  32. Dao *projDao.ProjBusinessDao
  33. ContactDao *projDao.ProjBusinessContactDao
  34. FollowDao *platDao.PlatFollowupDao
  35. fileDao *projDao.ProjBusinessFileDao
  36. WorkTypeDao *work.WorkOrderTypeDao
  37. }
  38. func NewBusinessService(ctx context.Context) (svc *businessService, err error) {
  39. svc = new(businessService)
  40. if svc.ContextService, err = svc.Init(ctx); err != nil {
  41. return nil, err
  42. }
  43. svc.Dao = projDao.NewProjBusinessDao(svc.Tenant)
  44. svc.ContactDao = projDao.NewProjBusinessContactDao(svc.Tenant)
  45. svc.FollowDao = platDao.NewPlatFollowupDao(svc.Tenant)
  46. svc.fileDao = projDao.NewProjBusinessFileDao(svc.Tenant)
  47. svc.WorkTypeDao = work.NewWorkOrderTypeDao(svc.Tenant)
  48. return svc, nil
  49. }
  50. func (p *businessService) GetList(req *model.ProjBusinessSearchReq) (total int, businessList []*model.ProjBusinessRes, err error) {
  51. db := p.Dao.As("proj").DataScope(p.Ctx, "sale_id")
  52. if req.NboName != "" {
  53. db = db.WhereLike("proj."+p.Dao.C.NboName, "%"+req.NboName+"%")
  54. }
  55. if req.CustId != 0 { // 客户-项目记录 查看已删除的项目记录
  56. db = db.Where("proj."+p.Dao.C.CustId, req.CustId).Unscoped()
  57. }
  58. if req.CustName != "" {
  59. db = db.WhereLike("proj."+p.Dao.C.CustName, "%"+req.CustName+"%")
  60. }
  61. if req.SaleName != "" {
  62. db = db.WhereLike("proj."+p.Dao.C.SaleName, "%"+req.SaleName+"%")
  63. }
  64. if req.NboType != "" {
  65. db = db.Where("proj."+p.Dao.C.NboType, req.NboType)
  66. }
  67. if req.ProductLine != "" {
  68. db = db.Where("proj."+p.Dao.C.ProductLine, req.ProductLine)
  69. }
  70. if req.NboSource != "" {
  71. db = db.Where("proj."+p.Dao.C.NboSource, req.NboSource)
  72. }
  73. if req.DistributorName != "" {
  74. db = db.WhereLike("proj."+p.Dao.C.DistributorName, "%"+req.DistributorName+"%")
  75. }
  76. if req.BeginTime != "" {
  77. db = db.WhereGTE("proj."+p.Dao.C.FilingTime, req.BeginTime)
  78. }
  79. if req.EndTime != "" {
  80. db = db.WhereLTE("proj."+p.Dao.C.FilingTime, req.EndTime)
  81. }
  82. if req.ProvinceId != 0 {
  83. db = db.Where("proj."+p.Dao.C.CustProvinceId, req.ProvinceId)
  84. }
  85. total, err = db.Count()
  86. if err != nil {
  87. err = myerrors.DbError("获取总行数失败。")
  88. return
  89. }
  90. if req.NboType == StatusDeal {
  91. db = db.Unscoped().WhereNull(`proj.deleted_time`).
  92. LeftJoin(contractDao.CtrContract.Table, "contract", "`proj`.id=`contract`.nbo_id AND `contract`.`deleted_time` IS NULL ").
  93. Fields("`proj`.cust_city_id as cust_city_id,`contract`.contract_amount, `contract`.created_time as proj_closing_time")
  94. }
  95. db = db.Fields("`proj`.*")
  96. err = db.Page(req.GetPage()).OrderDesc("id").Scan(&businessList)
  97. return
  98. }
  99. func (p *businessService) GetEntityById(id int64) (business *model.ProjBusinessRes, err error) {
  100. err = p.Dao.Where(projDao.ProjBusiness.C.Id, id).Scan(&business)
  101. if err != nil {
  102. return nil, err
  103. }
  104. if business == nil {
  105. return nil, myerrors.TipsError("项目不存在")
  106. }
  107. return
  108. }
  109. func (p *businessService) GetBusinessInfoById(id int64) (business *model.ProjBusinessRes, err error) {
  110. err = p.Dao.Where(projDao.ProjBusiness.C.Id, id).Scan(&business)
  111. if err != nil {
  112. return nil, err
  113. }
  114. if business == nil {
  115. return nil, myerrors.TipsError("项目不存在")
  116. }
  117. business.FollowCount, err = p.FollowDao.Where(p.FollowDao.C.TargetType, "20").Where(p.FollowDao.C.TargetId, business.Id).Count()
  118. if err != nil {
  119. return nil, err
  120. }
  121. productList, err := p.GetBusinessProduct(id)
  122. if err != nil {
  123. return nil, err
  124. }
  125. if err := gconv.Structs(productList, &business.Products); err != nil {
  126. return nil, err
  127. }
  128. files, err := p.fileDao.Where(p.fileDao.C.BusId, id).WhereLike(p.fileDao.C.FileSource, "%报价单%").OrderDesc(p.fileDao.C.Id).Limit(1).All()
  129. if err != nil {
  130. return nil, err
  131. }
  132. business.QuotationFileList = files
  133. return
  134. }
  135. func (p *businessService) GetBusinessProduct(id int64) (productList []*model.ProjBusinessProduct, err error) {
  136. productDao := projDao.NewProjBusinessProductDao(p.Tenant)
  137. err = productDao.Where(productDao.ProjBusinessProductDao.C.BusId, id).Scan(&productList)
  138. return
  139. }
  140. func (p *businessService) GetBusinessDynamics(req *model.BusinessReq) (total int, result g.MapStrAny, err error) {
  141. result = make(g.MapStrAny, 0)
  142. dynamicsDao := projDao.NewProjBusinessDynamicsDao(p.Tenant).ProjBusinessDynamicsDao.Where(projDao.ProjBusinessDynamics.C.BusId, req.BusId)
  143. total, err = dynamicsDao.Count()
  144. if err != nil {
  145. g.Log().Error(err)
  146. return
  147. }
  148. dynamicsList, err := dynamicsDao.Page(req.GetPage()).Order("created_time desc").All()
  149. if err != nil || dynamicsList == nil {
  150. return
  151. }
  152. // 数据树格式转换
  153. opnDateFlag := gtime.New(dynamicsList[0].OpnDate).Format("Y-m-d")
  154. for k, v := range dynamicsList {
  155. opnDate := gtime.New(v.OpnDate).Format("Y-m-d")
  156. if opnDateFlag == opnDate && k != 0 {
  157. result[opnDate] = append(result[opnDate].(g.ListStrAny), g.Map{
  158. "opnPeople": v.OpnPeople,
  159. "opnDate": v.OpnDate,
  160. "opnType": v.OpnType,
  161. "remark": v.Remark,
  162. "opnContent": gconv.Map(v.OpnContent),
  163. })
  164. } else {
  165. temp := make(g.ListStrAny, 0)
  166. temp = append(temp, g.Map{
  167. "opnPeople": v.OpnPeople,
  168. "opnDate": v.OpnDate,
  169. "opnType": v.OpnType,
  170. "remark": v.Remark,
  171. "opnContent": gconv.Map(v.OpnContent),
  172. })
  173. result[opnDate] = temp
  174. opnDateFlag = opnDate
  175. }
  176. }
  177. return
  178. }
  179. func (p *businessService) GetBusinessDynamicsList(req *model.BusinessDynamicsReq) (total int, list []map[string]interface{}, err error) {
  180. dynamicsDao := projDao.NewProjBusinessDynamicsDao(p.Tenant).Where(projDao.ProjBusinessDynamics.C.BusId, req.BusId)
  181. if req.OpnType != "" {
  182. dynamicsDao = dynamicsDao.Where(projDao.ProjBusinessDynamics.C.OpnType+" = ?", req.OpnType)
  183. }
  184. total, err = dynamicsDao.Count()
  185. if err != nil {
  186. g.Log().Error(err)
  187. return
  188. }
  189. dynamicsList, err := dynamicsDao.Page(req.GetPage()).Order("created_time desc").All()
  190. for _, v := range dynamicsList {
  191. val := gconv.Map(v)
  192. val["opnContent"] = gconv.Map(v.OpnContent)
  193. list = append(list, val)
  194. }
  195. return
  196. }
  197. // 获取项目编号
  198. func (p *businessService) getNboCode(customerCode string) (string, error) {
  199. sequence, err := service.Sequence(p.Dao.DB, "nbo_code")
  200. if err != nil {
  201. return "", err
  202. }
  203. return customerCode + sequence, nil
  204. }
  205. func (p *businessService) Create(req *model.AddProjBusinessReq) (err error) {
  206. // 获取客户信息
  207. customer, err := custDao.NewCustCustomerDao(p.Tenant).WherePri(req.CustId).One()
  208. if err != nil {
  209. return err
  210. }
  211. if customer == nil {
  212. return myerrors.TipsError("客户不存在")
  213. }
  214. // 获取项目编号
  215. nboCode, err := p.getNboCode(customer.CustCode)
  216. if err != nil {
  217. return err
  218. }
  219. // 初始化项目信息
  220. business := new(model.ProjBusiness)
  221. if err = gconv.Struct(req, business); err != nil {
  222. return
  223. }
  224. business.NboCode = nboCode
  225. if business.NboType == "" {
  226. business.NboType = StatusC
  227. }
  228. business.ApproStatus = ApprovalWaiting
  229. business.CustProvinceId = customer.CustProvinceId
  230. business.CustProvince = customer.CustProvince
  231. business.CustCityId = customer.CustCityId
  232. business.CustCity = customer.CustCity
  233. business.CustRegionId = customer.CustRegionId
  234. business.CustRegion = customer.CustRegion
  235. business.DeptId = p.GetCxtUserDeptId()
  236. service.SetCreatedInfo(business, p.GetCxtUserId(), p.GetCxtUserName())
  237. business.FilingTime = business.CreatedTime
  238. productLine, _ := service.GetDictLabelByTypeAndValue(p.Ctx, "sys_product_line", business.ProductLine)
  239. nboSource, _ := service.GetDictLabelByTypeAndValue(p.Ctx, "proj_nbo_source", business.NboSource)
  240. salesModel, _ := service.GetDictLabelByTypeAndValue(p.Ctx, "proj_sales_model", business.SalesModel)
  241. // 事务
  242. err = p.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  243. // 添加项目
  244. lastId, err := p.Dao.TX(tx).InsertAndGetId(business)
  245. if err != nil {
  246. return err
  247. }
  248. // 添加项目动态
  249. dynamics := model.ProjBusinessDynamics{
  250. BusId: int(lastId),
  251. OpnType: OpnCreate,
  252. Remark: business.Remark,
  253. }
  254. _, err = p.CreateProjBusinessDynamics(tx, dynamics, business)
  255. // 审批流
  256. workflowSrv, _ := workflowService.NewFlowService(p.Ctx)
  257. // OMS项目创建 审批
  258. bizCode := business.NboCode + ":" + gconv.String(lastId)
  259. business.ApproType = BusinessCreateRequestProcessCode
  260. applyData := gconv.Map(business)
  261. applyData["abstract"] = fmt.Sprintf("销售:%v 根据客户:%v 创建项目:%v", business.SaleName, business.CustName, business.NboName)
  262. applyData["productLine"] = productLine
  263. applyData["nboSource"] = nboSource
  264. applyData["salesModel"] = salesModel
  265. applyData["isBig"] = yesOrNoType[business.IsBig]
  266. applyData["bidInfo"] = req.BidInfo
  267. applyData["productList"] = []map[string]string{{
  268. "prodName": "req.prodName",
  269. "prodCode": "req.prodCode",
  270. "prodClass": "req.prodClass",
  271. "prodNum": "1",
  272. "prodPrice": "1",
  273. }, {
  274. "prodName": "req.prodName",
  275. "prodCode": "req.prodCode",
  276. "prodClass": "req.prodClass",
  277. "prodNum": "2.2",
  278. "prodPrice": "2.2",
  279. }}
  280. instanceId, err := workflowSrv.CheckStartProcessInstance(bizCode, workflowModel.ProjectCreate, "", applyData)
  281. if err != nil {
  282. g.Log().Error(err)
  283. return err
  284. }
  285. // 更新项目审批信息
  286. _, err = p.Dao.TX(tx).Where(p.Dao.C.Id, lastId).Data(g.Map{p.Dao.C.ApproType: business.ApproType, p.Dao.C.ApproInstanceId: instanceId}).Update()
  287. if err != nil {
  288. return err
  289. }
  290. return nil
  291. })
  292. return
  293. }
  294. // BusinessCreatedNotify 项目创建 审批结果通知
  295. func (p *businessService) BusinessCreatedNotify(flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
  296. business, err := p.checkDingTalkNotify(flow, msg)
  297. if err != nil {
  298. return err
  299. }
  300. var data = g.Map{}
  301. if msg.ProcessType == "terminate" {
  302. data[p.Dao.C.ApproStatus] = ApprovalReturn
  303. }
  304. if msg.ProcessType == "finish" && msg.Result == "refuse" {
  305. // 创建项目 审批拒绝后删除项目
  306. data[p.Dao.C.ApproStatus] = ApprovalRejection
  307. data[p.Dao.C.DeletedTime] = gtime.Now()
  308. }
  309. if msg.ProcessType == "finish" && msg.Result == "agree" {
  310. data[p.Dao.C.ApproStatus] = ApprovalOK
  311. }
  312. // 项目修改
  313. _, err = p.Dao.WherePri(business.Id).FieldsEx(service.UpdateFieldEx...).Data(data).Update()
  314. if err != nil {
  315. return err
  316. }
  317. // 添加项目动态
  318. dynamics := model.ProjBusinessDynamics{
  319. BusId: business.Id,
  320. OpnType: OpnCreatedApproval,
  321. }
  322. _, err = p.CreateProjBusinessDynamics(nil, dynamics, data)
  323. if err != nil {
  324. return err
  325. }
  326. return err
  327. }
  328. // setProductInfo 设置产品信息
  329. func (p *businessService) setProductInfo(busId int, productInfo []model.BusinessProduct) (total float64, products []*model.ProjBusinessProduct, err error) {
  330. products = make([]*model.ProjBusinessProduct, len(productInfo))
  331. if err = gconv.Structs(productInfo, &products); err != nil {
  332. return 0, nil, err
  333. }
  334. var totalPrice decimal.Decimal
  335. for _, v := range products {
  336. v.Id = 0
  337. v.BusId = busId
  338. v.TotalPrice = decimal.NewFromFloat(v.ProdPrice).Mul(decimal.NewFromInt(int64(v.ProdNum))).InexactFloat64()
  339. totalPrice = totalPrice.Add(decimal.NewFromFloat(v.TotalPrice))
  340. service.SetCreatedInfo(v, p.GetCxtUserId(), p.GetCxtUserName())
  341. }
  342. return totalPrice.InexactFloat64(), products, nil
  343. }
  344. // setBusinessContact 设置项目联系人
  345. func (p *businessService) setBusinessContact(tx *gdb.TX, contactList []model.SetBusinessContactReq) (err error) {
  346. for _, item := range contactList {
  347. count, err := p.ContactDao.Where(p.ContactDao.C.BusId, item.BusId).Where(p.ContactDao.C.ContactType, item.ContactType).Count()
  348. if err != nil {
  349. return err
  350. }
  351. if count == 0 {
  352. data := new(model.ProjBusinessContact)
  353. data.BusId = item.BusId
  354. data.ContactId = item.ContactId
  355. data.ContactType = item.ContactType
  356. service.SetCreatedInfo(data, p.GetCxtUserId(), p.GetCxtUserName())
  357. _, err = p.ContactDao.TX(tx).Data(data).Insert()
  358. if err != nil {
  359. return err
  360. }
  361. }
  362. }
  363. return
  364. }
  365. func (p *businessService) UpdateById(req *model.UpdateProjBusinessReq) error {
  366. record, err := p.Dao.WherePri(req.Id).Count()
  367. if err != nil {
  368. return err
  369. }
  370. if record == 0 {
  371. return myerrors.TipsError("项目不存在。")
  372. }
  373. // 设置产品信息
  374. totalPrice, products, err := p.setProductInfo(req.Id, req.Products)
  375. if err != nil {
  376. return err
  377. }
  378. // 设置默认联系人
  379. contactList := make([]model.SetBusinessContactReq, 0)
  380. if req.ContactId != 0 {
  381. contactList = append(contactList, model.SetBusinessContactReq{
  382. BusId: req.Id,
  383. ContactId: req.ContactId,
  384. ContactType: "10",
  385. })
  386. }
  387. if req.DealerSalesId != 0 {
  388. contactList = append(contactList, model.SetBusinessContactReq{
  389. BusId: req.Id,
  390. ContactId: req.DealerSalesId,
  391. ContactType: "20",
  392. })
  393. }
  394. // 设置项目信息
  395. req.EstTransPrice = totalPrice
  396. businessData := gconv.Map(req)
  397. service.SetUpdatedInfo(businessData, p.GetCxtUserId(), p.GetCxtUserName())
  398. err = p.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  399. // 更新项目
  400. updateFieldEx := append(service.UpdateFieldEx, p.Dao.C.SaleId, p.Dao.C.SaleName, p.Dao.C.NboType, p.Dao.C.NboCode)
  401. _, err = p.Dao.TX(tx).FieldsEx(updateFieldEx...).WherePri(projDao.ProjBusiness.C.Id, req.Id).Update(businessData)
  402. if err != nil {
  403. return err
  404. }
  405. // 删除项目产品
  406. _, err = projDao.NewProjBusinessProductDao(p.Tenant).TX(tx).Where(projDao.ProjBusinessProduct.C.BusId, req.Id).Delete()
  407. if err != nil {
  408. return err
  409. }
  410. // 添加项目产品
  411. _, err = projDao.NewProjBusinessProductDao(p.Tenant).TX(tx).Insert(products)
  412. if err != nil {
  413. return err
  414. }
  415. // 关联联系人
  416. err = p.setBusinessContact(tx, contactList)
  417. if err != nil {
  418. return err
  419. }
  420. // 添加项目动态
  421. dynamics := model.ProjBusinessDynamics{
  422. BusId: req.Id,
  423. OpnType: OpnUpdate,
  424. Remark: req.Remark,
  425. }
  426. _, err = p.CreateProjBusinessDynamics(tx, dynamics, req)
  427. return err
  428. })
  429. return err
  430. }
  431. // UpdateBusinessContactInfo 清理项目表联系人信息
  432. func (p *businessService) UpdateBusinessContactInfo(tx *gdb.TX, busId int, data g.Map) (err error) {
  433. fields := []interface{}{p.Dao.C.ContactId, p.Dao.C.ContactName, p.Dao.C.ContactPostion, p.Dao.C.ContactTelephone, p.Dao.C.DealerSalesId, p.Dao.C.DealerSalesName, p.Dao.C.DealerSalesContact}
  434. _, err = p.Dao.TX(tx).Fields(fields...).WherePri(busId).Data(data).Update()
  435. return
  436. }
  437. func (p *businessService) DeleteByIds(ids []int64) (err error) {
  438. _, err = p.Dao.WhereIn(projDao.ProjBusiness.C.Id, ids).Delete()
  439. return
  440. }
  441. // SysAdminBusinessTransfer 管理员项目转移销售(未涉及审批的)
  442. func (p *businessService) SysAdminBusinessTransfer(req *model.SysAdminBusinessTransferReq) error {
  443. // 校验用户是否有修改权限
  444. arr := garray.NewStrArrayFrom(p.CxtUser.Roles, true)
  445. if !arr.Contains("SysAdmin") {
  446. return myerrors.TipsError("权限不足")
  447. }
  448. businessList, err := p.Dao.WherePri(req.Ids).WhereNot(p.Dao.C.ApproStatus, ApprovalWaiting).All()
  449. if err != nil {
  450. return err
  451. }
  452. if len(businessList) == 0 {
  453. return myerrors.TipsError("转移项目不能为空")
  454. }
  455. var updateData = g.Map{}
  456. updateData[p.Dao.C.SaleId] = req.UserId
  457. updateData[p.Dao.C.SaleName] = req.UserName
  458. updateData[p.Dao.C.Remark] = req.Remark
  459. service.SetUpdatedInfo(updateData, p.GetCxtUserId(), p.GetCxtUserName())
  460. // 添加项目动态
  461. for _, item := range businessList {
  462. err := p.Dao.Transaction(p.Ctx, func(ctx context.Context, tx *gdb.TX) error {
  463. // 项目修改
  464. _, err = p.Dao.TX(tx).WherePri(item.Id).FieldsEx(service.UpdateFieldEx...).Data(updateData).Update()
  465. if err != nil {
  466. return err
  467. }
  468. dynamics := model.ProjBusinessDynamics{
  469. BusId: item.Id,
  470. OpnType: OpnTransfer,
  471. Remark: req.Remark,
  472. }
  473. opnContent := gconv.Map(gconv.String(updateData))
  474. opnContent["origSaleId"] = item.SaleId
  475. opnContent["origSaleName"] = item.SaleName
  476. _, err = p.CreateProjBusinessDynamics(tx, dynamics, opnContent)
  477. if err != nil {
  478. g.Log().Error(err)
  479. return err
  480. }
  481. return nil
  482. })
  483. if err != nil {
  484. g.Log().Error(fmt.Sprintf("管理员转移项目销售:%v 由%v转移至%v失败", item.NboName, item.SaleName, req.UserName), err.Error())
  485. }
  486. }
  487. return nil
  488. }
  489. // BusinessTransfer 项目转移
  490. func (p *businessService) BusinessTransfer(req *model.BusinessTransferReq) error {
  491. business, err := p.Dao.WherePri(req.Id).WhereNot(p.Dao.C.ApproStatus, ApprovalWaiting).One()
  492. if err != nil {
  493. return err
  494. }
  495. if business == nil {
  496. return myerrors.TipsError("项目已提交审批任务,无法重复提交。")
  497. }
  498. businessMap := g.Map{
  499. p.Dao.C.ApproStatus: ApprovalWaiting,
  500. }
  501. service.SetUpdatedInfo(businessMap, p.GetCxtUserId(), p.GetCxtUserName())
  502. opnContent := gconv.Map(gconv.String(businessMap))
  503. opnContent["origSaleId"] = business.SaleId
  504. opnContent["origSaleName"] = business.SaleName
  505. opnContent["saleId"] = req.UserId
  506. opnContent["saleName"] = req.UserName
  507. opnContent["remark"] = req.Remark
  508. productLine, _ := service.GetDictLabelByTypeAndValue(p.Ctx, "sys_product_line", business.ProductLine)
  509. // 审批流
  510. workflowSrv, _ := workflowService.NewFlowService(p.Ctx)
  511. err = p.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  512. // 更新项目
  513. _, err = p.Dao.TX(tx).WherePri(projDao.ProjBusiness.C.Id, req.Id).Data(businessMap).Update()
  514. if err != nil {
  515. return err
  516. }
  517. // 添加项目动态
  518. dynamics := model.ProjBusinessDynamics{
  519. BusId: req.Id,
  520. OpnType: OpnTransfer,
  521. Remark: req.Remark,
  522. }
  523. _, err = p.CreateProjBusinessDynamics(tx, dynamics, opnContent)
  524. if err != nil {
  525. g.Log().Error(err)
  526. return err
  527. }
  528. // OMS项目转移 审批
  529. bizCode := business.NboCode + ":" + strconv.Itoa(business.Id)
  530. business.ApproType = BusinessTransferRequestProcessCode
  531. applyData := gconv.Map(business)
  532. applyData["abstract"] = fmt.Sprintf("申请人:%v 申请将项目:%v 转移给:%v", p.GetCxtUserName(), business.NboName, req.UserName)
  533. applyData["productLine"] = productLine
  534. applyData["nboType"] = nboType[business.NboType]
  535. applyData["applicant"] = p.GetCxtUserName()
  536. applyData["remark"] = req.Remark
  537. applyData["recipient"] = req.UserName
  538. instanceId, err := workflowSrv.CheckStartProcessInstance(bizCode, workflowModel.ProjectTransfer, "", applyData)
  539. if err != nil {
  540. g.Log().Error(err)
  541. return err
  542. }
  543. // 更新项目审批信息
  544. _, err = p.Dao.TX(tx).Data(g.Map{p.Dao.C.ApproType: business.ApproType, p.Dao.C.ApproInstanceId: instanceId}).Update()
  545. if err != nil {
  546. return err
  547. }
  548. return nil
  549. })
  550. return err
  551. }
  552. // BusinessTransferNotify 项目转移 审批结果通知
  553. func (p *businessService) BusinessTransferNotify(flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
  554. business, err := p.checkDingTalkNotify(flow, msg)
  555. if err != nil {
  556. return err
  557. }
  558. var data = g.Map{}
  559. if msg.ProcessType == "terminate" {
  560. data[p.Dao.C.ApproStatus] = ApprovalReturn
  561. }
  562. if msg.ProcessType == "finish" && msg.Result == "refuse" {
  563. data[p.Dao.C.ApproStatus] = ApprovalRejection
  564. }
  565. if msg.ProcessType == "finish" && msg.Result == "agree" {
  566. // 从项目动态内获取变更信息
  567. var transferDynamics model.ProjBusinessDynamics
  568. dynamicsDao := projDao.NewProjBusinessDynamicsDao(p.Tenant).Where(projDao.ProjBusinessDynamics.C.BusId, business.Id)
  569. err = dynamicsDao.Where(projDao.ProjBusinessDynamics.C.OpnType, OpnTransfer).OrderDesc("created_time").Scan(&transferDynamics)
  570. if err != nil {
  571. return err
  572. }
  573. changeData := gconv.Map(transferDynamics.OpnContent)
  574. data[p.Dao.C.SaleId] = changeData["saleId"]
  575. data[p.Dao.C.SaleName] = changeData["saleName"]
  576. data[p.Dao.C.Remark] = changeData["remark"]
  577. data[p.Dao.C.ApproStatus] = ApprovalOK
  578. }
  579. // 项目修改
  580. _, err = p.Dao.WherePri(business.Id).FieldsEx(service.UpdateFieldEx...).Data(data).Update()
  581. if err != nil {
  582. return err
  583. }
  584. // 添加项目动态
  585. dynamics := model.ProjBusinessDynamics{
  586. BusId: business.Id,
  587. OpnType: OpnTransferApproval,
  588. }
  589. _, err = p.CreateProjBusinessDynamics(nil, dynamics, data)
  590. if err != nil {
  591. return err
  592. }
  593. return err
  594. }
  595. // BusinessGradation 项目调级
  596. func (p *businessService) BusinessGradation(busId int, nboType, busType string) (*model.ProjBusiness, error) {
  597. business, err := p.Dao.WherePri(busId).WhereNot(p.Dao.C.ApproStatus, ApprovalWaiting).One()
  598. if err != nil {
  599. return nil, err
  600. }
  601. if business == nil {
  602. return nil, myerrors.TipsError("项目已提交审批任务,无法重复提交。")
  603. }
  604. if business.NboType == nboType {
  605. return nil, myerrors.TipsError("同级别无法进行调级。")
  606. }
  607. if business.NboType == StatusDeal {
  608. return nil, myerrors.TipsError("成交项目无法进行调级。")
  609. }
  610. if business.NboType == StatusReserve && nboType == StatusDeal {
  611. return nil, myerrors.TipsError("储备项目无法直接转为成交项目。")
  612. }
  613. if busType == "up" && gconv.Int(business.NboType) < gconv.Int(nboType) {
  614. return nil, myerrors.TipsError("项目级别错误。")
  615. }
  616. if busType == "down" && gconv.Int(business.NboType) > gconv.Int(nboType) {
  617. return nil, myerrors.TipsError("项目级别错误。")
  618. }
  619. return business, err
  620. }
  621. // BusinessUpgrade 项目升级
  622. func (p *businessService) BusinessUpgrade(req *model.BusinessUpgradeReq, fileMap map[string]*multipart.FileHeader) error {
  623. business, err := p.BusinessGradation(req.Id, req.NboType, "up")
  624. if err != nil {
  625. return err
  626. }
  627. businessMap := g.Map{p.Dao.C.ApproStatus: ApprovalWaiting}
  628. service.SetUpdatedInfo(businessMap, p.GetCxtUserId(), p.GetCxtUserName())
  629. opnContent := gconv.Map(req)
  630. opnContent["origNboType"] = business.NboType
  631. opnContent["approStatus"] = ApprovalWaiting
  632. service.SetUpdatedInfo(opnContent, p.GetCxtUserId(), p.GetCxtUserName())
  633. if fileMap == nil {
  634. fileMap = make(map[string]*multipart.FileHeader)
  635. }
  636. if (req.NboType == StatusA || req.NboType == StatusB) && !strings.HasPrefix(req.QuotationFile, "dingtalk") {
  637. fileMap["quotationFile"], err = service.DownloadTempFile(req.QuotationFile)
  638. if err != nil {
  639. return err
  640. }
  641. defer os.Remove(fileMap["quotationFile"].File.Name())
  642. }
  643. if req.NboType == StatusA && req.IsAdoptDashoo == "10" {
  644. fileMap["dashooParamFile"], err = service.DownloadTempFile(req.DashooParamFile)
  645. if err != nil {
  646. return err
  647. }
  648. defer os.Remove(fileMap["dashooParamFile"].File.Name())
  649. }
  650. contactList := make([]model.SetBusinessContactReq, 0)
  651. if req.ContactId != 0 {
  652. contactList = append(contactList, model.SetBusinessContactReq{
  653. BusId: req.Id,
  654. ContactId: req.ContactId,
  655. ContactType: "10",
  656. })
  657. }
  658. if req.DealerSalesId != 0 {
  659. contactList = append(contactList, model.SetBusinessContactReq{
  660. BusId: req.Id,
  661. ContactId: req.DealerSalesId,
  662. ContactType: "20",
  663. })
  664. }
  665. err = p.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  666. // 更新项目调级
  667. _, err = p.Dao.TX(tx).WherePri(req.Id).Data(businessMap).Update()
  668. if err != nil {
  669. return err
  670. }
  671. // 关联联系人
  672. err = p.setBusinessContact(tx, contactList)
  673. if err != nil {
  674. return err
  675. }
  676. // 添加项目动态
  677. dynamics := model.ProjBusinessDynamics{
  678. BusId: business.Id,
  679. OpnType: OpnUpgrade,
  680. Remark: req.Remark,
  681. }
  682. _, err = p.CreateProjBusinessDynamics(tx, dynamics, opnContent)
  683. if err != nil {
  684. return err
  685. }
  686. instanceId, err := p.BusUpgradeDingEvent(business, req, fileMap)
  687. if err != nil {
  688. return err
  689. }
  690. // 更新项目审批信息
  691. _, err = p.Dao.TX(tx).Data(g.Map{p.Dao.C.ApproType: business.ApproType, p.Dao.C.ApproInstanceId: instanceId}).Update()
  692. if err != nil {
  693. return err
  694. }
  695. return nil
  696. })
  697. if err != nil {
  698. return err
  699. }
  700. return nil
  701. }
  702. // 获取项目的钉钉审批的升级类型
  703. func (p *businessService) getBusDingUpgradeType(dbNboType, reqNboType string) string {
  704. var upgradeType string
  705. switch true {
  706. case dbNboType == StatusReserve && reqNboType == StatusC: // 储备转C/option_0
  707. upgradeType = "储备转C"
  708. case dbNboType == StatusReserve && reqNboType == StatusB: // 储备转B/option_1
  709. upgradeType = "储备转B"
  710. case dbNboType == StatusReserve && reqNboType == StatusA: // 储备转A/option_KTAX3Y9K5340
  711. upgradeType = "储备转A"
  712. case dbNboType == StatusC && reqNboType == StatusB: // C转B/option_0
  713. upgradeType = "C转B"
  714. case dbNboType == StatusC && reqNboType == StatusA: // C转A/option_0
  715. upgradeType = "C转A"
  716. case dbNboType == StatusB && reqNboType == StatusA: // B转A/option_1
  717. upgradeType = "B转A"
  718. default:
  719. }
  720. return upgradeType
  721. }
  722. // BusUpgradeDingEvent 项目升级钉钉审批流调用
  723. func (p *businessService) BusUpgradeDingEvent(business *model.ProjBusiness, req *model.BusinessUpgradeReq, fileMap map[string]*multipart.FileHeader) (instanceId string, err error) {
  724. upgradeType := p.getBusDingUpgradeType(business.NboType, req.NboType)
  725. if upgradeType == "" {
  726. return "", myerrors.TipsError("错误的升级类型")
  727. }
  728. productLineMap, err := service.GetDictDataTreeByType(p.Ctx, "sys_product_line")
  729. if err != nil {
  730. return "", err
  731. }
  732. productLine := gconv.String(productLineMap.Get(business.ProductLine))
  733. // 审批流
  734. workflowSrv, _ := workflowService.NewFlowService(p.Ctx)
  735. // OMS项目升级 审批
  736. bizCode := business.NboCode + ":" + strconv.Itoa(business.Id)
  737. applyData := gconv.Map(business)
  738. applyData["abstract"] = fmt.Sprintf("申请人:%v 申请将项目:%v 转为储备项目", p.GetCxtUserName(), business.NboName)
  739. applyData["wxNboType"] = wxBusUpType[business.NboType]
  740. applyData["productLine"] = productLine
  741. applyData["upgradeType"] = upgradeType
  742. applyData["nboType"] = convertToReserveType[business.NboType]
  743. applyData["purchasingWay"] = purchasingWayType[req.PurchasingWay]
  744. applyData["dealerSalesName"] = req.DealerSalesName
  745. applyData["dealerSalesContact"] = req.DealerSalesContact
  746. applyData["planPurchaseTime"] = req.PlanPurchaseTime.Format("Y-m-d")
  747. applyData["makerName"] = req.MakerName
  748. applyData["makerDept"] = req.MakerDept
  749. applyData["contactName"] = req.ContactName
  750. applyData["contactTelephone"] = req.ContactTelephone
  751. applyData["capitalSource"] = req.CapitalSource
  752. applyData["competitor"] = req.Competitor
  753. applyData["customerIntentionFactory"] = req.CustomerIntentionFactory
  754. applyData["isAdoptDashoo"] = yesOrNoType[req.IsAdoptDashoo]
  755. applyData["projConversionReason"] = req.ProjConversionReason
  756. applyData["productList"] = gconv.Maps(req.Products)
  757. applyData["remark"] = req.Remark
  758. instanceId, err = workflowSrv.CheckStartProcessInstance(bizCode, workflowModel.ProjectDownGrade, "", applyData)
  759. if err != nil {
  760. g.Log().Error(err)
  761. return "", err
  762. }
  763. return instanceId, nil
  764. }
  765. // 项目上传文件至钉钉
  766. func (p *businessService) txCreateBusinessDingTalkFile(businessId int, upgradeType, fileType string, file *multipart.FileHeader) ([]contractModel.DingFileInfo, error) {
  767. dingTalkFiles := make([]contractModel.DingFileInfo, 0)
  768. //for _, file := range files {
  769. resp, err := dingtalk.Client.GetStorage().UploadFile(service.DingTalkSpaceId, p.GetCxtUserDingtalkId(), file.FileName, file.File.Name())
  770. if err != nil {
  771. g.Log().Error(err)
  772. return nil, myerrors.TipsError("钉钉上传文件异常")
  773. }
  774. typ := "项目" + upgradeType
  775. if fileType == "quotationFile" {
  776. typ += "上传报价单文件"
  777. }
  778. if fileType == "dashooParamFile" {
  779. typ += "上传大数技术参数文件"
  780. }
  781. g.Log().Info(typ, resp)
  782. dingTalkFiles = append(dingTalkFiles, contractModel.DingFileInfo{
  783. SpaceId: resp.Dentry.SpaceId,
  784. FileId: resp.Dentry.Id,
  785. FileName: resp.Dentry.Name,
  786. FileSize: resp.Dentry.Size,
  787. FileType: resp.Dentry.Extension,
  788. })
  789. //}
  790. err = p.txCreateBusinessFile(businessId, typ, dingTalkFiles)
  791. if err != nil {
  792. return nil, err
  793. }
  794. return dingTalkFiles, nil
  795. }
  796. // 采用大数参数文件记录
  797. func (p *businessService) txCreateBusinessFile(busId int, fileSource string, files []contractModel.DingFileInfo) error {
  798. dataList := make([]*model.ProjBusinessFile, 0)
  799. for _, v := range files {
  800. data := new(model.ProjBusinessFile)
  801. data.BusId = busId
  802. data.FileName = v.FileName
  803. data.FileSource = fileSource
  804. data.FileSize = gconv.String(v.FileSize)
  805. data.FileUrl = strings.Join([]string{"dingtalk", v.SpaceId, v.FileId}, ":")
  806. service.SetCreatedInfo(data, p.GetCxtUserId(), p.GetCxtUserName())
  807. dataList = append(dataList, data)
  808. }
  809. _, err := projDao.NewProjBusinessFileDao(p.Tenant).Insert(&dataList)
  810. return err
  811. }
  812. // BusinessUpgradeNotify 项目升级 审批结果通知
  813. func (p *businessService) BusinessUpgradeNotify(flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
  814. business, err := p.checkDingTalkNotify(flow, msg)
  815. if err != nil {
  816. return err
  817. }
  818. var data = g.Map{}
  819. var updateData *model.BusinessUpgradeReq
  820. var remark string
  821. if msg.ProcessType == "terminate" {
  822. data[p.Dao.C.ApproStatus] = ApprovalReturn
  823. }
  824. if msg.ProcessType == "finish" && msg.Result == "refuse" {
  825. data[p.Dao.C.ApproStatus] = ApprovalRejection
  826. }
  827. if msg.ProcessType == "finish" && msg.Result == "agree" {
  828. // 从项目动态内获取变更信息
  829. dynamics := new(model.ProjBusinessDynamics)
  830. dynamicsDao := projDao.NewProjBusinessDynamicsDao(p.Tenant).Where(projDao.ProjBusinessDynamics.C.BusId, business.Id)
  831. err = dynamicsDao.Where(projDao.ProjBusinessDynamics.C.OpnType, OpnUpgrade).OrderDesc("created_time").Scan(dynamics)
  832. if err != nil {
  833. return err
  834. }
  835. updateData = new(model.BusinessUpgradeReq)
  836. gconv.Struct(dynamics.OpnContent, updateData)
  837. data = gconv.Map(updateData)
  838. data[p.Dao.C.ApproStatus] = ApprovalOK
  839. remarkMap := gconv.Map(dynamics.OpnContent)
  840. remark = gconv.String(g.Map{"nboType": remarkMap["nboType"], "origNboType": remarkMap["origNboType"]})
  841. }
  842. err = p.Dao.Transaction(p.Ctx, func(ctx context.Context, tx *gdb.TX) error {
  843. // 添加产品
  844. if updateData != nil && (updateData.NboType == "20" || updateData.NboType == "10") {
  845. // 设置产品信息
  846. totalPrice, products, err := p.setProductInfo(updateData.Id, updateData.Products)
  847. if err != nil {
  848. return err
  849. }
  850. // 删除项目产品
  851. _, err = projDao.NewProjBusinessProductDao(p.Tenant).TX(tx).Where(projDao.ProjBusinessProduct.C.BusId, updateData.Id).Delete()
  852. if err != nil {
  853. return err
  854. }
  855. // 添加项目产品
  856. _, err = projDao.NewProjBusinessProductDao(p.Tenant).TX(tx).Insert(products)
  857. if err != nil {
  858. return err
  859. }
  860. data[p.Dao.C.EstTransPrice] = totalPrice
  861. }
  862. // 项目修改
  863. _, err = p.Dao.TX(tx).WherePri(business.Id).FieldsEx(service.UpdateFieldEx...).Data(data).Update()
  864. if err != nil {
  865. return err
  866. }
  867. // 添加项目动态
  868. dynamics := model.ProjBusinessDynamics{
  869. BusId: business.Id,
  870. OpnType: OpnUpgradeApproval,
  871. Remark: remark,
  872. }
  873. _, err = p.CreateProjBusinessDynamics(tx, dynamics, data)
  874. if err != nil {
  875. return err
  876. }
  877. return nil
  878. })
  879. if err != nil {
  880. return err
  881. }
  882. return nil
  883. }
  884. // 获取项目的钉钉审批的降级类型
  885. func (p *businessService) getBusDingDowngradeType(dbNboType, reqNboType string) string {
  886. var downgradeType string
  887. switch true {
  888. case dbNboType == StatusB && reqNboType == StatusC: // B转C/option_0
  889. downgradeType = "B转C"
  890. case dbNboType == StatusA && reqNboType == StatusB: // A转B/option_1
  891. downgradeType = "A转B"
  892. case dbNboType == StatusA && reqNboType == StatusC: // A转C/option_2
  893. downgradeType = "A转C"
  894. case dbNboType == StatusA && reqNboType == StatusReserve: // A转储备/option_YZMFJYQQK6O0
  895. downgradeType = "A转储备"
  896. case dbNboType == StatusB && reqNboType == StatusReserve: // B转储备/option_232GR5NMFCSG0
  897. downgradeType = "B转储备"
  898. case dbNboType == StatusC && reqNboType == StatusReserve: // C转储备/option_1ZV2GJLDKQOW0
  899. downgradeType = "C转储备"
  900. default:
  901. }
  902. return downgradeType
  903. }
  904. // BusinessDowngrade 项目降级
  905. func (p *businessService) BusinessDowngrade(req *model.BusinessDowngradeReq) error {
  906. business, err := p.BusinessGradation(req.Id, req.NboType, "down")
  907. if err != nil {
  908. return err
  909. }
  910. downgradeType := p.getBusDingDowngradeType(business.NboType, req.NboType)
  911. if downgradeType == "" {
  912. return myerrors.TipsError("错误的降级类型")
  913. }
  914. businessMap := g.Map{
  915. p.Dao.C.ApproStatus: ApprovalWaiting,
  916. }
  917. service.SetUpdatedInfo(businessMap, p.GetCxtUserId(), p.GetCxtUserName())
  918. opnContent := gconv.Map(req)
  919. opnContent["origNboType"] = business.NboType
  920. opnContent["approStatus"] = ApprovalWaiting
  921. service.SetUpdatedInfo(opnContent, p.GetCxtUserId(), p.GetCxtUserName())
  922. productLine, _ := service.GetDictLabelByTypeAndValue(p.Ctx, "sys_product_line", business.ProductLine)
  923. // 审批流
  924. workflowSrv, _ := workflowService.NewFlowService(p.Ctx)
  925. err = p.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  926. // 更新项目调级
  927. _, err = p.Dao.TX(tx).WherePri(req.Id).Data(businessMap).Update()
  928. if err != nil {
  929. return err
  930. }
  931. // 添加项目动态
  932. dynamics := model.ProjBusinessDynamics{
  933. BusId: business.Id,
  934. OpnType: OpnDowngrade,
  935. Remark: req.Remark,
  936. }
  937. _, err = p.CreateProjBusinessDynamics(tx, dynamics, opnContent)
  938. if err != nil {
  939. return err
  940. }
  941. // OMS项目降级 审批
  942. bizCode := business.NboCode + ":" + strconv.Itoa(business.Id)
  943. business.ApproType = BusinessDowngradeRequestProcessCode
  944. applyData := gconv.Map(business)
  945. applyData["abstract"] = fmt.Sprintf("申请人:%v 申请将项目:%v 转为储备项目", p.GetCxtUserName(), business.NboName)
  946. applyData["productLine"] = productLine
  947. applyData["nboType"] = convertToReserveType[business.NboType]
  948. applyData["downgradeType"] = downgradeType
  949. applyData["remark"] = req.Remark
  950. instanceId, err := workflowSrv.CheckStartProcessInstance(bizCode, workflowModel.ProjectDownGrade, "", applyData)
  951. if err != nil {
  952. g.Log().Error(err)
  953. return err
  954. }
  955. // 更新项目审批信息
  956. _, err = p.Dao.TX(tx).Data(g.Map{p.Dao.C.ApproType: business.ApproType, p.Dao.C.ApproInstanceId: instanceId}).Update()
  957. if err != nil {
  958. return err
  959. }
  960. return nil
  961. })
  962. return err
  963. }
  964. // BusinessDowngradeNotify 项目降级 审批结果通知
  965. func (p *businessService) BusinessDowngradeNotify(flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
  966. business, err := p.checkDingTalkNotify(flow, msg)
  967. if err != nil {
  968. return err
  969. }
  970. var data = g.Map{}
  971. var remark string
  972. if msg.ProcessType == "terminate" {
  973. data[p.Dao.C.ApproStatus] = ApprovalReturn
  974. }
  975. if msg.ProcessType == "finish" && msg.Result == "refuse" {
  976. data[p.Dao.C.ApproStatus] = ApprovalRejection
  977. }
  978. if msg.ProcessType == "finish" && msg.Result == "agree" {
  979. // 从项目动态内获取变更信息
  980. dynamics := new(model.ProjBusinessDynamics)
  981. dynamicsDao := projDao.NewProjBusinessDynamicsDao(p.Tenant).Where(projDao.ProjBusinessDynamics.C.BusId, business.Id)
  982. err = dynamicsDao.Where(projDao.ProjBusinessDynamics.C.OpnType, OpnDowngrade).OrderDesc("created_time").Scan(dynamics)
  983. if err != nil {
  984. return err
  985. }
  986. updateData := new(model.BusinessDowngradeReq)
  987. gconv.Struct(dynamics.OpnContent, updateData)
  988. data = gconv.Map(updateData)
  989. data[p.Dao.C.ApproStatus] = ApprovalOK
  990. remarkMap := gconv.Map(dynamics.OpnContent)
  991. remark = gconv.String(g.Map{"nboType": remarkMap["nboType"], "origNboType": remarkMap["origNboType"]})
  992. }
  993. // 项目修改
  994. _, err = p.Dao.WherePri(business.Id).FieldsEx(service.UpdateFieldEx...).Data(data).Update()
  995. if err != nil {
  996. return err
  997. }
  998. // 添加项目动态
  999. dynamics := model.ProjBusinessDynamics{
  1000. BusId: business.Id,
  1001. OpnType: OpnDowngradeApproval,
  1002. Remark: remark,
  1003. }
  1004. _, err = p.CreateProjBusinessDynamics(nil, dynamics, data)
  1005. if err != nil {
  1006. return err
  1007. }
  1008. return nil
  1009. }
  1010. // SetPrimacyContact 项目设置首要联系人
  1011. func (p *businessService) SetPrimacyContact(req *model.BusinessPrimacyContactReq) (err error) {
  1012. business, err := p.Dao.Where(projDao.ProjBusiness.C.Id, req.Id).One()
  1013. if err != nil {
  1014. return err
  1015. }
  1016. if business == nil {
  1017. return myerrors.TipsError("项目不存在。")
  1018. }
  1019. businessMap := g.Map{
  1020. p.Dao.C.ContactId: req.ContactId,
  1021. p.Dao.C.ContactName: req.ContactName,
  1022. p.Dao.C.ContactPostion: req.ContactPostion,
  1023. p.Dao.C.ContactTelephone: req.ContactTelephone,
  1024. }
  1025. service.SetUpdatedInfo(businessMap, p.GetCxtUserId(), p.GetCxtUserName())
  1026. opnContent := gconv.Map(gconv.String(businessMap))
  1027. opnContent["origContactId"] = business.ContactId
  1028. opnContent["origContactName"] = business.ContactName
  1029. opnContent["origContactPostion"] = business.ContactPostion
  1030. opnContent["origContactTelephone"] = business.ContactTelephone
  1031. err = p.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  1032. // 更新项目
  1033. _, err = p.Dao.TX(tx).WherePri(projDao.ProjBusiness.C.Id, req.Id).Data(businessMap).Update()
  1034. if err != nil {
  1035. return err
  1036. }
  1037. // 添加项目动态
  1038. dynamics := model.ProjBusinessDynamics{
  1039. BusId: req.Id,
  1040. OpnType: OpnPrimacyContact,
  1041. Remark: req.Remark,
  1042. }
  1043. _, err = p.CreateProjBusinessDynamics(tx, dynamics, opnContent)
  1044. return err
  1045. })
  1046. return err
  1047. }
  1048. // UpdateBusinessStatus 更新项目状态
  1049. func (p *businessService) UpdateBusinessStatus(req *model.UpdateBusinessStatusReq) error {
  1050. business, err := p.Dao.WherePri(req.Id).One()
  1051. if err != nil {
  1052. return err
  1053. }
  1054. if business == nil {
  1055. return myerrors.TipsError("项目不存在。")
  1056. }
  1057. businessMap := g.Map{
  1058. p.Dao.C.NboStatus: req.NboStatus,
  1059. p.Dao.C.Remark: req.Remark,
  1060. }
  1061. service.SetUpdatedInfo(businessMap, p.GetCxtUserId(), p.GetCxtUserName())
  1062. opnContent := gconv.Map(gconv.String(businessMap))
  1063. opnContent["origNboStatus"] = business.NboStatus
  1064. err = p.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  1065. // 更新项目
  1066. _, err = p.Dao.TX(tx).WherePri(projDao.ProjBusiness.C.Id, req.Id).Data(businessMap).Update()
  1067. if err != nil {
  1068. return err
  1069. }
  1070. // 添加项目动态
  1071. dynamics := model.ProjBusinessDynamics{
  1072. BusId: req.Id,
  1073. OpnType: OpnStatus,
  1074. Remark: req.Remark,
  1075. }
  1076. _, err = p.CreateProjBusinessDynamics(tx, dynamics, opnContent)
  1077. return err
  1078. })
  1079. return err
  1080. }
  1081. // CreateProjBusinessDynamics 创建项目动态
  1082. func (p *businessService) CreateProjBusinessDynamics(tx *gdb.TX, dynamics model.ProjBusinessDynamics, opnContent interface{}) (int64, error) {
  1083. if v, ok := opnContent.(g.Map); ok {
  1084. opnContent = utils.MapKeySnakeCamelCase(v)
  1085. }
  1086. // 添加项目动态
  1087. dynamics.OpnPeopleId = p.GetCxtUserId()
  1088. dynamics.OpnPeople = p.GetCxtUserName()
  1089. dynamics.OpnDate = gtime.Now()
  1090. dynamics.OpnContent = gconv.String(opnContent)
  1091. service.SetCreatedInfo(&dynamics, p.GetCxtUserId(), p.GetCxtUserName())
  1092. dao := projDao.NewProjBusinessDynamicsDao(p.Tenant).M
  1093. if tx != nil {
  1094. dao = dao.TX(tx)
  1095. }
  1096. lastId, err := dao.InsertAndGetId(&dynamics)
  1097. return lastId, err
  1098. }
  1099. // ConvertToReserve 转为储备项目
  1100. func (p *businessService) ConvertToReserve(req *model.BusinessToReserveReq) error {
  1101. business, err := p.Dao.WherePri(req.Id).WhereNot(p.Dao.C.ApproStatus, ApprovalWaiting).One()
  1102. if err != nil {
  1103. return err
  1104. }
  1105. if business == nil {
  1106. return myerrors.TipsError("项目已提交审批任务,无法重复提交。")
  1107. }
  1108. productLine, _ := service.GetDictLabelByTypeAndValue(p.Ctx, "sys_product_line", business.ProductLine)
  1109. // 审批流
  1110. workflowSrv, _ := workflowService.NewFlowService(p.Ctx)
  1111. err = p.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  1112. // 更新项目
  1113. businessMap := g.Map{
  1114. p.Dao.C.ApproStatus: ApprovalWaiting,
  1115. p.Dao.C.ProjConversionTime: gtime.Now(),
  1116. p.Dao.C.ProjConversionReason: req.ProjConversionReason,
  1117. }
  1118. service.SetUpdatedInfo(businessMap, p.GetCxtUserId(), p.GetCxtUserName())
  1119. _, err = p.Dao.TX(tx).WherePri(business.Id).Data(businessMap).Update()
  1120. if err != nil {
  1121. return err
  1122. }
  1123. // 添加项目动态
  1124. dynamics := model.ProjBusinessDynamics{
  1125. BusId: business.Id,
  1126. OpnType: OpnToReserve,
  1127. Remark: req.ProjConversionReason,
  1128. }
  1129. _, err = p.CreateProjBusinessDynamics(tx, dynamics, businessMap)
  1130. if err != nil {
  1131. return err
  1132. }
  1133. // OMS项目转储备 审批
  1134. bizCode := business.NboCode + ":" + strconv.Itoa(business.Id)
  1135. business.ApproType = ConvertToReserveRequestProcessCode
  1136. applyData := gconv.Map(business)
  1137. applyData["abstract"] = fmt.Sprintf("申请人:%v 申请将项目:%v 转为储备项目", p.GetCxtUserName(), business.NboName)
  1138. applyData["productLine"] = productLine
  1139. applyData["nboType"] = convertToReserveType[business.NboType]
  1140. applyData["projConversionReason"] = req.ProjConversionReason
  1141. instanceId, err := workflowSrv.CheckStartProcessInstance(bizCode, workflowModel.ProjectToReserve, "", applyData)
  1142. if err != nil {
  1143. g.Log().Error(err)
  1144. return err
  1145. }
  1146. // 更新项目审批信息
  1147. _, err = p.Dao.TX(tx).Data(g.Map{p.Dao.C.ApproType: business.ApproType, p.Dao.C.ApproInstanceId: instanceId}).Update()
  1148. if err != nil {
  1149. return err
  1150. }
  1151. return nil
  1152. })
  1153. return err
  1154. }
  1155. // ConvertToReserveNotify 转为储备项目 审批结果通知
  1156. func (p *businessService) ConvertToReserveNotify(flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
  1157. business, err := p.checkDingTalkNotify(flow, msg)
  1158. if err != nil {
  1159. return err
  1160. }
  1161. var data = g.Map{}
  1162. if msg.ProcessType == "terminate" {
  1163. data[p.Dao.C.ApproStatus] = ApprovalReturn
  1164. }
  1165. if msg.ProcessType == "finish" && msg.Result == "refuse" {
  1166. data[p.Dao.C.ApproStatus] = ApprovalRejection
  1167. }
  1168. if msg.ProcessType == "finish" && msg.Result == "agree" {
  1169. data[p.Dao.C.NboType] = StatusReserve
  1170. data[p.Dao.C.ApproStatus] = ApprovalOK
  1171. }
  1172. // 项目修改
  1173. _, err = p.Dao.WherePri(business.Id).FieldsEx(service.UpdateFieldEx...).Data(data).Update()
  1174. if err != nil {
  1175. return err
  1176. }
  1177. // 添加项目动态
  1178. dynamics := model.ProjBusinessDynamics{
  1179. BusId: business.Id,
  1180. OpnType: OpnToReserveApproval,
  1181. }
  1182. _, err = p.CreateProjBusinessDynamics(nil, dynamics, data)
  1183. if err != nil {
  1184. return err
  1185. }
  1186. return err
  1187. }
  1188. // 钉钉审批通知检查
  1189. func (p *businessService) checkDingTalkNotify(flow *workflowModel.PlatWorkflow, msg *message.MixMessage) (*model.ProjBusiness, error) {
  1190. bizCode := strings.Split(flow.BizCode, ":")
  1191. if len(bizCode) != 2 {
  1192. return nil, fmt.Errorf("项目审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  1193. }
  1194. nboCode := bizCode[0]
  1195. busId, err := strconv.Atoi(bizCode[1])
  1196. if err != nil {
  1197. return nil, fmt.Errorf("项目审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  1198. }
  1199. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  1200. return nil, fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  1201. }
  1202. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  1203. return nil, fmt.Errorf("无法识别的 Result :%s", msg.Result)
  1204. }
  1205. fmt.Println(msg)
  1206. business, err := p.Dao.WherePri(busId).Where(p.Dao.C.NboCode, nboCode).One()
  1207. if err != nil {
  1208. return nil, err
  1209. }
  1210. if business == nil {
  1211. return nil, fmt.Errorf("项目不存在:%s Id: %d", flow.BizCode, flow.Id)
  1212. }
  1213. return business, nil
  1214. }