base_distributor.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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. // DeleteByIds 删除
  642. func (s *distributorService) DeleteByIds(ids []int64) (err error) {
  643. _, err = s.Dao.WhereIn(s.Dao.C.Id, ids).Delete()
  644. if err != nil {
  645. return err
  646. }
  647. return
  648. }
  649. func (s distributorService) AddDynamicsByCurrentUser(tx *gdb.TX, distId int, opnType string, content map[string]interface{}) error {
  650. contentByte, err := json.Marshal(content)
  651. if err != nil {
  652. return err
  653. }
  654. _, err = tx.InsertAndGetId("base_distributor_dynamics", model.BaseDistributorDynamics{
  655. DistId: distId,
  656. OpnPeopleId: s.GetCxtUserId(),
  657. OpnPeople: s.GetCxtUserName(),
  658. OpnDate: gtime.Now(),
  659. OpnType: opnType,
  660. OpnContent: string(contentByte),
  661. Remark: "",
  662. CreatedBy: s.GetCxtUserId(),
  663. CreatedName: s.GetCxtUserName(),
  664. CreatedTime: gtime.Now(),
  665. UpdatedBy: s.GetCxtUserId(),
  666. UpdatedName: s.GetCxtUserName(),
  667. UpdatedTime: gtime.Now(),
  668. })
  669. return err
  670. }
  671. func (s distributorService) ContractList(ctx context.Context, req *model.DistributorContractListReq) (int, []*contractmodel.CtrContractListRsp, error) {
  672. dao := s.ContractDao.As("a")
  673. if req.DistId != 0 {
  674. dao = dao.Where("a.distributor_id = ?", req.DistId)
  675. }
  676. if req.SearchText != "" {
  677. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  678. dao = dao.Where("(a.contract_code LIKE ? || a.contract_name LIKE ? || a.cust_name LIKE ? || a.nbo_name LIKE ?)", likestr, likestr, likestr, likestr)
  679. }
  680. if req.ContractCode != "" {
  681. likestr := fmt.Sprintf("%%%s%%", req.ContractCode)
  682. dao = dao.Where("a.contract_code like ?", likestr)
  683. }
  684. if req.ContractName != "" {
  685. likestr := fmt.Sprintf("%%%s%%", req.ContractName)
  686. dao = dao.Where("a.contract_name like ?", likestr)
  687. }
  688. if req.CustId != 0 {
  689. dao = dao.Where("a.cust_id = ?", req.CustId)
  690. }
  691. if req.CustName != "" {
  692. likestr := fmt.Sprintf("%%%s%%", req.CustName)
  693. dao = dao.Where("a.cust_name like ?", likestr)
  694. }
  695. if req.NboId != 0 {
  696. dao = dao.Where("a.nbo_id = ?", req.NboId)
  697. }
  698. if req.NboName != "" {
  699. likestr := fmt.Sprintf("%%%s%%", req.NboName)
  700. dao = dao.Where("a.nbo_name like ?", likestr)
  701. }
  702. if req.ApproStatus != "" {
  703. dao = dao.Where("a.appro_status = ?", req.ApproStatus)
  704. }
  705. if req.ContractType != "" {
  706. dao = dao.Where("a.contract_type = ?", req.ContractType)
  707. }
  708. if req.InchargeId != 0 {
  709. dao = dao.Where("a.incharge_id = ?", req.InchargeId)
  710. }
  711. if req.InchargeName != "" {
  712. likestr := fmt.Sprintf("%%%s%%", req.InchargeName)
  713. dao = dao.Where("a.incharge_name like ?", likestr)
  714. }
  715. if req.SignatoryId != 0 {
  716. dao = dao.Where("a.signatory_id = ?", req.SignatoryId)
  717. }
  718. if req.SignatoryName != "" {
  719. likestr := fmt.Sprintf("%%%s%%", req.SignatoryName)
  720. dao = dao.Where("a.signatory_name like ?", likestr)
  721. }
  722. if req.DistributorName != "" {
  723. likestr := fmt.Sprintf("%%%s%%", req.DistributorName)
  724. dao = dao.Where("a.distributor_name like ?", likestr)
  725. }
  726. if req.BeginTime != "" {
  727. dao = dao.Where("a.created_time > ?", req.BeginTime)
  728. }
  729. if req.EndTime != "" {
  730. dao = dao.Where("a.created_time < ?", req.EndTime)
  731. }
  732. total, err := dao.Count()
  733. if err != nil {
  734. return 0, nil, err
  735. }
  736. if req.PageNum != 0 {
  737. dao = dao.Page(req.GetPage())
  738. }
  739. orderby := "a.created_time desc"
  740. if req.OrderBy != "" {
  741. orderby = req.OrderBy
  742. }
  743. dao = dao.Order(orderby)
  744. ents := []*contractmodel.CtrContractListRsp{}
  745. err = dao.Structs(&ents)
  746. if err != nil && err != sql.ErrNoRows {
  747. return 0, nil, err
  748. }
  749. return total, ents, nil
  750. }
  751. func (s distributorService) ProjectList(ctx context.Context, req *model.DistributorProjectListReq) (int, []*projmodel.ProjBusiness, error) {
  752. dao := &s.ProjDao.ProjBusinessDao
  753. if req.DistId != 0 {
  754. dao = dao.Where("distributor_id = ?", req.DistId)
  755. }
  756. if req.SearchText != "" {
  757. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  758. dao = dao.Where("(cust_name LIKE ? || nbo_name LIKE ?)", likestr, likestr)
  759. }
  760. if req.NboName != "" {
  761. likestr := fmt.Sprintf("%%%s%%", req.NboName)
  762. dao = dao.Where("nbo_name like ?", likestr)
  763. }
  764. if req.CustName != "" {
  765. likestr := fmt.Sprintf("%%%s%%", req.CustName)
  766. dao = dao.Where("cust_name like ?", likestr)
  767. }
  768. if req.CreatedTimeStart != nil {
  769. dao = dao.Where("created_time > ?", req.CreatedTimeStart)
  770. }
  771. if req.CreatedTimeEnd != nil {
  772. dao = dao.Where("created_time < ?", req.CreatedTimeEnd)
  773. }
  774. total, err := dao.Count()
  775. if err != nil {
  776. return 0, nil, err
  777. }
  778. if req.PageNum != 0 {
  779. dao = dao.Page(req.GetPage())
  780. }
  781. orderby := "created_time desc"
  782. if req.OrderBy != "" {
  783. orderby = req.OrderBy
  784. }
  785. dao = dao.Order(orderby)
  786. ents := []*projmodel.ProjBusiness{}
  787. err = dao.Structs(&ents)
  788. if err != nil && err != sql.ErrNoRows {
  789. return 0, nil, err
  790. }
  791. return total, ents, nil
  792. }
  793. func (s distributorService) DynamicsList(ctx context.Context, req *model.DistributorDynamicsListReq) (int, interface{}, error) {
  794. dao := &s.DynamicsDao.BaseDistributorDynamicsDao
  795. if req.SearchText != "" {
  796. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  797. dao = dao.Where("(opn_people LIKE ? || opn_content LIKE ?)", likestr, likestr)
  798. }
  799. if req.DistId != 0 {
  800. dao = dao.Where("dist_id = ?", req.DistId)
  801. }
  802. if req.OpnPeopleId != 0 {
  803. dao = dao.Where("opn_people_id = ?", req.OpnPeopleId)
  804. }
  805. if req.OpnPeople != "" {
  806. likestr := fmt.Sprintf("%%%s%%", req.OpnPeople)
  807. dao = dao.Where("opn_people like ?", likestr)
  808. }
  809. if req.OpnType != "" {
  810. dao = dao.Where("opn_type = ?", req.OpnType)
  811. }
  812. if req.BeginTime != "" {
  813. dao = dao.Where("created_time > ?", req.BeginTime)
  814. }
  815. if req.EndTime != "" {
  816. dao = dao.Where("created_time < ?", req.EndTime)
  817. }
  818. total, err := dao.Count()
  819. if err != nil {
  820. return 0, nil, err
  821. }
  822. if req.PageNum != 0 {
  823. dao = dao.Page(req.GetPage())
  824. }
  825. orderby := "created_time desc"
  826. if req.OrderBy != "" {
  827. orderby = req.OrderBy
  828. }
  829. dao = dao.Order(orderby)
  830. ents := []*model.BaseDistributorDynamics{}
  831. err = dao.Structs(&ents)
  832. if err != nil && err != sql.ErrNoRows {
  833. return 0, nil, err
  834. }
  835. ret := map[string][]*model.BaseDistributorDynamics{}
  836. for _, ent := range ents {
  837. date := ent.OpnDate.Format("Y-m-d")
  838. ret[date] = append(ret[date], ent)
  839. }
  840. return total, ret, err
  841. }
  842. func DownFile(url string) ([]byte, error) {
  843. r, err := http.Get(url)
  844. if err != nil {
  845. return nil, err
  846. }
  847. if r.StatusCode != http.StatusOK {
  848. return nil, fmt.Errorf("DownFile from %s StatusCode %d", url, r.StatusCode)
  849. }
  850. defer r.Body.Close()
  851. return ioutil.ReadAll(r.Body)
  852. }
  853. // '审核状态 20 待审核 30 审核已同意 40 审核已拒绝 50 审核已撤销'
  854. func ApprovalProxyCreate(ctx context.Context, flow *workflowmodel.PlatWorkflow, msg *message.MixMessage) error {
  855. tenant, err := micro_srv.GetTenant(ctx)
  856. if err != nil {
  857. return fmt.Errorf("获取租户码异常:%s", err.Error())
  858. }
  859. distdao := base.NewBaseDistributorDao(tenant)
  860. entId, err := strconv.Atoi(flow.BizCode)
  861. if err != nil {
  862. return fmt.Errorf("创建代理商钉钉审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  863. }
  864. ent, err := distdao.Where("id = ?", entId).One()
  865. if err != nil {
  866. return err
  867. }
  868. if ent == nil {
  869. return fmt.Errorf("代理商不存在:%s Id: %d", flow.BizCode, flow.Id)
  870. }
  871. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  872. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  873. }
  874. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  875. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  876. }
  877. if msg.ProcessType == "terminate" {
  878. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  879. "appro_status": "50",
  880. "appro_data": "",
  881. }).Update()
  882. return err
  883. }
  884. pass := msg.Result == "agree"
  885. if !pass {
  886. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  887. "appro_status": "40",
  888. "appro_data": "",
  889. }).Update()
  890. return err
  891. }
  892. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  893. "appro_status": "30",
  894. "appro_data": "",
  895. }).Update()
  896. return err
  897. }
  898. func ApprovalDistToProxy(ctx context.Context, flow *workflowmodel.PlatWorkflow, msg *message.MixMessage) error {
  899. tenant, err := micro_srv.GetTenant(ctx)
  900. if err != nil {
  901. return fmt.Errorf("获取租户码异常:%s", err.Error())
  902. }
  903. distdao := base.NewBaseDistributorDao(tenant)
  904. entId, err := strconv.Atoi(flow.BizCode)
  905. if err != nil {
  906. return fmt.Errorf("经销商转代理商钉钉审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  907. }
  908. ent, err := distdao.Where("id = ?", entId).One()
  909. if err != nil {
  910. return err
  911. }
  912. if ent == nil {
  913. return fmt.Errorf("经销商不存在:%s Id: %d", flow.BizCode, flow.Id)
  914. }
  915. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  916. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  917. }
  918. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  919. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  920. }
  921. if msg.ProcessType == "terminate" {
  922. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  923. "appro_status": "50",
  924. "appro_data": "",
  925. }).Update()
  926. return err
  927. }
  928. pass := msg.Result == "agree"
  929. if !pass {
  930. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  931. "appro_status": "40",
  932. "appro_data": "",
  933. }).Update()
  934. return err
  935. }
  936. approData := model.ToProxyApproveData{}
  937. err = json.Unmarshal([]byte(ent.ApproData), &approData)
  938. if err != nil {
  939. return fmt.Errorf("经销商转代理商钉钉审批 ApproData 解析异常:%s Id: %d ApproData:%s", flow.BizCode, flow.Id, ent.ApproData)
  940. }
  941. txerr := distdao.DB.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  942. _, err = tx.Update("base_distributor", map[string]interface{}{
  943. "dist_type": "20",
  944. "appro_status": "30",
  945. "appro_data": "",
  946. "customer_type": approData.CustomerType,
  947. "proxy_start_time": approData.ProxyStartTime,
  948. "proxy_end_time": approData.ProxyEndTime,
  949. "proxy_district": approData.ProxyDistrict,
  950. "contract_url": approData.ContractUrl,
  951. }, "id = ?", ent.Id)
  952. if err != nil {
  953. return err
  954. }
  955. _, err = tx.Insert("base_distributor_record", model.BaseDistributorRecord{
  956. DistId: ent.Id,
  957. DistType: "20",
  958. BusinessScope: ent.BusinessScope,
  959. CustomerType: approData.CustomerType,
  960. ProxyDistrict: approData.ProxyDistrict,
  961. ProxyStartTime: approData.ProxyStartTime,
  962. ProxyEndTime: approData.ProxyEndTime,
  963. ContractUrl: approData.ContractUrl,
  964. ExistedProduct: ent.ExistedProduct,
  965. HistoryCustomer: ent.HistoryCustomer,
  966. ToDistReason: "",
  967. Remark: "",
  968. CreatedBy: approData.OperatedId,
  969. CreatedName: approData.OperatedName,
  970. CreatedTime: gtime.Now(),
  971. UpdatedBy: approData.OperatedId,
  972. UpdatedName: approData.OperatedName,
  973. UpdatedTime: gtime.Now(),
  974. })
  975. if err != nil {
  976. return err
  977. }
  978. err = addDynamicsByCurrentUser(tx, ent.Id, "转为代理商",
  979. approData, approData.OperatedId, approData.OperatedName)
  980. if err != nil {
  981. return err
  982. }
  983. return nil
  984. })
  985. return txerr
  986. }
  987. func ApprovalDistRenew(ctx context.Context, flow *workflowmodel.PlatWorkflow, msg *message.MixMessage) error {
  988. tenant, err := micro_srv.GetTenant(ctx)
  989. if err != nil {
  990. return fmt.Errorf("获取租户码异常:%s", err.Error())
  991. }
  992. distdao := base.NewBaseDistributorDao(tenant)
  993. entId, err := strconv.Atoi(flow.BizCode)
  994. if err != nil {
  995. return fmt.Errorf("代理商续签钉钉审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  996. }
  997. ent, err := distdao.Where("id = ?", entId).One()
  998. if err != nil {
  999. return err
  1000. }
  1001. if ent == nil {
  1002. return fmt.Errorf("代理商不存在:%s Id: %d", flow.BizCode, flow.Id)
  1003. }
  1004. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  1005. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  1006. }
  1007. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  1008. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  1009. }
  1010. if msg.ProcessType == "terminate" {
  1011. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  1012. "appro_status": "50",
  1013. "appro_data": "",
  1014. }).Update()
  1015. return err
  1016. }
  1017. pass := msg.Result == "agree"
  1018. if !pass {
  1019. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  1020. "appro_status": "40",
  1021. "appro_data": "",
  1022. }).Update()
  1023. return err
  1024. }
  1025. approData := model.RenewApproveData{}
  1026. err = json.Unmarshal([]byte(ent.ApproData), &approData)
  1027. if err != nil {
  1028. return fmt.Errorf("代理商续签钉钉审批 ApproData 解析异常:%s Id: %d ApproData:%s", flow.BizCode, flow.Id, ent.ApproData)
  1029. }
  1030. txerr := distdao.DB.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  1031. _, err = tx.Update("base_distributor", map[string]interface{}{
  1032. "appro_status": "30",
  1033. "appro_data": "",
  1034. "customer_type": approData.CustomerType,
  1035. "proxy_start_time": approData.ProxyStartTime,
  1036. "proxy_end_time": approData.ProxyEndTime,
  1037. "proxy_district": approData.ProxyDistrict,
  1038. "contract_url": approData.ContractUrl,
  1039. }, "id = ?", ent.Id)
  1040. if err != nil {
  1041. return err
  1042. }
  1043. _, err = tx.Insert("base_distributor_record", model.BaseDistributorRecord{
  1044. DistId: ent.Id,
  1045. DistType: "20",
  1046. BusinessScope: ent.BusinessScope,
  1047. CustomerType: approData.CustomerType,
  1048. ProxyDistrict: approData.ProxyDistrict,
  1049. ProxyStartTime: approData.ProxyStartTime,
  1050. ProxyEndTime: approData.ProxyEndTime,
  1051. ContractUrl: approData.ContractUrl,
  1052. ExistedProduct: ent.ExistedProduct,
  1053. HistoryCustomer: ent.HistoryCustomer,
  1054. ToDistReason: "",
  1055. Remark: "",
  1056. CreatedBy: approData.OperatedId,
  1057. CreatedName: approData.OperatedName,
  1058. CreatedTime: gtime.Now(),
  1059. UpdatedBy: approData.OperatedId,
  1060. UpdatedName: approData.OperatedName,
  1061. UpdatedTime: gtime.Now(),
  1062. })
  1063. if err != nil {
  1064. return err
  1065. }
  1066. err = addDynamicsByCurrentUser(tx, ent.Id, "续签代理商",
  1067. approData, approData.OperatedId, approData.OperatedName)
  1068. if err != nil {
  1069. return err
  1070. }
  1071. return nil
  1072. })
  1073. return txerr
  1074. }
  1075. func ApprovalDistToDist(ctx context.Context, flow *workflowmodel.PlatWorkflow, msg *message.MixMessage) error {
  1076. tenant, err := micro_srv.GetTenant(ctx)
  1077. if err != nil {
  1078. return fmt.Errorf("获取租户码异常:%s", err.Error())
  1079. }
  1080. distdao := base.NewBaseDistributorDao(tenant)
  1081. entId, err := strconv.Atoi(flow.BizCode)
  1082. if err != nil {
  1083. return fmt.Errorf("代理商转经销商钉钉审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  1084. }
  1085. ent, err := distdao.Where("id = ?", entId).One()
  1086. if err != nil {
  1087. return err
  1088. }
  1089. if ent == nil {
  1090. return fmt.Errorf("代理商不存在:%s Id: %d", flow.BizCode, flow.Id)
  1091. }
  1092. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  1093. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  1094. }
  1095. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  1096. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  1097. }
  1098. if msg.ProcessType == "terminate" {
  1099. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  1100. "appro_status": "50",
  1101. "appro_data": "",
  1102. }).Update()
  1103. return err
  1104. }
  1105. pass := msg.Result == "agree"
  1106. if !pass {
  1107. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  1108. "appro_status": "40",
  1109. "appro_data": "",
  1110. }).Update()
  1111. return err
  1112. }
  1113. approData := model.ToDistApproveData{}
  1114. err = json.Unmarshal([]byte(ent.ApproData), &approData)
  1115. if err != nil {
  1116. return fmt.Errorf("代理商转经销商钉钉审批 ApproData 解析异常:%s Id: %d ApproData:%s", flow.BizCode, flow.Id, ent.ApproData)
  1117. }
  1118. txerr := distdao.DB.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  1119. _, err = tx.Update("base_distributor", map[string]interface{}{
  1120. "dist_type": "10",
  1121. "appro_status": "30",
  1122. "appro_data": "",
  1123. }, "id = ?", ent.Id)
  1124. if err != nil {
  1125. return err
  1126. }
  1127. _, err = tx.Insert("base_distributor_record", model.BaseDistributorRecord{
  1128. DistId: ent.Id,
  1129. DistType: "10",
  1130. BusinessScope: ent.BusinessScope,
  1131. CustomerType: ent.CustomerType,
  1132. ProxyDistrict: "",
  1133. ProxyStartTime: nil,
  1134. ProxyEndTime: nil,
  1135. ContractUrl: "",
  1136. ExistedProduct: ent.ExistedProduct,
  1137. HistoryCustomer: ent.HistoryCustomer,
  1138. ToDistReason: approData.ToDistReason,
  1139. Remark: "",
  1140. CreatedBy: approData.OperatedId,
  1141. CreatedName: approData.OperatedName,
  1142. CreatedTime: gtime.Now(),
  1143. UpdatedBy: approData.OperatedId,
  1144. UpdatedName: approData.OperatedName,
  1145. UpdatedTime: gtime.Now(),
  1146. })
  1147. if err != nil {
  1148. return err
  1149. }
  1150. err = addDynamicsByCurrentUser(tx, ent.Id, "转为经销商",
  1151. approData, approData.OperatedId, approData.OperatedName)
  1152. if err != nil {
  1153. return err
  1154. }
  1155. return nil
  1156. })
  1157. return txerr
  1158. }
  1159. func addDynamicsByCurrentUser(tx *gdb.TX, distId int, opnType string, content interface{}, operatedId int, opreatedName string) error {
  1160. contentByte, err := json.Marshal(content)
  1161. if err != nil {
  1162. return err
  1163. }
  1164. _, err = tx.InsertAndGetId("base_distributor_dynamics", model.BaseDistributorDynamics{
  1165. DistId: distId,
  1166. OpnPeopleId: operatedId,
  1167. OpnPeople: opreatedName,
  1168. OpnDate: gtime.Now(),
  1169. OpnType: opnType,
  1170. OpnContent: string(contentByte),
  1171. Remark: "",
  1172. CreatedBy: operatedId,
  1173. CreatedName: opreatedName,
  1174. CreatedTime: gtime.Now(),
  1175. UpdatedBy: operatedId,
  1176. UpdatedName: opreatedName,
  1177. UpdatedTime: gtime.Now(),
  1178. })
  1179. return err
  1180. }
  1181. func UploadDingtalk(uid, url, name string) ([]byte, error) {
  1182. if uid == "" {
  1183. return nil, fmt.Errorf("该用户钉钉 uid 为空")
  1184. }
  1185. filedata, err := DownFile(url)
  1186. if err != nil {
  1187. return nil, err
  1188. }
  1189. filepath := path.Join(os.TempDir(), name)
  1190. err = ioutil.WriteFile(filepath, filedata, 0644)
  1191. if err != nil {
  1192. return nil, fmt.Errorf("WriteFile %s %s", filepath, err)
  1193. }
  1194. defer os.Remove(filepath)
  1195. resp, err := dingtalk.Client.GetStorage().UploadFile(service.DingTalkSpaceId, uid, name, filepath)
  1196. if err != nil {
  1197. return nil, fmt.Errorf("钉钉上传文件异常 %s", err.Error())
  1198. }
  1199. file := []contractmodel.DingFileInfo{
  1200. {
  1201. SpaceId: resp.Dentry.SpaceId,
  1202. FileId: resp.Dentry.Id,
  1203. FileName: resp.Dentry.Name,
  1204. FileSize: resp.Dentry.Size,
  1205. FileType: resp.Dentry.Extension,
  1206. },
  1207. }
  1208. return json.Marshal(file)
  1209. }
  1210. func init() {
  1211. c := gcron.New()
  1212. // 每天凌晨2点执行
  1213. c.Add("0 0 2 * * *", notifyToComplete)
  1214. }
  1215. func notifyToComplete() {
  1216. defer func() {
  1217. if r := recover(); r != nil {
  1218. glog.Errorf("完善经销商定时提醒异常 %v", r)
  1219. }
  1220. }()
  1221. tenant := g.Config().GetString("micro_srv.tenant")
  1222. if tenant == "" {
  1223. glog.Error("定时任务租户码未设置,请前往配置")
  1224. return
  1225. }
  1226. dao := base.NewBaseDistributorDao(tenant)
  1227. created := gtime.Now().Add(-time.Hour * 24 * 30)
  1228. 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()
  1229. if err != nil {
  1230. glog.Errorf("完善经销商定时提醒异常 %s", err.Error())
  1231. return
  1232. }
  1233. if len(dist) == 0 {
  1234. return
  1235. }
  1236. extraUserId, err := service.UserIdByRoles(dao.DB, "SalesDirector", "SaleAssociate")
  1237. if err != nil {
  1238. glog.Errorf("查询销售助理销售总监异常 %s", err.Error())
  1239. return
  1240. }
  1241. glog.Infof("销售助理销售总监 %v", extraUserId)
  1242. for _, d := range dist {
  1243. recvUserIds := service.SliceIntDeduplication(extraUserId)
  1244. recvUserIds = append(recvUserIds, d.BelongSaleId)
  1245. recvUserIdString := []string{}
  1246. for _, uid := range recvUserIds {
  1247. recvUserIdString = append(recvUserIdString, strconv.Itoa(uid))
  1248. }
  1249. msg := g.MapStrStr{
  1250. "msgTitle": "经销商信息完善提醒",
  1251. "msgContent": fmt.Sprintf("<p>经销商:<a href='%s'>%s</a> 的必要信息未填写完整,请及时完善</p>", distUrl(*d), d.DistName),
  1252. "msgType": "20",
  1253. "recvUserIds": strings.Join(recvUserIdString, ","),
  1254. "msgStatus": "10",
  1255. "sendType": "10",
  1256. }
  1257. if err := service.CreateSystemMessage(msg); err != nil {
  1258. g.Log().Error("经销商信息完善提醒异常:%s", err)
  1259. }
  1260. }
  1261. }