base_distributor.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402
  1. package base
  2. import (
  3. "context"
  4. "database/sql"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "os"
  10. "path"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/gogf/gf/container/garray"
  15. "dashoo.cn/opms_libary/micro_srv"
  16. "dashoo.cn/opms_libary/myerrors"
  17. "dashoo.cn/opms_libary/plugin/dingtalk"
  18. "github.com/gogf/gf/database/gdb"
  19. "github.com/gogf/gf/frame/g"
  20. "github.com/gogf/gf/os/gcron"
  21. "github.com/gogf/gf/os/glog"
  22. "github.com/gogf/gf/os/gtime"
  23. "github.com/gogf/gf/util/gconv"
  24. "github.com/gogf/gf/util/gvalid"
  25. "dashoo.cn/micro/app/dao/base"
  26. contractdao "dashoo.cn/micro/app/dao/contract"
  27. projdao "dashoo.cn/micro/app/dao/proj"
  28. model "dashoo.cn/micro/app/model/base"
  29. contractmodel "dashoo.cn/micro/app/model/contract"
  30. projmodel "dashoo.cn/micro/app/model/proj"
  31. workflowmodel "dashoo.cn/micro/app/model/workflow"
  32. "dashoo.cn/micro/app/service"
  33. workflowService "dashoo.cn/micro/app/service/workflow"
  34. "dashoo.cn/opms_libary/plugin/dingtalk/message"
  35. "dashoo.cn/opms_libary/plugin/dingtalk/workflow"
  36. "dashoo.cn/opms_libary/utils"
  37. )
  38. type distributorService struct {
  39. *service.ContextService
  40. Dao *base.BaseDistributorDao
  41. DynamicsDao *base.BaseDistributorDynamicsDao
  42. TargetDao *base.BaseDistributorTargetDao
  43. RecordDao *base.BaseDistributorRecordDao
  44. ProjDao *projdao.ProjBusinessDao
  45. ContractDao *contractdao.CtrContractDao
  46. }
  47. func NewDistributorService(ctx context.Context) (svc *distributorService, err error) {
  48. svc = new(distributorService)
  49. if svc.ContextService, err = svc.Init(ctx); err != nil {
  50. return nil, err
  51. }
  52. svc.Dao = base.NewBaseDistributorDao(svc.Tenant)
  53. svc.DynamicsDao = base.NewBaseDistributorDynamicsDao(svc.Tenant)
  54. svc.ProjDao = projdao.NewProjBusinessDao(svc.Tenant)
  55. svc.ContractDao = contractdao.NewCtrContractDao(svc.Tenant)
  56. svc.TargetDao = base.NewBaseDistributorTargetDao(svc.Tenant)
  57. svc.RecordDao = base.NewBaseDistributorRecordDao(svc.Tenant)
  58. return svc, nil
  59. }
  60. // GetList 经销商信息列表
  61. func (s *distributorService) GetList(ctx context.Context, req *model.BaseDistributorSearchReq) (total int, distributorList []*model.BaseDistributorListRsp, err error) {
  62. distributorModel := s.Dao.FieldsEx(s.Dao.C.DeletedTime)
  63. if garray.NewStrArrayFrom(s.CxtUser.Roles, true).Contains("SalesEngineer") {
  64. distributorModel = distributorModel.DataScope(s.Ctx, "belong_sale_id")
  65. }
  66. if req.DistCode != "" {
  67. distributorModel = distributorModel.WhereLike(s.Dao.C.DistCode, "%"+req.DistCode+"%")
  68. }
  69. if req.DistName != "" {
  70. distributorModel = distributorModel.WhereLike(s.Dao.C.DistName, "%"+req.DistName+"%")
  71. }
  72. if req.BelongSale != "" {
  73. distributorModel = distributorModel.WhereLike(s.Dao.C.BelongSale, "%"+req.BelongSale+"%")
  74. }
  75. if len(req.ProvinceId) > 0 {
  76. distributorModel = distributorModel.WhereIn(s.Dao.C.ProvinceId, req.ProvinceId)
  77. }
  78. if req.DistType != "" {
  79. distributorModel = distributorModel.WhereIn(s.Dao.C.DistType, req.DistType)
  80. }
  81. total, err = distributorModel.Count()
  82. if err != nil {
  83. err = myerrors.DbError("获取总行数失败。")
  84. return
  85. }
  86. err = distributorModel.Page(req.GetPage()).Order("id desc").Scan(&distributorList)
  87. if req.WithStatistic {
  88. for i, dist := range distributorList {
  89. statistic, err := s.statistic(dist.Id)
  90. if err != nil {
  91. return 0, nil, err
  92. }
  93. distributorList[i].BaseDistributorStatistic = statistic
  94. }
  95. }
  96. return
  97. }
  98. func (s *distributorService) statistic(id int) (stat model.BaseDistributorStatistic, err error) {
  99. v, err := s.Dao.DB.GetValue("select count(*) from proj_business where distributor_id=? and appro_status ='30' and nbo_type in (10,20,30) and deleted_time is null", id)
  100. if err != nil {
  101. return stat, err
  102. }
  103. stat.ProjectNum = v.Int()
  104. v, err = s.Dao.DB.GetValue("select sum(est_trans_price) from proj_business where distributor_id=? and appro_status ='30' and nbo_type in (10,20,30) and deleted_time is null", id)
  105. if err != nil {
  106. return stat, err
  107. }
  108. stat.AllProductAmount = v.Float64()
  109. v, err = s.Dao.DB.GetValue("select count(distinct(b.id)) from ctr_contract a left join proj_business b on a.nbo_id=b.id where a.distributor_id=? and a.appro_status ='30' and b.appro_status ='30' and a.deleted_time is null and b.deleted_time is null", id)
  110. if err != nil {
  111. return stat, err
  112. }
  113. stat.SaledProjectNum = v.Int()
  114. v, err = s.Dao.DB.GetValue("select sum(contract_amount) from ctr_contract where distributor_id=? and appro_status='30' and deleted_time is null", id)
  115. if err != nil {
  116. return stat, err
  117. }
  118. stat.SaledAmount = v.Float64()
  119. v, err = s.Dao.DB.GetValue("select sum(contract_amount - collected_amount) from ctr_contract where distributor_id=? and appro_status='30' and deleted_time is null", id)
  120. if err != nil {
  121. return stat, err
  122. }
  123. stat.UnpaidAmount = v.Float64()
  124. v, err = s.Dao.DB.GetValue("select sum(invoice_amount) from ctr_contract where distributor_id=? and appro_status='30' and deleted_time is null", id)
  125. if err != nil {
  126. return stat, err
  127. }
  128. stat.InvoicedAmount = v.Float64()
  129. return
  130. }
  131. // 获取经销商编号
  132. func (s *distributorService) getDistributorCode(distCode string) (string, error) {
  133. sequence, err := service.Sequence(s.Dao.DB, "distributor_code")
  134. if err != nil {
  135. return "", err
  136. }
  137. return distCode + sequence, nil
  138. }
  139. // Create 经销商创建
  140. func (s *distributorService) Create(ctx context.Context, req *model.AddDistributor) (int64, error) {
  141. if req.DistType == "10" {
  142. if req.DistName == "" {
  143. return 0, myerrors.TipsError("经销商名称不能为空")
  144. }
  145. if req.ProvinceId == 0 {
  146. return 0, myerrors.TipsError("所属省份Id不能为空")
  147. }
  148. if req.ProvinceDesc == "" {
  149. return 0, myerrors.TipsError("所属省份名称不能为空")
  150. }
  151. if req.RegisterDistrict == "" {
  152. return 0, myerrors.TipsError("注册地不能为空")
  153. }
  154. if req.BelongSaleId == 0 {
  155. return 0, myerrors.TipsError("归属销售ID不能为空")
  156. }
  157. if req.BelongSale == "" {
  158. return 0, myerrors.TipsError("归属销售不能为空")
  159. }
  160. } else {
  161. if err := gvalid.CheckStruct(ctx, req, nil); err != nil {
  162. return 0, err
  163. }
  164. }
  165. DistributorData := new(model.BaseDistributor)
  166. if err := gconv.Struct(req, DistributorData); err != nil {
  167. return 0, err
  168. }
  169. code, err := s.getDistributorCode("JXS")
  170. if err != nil {
  171. return 0, err
  172. }
  173. DistributorData.DistCode = code
  174. if DistributorData.DistType == "20" {
  175. DistributorData.ApproItem = "创建代理商"
  176. DistributorData.ApproStatus = "20"
  177. if req.ContractUrl != "" && req.ContractFileName == "" {
  178. return 0, myerrors.TipsError("合同文件名不能为空")
  179. }
  180. }
  181. service.SetCreatedInfo(DistributorData, s.GetCxtUserId(), s.GetCxtUserName())
  182. var id int64
  183. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  184. id, err = tx.InsertAndGetId("base_distributor", DistributorData)
  185. if err != nil {
  186. return err
  187. }
  188. DistributorData.Id = int(id)
  189. if DistributorData.DistType == "20" {
  190. err = s.createDingtalkProcess(ctx, DistributorData, req.ContractFileName)
  191. if err != nil {
  192. return err
  193. }
  194. }
  195. err = s.AddDynamicsByCurrentUser(tx, int(id), "创建经销商/代理商", map[string]interface{}{})
  196. return err
  197. })
  198. if txerr != nil {
  199. return 0, txerr
  200. }
  201. if req.ProvinceId == 0 || req.BelongSaleId == 0 || req.Capital == 0 || req.RegisterDistrict == "" || req.BusinessScope == "" || req.SaleNum == 0 || req.CustomerType == "" || req.ExistedProduct == "" || req.HistoryCustomer == "" {
  202. msg := g.MapStrStr{
  203. "msgTitle": "经销商信息完善提醒",
  204. "msgContent": fmt.Sprintf("<p>经销商:<a href='%s'>%s</a> 的必要信息未填写完整,请及时完善</p>", distUrl(*DistributorData), req.DistName),
  205. "msgType": "20",
  206. "recvUserIds": strconv.Itoa(req.BelongSaleId),
  207. "msgStatus": "10",
  208. "sendType": "10",
  209. }
  210. if err := service.CreateSystemMessage(msg); err != nil {
  211. g.Log().Error("经销商信息完善提醒异常:", err)
  212. }
  213. }
  214. return id, nil
  215. }
  216. func distUrl(ent model.BaseDistributor) string {
  217. if ent.DistType == "20" {
  218. return fmt.Sprintf("#/base/agentDetails?id=%d", ent.Id)
  219. }
  220. return fmt.Sprintf("#/base/info?id=%d", ent.Id)
  221. }
  222. var ProcessCodeDistProxyCreate = "PROC-9494B87D-DE96-49EE-B676-D3913911BE21" // 创建代理商
  223. func (s *distributorService) createDingtalkProcess(ctx context.Context, ent *model.BaseDistributor, contractFileName string) error {
  224. var fileinfoByte []byte
  225. if ent.ContractUrl != "" {
  226. var err error
  227. fileinfoByte, err = UploadDingtalk(s.CxtUser.DingtalkId, ent.ContractUrl, contractFileName)
  228. if err != nil {
  229. return err
  230. }
  231. }
  232. workflowSrv, err := workflowService.NewFlowService(ctx)
  233. if err != nil {
  234. return err
  235. }
  236. bizCode := strconv.Itoa(ent.Id)
  237. form := []*workflow.StartProcessInstanceRequestFormComponentValues{
  238. {
  239. Id: utils.String("TextField-K2AD4O5B"),
  240. Name: utils.String("代理商名称"),
  241. Value: utils.String(ent.DistName),
  242. },
  243. {
  244. Id: utils.String("TextField_DZ2HNXRKHCG"),
  245. Name: utils.String("所在省"),
  246. Value: utils.String(ent.ProvinceDesc),
  247. },
  248. {
  249. Id: utils.String("TextField_1M07EV7YVOPS0"),
  250. Name: utils.String("业务范围"),
  251. Value: utils.String(ent.BusinessScope),
  252. },
  253. {
  254. Id: utils.String("TextField_UGJ0UKCU5DS0"),
  255. Name: utils.String("注册资金(万元)"),
  256. Value: utils.String(strconv.FormatFloat(ent.Capital, 'f', 2, 64)),
  257. },
  258. {
  259. Id: utils.String("TextField_1RC4FO1WUZ4W0"),
  260. Name: utils.String("注册地"),
  261. Value: utils.String(ent.RegisterDistrict),
  262. },
  263. {
  264. Id: utils.String("TextField_FKM6LUQYLFS0"),
  265. Name: utils.String("现有销售人数"),
  266. Value: utils.String(strconv.Itoa(ent.SaleNum)),
  267. },
  268. {
  269. Id: utils.String("TextField_1L89WCJM3ZMO0"),
  270. Name: utils.String("已有代理名牌和产品"),
  271. Value: utils.String(ent.ExistedProduct),
  272. },
  273. {
  274. Id: utils.String("TextField_P5JA5OZ5XKW0"),
  275. Name: utils.String("历史合作的终端客户名称"),
  276. Value: utils.String(ent.HistoryCustomer),
  277. },
  278. }
  279. if len(fileinfoByte) != 0 {
  280. form = append(form, &workflow.StartProcessInstanceRequestFormComponentValues{
  281. Id: utils.String("DDAttachment_SD6QFFBOSAO0"),
  282. Name: utils.String("代理合同"),
  283. Value: utils.String(string(fileinfoByte)),
  284. })
  285. }
  286. _, err = workflowSrv.StartProcessInstance(bizCode, workflowmodel.DistProxyCreate, "", &workflow.StartProcessInstanceRequest{
  287. ProcessCode: &ProcessCodeDistProxyCreate,
  288. FormComponentValues: form,
  289. })
  290. return err
  291. }
  292. // GetEntityById 详情
  293. func (s *distributorService) GetEntityById(id int64) (distributorInfo *model.BaseDistributorListRsp, err error) {
  294. err = s.Dao.Where(base.BaseProduct.C.Id, id).Scan(&distributorInfo)
  295. if err != nil {
  296. return nil, err
  297. }
  298. statistic, err := s.statistic(int(id))
  299. if err != nil {
  300. return nil, err
  301. }
  302. distributorInfo.BaseDistributorStatistic = statistic
  303. target, err := s.TargetDao.Where("dist_id = ?", id).Where("year = ?", time.Now().Year()).One()
  304. if err != nil {
  305. return nil, err
  306. }
  307. if target != nil {
  308. distributorInfo.YearTarget = target.Total
  309. }
  310. return
  311. }
  312. // UpdateById 修改数据
  313. func (s *distributorService) UpdateById(req *model.UpdateDistributorReq) (err error) {
  314. ent, err := s.Dao.Where("id = ", req.Id).One()
  315. if err != nil {
  316. g.Log().Error(err)
  317. return
  318. }
  319. if ent == nil {
  320. err = myerrors.TipsError("无修改数据")
  321. return
  322. }
  323. if ent.ApproStatus == "20" {
  324. err = myerrors.TipsError("不能修改待审核数据")
  325. return
  326. }
  327. distData := new(model.BaseDistributor)
  328. if err = gconv.Struct(req, distData); err != nil {
  329. return
  330. }
  331. service.SetUpdatedInfo(distData, s.GetCxtUserId(), s.GetCxtUserName())
  332. _, err = s.Dao.FieldsEx(s.Dao.C.DistCode, s.Dao.C.Id,
  333. s.Dao.C.CreatedName, s.Dao.C.CreatedBy, s.Dao.C.CreatedTime).WherePri(s.Dao.C.Id, req.Id).Update(distData)
  334. if err != nil {
  335. g.Log().Error(err)
  336. return
  337. }
  338. err = s.Dao.DB.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  339. err = s.AddDynamicsByCurrentUser(tx, req.Id, "更新经销商/代理商", map[string]interface{}{})
  340. return err
  341. })
  342. return
  343. }
  344. func (s *distributorService) ToProxy(ctx context.Context, req *model.DistributorToProxyReq) (err error) {
  345. validErr := gvalid.CheckStruct(ctx, req, nil)
  346. if validErr != nil {
  347. return myerrors.TipsError(validErr.Current().Error())
  348. }
  349. if req.ContractUrl != "" && req.ContractFileName == "" {
  350. return myerrors.TipsError("合同文件名不能为空")
  351. }
  352. ent, err := s.Dao.Where("id = ?", req.Id).One()
  353. if err != nil {
  354. return err
  355. }
  356. if ent == nil {
  357. return myerrors.TipsError(fmt.Sprintf("代理商/经销商不存在: %d", req.Id))
  358. }
  359. approvalData := model.ToProxyApproveData{
  360. CustomerType: req.CustomerType,
  361. ProxyStartTime: req.ProxyStartTime,
  362. ProxyEndTime: req.ProxyEndTime,
  363. ProxyDistrict: req.ProxyDistrict,
  364. ContractUrl: req.ContractUrl,
  365. OperatedId: s.CxtUser.Id,
  366. OperatedName: s.CxtUser.NickName,
  367. }
  368. approvalDataByte, err := json.Marshal(approvalData)
  369. if err != nil {
  370. return err
  371. }
  372. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  373. _, err = tx.Update("base_distributor", map[string]interface{}{
  374. "appro_status": "20",
  375. "appro_data": string(approvalDataByte),
  376. "appro_item": "经销商转代理商",
  377. }, "id = ?", req.Id)
  378. if err != nil {
  379. return err
  380. }
  381. return s.toProxyDingtalkProcess(ctx, ent, req)
  382. })
  383. return txerr
  384. }
  385. var ProcessCodeDistToProxy = "PROC-39C96165-131C-48EC-B8C0-AA528E0C9F3A" // 经销商转代理商
  386. func (s *distributorService) toProxyDingtalkProcess(ctx context.Context, ent *model.BaseDistributor, req *model.DistributorToProxyReq) error {
  387. var fileinfoByte []byte
  388. if req.ContractUrl != "" {
  389. var err error
  390. fileinfoByte, err = UploadDingtalk(s.CxtUser.DingtalkId, req.ContractUrl, req.ContractFileName)
  391. if err != nil {
  392. return err
  393. }
  394. }
  395. cusTypeMap, err := service.GetDictDataByType(ctx, "cust_idy")
  396. if err != nil {
  397. return err
  398. }
  399. cusType := []string{}
  400. for _, t := range strings.Split(req.CustomerType, ",") {
  401. if v := cusTypeMap[t]; v != "" {
  402. cusType = append(cusType, v)
  403. }
  404. }
  405. custTypeByte, err := json.Marshal(cusType)
  406. if err != nil {
  407. return err
  408. }
  409. proxyTime := req.ProxyStartTime.Time.Format("2006/01/02") + "-" +
  410. req.ProxyEndTime.Time.Format("2006/01/02")
  411. workflowSrv, err := workflowService.NewFlowService(ctx)
  412. if err != nil {
  413. return err
  414. }
  415. form := []*workflow.StartProcessInstanceRequestFormComponentValues{
  416. {
  417. Id: utils.String("TextField-K2AD4O5B"),
  418. Name: utils.String("代理商名称"),
  419. Value: utils.String(ent.DistName),
  420. },
  421. {
  422. Id: utils.String("DDSelectField_X3ALRAZA4BK0"),
  423. Name: utils.String("授权客户类型"),
  424. Value: utils.String(string(custTypeByte)),
  425. },
  426. {
  427. Id: utils.String("TextField_1M07EV7YVOPS0"),
  428. Name: utils.String("授权代理区域"),
  429. Value: utils.String(req.ProxyDistrict),
  430. },
  431. {
  432. Id: utils.String("TextField_UGJ0UKCU5DS0"),
  433. Name: utils.String("代理签约有效期"),
  434. Value: utils.String(proxyTime),
  435. },
  436. }
  437. if len(fileinfoByte) != 0 {
  438. form = append(form, &workflow.StartProcessInstanceRequestFormComponentValues{
  439. Id: utils.String("DDAttachment_SD6QFFBOSAO0"),
  440. Name: utils.String("代理合同"),
  441. Value: utils.String(string(fileinfoByte)),
  442. })
  443. }
  444. bizCode := strconv.Itoa(ent.Id)
  445. _, err = workflowSrv.StartProcessInstance(bizCode, workflowmodel.DistToProxy, "", &workflow.StartProcessInstanceRequest{
  446. ProcessCode: &ProcessCodeDistToProxy,
  447. FormComponentValues: form,
  448. })
  449. return err
  450. }
  451. func (s *distributorService) Renew(ctx context.Context, req *model.DistributorRenewReq) (err error) {
  452. validErr := gvalid.CheckStruct(ctx, req, nil)
  453. if validErr != nil {
  454. return myerrors.TipsError(validErr.Current().Error())
  455. }
  456. if req.ContractUrl != "" && req.ContractFileName == "" {
  457. return myerrors.TipsError("合同文件名不能为空")
  458. }
  459. ent, err := s.Dao.Where("id = ?", req.Id).One()
  460. if err != nil {
  461. return err
  462. }
  463. if ent == nil {
  464. return myerrors.TipsError(fmt.Sprintf("代理商/经销商不存在: %d", req.Id))
  465. }
  466. approvalData := model.RenewApproveData{
  467. CustomerType: req.CustomerType,
  468. ProxyStartTime: req.ProxyStartTime,
  469. ProxyEndTime: req.ProxyEndTime,
  470. ProxyDistrict: req.ProxyDistrict,
  471. ContractUrl: req.ContractUrl,
  472. OperatedId: s.CxtUser.Id,
  473. OperatedName: s.CxtUser.NickName,
  474. }
  475. approvalDataByte, err := json.Marshal(approvalData)
  476. if err != nil {
  477. return err
  478. }
  479. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  480. _, err = tx.Update("base_distributor", map[string]interface{}{
  481. "appro_status": "20",
  482. "appro_data": string(approvalDataByte),
  483. "appro_item": "代理商续签",
  484. }, "id = ?", req.Id)
  485. if err != nil {
  486. return err
  487. }
  488. return s.renewDingtalkProcess(ctx, ent, req)
  489. })
  490. return txerr
  491. }
  492. var ProcessCodeDistRenew = "PROC-33514974-4E38-430F-A852-D5694944F20B" // 代理商续签
  493. func (s *distributorService) renewDingtalkProcess(ctx context.Context, ent *model.BaseDistributor, req *model.DistributorRenewReq) error {
  494. var fileinfoByte []byte
  495. if req.ContractUrl != "" {
  496. var err error
  497. fileinfoByte, err = UploadDingtalk(s.CxtUser.DingtalkId, req.ContractUrl, req.ContractFileName)
  498. if err != nil {
  499. return err
  500. }
  501. }
  502. cusTypeMap, err := service.GetDictDataByType(ctx, "cust_idy")
  503. if err != nil {
  504. return err
  505. }
  506. cusType := []string{}
  507. for _, t := range strings.Split(req.CustomerType, ",") {
  508. if v := cusTypeMap[t]; v != "" {
  509. cusType = append(cusType, v)
  510. }
  511. }
  512. custTypeByte, err := json.Marshal(cusType)
  513. if err != nil {
  514. return err
  515. }
  516. proxyTime := req.ProxyStartTime.Time.Format("2006/01/02") + "-" +
  517. req.ProxyEndTime.Time.Format("2006/01/02")
  518. workflowSrv, err := workflowService.NewFlowService(ctx)
  519. if err != nil {
  520. return err
  521. }
  522. form := []*workflow.StartProcessInstanceRequestFormComponentValues{
  523. {
  524. Id: utils.String("TextField-K2AD4O5B"),
  525. Name: utils.String("代理商名称"),
  526. Value: utils.String(ent.DistName),
  527. },
  528. {
  529. Id: utils.String("DDSelectField_X3ALRAZA4BK0"),
  530. Name: utils.String("授权客户类型"),
  531. Value: utils.String(string(custTypeByte)),
  532. },
  533. {
  534. Id: utils.String("TextField_1M07EV7YVOPS0"),
  535. Name: utils.String("授权代理区域"),
  536. Value: utils.String(req.ProxyDistrict),
  537. },
  538. {
  539. Id: utils.String("TextField_UGJ0UKCU5DS0"),
  540. Name: utils.String("代理签约有效期"),
  541. Value: utils.String(proxyTime),
  542. },
  543. }
  544. if len(fileinfoByte) != 0 {
  545. form = append(form, &workflow.StartProcessInstanceRequestFormComponentValues{
  546. Id: utils.String("DDAttachment_SD6QFFBOSAO0"),
  547. Name: utils.String("代理合同"),
  548. Value: utils.String(string(fileinfoByte)),
  549. })
  550. }
  551. bizCode := strconv.Itoa(ent.Id)
  552. _, err = workflowSrv.StartProcessInstance(bizCode, workflowmodel.DistProxyRenew, "", &workflow.StartProcessInstanceRequest{
  553. ProcessCode: &ProcessCodeDistRenew,
  554. FormComponentValues: form,
  555. })
  556. return err
  557. }
  558. func (s *distributorService) ToDist(ctx context.Context, req *model.DistributorToDistReq) (err error) {
  559. validErr := gvalid.CheckStruct(ctx, req, nil)
  560. if validErr != nil {
  561. return myerrors.TipsError(validErr.Current().Error())
  562. }
  563. ent, err := s.Dao.Where("id = ?", req.Id).One()
  564. if err != nil {
  565. return err
  566. }
  567. if ent == nil {
  568. return myerrors.TipsError(fmt.Sprintf("代理商/经销商不存在: %d", req.Id))
  569. }
  570. approvalData := model.ToDistApproveData{
  571. ToDistReason: req.ToDistReason,
  572. OperatedId: s.CxtUser.Id,
  573. OperatedName: s.CxtUser.NickName,
  574. }
  575. approvalDataByte, err := json.Marshal(approvalData)
  576. if err != nil {
  577. return err
  578. }
  579. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  580. _, err = tx.Update("base_distributor", map[string]interface{}{
  581. "appro_status": "20",
  582. "appro_data": string(approvalDataByte),
  583. "appro_item": "代理商转经销商",
  584. }, "id = ?", req.Id)
  585. if err != nil {
  586. return err
  587. }
  588. return s.toDistDingtalkProcess(ctx, ent, req)
  589. })
  590. return txerr
  591. }
  592. var ProcessCodeProxyToDist = "PROC-59A0E9F5-8233-41D5-B36D-021F3E8B48D2" // 代理商转经销商
  593. func (s *distributorService) toDistDingtalkProcess(ctx context.Context, ent *model.BaseDistributor, req *model.DistributorToDistReq) error {
  594. workflowSrv, err := workflowService.NewFlowService(ctx)
  595. if err != nil {
  596. return err
  597. }
  598. form := []*workflow.StartProcessInstanceRequestFormComponentValues{
  599. {
  600. Id: utils.String("TextField-K2AD4O5B"),
  601. Name: utils.String("代理商名称"),
  602. Value: utils.String(ent.DistName),
  603. },
  604. {
  605. Id: utils.String("TextareaField_5XMN9CGTDAS0"),
  606. Name: utils.String("转移原因"),
  607. Value: utils.String(req.ToDistReason),
  608. },
  609. }
  610. bizCode := strconv.Itoa(ent.Id)
  611. _, err = workflowSrv.StartProcessInstance(bizCode, workflowmodel.DistToDist, "", &workflow.StartProcessInstanceRequest{
  612. ProcessCode: &ProcessCodeProxyToDist,
  613. FormComponentValues: form,
  614. })
  615. return err
  616. }
  617. func (s *distributorService) TransRecord(ctx context.Context, req *model.DistributorTransRecordReq) (int, []*model.BaseDistributorRecord, error) {
  618. dao := s.RecordDao.As("a")
  619. if req.DistId != 0 {
  620. dao = dao.Where("a.dist_id = ?", req.DistId)
  621. }
  622. total, err := dao.Count()
  623. if err != nil {
  624. return 0, nil, err
  625. }
  626. if req.PageNum != 0 {
  627. dao = dao.Page(req.GetPage())
  628. }
  629. orderby := "a.created_time desc"
  630. if req.OrderBy != "" {
  631. orderby = req.OrderBy
  632. }
  633. dao = dao.Order(orderby)
  634. ents := []*model.BaseDistributorRecord{}
  635. err = dao.Structs(&ents)
  636. if err != nil && err != sql.ErrNoRows {
  637. return 0, nil, err
  638. }
  639. return total, ents, nil
  640. }
  641. func (s *distributorService) SysAdminTransferDistributor(ctx context.Context, req *model.SysAdminTransferDistributorReq) (err error) {
  642. // 校验用户是否有修改权限
  643. arr := garray.NewStrArrayFrom(s.CxtUser.Roles, true)
  644. if !arr.Contains("SysAdmin") {
  645. return myerrors.TipsError("权限不足")
  646. }
  647. var updateData = g.Map{}
  648. updateData[s.Dao.C.BelongSaleId] = req.UserId
  649. updateData[s.Dao.C.BelongSale] = req.UserName
  650. service.SetUpdatedInfo(updateData, s.GetCxtUserId(), s.GetCxtUserName())
  651. dynamicsList := make([]model.BaseDistributorDynamics, 0)
  652. for _, id := range req.Ids {
  653. dynamics := model.BaseDistributorDynamics{
  654. DistId: id,
  655. OpnPeopleId: s.GetCxtUserId(),
  656. OpnPeople: s.GetCxtUserName(),
  657. OpnDate: gtime.Now(),
  658. OpnType: "转移渠道",
  659. OpnContent: gconv.String(g.Map{"toUserId": req.UserId, "toUserNickName": req.UserName, "operName": s.GetCxtUserName()}),
  660. Remark: "",
  661. CreatedBy: s.GetCxtUserId(),
  662. CreatedName: s.GetCxtUserName(),
  663. }
  664. dynamicsList = append(dynamicsList, dynamics)
  665. }
  666. err = s.Dao.Transaction(s.Ctx, func(ctx context.Context, tx *gdb.TX) error {
  667. // 项目修改
  668. _, err = s.Dao.TX(tx).WherePri(req.Ids).FieldsEx(service.UpdateFieldEx...).Data(updateData).Update()
  669. if err != nil {
  670. return err
  671. }
  672. _, err = s.DynamicsDao.TX(tx).InsertAndGetId(dynamicsList)
  673. return err
  674. })
  675. return err
  676. }
  677. // DeleteByIds 删除
  678. func (s *distributorService) DeleteByIds(ids []int64) (err error) {
  679. _, err = s.Dao.WhereIn(s.Dao.C.Id, ids).Delete()
  680. if err != nil {
  681. return err
  682. }
  683. return
  684. }
  685. func (s *distributorService) AddDynamicsByCurrentUser(tx *gdb.TX, distId int, opnType string, content map[string]interface{}) error {
  686. contentByte, err := json.Marshal(content)
  687. if err != nil {
  688. return err
  689. }
  690. _, err = tx.InsertAndGetId("base_distributor_dynamics", model.BaseDistributorDynamics{
  691. DistId: distId,
  692. OpnPeopleId: s.GetCxtUserId(),
  693. OpnPeople: s.GetCxtUserName(),
  694. OpnDate: gtime.Now(),
  695. OpnType: opnType,
  696. OpnContent: string(contentByte),
  697. Remark: "",
  698. CreatedBy: s.GetCxtUserId(),
  699. CreatedName: s.GetCxtUserName(),
  700. CreatedTime: gtime.Now(),
  701. UpdatedBy: s.GetCxtUserId(),
  702. UpdatedName: s.GetCxtUserName(),
  703. UpdatedTime: gtime.Now(),
  704. })
  705. return err
  706. }
  707. func (s *distributorService) ContractList(ctx context.Context, req *model.DistributorContractListReq) (int, []*contractmodel.CtrContractListRsp, error) {
  708. dao := s.ContractDao.As("a")
  709. if req.DistId != 0 {
  710. dao = dao.Where("a.distributor_id = ?", req.DistId)
  711. }
  712. if req.SearchText != "" {
  713. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  714. dao = dao.Where("(a.contract_code LIKE ? || a.contract_name LIKE ? || a.cust_name LIKE ? || a.nbo_name LIKE ?)", likestr, likestr, likestr, likestr)
  715. }
  716. if req.ContractCode != "" {
  717. likestr := fmt.Sprintf("%%%s%%", req.ContractCode)
  718. dao = dao.Where("a.contract_code like ?", likestr)
  719. }
  720. if req.ContractName != "" {
  721. likestr := fmt.Sprintf("%%%s%%", req.ContractName)
  722. dao = dao.Where("a.contract_name like ?", likestr)
  723. }
  724. if req.CustId != 0 {
  725. dao = dao.Where("a.cust_id = ?", req.CustId)
  726. }
  727. if req.CustName != "" {
  728. likestr := fmt.Sprintf("%%%s%%", req.CustName)
  729. dao = dao.Where("a.cust_name like ?", likestr)
  730. }
  731. if req.NboId != 0 {
  732. dao = dao.Where("a.nbo_id = ?", req.NboId)
  733. }
  734. if req.NboName != "" {
  735. likestr := fmt.Sprintf("%%%s%%", req.NboName)
  736. dao = dao.Where("a.nbo_name like ?", likestr)
  737. }
  738. if req.ApproStatus != "" {
  739. dao = dao.Where("a.appro_status = ?", req.ApproStatus)
  740. }
  741. if req.ContractType != "" {
  742. dao = dao.Where("a.contract_type = ?", req.ContractType)
  743. }
  744. if req.InchargeId != 0 {
  745. dao = dao.Where("a.incharge_id = ?", req.InchargeId)
  746. }
  747. if req.InchargeName != "" {
  748. likestr := fmt.Sprintf("%%%s%%", req.InchargeName)
  749. dao = dao.Where("a.incharge_name like ?", likestr)
  750. }
  751. if req.SignatoryId != 0 {
  752. dao = dao.Where("a.signatory_id = ?", req.SignatoryId)
  753. }
  754. if req.SignatoryName != "" {
  755. likestr := fmt.Sprintf("%%%s%%", req.SignatoryName)
  756. dao = dao.Where("a.signatory_name like ?", likestr)
  757. }
  758. if req.DistributorName != "" {
  759. likestr := fmt.Sprintf("%%%s%%", req.DistributorName)
  760. dao = dao.Where("a.distributor_name like ?", likestr)
  761. }
  762. if req.BeginTime != "" {
  763. dao = dao.Where("a.created_time > ?", req.BeginTime)
  764. }
  765. if req.EndTime != "" {
  766. dao = dao.Where("a.created_time < ?", req.EndTime)
  767. }
  768. total, err := dao.Count()
  769. if err != nil {
  770. return 0, nil, err
  771. }
  772. if req.PageNum != 0 {
  773. dao = dao.Page(req.GetPage())
  774. }
  775. orderby := "a.created_time desc"
  776. if req.OrderBy != "" {
  777. orderby = req.OrderBy
  778. }
  779. dao = dao.Order(orderby)
  780. ents := []*contractmodel.CtrContractListRsp{}
  781. err = dao.Structs(&ents)
  782. if err != nil && err != sql.ErrNoRows {
  783. return 0, nil, err
  784. }
  785. return total, ents, nil
  786. }
  787. func (s *distributorService) ProjectList(ctx context.Context, req *model.DistributorProjectListReq) (int, []*projmodel.ProjBusiness, error) {
  788. dao := &s.ProjDao.ProjBusinessDao
  789. if req.DistId != 0 {
  790. dao = dao.Where("distributor_id = ?", req.DistId)
  791. }
  792. if req.SearchText != "" {
  793. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  794. dao = dao.Where("(cust_name LIKE ? || nbo_name LIKE ?)", likestr, likestr)
  795. }
  796. if req.NboName != "" {
  797. likestr := fmt.Sprintf("%%%s%%", req.NboName)
  798. dao = dao.Where("nbo_name like ?", likestr)
  799. }
  800. if req.CustName != "" {
  801. likestr := fmt.Sprintf("%%%s%%", req.CustName)
  802. dao = dao.Where("cust_name like ?", likestr)
  803. }
  804. if req.CreatedTimeStart != nil {
  805. dao = dao.Where("created_time > ?", req.CreatedTimeStart)
  806. }
  807. if req.CreatedTimeEnd != nil {
  808. dao = dao.Where("created_time < ?", req.CreatedTimeEnd)
  809. }
  810. total, err := dao.Count()
  811. if err != nil {
  812. return 0, nil, err
  813. }
  814. if req.PageNum != 0 {
  815. dao = dao.Page(req.GetPage())
  816. }
  817. orderby := "created_time desc"
  818. if req.OrderBy != "" {
  819. orderby = req.OrderBy
  820. }
  821. dao = dao.Order(orderby)
  822. ents := []*projmodel.ProjBusiness{}
  823. err = dao.Structs(&ents)
  824. if err != nil && err != sql.ErrNoRows {
  825. return 0, nil, err
  826. }
  827. return total, ents, nil
  828. }
  829. func (s *distributorService) DynamicsList(ctx context.Context, req *model.DistributorDynamicsListReq) (int, interface{}, error) {
  830. dao := &s.DynamicsDao.BaseDistributorDynamicsDao
  831. if req.SearchText != "" {
  832. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  833. dao = dao.Where("(opn_people LIKE ? || opn_content LIKE ?)", likestr, likestr)
  834. }
  835. if req.DistId != 0 {
  836. dao = dao.Where("dist_id = ?", req.DistId)
  837. }
  838. if req.OpnPeopleId != 0 {
  839. dao = dao.Where("opn_people_id = ?", req.OpnPeopleId)
  840. }
  841. if req.OpnPeople != "" {
  842. likestr := fmt.Sprintf("%%%s%%", req.OpnPeople)
  843. dao = dao.Where("opn_people like ?", likestr)
  844. }
  845. if req.OpnType != "" {
  846. dao = dao.Where("opn_type = ?", req.OpnType)
  847. }
  848. if req.BeginTime != "" {
  849. dao = dao.Where("created_time > ?", req.BeginTime)
  850. }
  851. if req.EndTime != "" {
  852. dao = dao.Where("created_time < ?", req.EndTime)
  853. }
  854. total, err := dao.Count()
  855. if err != nil {
  856. return 0, nil, err
  857. }
  858. if req.PageNum != 0 {
  859. dao = dao.Page(req.GetPage())
  860. }
  861. orderby := "created_time desc"
  862. if req.OrderBy != "" {
  863. orderby = req.OrderBy
  864. }
  865. dao = dao.Order(orderby)
  866. ents := []*model.BaseDistributorDynamics{}
  867. err = dao.Structs(&ents)
  868. if err != nil && err != sql.ErrNoRows {
  869. return 0, nil, err
  870. }
  871. ret := map[string][]*model.BaseDistributorDynamics{}
  872. for _, ent := range ents {
  873. date := ent.OpnDate.Format("Y-m-d")
  874. ret[date] = append(ret[date], ent)
  875. }
  876. return total, ret, err
  877. }
  878. func DownFile(url string) ([]byte, error) {
  879. r, err := http.Get(url)
  880. if err != nil {
  881. return nil, err
  882. }
  883. if r.StatusCode != http.StatusOK {
  884. return nil, fmt.Errorf("DownFile from %s StatusCode %d", url, r.StatusCode)
  885. }
  886. defer r.Body.Close()
  887. return ioutil.ReadAll(r.Body)
  888. }
  889. // '审核状态 20 待审核 30 审核已同意 40 审核已拒绝 50 审核已撤销'
  890. func ApprovalProxyCreate(ctx context.Context, flow *workflowmodel.PlatWorkflow, msg *message.MixMessage) error {
  891. tenant, err := micro_srv.GetTenant(ctx)
  892. if err != nil {
  893. return fmt.Errorf("获取租户码异常:%s", err.Error())
  894. }
  895. distdao := base.NewBaseDistributorDao(tenant)
  896. entId, err := strconv.Atoi(flow.BizCode)
  897. if err != nil {
  898. return fmt.Errorf("创建代理商钉钉审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  899. }
  900. ent, err := distdao.Where("id = ?", entId).One()
  901. if err != nil {
  902. return err
  903. }
  904. if ent == nil {
  905. return fmt.Errorf("代理商不存在:%s Id: %d", flow.BizCode, flow.Id)
  906. }
  907. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  908. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  909. }
  910. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  911. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  912. }
  913. if msg.ProcessType == "terminate" {
  914. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  915. "appro_status": "50",
  916. "appro_data": "",
  917. }).Update()
  918. return err
  919. }
  920. pass := msg.Result == "agree"
  921. if !pass {
  922. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  923. "appro_status": "40",
  924. "appro_data": "",
  925. }).Update()
  926. return err
  927. }
  928. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  929. "appro_status": "30",
  930. "appro_data": "",
  931. }).Update()
  932. return err
  933. }
  934. func ApprovalDistToProxy(ctx context.Context, flow *workflowmodel.PlatWorkflow, msg *message.MixMessage) error {
  935. tenant, err := micro_srv.GetTenant(ctx)
  936. if err != nil {
  937. return fmt.Errorf("获取租户码异常:%s", err.Error())
  938. }
  939. distdao := base.NewBaseDistributorDao(tenant)
  940. entId, err := strconv.Atoi(flow.BizCode)
  941. if err != nil {
  942. return fmt.Errorf("经销商转代理商钉钉审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  943. }
  944. ent, err := distdao.Where("id = ?", entId).One()
  945. if err != nil {
  946. return err
  947. }
  948. if ent == nil {
  949. return fmt.Errorf("经销商不存在:%s Id: %d", flow.BizCode, flow.Id)
  950. }
  951. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  952. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  953. }
  954. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  955. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  956. }
  957. if msg.ProcessType == "terminate" {
  958. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  959. "appro_status": "50",
  960. "appro_data": "",
  961. }).Update()
  962. return err
  963. }
  964. pass := msg.Result == "agree"
  965. if !pass {
  966. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  967. "appro_status": "40",
  968. "appro_data": "",
  969. }).Update()
  970. return err
  971. }
  972. approData := model.ToProxyApproveData{}
  973. err = json.Unmarshal([]byte(ent.ApproData), &approData)
  974. if err != nil {
  975. return fmt.Errorf("经销商转代理商钉钉审批 ApproData 解析异常:%s Id: %d ApproData:%s", flow.BizCode, flow.Id, ent.ApproData)
  976. }
  977. txerr := distdao.DB.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  978. _, err = tx.Update("base_distributor", map[string]interface{}{
  979. "dist_type": "20",
  980. "appro_status": "30",
  981. "appro_data": "",
  982. "customer_type": approData.CustomerType,
  983. "proxy_start_time": approData.ProxyStartTime,
  984. "proxy_end_time": approData.ProxyEndTime,
  985. "proxy_district": approData.ProxyDistrict,
  986. "contract_url": approData.ContractUrl,
  987. }, "id = ?", ent.Id)
  988. if err != nil {
  989. return err
  990. }
  991. _, err = tx.Insert("base_distributor_record", model.BaseDistributorRecord{
  992. DistId: ent.Id,
  993. DistType: "20",
  994. BusinessScope: ent.BusinessScope,
  995. CustomerType: approData.CustomerType,
  996. ProxyDistrict: approData.ProxyDistrict,
  997. ProxyStartTime: approData.ProxyStartTime,
  998. ProxyEndTime: approData.ProxyEndTime,
  999. ContractUrl: approData.ContractUrl,
  1000. ExistedProduct: ent.ExistedProduct,
  1001. HistoryCustomer: ent.HistoryCustomer,
  1002. ToDistReason: "",
  1003. Remark: "",
  1004. CreatedBy: approData.OperatedId,
  1005. CreatedName: approData.OperatedName,
  1006. CreatedTime: gtime.Now(),
  1007. UpdatedBy: approData.OperatedId,
  1008. UpdatedName: approData.OperatedName,
  1009. UpdatedTime: gtime.Now(),
  1010. })
  1011. if err != nil {
  1012. return err
  1013. }
  1014. err = addDynamicsByCurrentUser(tx, ent.Id, "转为代理商",
  1015. approData, approData.OperatedId, approData.OperatedName)
  1016. if err != nil {
  1017. return err
  1018. }
  1019. return nil
  1020. })
  1021. return txerr
  1022. }
  1023. func ApprovalDistRenew(ctx context.Context, flow *workflowmodel.PlatWorkflow, msg *message.MixMessage) error {
  1024. tenant, err := micro_srv.GetTenant(ctx)
  1025. if err != nil {
  1026. return fmt.Errorf("获取租户码异常:%s", err.Error())
  1027. }
  1028. distdao := base.NewBaseDistributorDao(tenant)
  1029. entId, err := strconv.Atoi(flow.BizCode)
  1030. if err != nil {
  1031. return fmt.Errorf("代理商续签钉钉审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  1032. }
  1033. ent, err := distdao.Where("id = ?", entId).One()
  1034. if err != nil {
  1035. return err
  1036. }
  1037. if ent == nil {
  1038. return fmt.Errorf("代理商不存在:%s Id: %d", flow.BizCode, flow.Id)
  1039. }
  1040. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  1041. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  1042. }
  1043. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  1044. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  1045. }
  1046. if msg.ProcessType == "terminate" {
  1047. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  1048. "appro_status": "50",
  1049. "appro_data": "",
  1050. }).Update()
  1051. return err
  1052. }
  1053. pass := msg.Result == "agree"
  1054. if !pass {
  1055. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  1056. "appro_status": "40",
  1057. "appro_data": "",
  1058. }).Update()
  1059. return err
  1060. }
  1061. approData := model.RenewApproveData{}
  1062. err = json.Unmarshal([]byte(ent.ApproData), &approData)
  1063. if err != nil {
  1064. return fmt.Errorf("代理商续签钉钉审批 ApproData 解析异常:%s Id: %d ApproData:%s", flow.BizCode, flow.Id, ent.ApproData)
  1065. }
  1066. txerr := distdao.DB.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  1067. _, err = tx.Update("base_distributor", map[string]interface{}{
  1068. "appro_status": "30",
  1069. "appro_data": "",
  1070. "customer_type": approData.CustomerType,
  1071. "proxy_start_time": approData.ProxyStartTime,
  1072. "proxy_end_time": approData.ProxyEndTime,
  1073. "proxy_district": approData.ProxyDistrict,
  1074. "contract_url": approData.ContractUrl,
  1075. }, "id = ?", ent.Id)
  1076. if err != nil {
  1077. return err
  1078. }
  1079. _, err = tx.Insert("base_distributor_record", model.BaseDistributorRecord{
  1080. DistId: ent.Id,
  1081. DistType: "20",
  1082. BusinessScope: ent.BusinessScope,
  1083. CustomerType: approData.CustomerType,
  1084. ProxyDistrict: approData.ProxyDistrict,
  1085. ProxyStartTime: approData.ProxyStartTime,
  1086. ProxyEndTime: approData.ProxyEndTime,
  1087. ContractUrl: approData.ContractUrl,
  1088. ExistedProduct: ent.ExistedProduct,
  1089. HistoryCustomer: ent.HistoryCustomer,
  1090. ToDistReason: "",
  1091. Remark: "",
  1092. CreatedBy: approData.OperatedId,
  1093. CreatedName: approData.OperatedName,
  1094. CreatedTime: gtime.Now(),
  1095. UpdatedBy: approData.OperatedId,
  1096. UpdatedName: approData.OperatedName,
  1097. UpdatedTime: gtime.Now(),
  1098. })
  1099. if err != nil {
  1100. return err
  1101. }
  1102. err = addDynamicsByCurrentUser(tx, ent.Id, "续签代理商",
  1103. approData, approData.OperatedId, approData.OperatedName)
  1104. if err != nil {
  1105. return err
  1106. }
  1107. return nil
  1108. })
  1109. return txerr
  1110. }
  1111. func ApprovalDistToDist(ctx context.Context, flow *workflowmodel.PlatWorkflow, msg *message.MixMessage) error {
  1112. tenant, err := micro_srv.GetTenant(ctx)
  1113. if err != nil {
  1114. return fmt.Errorf("获取租户码异常:%s", err.Error())
  1115. }
  1116. distdao := base.NewBaseDistributorDao(tenant)
  1117. entId, err := strconv.Atoi(flow.BizCode)
  1118. if err != nil {
  1119. return fmt.Errorf("代理商转经销商钉钉审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  1120. }
  1121. ent, err := distdao.Where("id = ?", entId).One()
  1122. if err != nil {
  1123. return err
  1124. }
  1125. if ent == nil {
  1126. return fmt.Errorf("代理商不存在:%s Id: %d", flow.BizCode, flow.Id)
  1127. }
  1128. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  1129. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  1130. }
  1131. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  1132. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  1133. }
  1134. if msg.ProcessType == "terminate" {
  1135. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  1136. "appro_status": "50",
  1137. "appro_data": "",
  1138. }).Update()
  1139. return err
  1140. }
  1141. pass := msg.Result == "agree"
  1142. if !pass {
  1143. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  1144. "appro_status": "40",
  1145. "appro_data": "",
  1146. }).Update()
  1147. return err
  1148. }
  1149. approData := model.ToDistApproveData{}
  1150. err = json.Unmarshal([]byte(ent.ApproData), &approData)
  1151. if err != nil {
  1152. return fmt.Errorf("代理商转经销商钉钉审批 ApproData 解析异常:%s Id: %d ApproData:%s", flow.BizCode, flow.Id, ent.ApproData)
  1153. }
  1154. txerr := distdao.DB.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  1155. _, err = tx.Update("base_distributor", map[string]interface{}{
  1156. "dist_type": "10",
  1157. "appro_status": "30",
  1158. "appro_data": "",
  1159. }, "id = ?", ent.Id)
  1160. if err != nil {
  1161. return err
  1162. }
  1163. _, err = tx.Insert("base_distributor_record", model.BaseDistributorRecord{
  1164. DistId: ent.Id,
  1165. DistType: "10",
  1166. BusinessScope: ent.BusinessScope,
  1167. CustomerType: ent.CustomerType,
  1168. ProxyDistrict: "",
  1169. ProxyStartTime: nil,
  1170. ProxyEndTime: nil,
  1171. ContractUrl: "",
  1172. ExistedProduct: ent.ExistedProduct,
  1173. HistoryCustomer: ent.HistoryCustomer,
  1174. ToDistReason: approData.ToDistReason,
  1175. Remark: "",
  1176. CreatedBy: approData.OperatedId,
  1177. CreatedName: approData.OperatedName,
  1178. CreatedTime: gtime.Now(),
  1179. UpdatedBy: approData.OperatedId,
  1180. UpdatedName: approData.OperatedName,
  1181. UpdatedTime: gtime.Now(),
  1182. })
  1183. if err != nil {
  1184. return err
  1185. }
  1186. err = addDynamicsByCurrentUser(tx, ent.Id, "转为经销商",
  1187. approData, approData.OperatedId, approData.OperatedName)
  1188. if err != nil {
  1189. return err
  1190. }
  1191. return nil
  1192. })
  1193. return txerr
  1194. }
  1195. func addDynamicsByCurrentUser(tx *gdb.TX, distId int, opnType string, content interface{}, operatedId int, opreatedName string) error {
  1196. contentByte, err := json.Marshal(content)
  1197. if err != nil {
  1198. return err
  1199. }
  1200. _, err = tx.InsertAndGetId("base_distributor_dynamics", model.BaseDistributorDynamics{
  1201. DistId: distId,
  1202. OpnPeopleId: operatedId,
  1203. OpnPeople: opreatedName,
  1204. OpnDate: gtime.Now(),
  1205. OpnType: opnType,
  1206. OpnContent: string(contentByte),
  1207. Remark: "",
  1208. CreatedBy: operatedId,
  1209. CreatedName: opreatedName,
  1210. CreatedTime: gtime.Now(),
  1211. UpdatedBy: operatedId,
  1212. UpdatedName: opreatedName,
  1213. UpdatedTime: gtime.Now(),
  1214. })
  1215. return err
  1216. }
  1217. func UploadDingtalk(uid, url, name string) ([]byte, error) {
  1218. if uid == "" {
  1219. return nil, fmt.Errorf("该用户钉钉 uid 为空")
  1220. }
  1221. filedata, err := DownFile(url)
  1222. if err != nil {
  1223. return nil, err
  1224. }
  1225. filepath := path.Join(os.TempDir(), name)
  1226. err = ioutil.WriteFile(filepath, filedata, 0644)
  1227. if err != nil {
  1228. return nil, fmt.Errorf("WriteFile %s %s", filepath, err)
  1229. }
  1230. defer os.Remove(filepath)
  1231. resp, err := dingtalk.Client.GetStorage().UploadFile(service.DingTalkSpaceId, uid, name, filepath)
  1232. if err != nil {
  1233. return nil, fmt.Errorf("钉钉上传文件异常 %s", err.Error())
  1234. }
  1235. file := []contractmodel.DingFileInfo{
  1236. {
  1237. SpaceId: resp.Dentry.SpaceId,
  1238. FileId: resp.Dentry.Id,
  1239. FileName: resp.Dentry.Name,
  1240. FileSize: resp.Dentry.Size,
  1241. FileType: resp.Dentry.Extension,
  1242. },
  1243. }
  1244. return json.Marshal(file)
  1245. }
  1246. func init() {
  1247. c := gcron.New()
  1248. // 每天凌晨2点执行
  1249. c.Add("0 0 2 * * *", notifyToComplete)
  1250. }
  1251. func notifyToComplete() {
  1252. defer func() {
  1253. if r := recover(); r != nil {
  1254. glog.Errorf("完善经销商定时提醒异常 %v", r)
  1255. }
  1256. }()
  1257. tenant := g.Config().GetString("micro_srv.tenant")
  1258. if tenant == "" {
  1259. glog.Error("定时任务租户码未设置,请前往配置")
  1260. return
  1261. }
  1262. dao := base.NewBaseDistributorDao(tenant)
  1263. created := gtime.Now().Add(-time.Hour * 24 * 30)
  1264. dist, err := dao.Where("province_id = 0 or belong_sale_id = 0 or capital = 0 or register_district = '' or business_scope = '' or sale_num = 0 or customer_type = '' or existed_product = '' or history_customer = ''").Where("created_time < ?", created).Where("dist_type = 10").All()
  1265. if err != nil {
  1266. glog.Errorf("完善经销商定时提醒异常 %s", err.Error())
  1267. return
  1268. }
  1269. if len(dist) == 0 {
  1270. return
  1271. }
  1272. extraUserId, err := service.UserIdByRoles(dao.DB, "SalesDirector", "SaleAssociate")
  1273. if err != nil {
  1274. glog.Errorf("查询销售助理销售总监异常 %s", err.Error())
  1275. return
  1276. }
  1277. glog.Infof("销售助理销售总监 %v", extraUserId)
  1278. for _, d := range dist {
  1279. recvUserIds := service.SliceIntDeduplication(extraUserId)
  1280. recvUserIds = append(recvUserIds, d.BelongSaleId)
  1281. recvUserIdString := []string{}
  1282. for _, uid := range recvUserIds {
  1283. recvUserIdString = append(recvUserIdString, strconv.Itoa(uid))
  1284. }
  1285. msg := g.MapStrStr{
  1286. "msgTitle": "经销商信息完善提醒",
  1287. "msgContent": fmt.Sprintf("<p>经销商:<a href='%s'>%s</a> 的必要信息未填写完整,请及时完善</p>", distUrl(*d), d.DistName),
  1288. "msgType": "20",
  1289. "recvUserIds": strings.Join(recvUserIdString, ","),
  1290. "msgStatus": "10",
  1291. "sendType": "10",
  1292. }
  1293. if err := service.CreateSystemMessage(msg); err != nil {
  1294. g.Log().Error("经销商信息完善提醒异常:%s", err)
  1295. }
  1296. }
  1297. }