base_distributor.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  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>经销商:%s 的必要信息未填写完整,请及时完善</p>", 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. var ProcessCodeDistProxyCreate = "PROC-9494B87D-DE96-49EE-B676-D3913911BE21" // 创建代理商
  217. func (s *distributorService) createDingtalkProcess(ctx context.Context, ent *model.BaseDistributor, contractFileName string) error {
  218. var fileinfoByte []byte
  219. if ent.ContractUrl != "" {
  220. var err error
  221. fileinfoByte, err = UploadDingtalk(s.CxtUser.DingtalkId, ent.ContractUrl, contractFileName)
  222. if err != nil {
  223. return err
  224. }
  225. }
  226. workflowSrv, err := workflowService.NewFlowService(ctx)
  227. if err != nil {
  228. return err
  229. }
  230. bizCode := strconv.Itoa(ent.Id)
  231. form := []*workflow.StartProcessInstanceRequestFormComponentValues{
  232. {
  233. Id: utils.String("TextField-K2AD4O5B"),
  234. Name: utils.String("代理商名称"),
  235. Value: utils.String(ent.DistName),
  236. },
  237. {
  238. Id: utils.String("TextField_DZ2HNXRKHCG"),
  239. Name: utils.String("所在省"),
  240. Value: utils.String(ent.ProvinceDesc),
  241. },
  242. {
  243. Id: utils.String("TextField_1M07EV7YVOPS0"),
  244. Name: utils.String("业务范围"),
  245. Value: utils.String(ent.BusinessScope),
  246. },
  247. {
  248. Id: utils.String("TextField_UGJ0UKCU5DS0"),
  249. Name: utils.String("注册资金(万元)"),
  250. Value: utils.String(strconv.FormatFloat(ent.Capital, 'f', 2, 64)),
  251. },
  252. {
  253. Id: utils.String("TextField_1RC4FO1WUZ4W0"),
  254. Name: utils.String("注册地"),
  255. Value: utils.String(ent.RegisterDistrict),
  256. },
  257. {
  258. Id: utils.String("TextField_FKM6LUQYLFS0"),
  259. Name: utils.String("现有销售人数"),
  260. Value: utils.String(strconv.Itoa(ent.SaleNum)),
  261. },
  262. {
  263. Id: utils.String("TextField_1L89WCJM3ZMO0"),
  264. Name: utils.String("已有代理名牌和产品"),
  265. Value: utils.String(ent.ExistedProduct),
  266. },
  267. {
  268. Id: utils.String("TextField_P5JA5OZ5XKW0"),
  269. Name: utils.String("历史合作的终端客户名称"),
  270. Value: utils.String(ent.HistoryCustomer),
  271. },
  272. }
  273. if len(fileinfoByte) != 0 {
  274. form = append(form, &workflow.StartProcessInstanceRequestFormComponentValues{
  275. Id: utils.String("DDAttachment_SD6QFFBOSAO0"),
  276. Name: utils.String("代理合同"),
  277. Value: utils.String(string(fileinfoByte)),
  278. })
  279. }
  280. _, err = workflowSrv.StartProcessInstance(bizCode, workflowmodel.DistProxyCreate, "", &workflow.StartProcessInstanceRequest{
  281. ProcessCode: &ProcessCodeDistProxyCreate,
  282. FormComponentValues: form,
  283. })
  284. return err
  285. }
  286. // GetEntityById 详情
  287. func (s *distributorService) GetEntityById(id int64) (distributorInfo *model.BaseDistributorListRsp, err error) {
  288. err = s.Dao.Where(base.BaseProduct.C.Id, id).Scan(&distributorInfo)
  289. if err != nil {
  290. return nil, err
  291. }
  292. statistic, err := s.statistic(int(id))
  293. if err != nil {
  294. return nil, err
  295. }
  296. distributorInfo.BaseDistributorStatistic = statistic
  297. target, err := s.TargetDao.Where("dist_id = ?", id).Where("year = ?", time.Now().Year()).One()
  298. if err != nil {
  299. return nil, err
  300. }
  301. if target != nil {
  302. distributorInfo.YearTarget = target.Total
  303. }
  304. return
  305. }
  306. // UpdateById 修改数据
  307. func (s *distributorService) UpdateById(req *model.UpdateDistributorReq) (err error) {
  308. ent, err := s.Dao.Where("id = ", req.Id).One()
  309. if err != nil {
  310. g.Log().Error(err)
  311. return
  312. }
  313. if ent == nil {
  314. err = myerrors.TipsError("无修改数据")
  315. return
  316. }
  317. if ent.ApproStatus == "20" {
  318. err = myerrors.TipsError("不能修改待审核数据")
  319. return
  320. }
  321. distData := new(model.BaseDistributor)
  322. if err = gconv.Struct(req, distData); err != nil {
  323. return
  324. }
  325. service.SetUpdatedInfo(distData, s.GetCxtUserId(), s.GetCxtUserName())
  326. _, err = s.Dao.FieldsEx(s.Dao.C.DistCode, s.Dao.C.Id,
  327. s.Dao.C.CreatedName, s.Dao.C.CreatedBy, s.Dao.C.CreatedTime).WherePri(s.Dao.C.Id, req.Id).Update(distData)
  328. if err != nil {
  329. g.Log().Error(err)
  330. return
  331. }
  332. err = s.Dao.DB.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  333. err = s.AddDynamicsByCurrentUser(tx, req.Id, "更新经销商/代理商", map[string]interface{}{})
  334. return err
  335. })
  336. return
  337. }
  338. func (s *distributorService) ToProxy(ctx context.Context, req *model.DistributorToProxyReq) (err error) {
  339. validErr := gvalid.CheckStruct(ctx, req, nil)
  340. if validErr != nil {
  341. return myerrors.TipsError(validErr.Current().Error())
  342. }
  343. if req.ContractUrl != "" && req.ContractFileName == "" {
  344. return myerrors.TipsError("合同文件名不能为空")
  345. }
  346. ent, err := s.Dao.Where("id = ?", req.Id).One()
  347. if err != nil {
  348. return err
  349. }
  350. if ent == nil {
  351. return myerrors.TipsError(fmt.Sprintf("代理商/经销商不存在: %d", req.Id))
  352. }
  353. approvalData := model.ToProxyApproveData{
  354. CustomerType: req.CustomerType,
  355. ProxyStartTime: req.ProxyStartTime,
  356. ProxyEndTime: req.ProxyEndTime,
  357. ProxyDistrict: req.ProxyDistrict,
  358. ContractUrl: req.ContractUrl,
  359. OperatedId: s.CxtUser.Id,
  360. OperatedName: s.CxtUser.NickName,
  361. }
  362. approvalDataByte, err := json.Marshal(approvalData)
  363. if err != nil {
  364. return err
  365. }
  366. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  367. _, err = tx.Update("base_distributor", map[string]interface{}{
  368. "appro_status": "20",
  369. "appro_data": string(approvalDataByte),
  370. "appro_item": "经销商转代理商",
  371. }, "id = ?", req.Id)
  372. if err != nil {
  373. return err
  374. }
  375. return s.toProxyDingtalkProcess(ctx, ent, req)
  376. })
  377. return txerr
  378. }
  379. var ProcessCodeDistToProxy = "PROC-39C96165-131C-48EC-B8C0-AA528E0C9F3A" // 经销商转代理商
  380. func (s *distributorService) toProxyDingtalkProcess(ctx context.Context, ent *model.BaseDistributor, req *model.DistributorToProxyReq) error {
  381. var fileinfoByte []byte
  382. if req.ContractUrl != "" {
  383. var err error
  384. fileinfoByte, err = UploadDingtalk(s.CxtUser.DingtalkId, req.ContractUrl, req.ContractFileName)
  385. if err != nil {
  386. return err
  387. }
  388. }
  389. cusTypeMap, err := service.GetDictDataByType(ctx, "cust_idy")
  390. if err != nil {
  391. return err
  392. }
  393. cusType := []string{}
  394. for _, t := range strings.Split(req.CustomerType, ",") {
  395. if v := cusTypeMap[t]; v != "" {
  396. cusType = append(cusType, v)
  397. }
  398. }
  399. custTypeByte, err := json.Marshal(cusType)
  400. if err != nil {
  401. return err
  402. }
  403. proxyTime := req.ProxyStartTime.Time.Format("2006/01/02") + "-" +
  404. req.ProxyEndTime.Time.Format("2006/01/02")
  405. workflowSrv, err := workflowService.NewFlowService(ctx)
  406. if err != nil {
  407. return err
  408. }
  409. form := []*workflow.StartProcessInstanceRequestFormComponentValues{
  410. {
  411. Id: utils.String("TextField-K2AD4O5B"),
  412. Name: utils.String("代理商名称"),
  413. Value: utils.String(ent.DistName),
  414. },
  415. {
  416. Id: utils.String("DDSelectField_X3ALRAZA4BK0"),
  417. Name: utils.String("授权客户类型"),
  418. Value: utils.String(string(custTypeByte)),
  419. },
  420. {
  421. Id: utils.String("TextField_1M07EV7YVOPS0"),
  422. Name: utils.String("授权代理区域"),
  423. Value: utils.String(req.ProxyDistrict),
  424. },
  425. {
  426. Id: utils.String("TextField_UGJ0UKCU5DS0"),
  427. Name: utils.String("代理签约有效期"),
  428. Value: utils.String(proxyTime),
  429. },
  430. }
  431. if len(fileinfoByte) != 0 {
  432. form = append(form, &workflow.StartProcessInstanceRequestFormComponentValues{
  433. Id: utils.String("DDAttachment_SD6QFFBOSAO0"),
  434. Name: utils.String("代理合同"),
  435. Value: utils.String(string(fileinfoByte)),
  436. })
  437. }
  438. bizCode := strconv.Itoa(ent.Id)
  439. _, err = workflowSrv.StartProcessInstance(bizCode, workflowmodel.DistToProxy, "", &workflow.StartProcessInstanceRequest{
  440. ProcessCode: &ProcessCodeDistToProxy,
  441. FormComponentValues: form,
  442. })
  443. return err
  444. }
  445. func (s *distributorService) Renew(ctx context.Context, req *model.DistributorRenewReq) (err error) {
  446. validErr := gvalid.CheckStruct(ctx, req, nil)
  447. if validErr != nil {
  448. return myerrors.TipsError(validErr.Current().Error())
  449. }
  450. if req.ContractUrl != "" && req.ContractFileName == "" {
  451. return myerrors.TipsError("合同文件名不能为空")
  452. }
  453. ent, err := s.Dao.Where("id = ?", req.Id).One()
  454. if err != nil {
  455. return err
  456. }
  457. if ent == nil {
  458. return myerrors.TipsError(fmt.Sprintf("代理商/经销商不存在: %d", req.Id))
  459. }
  460. approvalData := model.RenewApproveData{
  461. CustomerType: req.CustomerType,
  462. ProxyStartTime: req.ProxyStartTime,
  463. ProxyEndTime: req.ProxyEndTime,
  464. ProxyDistrict: req.ProxyDistrict,
  465. ContractUrl: req.ContractUrl,
  466. OperatedId: s.CxtUser.Id,
  467. OperatedName: s.CxtUser.NickName,
  468. }
  469. approvalDataByte, err := json.Marshal(approvalData)
  470. if err != nil {
  471. return err
  472. }
  473. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  474. _, err = tx.Update("base_distributor", map[string]interface{}{
  475. "appro_status": "20",
  476. "appro_data": string(approvalDataByte),
  477. "appro_item": "代理商续签",
  478. }, "id = ?", req.Id)
  479. if err != nil {
  480. return err
  481. }
  482. return s.renewDingtalkProcess(ctx, ent, req)
  483. })
  484. return txerr
  485. }
  486. var ProcessCodeDistRenew = "PROC-33514974-4E38-430F-A852-D5694944F20B" // 代理商续签
  487. func (s *distributorService) renewDingtalkProcess(ctx context.Context, ent *model.BaseDistributor, req *model.DistributorRenewReq) error {
  488. var fileinfoByte []byte
  489. if req.ContractUrl != "" {
  490. var err error
  491. fileinfoByte, err = UploadDingtalk(s.CxtUser.DingtalkId, req.ContractUrl, req.ContractFileName)
  492. if err != nil {
  493. return err
  494. }
  495. }
  496. cusTypeMap, err := service.GetDictDataByType(ctx, "cust_idy")
  497. if err != nil {
  498. return err
  499. }
  500. cusType := []string{}
  501. for _, t := range strings.Split(req.CustomerType, ",") {
  502. if v := cusTypeMap[t]; v != "" {
  503. cusType = append(cusType, v)
  504. }
  505. }
  506. custTypeByte, err := json.Marshal(cusType)
  507. if err != nil {
  508. return err
  509. }
  510. proxyTime := req.ProxyStartTime.Time.Format("2006/01/02") + "-" +
  511. req.ProxyEndTime.Time.Format("2006/01/02")
  512. workflowSrv, err := workflowService.NewFlowService(ctx)
  513. if err != nil {
  514. return err
  515. }
  516. form := []*workflow.StartProcessInstanceRequestFormComponentValues{
  517. {
  518. Id: utils.String("TextField-K2AD4O5B"),
  519. Name: utils.String("代理商名称"),
  520. Value: utils.String(ent.DistName),
  521. },
  522. {
  523. Id: utils.String("DDSelectField_X3ALRAZA4BK0"),
  524. Name: utils.String("授权客户类型"),
  525. Value: utils.String(string(custTypeByte)),
  526. },
  527. {
  528. Id: utils.String("TextField_1M07EV7YVOPS0"),
  529. Name: utils.String("授权代理区域"),
  530. Value: utils.String(req.ProxyDistrict),
  531. },
  532. {
  533. Id: utils.String("TextField_UGJ0UKCU5DS0"),
  534. Name: utils.String("代理签约有效期"),
  535. Value: utils.String(proxyTime),
  536. },
  537. }
  538. if len(fileinfoByte) != 0 {
  539. form = append(form, &workflow.StartProcessInstanceRequestFormComponentValues{
  540. Id: utils.String("DDAttachment_SD6QFFBOSAO0"),
  541. Name: utils.String("代理合同"),
  542. Value: utils.String(string(fileinfoByte)),
  543. })
  544. }
  545. bizCode := strconv.Itoa(ent.Id)
  546. _, err = workflowSrv.StartProcessInstance(bizCode, workflowmodel.DistProxyRenew, "", &workflow.StartProcessInstanceRequest{
  547. ProcessCode: &ProcessCodeDistRenew,
  548. FormComponentValues: form,
  549. })
  550. return err
  551. }
  552. func (s *distributorService) ToDist(ctx context.Context, req *model.DistributorToDistReq) (err error) {
  553. validErr := gvalid.CheckStruct(ctx, req, nil)
  554. if validErr != nil {
  555. return myerrors.TipsError(validErr.Current().Error())
  556. }
  557. ent, err := s.Dao.Where("id = ?", req.Id).One()
  558. if err != nil {
  559. return err
  560. }
  561. if ent == nil {
  562. return myerrors.TipsError(fmt.Sprintf("代理商/经销商不存在: %d", req.Id))
  563. }
  564. approvalData := model.ToDistApproveData{
  565. ToDistReason: req.ToDistReason,
  566. OperatedId: s.CxtUser.Id,
  567. OperatedName: s.CxtUser.NickName,
  568. }
  569. approvalDataByte, err := json.Marshal(approvalData)
  570. if err != nil {
  571. return err
  572. }
  573. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  574. _, err = tx.Update("base_distributor", map[string]interface{}{
  575. "appro_status": "20",
  576. "appro_data": string(approvalDataByte),
  577. "appro_item": "代理商转经销商",
  578. }, "id = ?", req.Id)
  579. if err != nil {
  580. return err
  581. }
  582. return s.toDistDingtalkProcess(ctx, ent, req)
  583. })
  584. return txerr
  585. }
  586. var ProcessCodeProxyToDist = "PROC-59A0E9F5-8233-41D5-B36D-021F3E8B48D2" // 代理商转经销商
  587. func (s *distributorService) toDistDingtalkProcess(ctx context.Context, ent *model.BaseDistributor, req *model.DistributorToDistReq) error {
  588. workflowSrv, err := workflowService.NewFlowService(ctx)
  589. if err != nil {
  590. return err
  591. }
  592. form := []*workflow.StartProcessInstanceRequestFormComponentValues{
  593. {
  594. Id: utils.String("TextField-K2AD4O5B"),
  595. Name: utils.String("代理商名称"),
  596. Value: utils.String(ent.DistName),
  597. },
  598. {
  599. Id: utils.String("TextareaField_5XMN9CGTDAS0"),
  600. Name: utils.String("转移原因"),
  601. Value: utils.String(req.ToDistReason),
  602. },
  603. }
  604. bizCode := strconv.Itoa(ent.Id)
  605. _, err = workflowSrv.StartProcessInstance(bizCode, workflowmodel.DistToDist, "", &workflow.StartProcessInstanceRequest{
  606. ProcessCode: &ProcessCodeProxyToDist,
  607. FormComponentValues: form,
  608. })
  609. return err
  610. }
  611. func (s *distributorService) TransRecord(ctx context.Context, req *model.DistributorTransRecordReq) (int, []*model.BaseDistributorRecord, error) {
  612. dao := s.RecordDao.As("a")
  613. if req.DistId != 0 {
  614. dao = dao.Where("a.dist_id = ?", req.DistId)
  615. }
  616. total, err := dao.Count()
  617. if err != nil {
  618. return 0, nil, err
  619. }
  620. if req.PageNum != 0 {
  621. dao = dao.Page(req.GetPage())
  622. }
  623. orderby := "a.created_time desc"
  624. if req.OrderBy != "" {
  625. orderby = req.OrderBy
  626. }
  627. dao = dao.Order(orderby)
  628. ents := []*model.BaseDistributorRecord{}
  629. err = dao.Structs(&ents)
  630. if err != nil && err != sql.ErrNoRows {
  631. return 0, nil, err
  632. }
  633. return total, ents, nil
  634. }
  635. // DeleteByIds 删除
  636. func (s *distributorService) DeleteByIds(ids []int64) (err error) {
  637. _, err = s.Dao.WhereIn(s.Dao.C.Id, ids).Delete()
  638. if err != nil {
  639. return err
  640. }
  641. return
  642. }
  643. func (s distributorService) AddDynamicsByCurrentUser(tx *gdb.TX, distId int, opnType string, content map[string]interface{}) error {
  644. contentByte, err := json.Marshal(content)
  645. if err != nil {
  646. return err
  647. }
  648. _, err = tx.InsertAndGetId("base_distributor_dynamics", model.BaseDistributorDynamics{
  649. DistId: distId,
  650. OpnPeopleId: s.GetCxtUserId(),
  651. OpnPeople: s.GetCxtUserName(),
  652. OpnDate: gtime.Now(),
  653. OpnType: opnType,
  654. OpnContent: string(contentByte),
  655. Remark: "",
  656. CreatedBy: s.GetCxtUserId(),
  657. CreatedName: s.GetCxtUserName(),
  658. CreatedTime: gtime.Now(),
  659. UpdatedBy: s.GetCxtUserId(),
  660. UpdatedName: s.GetCxtUserName(),
  661. UpdatedTime: gtime.Now(),
  662. })
  663. return err
  664. }
  665. func (s distributorService) ContractList(ctx context.Context, req *model.DistributorContractListReq) (int, []*contractmodel.CtrContractListRsp, error) {
  666. dao := s.ContractDao.As("a")
  667. if req.DistId != 0 {
  668. dao = dao.Where("a.distributor_id = ?", req.DistId)
  669. }
  670. if req.SearchText != "" {
  671. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  672. dao = dao.Where("(a.contract_code LIKE ? || a.contract_name LIKE ? || a.cust_name LIKE ? || a.nbo_name LIKE ?)", likestr, likestr, likestr, likestr)
  673. }
  674. if req.ContractCode != "" {
  675. likestr := fmt.Sprintf("%%%s%%", req.ContractCode)
  676. dao = dao.Where("a.contract_code like ?", likestr)
  677. }
  678. if req.ContractName != "" {
  679. likestr := fmt.Sprintf("%%%s%%", req.ContractName)
  680. dao = dao.Where("a.contract_name like ?", likestr)
  681. }
  682. if req.CustId != 0 {
  683. dao = dao.Where("a.cust_id = ?", req.CustId)
  684. }
  685. if req.CustName != "" {
  686. likestr := fmt.Sprintf("%%%s%%", req.CustName)
  687. dao = dao.Where("a.cust_name like ?", likestr)
  688. }
  689. if req.NboId != 0 {
  690. dao = dao.Where("a.nbo_id = ?", req.NboId)
  691. }
  692. if req.NboName != "" {
  693. likestr := fmt.Sprintf("%%%s%%", req.NboName)
  694. dao = dao.Where("a.nbo_name like ?", likestr)
  695. }
  696. if req.ApproStatus != "" {
  697. dao = dao.Where("a.appro_status = ?", req.ApproStatus)
  698. }
  699. if req.ContractType != "" {
  700. dao = dao.Where("a.contract_type = ?", req.ContractType)
  701. }
  702. if req.InchargeId != 0 {
  703. dao = dao.Where("a.incharge_id = ?", req.InchargeId)
  704. }
  705. if req.InchargeName != "" {
  706. likestr := fmt.Sprintf("%%%s%%", req.InchargeName)
  707. dao = dao.Where("a.incharge_name like ?", likestr)
  708. }
  709. if req.SignatoryId != 0 {
  710. dao = dao.Where("a.signatory_id = ?", req.SignatoryId)
  711. }
  712. if req.SignatoryName != "" {
  713. likestr := fmt.Sprintf("%%%s%%", req.SignatoryName)
  714. dao = dao.Where("a.signatory_name like ?", likestr)
  715. }
  716. if req.DistributorName != "" {
  717. likestr := fmt.Sprintf("%%%s%%", req.DistributorName)
  718. dao = dao.Where("a.distributor_name like ?", likestr)
  719. }
  720. if req.BeginTime != "" {
  721. dao = dao.Where("a.created_time > ?", req.BeginTime)
  722. }
  723. if req.EndTime != "" {
  724. dao = dao.Where("a.created_time < ?", req.EndTime)
  725. }
  726. total, err := dao.Count()
  727. if err != nil {
  728. return 0, nil, err
  729. }
  730. if req.PageNum != 0 {
  731. dao = dao.Page(req.GetPage())
  732. }
  733. orderby := "a.created_time desc"
  734. if req.OrderBy != "" {
  735. orderby = req.OrderBy
  736. }
  737. dao = dao.Order(orderby)
  738. ents := []*contractmodel.CtrContractListRsp{}
  739. err = dao.Structs(&ents)
  740. if err != nil && err != sql.ErrNoRows {
  741. return 0, nil, err
  742. }
  743. return total, ents, nil
  744. }
  745. func (s distributorService) ProjectList(ctx context.Context, req *model.DistributorProjectListReq) (int, []*projmodel.ProjBusiness, error) {
  746. dao := &s.ProjDao.ProjBusinessDao
  747. if req.DistId != 0 {
  748. dao = dao.Where("distributor_id = ?", req.DistId)
  749. }
  750. if req.SearchText != "" {
  751. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  752. dao = dao.Where("(cust_name LIKE ? || nbo_name LIKE ?)", likestr, likestr)
  753. }
  754. if req.NboName != "" {
  755. likestr := fmt.Sprintf("%%%s%%", req.NboName)
  756. dao = dao.Where("nbo_name like ?", likestr)
  757. }
  758. if req.CustName != "" {
  759. likestr := fmt.Sprintf("%%%s%%", req.CustName)
  760. dao = dao.Where("cust_name like ?", likestr)
  761. }
  762. if req.CreatedTimeStart != nil {
  763. dao = dao.Where("created_time > ?", req.CreatedTimeStart)
  764. }
  765. if req.CreatedTimeEnd != nil {
  766. dao = dao.Where("created_time < ?", req.CreatedTimeEnd)
  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 := "created_time desc"
  776. if req.OrderBy != "" {
  777. orderby = req.OrderBy
  778. }
  779. dao = dao.Order(orderby)
  780. ents := []*projmodel.ProjBusiness{}
  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) DynamicsList(ctx context.Context, req *model.DistributorDynamicsListReq) (int, interface{}, error) {
  788. dao := &s.DynamicsDao.BaseDistributorDynamicsDao
  789. if req.SearchText != "" {
  790. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  791. dao = dao.Where("(opn_people LIKE ? || opn_content LIKE ?)", likestr, likestr)
  792. }
  793. if req.DistId != 0 {
  794. dao = dao.Where("dist_id = ?", req.DistId)
  795. }
  796. if req.OpnPeopleId != 0 {
  797. dao = dao.Where("opn_people_id = ?", req.OpnPeopleId)
  798. }
  799. if req.OpnPeople != "" {
  800. likestr := fmt.Sprintf("%%%s%%", req.OpnPeople)
  801. dao = dao.Where("opn_people like ?", likestr)
  802. }
  803. if req.OpnType != "" {
  804. dao = dao.Where("opn_type = ?", req.OpnType)
  805. }
  806. if req.BeginTime != "" {
  807. dao = dao.Where("created_time > ?", req.BeginTime)
  808. }
  809. if req.EndTime != "" {
  810. dao = dao.Where("created_time < ?", req.EndTime)
  811. }
  812. total, err := dao.Count()
  813. if err != nil {
  814. return 0, nil, err
  815. }
  816. if req.PageNum != 0 {
  817. dao = dao.Page(req.GetPage())
  818. }
  819. orderby := "created_time desc"
  820. if req.OrderBy != "" {
  821. orderby = req.OrderBy
  822. }
  823. dao = dao.Order(orderby)
  824. ents := []*model.BaseDistributorDynamics{}
  825. err = dao.Structs(&ents)
  826. if err != nil && err != sql.ErrNoRows {
  827. return 0, nil, err
  828. }
  829. ret := map[string][]*model.BaseDistributorDynamics{}
  830. for _, ent := range ents {
  831. date := ent.OpnDate.Format("Y-m-d")
  832. ret[date] = append(ret[date], ent)
  833. }
  834. return total, ret, err
  835. }
  836. func DownFile(url string) ([]byte, error) {
  837. r, err := http.Get(url)
  838. if err != nil {
  839. return nil, err
  840. }
  841. if r.StatusCode != http.StatusOK {
  842. return nil, fmt.Errorf("DownFile from %s StatusCode %d", url, r.StatusCode)
  843. }
  844. defer r.Body.Close()
  845. return ioutil.ReadAll(r.Body)
  846. }
  847. // '审核状态 20 待审核 30 审核已同意 40 审核已拒绝 50 审核已撤销'
  848. func ApprovalProxyCreate(ctx context.Context, flow *workflowmodel.PlatWorkflow, msg *message.MixMessage) error {
  849. tenant, err := micro_srv.GetTenant(ctx)
  850. if err != nil {
  851. return fmt.Errorf("获取租户码异常:%s", err.Error())
  852. }
  853. distdao := base.NewBaseDistributorDao(tenant)
  854. entId, err := strconv.Atoi(flow.BizCode)
  855. if err != nil {
  856. return fmt.Errorf("创建代理商钉钉审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  857. }
  858. ent, err := distdao.Where("id = ?", entId).One()
  859. if err != nil {
  860. return err
  861. }
  862. if ent == nil {
  863. return fmt.Errorf("代理商不存在:%s Id: %d", flow.BizCode, flow.Id)
  864. }
  865. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  866. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  867. }
  868. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  869. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  870. }
  871. if msg.ProcessType == "terminate" {
  872. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  873. "appro_status": "50",
  874. "appro_data": "",
  875. }).Update()
  876. return err
  877. }
  878. pass := msg.Result == "agree"
  879. if !pass {
  880. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  881. "appro_status": "40",
  882. "appro_data": "",
  883. }).Update()
  884. return err
  885. }
  886. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  887. "appro_status": "30",
  888. "appro_data": "",
  889. }).Update()
  890. return err
  891. }
  892. func ApprovalDistToProxy(ctx context.Context, flow *workflowmodel.PlatWorkflow, msg *message.MixMessage) error {
  893. tenant, err := micro_srv.GetTenant(ctx)
  894. if err != nil {
  895. return fmt.Errorf("获取租户码异常:%s", err.Error())
  896. }
  897. distdao := base.NewBaseDistributorDao(tenant)
  898. entId, err := strconv.Atoi(flow.BizCode)
  899. if err != nil {
  900. return fmt.Errorf("经销商转代理商钉钉审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  901. }
  902. ent, err := distdao.Where("id = ?", entId).One()
  903. if err != nil {
  904. return err
  905. }
  906. if ent == nil {
  907. return fmt.Errorf("经销商不存在:%s Id: %d", flow.BizCode, flow.Id)
  908. }
  909. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  910. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  911. }
  912. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  913. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  914. }
  915. if msg.ProcessType == "terminate" {
  916. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  917. "appro_status": "50",
  918. "appro_data": "",
  919. }).Update()
  920. return err
  921. }
  922. pass := msg.Result == "agree"
  923. if !pass {
  924. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  925. "appro_status": "40",
  926. "appro_data": "",
  927. }).Update()
  928. return err
  929. }
  930. approData := model.ToProxyApproveData{}
  931. err = json.Unmarshal([]byte(ent.ApproData), &approData)
  932. if err != nil {
  933. return fmt.Errorf("经销商转代理商钉钉审批 ApproData 解析异常:%s Id: %d ApproData:%s", flow.BizCode, flow.Id, ent.ApproData)
  934. }
  935. txerr := distdao.DB.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  936. _, err = tx.Update("base_distributor", map[string]interface{}{
  937. "dist_type": "20",
  938. "appro_status": "30",
  939. "appro_data": "",
  940. "customer_type": approData.CustomerType,
  941. "proxy_start_time": approData.ProxyStartTime,
  942. "proxy_end_time": approData.ProxyEndTime,
  943. "proxy_district": approData.ProxyDistrict,
  944. "contract_url": approData.ContractUrl,
  945. }, "id = ?", ent.Id)
  946. if err != nil {
  947. return err
  948. }
  949. _, err = tx.Insert("base_distributor_record", model.BaseDistributorRecord{
  950. DistId: ent.Id,
  951. DistType: "20",
  952. BusinessScope: ent.BusinessScope,
  953. CustomerType: approData.CustomerType,
  954. ProxyDistrict: approData.ProxyDistrict,
  955. ProxyStartTime: approData.ProxyStartTime,
  956. ProxyEndTime: approData.ProxyEndTime,
  957. ContractUrl: approData.ContractUrl,
  958. ExistedProduct: ent.ExistedProduct,
  959. HistoryCustomer: ent.HistoryCustomer,
  960. ToDistReason: "",
  961. Remark: "",
  962. CreatedBy: approData.OperatedId,
  963. CreatedName: approData.OperatedName,
  964. CreatedTime: gtime.Now(),
  965. UpdatedBy: approData.OperatedId,
  966. UpdatedName: approData.OperatedName,
  967. UpdatedTime: gtime.Now(),
  968. })
  969. if err != nil {
  970. return err
  971. }
  972. err = addDynamicsByCurrentUser(tx, ent.Id, "转为代理商",
  973. approData, approData.OperatedId, approData.OperatedName)
  974. if err != nil {
  975. return err
  976. }
  977. return nil
  978. })
  979. return txerr
  980. }
  981. func ApprovalDistRenew(ctx context.Context, flow *workflowmodel.PlatWorkflow, msg *message.MixMessage) error {
  982. tenant, err := micro_srv.GetTenant(ctx)
  983. if err != nil {
  984. return fmt.Errorf("获取租户码异常:%s", err.Error())
  985. }
  986. distdao := base.NewBaseDistributorDao(tenant)
  987. entId, err := strconv.Atoi(flow.BizCode)
  988. if err != nil {
  989. return fmt.Errorf("代理商续签钉钉审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  990. }
  991. ent, err := distdao.Where("id = ?", entId).One()
  992. if err != nil {
  993. return err
  994. }
  995. if ent == nil {
  996. return fmt.Errorf("代理商不存在:%s Id: %d", flow.BizCode, flow.Id)
  997. }
  998. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  999. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  1000. }
  1001. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  1002. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  1003. }
  1004. if msg.ProcessType == "terminate" {
  1005. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  1006. "appro_status": "50",
  1007. "appro_data": "",
  1008. }).Update()
  1009. return err
  1010. }
  1011. pass := msg.Result == "agree"
  1012. if !pass {
  1013. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  1014. "appro_status": "40",
  1015. "appro_data": "",
  1016. }).Update()
  1017. return err
  1018. }
  1019. approData := model.RenewApproveData{}
  1020. err = json.Unmarshal([]byte(ent.ApproData), &approData)
  1021. if err != nil {
  1022. return fmt.Errorf("代理商续签钉钉审批 ApproData 解析异常:%s Id: %d ApproData:%s", flow.BizCode, flow.Id, ent.ApproData)
  1023. }
  1024. txerr := distdao.DB.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  1025. _, err = tx.Update("base_distributor", map[string]interface{}{
  1026. "appro_status": "30",
  1027. "appro_data": "",
  1028. "customer_type": approData.CustomerType,
  1029. "proxy_start_time": approData.ProxyStartTime,
  1030. "proxy_end_time": approData.ProxyEndTime,
  1031. "proxy_district": approData.ProxyDistrict,
  1032. "contract_url": approData.ContractUrl,
  1033. }, "id = ?", ent.Id)
  1034. if err != nil {
  1035. return err
  1036. }
  1037. _, err = tx.Insert("base_distributor_record", model.BaseDistributorRecord{
  1038. DistId: ent.Id,
  1039. DistType: "20",
  1040. BusinessScope: ent.BusinessScope,
  1041. CustomerType: approData.CustomerType,
  1042. ProxyDistrict: approData.ProxyDistrict,
  1043. ProxyStartTime: approData.ProxyStartTime,
  1044. ProxyEndTime: approData.ProxyEndTime,
  1045. ContractUrl: approData.ContractUrl,
  1046. ExistedProduct: ent.ExistedProduct,
  1047. HistoryCustomer: ent.HistoryCustomer,
  1048. ToDistReason: "",
  1049. Remark: "",
  1050. CreatedBy: approData.OperatedId,
  1051. CreatedName: approData.OperatedName,
  1052. CreatedTime: gtime.Now(),
  1053. UpdatedBy: approData.OperatedId,
  1054. UpdatedName: approData.OperatedName,
  1055. UpdatedTime: gtime.Now(),
  1056. })
  1057. if err != nil {
  1058. return err
  1059. }
  1060. err = addDynamicsByCurrentUser(tx, ent.Id, "续签代理商",
  1061. approData, approData.OperatedId, approData.OperatedName)
  1062. if err != nil {
  1063. return err
  1064. }
  1065. return nil
  1066. })
  1067. return txerr
  1068. }
  1069. func ApprovalDistToDist(ctx context.Context, flow *workflowmodel.PlatWorkflow, msg *message.MixMessage) error {
  1070. tenant, err := micro_srv.GetTenant(ctx)
  1071. if err != nil {
  1072. return fmt.Errorf("获取租户码异常:%s", err.Error())
  1073. }
  1074. distdao := base.NewBaseDistributorDao(tenant)
  1075. entId, err := strconv.Atoi(flow.BizCode)
  1076. if err != nil {
  1077. return fmt.Errorf("代理商转经销商钉钉审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  1078. }
  1079. ent, err := distdao.Where("id = ?", entId).One()
  1080. if err != nil {
  1081. return err
  1082. }
  1083. if ent == nil {
  1084. return fmt.Errorf("代理商不存在:%s Id: %d", flow.BizCode, flow.Id)
  1085. }
  1086. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  1087. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  1088. }
  1089. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  1090. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  1091. }
  1092. if msg.ProcessType == "terminate" {
  1093. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  1094. "appro_status": "50",
  1095. "appro_data": "",
  1096. }).Update()
  1097. return err
  1098. }
  1099. pass := msg.Result == "agree"
  1100. if !pass {
  1101. _, err = distdao.Where("id = ?", entId).Data(map[string]interface{}{
  1102. "appro_status": "40",
  1103. "appro_data": "",
  1104. }).Update()
  1105. return err
  1106. }
  1107. approData := model.ToDistApproveData{}
  1108. err = json.Unmarshal([]byte(ent.ApproData), &approData)
  1109. if err != nil {
  1110. return fmt.Errorf("代理商转经销商钉钉审批 ApproData 解析异常:%s Id: %d ApproData:%s", flow.BizCode, flow.Id, ent.ApproData)
  1111. }
  1112. txerr := distdao.DB.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
  1113. _, err = tx.Update("base_distributor", map[string]interface{}{
  1114. "dist_type": "10",
  1115. "appro_status": "30",
  1116. "appro_data": "",
  1117. }, "id = ?", ent.Id)
  1118. if err != nil {
  1119. return err
  1120. }
  1121. _, err = tx.Insert("base_distributor_record", model.BaseDistributorRecord{
  1122. DistId: ent.Id,
  1123. DistType: "10",
  1124. BusinessScope: ent.BusinessScope,
  1125. CustomerType: ent.CustomerType,
  1126. ProxyDistrict: "",
  1127. ProxyStartTime: nil,
  1128. ProxyEndTime: nil,
  1129. ContractUrl: "",
  1130. ExistedProduct: ent.ExistedProduct,
  1131. HistoryCustomer: ent.HistoryCustomer,
  1132. ToDistReason: approData.ToDistReason,
  1133. Remark: "",
  1134. CreatedBy: approData.OperatedId,
  1135. CreatedName: approData.OperatedName,
  1136. CreatedTime: gtime.Now(),
  1137. UpdatedBy: approData.OperatedId,
  1138. UpdatedName: approData.OperatedName,
  1139. UpdatedTime: gtime.Now(),
  1140. })
  1141. if err != nil {
  1142. return err
  1143. }
  1144. err = addDynamicsByCurrentUser(tx, ent.Id, "转为经销商",
  1145. approData, approData.OperatedId, approData.OperatedName)
  1146. if err != nil {
  1147. return err
  1148. }
  1149. return nil
  1150. })
  1151. return txerr
  1152. }
  1153. func addDynamicsByCurrentUser(tx *gdb.TX, distId int, opnType string, content interface{}, operatedId int, opreatedName string) error {
  1154. contentByte, err := json.Marshal(content)
  1155. if err != nil {
  1156. return err
  1157. }
  1158. _, err = tx.InsertAndGetId("base_distributor_dynamics", model.BaseDistributorDynamics{
  1159. DistId: distId,
  1160. OpnPeopleId: operatedId,
  1161. OpnPeople: opreatedName,
  1162. OpnDate: gtime.Now(),
  1163. OpnType: opnType,
  1164. OpnContent: string(contentByte),
  1165. Remark: "",
  1166. CreatedBy: operatedId,
  1167. CreatedName: opreatedName,
  1168. CreatedTime: gtime.Now(),
  1169. UpdatedBy: operatedId,
  1170. UpdatedName: opreatedName,
  1171. UpdatedTime: gtime.Now(),
  1172. })
  1173. return err
  1174. }
  1175. func UploadDingtalk(uid, url, name string) ([]byte, error) {
  1176. if uid == "" {
  1177. return nil, fmt.Errorf("该用户钉钉 uid 为空")
  1178. }
  1179. filedata, err := DownFile(url)
  1180. if err != nil {
  1181. return nil, err
  1182. }
  1183. filepath := path.Join(os.TempDir(), name)
  1184. err = ioutil.WriteFile(filepath, filedata, 0644)
  1185. if err != nil {
  1186. return nil, fmt.Errorf("WriteFile %s %s", filepath, err)
  1187. }
  1188. defer os.Remove(filepath)
  1189. resp, err := dingtalk.Client.GetStorage().UploadFile(service.DingTalkSpaceId, uid, name, filepath)
  1190. if err != nil {
  1191. return nil, fmt.Errorf("钉钉上传文件异常 %s", err.Error())
  1192. }
  1193. file := []contractmodel.DingFileInfo{
  1194. {
  1195. SpaceId: resp.Dentry.SpaceId,
  1196. FileId: resp.Dentry.Id,
  1197. FileName: resp.Dentry.Name,
  1198. FileSize: resp.Dentry.Size,
  1199. FileType: resp.Dentry.Extension,
  1200. },
  1201. }
  1202. return json.Marshal(file)
  1203. }
  1204. func init() {
  1205. c := gcron.New()
  1206. // 每天凌晨2点执行
  1207. c.Add("0 0 2 * * *", notifyToComplete)
  1208. }
  1209. func notifyToComplete() {
  1210. defer func() {
  1211. if r := recover(); r != nil {
  1212. glog.Errorf("完善经销商定时提醒异常 %v", r)
  1213. }
  1214. }()
  1215. tenant := g.Config().GetString("micro_srv.tenant")
  1216. if tenant == "" {
  1217. glog.Error("定时任务租户码未设置,请前往配置")
  1218. return
  1219. }
  1220. dao := base.NewBaseDistributorDao(tenant)
  1221. created := gtime.Now().Add(-time.Hour * 24 * 30)
  1222. 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()
  1223. if err != nil {
  1224. glog.Errorf("完善经销商定时提醒异常 %s", err.Error())
  1225. return
  1226. }
  1227. for _, d := range dist {
  1228. msg := g.MapStrStr{
  1229. "msgTitle": "经销商信息完善提醒",
  1230. "msgContent": fmt.Sprintf("<p>经销商:%s 的必要信息未填写完整,请及时完善</p>", d.DistName),
  1231. "msgType": "20",
  1232. "recvUserIds": strconv.Itoa(d.BelongSaleId),
  1233. "msgStatus": "10",
  1234. "sendType": "10",
  1235. }
  1236. if err := service.CreateSystemMessage(msg); err != nil {
  1237. g.Log().Error("经销商信息完善提醒异常:%s", err)
  1238. }
  1239. }
  1240. }