ctr_contract.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. package service
  2. import (
  3. "context"
  4. "database/sql"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. "time"
  13. basedao "dashoo.cn/micro/app/dao/base"
  14. dao "dashoo.cn/micro/app/dao/contract"
  15. custdao "dashoo.cn/micro/app/dao/cust"
  16. projdao "dashoo.cn/micro/app/dao/proj"
  17. workflowdao "dashoo.cn/micro/app/dao/workflow"
  18. model "dashoo.cn/micro/app/model/contract"
  19. proj "dashoo.cn/micro/app/model/proj"
  20. workflowModel "dashoo.cn/micro/app/model/workflow"
  21. "dashoo.cn/micro/app/service"
  22. projsrv "dashoo.cn/micro/app/service/proj"
  23. workflowService "dashoo.cn/micro/app/service/workflow"
  24. "dashoo.cn/opms_libary/micro_srv"
  25. "dashoo.cn/opms_libary/multipart"
  26. "dashoo.cn/opms_libary/myerrors"
  27. "dashoo.cn/opms_libary/plugin/dingtalk"
  28. "dashoo.cn/opms_libary/plugin/dingtalk/message"
  29. "dashoo.cn/opms_libary/plugin/dingtalk/workflow"
  30. "dashoo.cn/opms_libary/request"
  31. "dashoo.cn/opms_libary/utils"
  32. "github.com/gogf/gf/database/gdb"
  33. "github.com/gogf/gf/frame/g"
  34. "github.com/gogf/gf/os/gcron"
  35. "github.com/gogf/gf/os/glog"
  36. "github.com/gogf/gf/os/gtime"
  37. "github.com/gogf/gf/util/gvalid"
  38. )
  39. type CtrContractService struct {
  40. Dao *dao.CtrContractDao
  41. ProjBusinessDao *projdao.ProjBusinessDao
  42. CustomerDao *custdao.CustCustomerDao
  43. CtrProductDao *dao.CtrContractProductDao
  44. ProductDao *basedao.BaseProductDao
  45. DynamicsDao *dao.CtrContractDynamicsDao
  46. WorkflowDao *workflowdao.PlatWorkflowDao
  47. AppendDao *dao.CtrContractAppendDao
  48. GoalDao *dao.CtrContractGoalDao
  49. Tenant string
  50. userInfo request.UserInfo
  51. DataScope g.Map `json:"dataScope"`
  52. }
  53. func NewCtrContractService(ctx context.Context) (*CtrContractService, error) {
  54. tenant, err := micro_srv.GetTenant(ctx)
  55. if err != nil {
  56. err = myerrors.TipsError(fmt.Sprintf("获取租户码异常:%s", err.Error()))
  57. return nil, err //fmt.Errorf("获取租户码异常:%s", err.Error())
  58. }
  59. // 获取用户信息
  60. userInfo, err := micro_srv.GetUserInfo(ctx)
  61. if err != nil {
  62. return nil, fmt.Errorf("获取用户信息异常:%s", err.Error())
  63. }
  64. return &CtrContractService{
  65. Dao: dao.NewCtrContractDao(tenant),
  66. ProjBusinessDao: projdao.NewProjBusinessDao(tenant),
  67. CustomerDao: custdao.NewCustCustomerDao(tenant),
  68. CtrProductDao: dao.NewCtrContractProductDao(tenant),
  69. ProductDao: basedao.NewBaseProductDao(tenant),
  70. DynamicsDao: dao.NewCtrContractDynamicsDao(tenant),
  71. WorkflowDao: workflowdao.NewPlatWorkflowDao(tenant),
  72. AppendDao: dao.NewCtrContractAppendDao(tenant),
  73. GoalDao: dao.NewCtrContractGoalDao(tenant),
  74. Tenant: tenant,
  75. userInfo: userInfo,
  76. DataScope: userInfo.DataScope,
  77. }, nil
  78. }
  79. func (s CtrContractService) Get(ctx context.Context, id int) (*model.CtrContractGetRsp, error) {
  80. ent, err := s.Dao.Where("Id = ?", id).One()
  81. if err != nil {
  82. return nil, err
  83. }
  84. if ent == nil {
  85. return nil, myerrors.TipsError("合同不存在")
  86. }
  87. product, err := s.CtrProductDao.Where("contract_id = ?", id).All()
  88. if err != nil {
  89. return nil, err
  90. }
  91. if product == nil {
  92. product = []*model.CtrContractProduct{}
  93. }
  94. return &model.CtrContractGetRsp{
  95. CtrContract: *ent,
  96. Product: product,
  97. }, nil
  98. }
  99. func (s CtrContractService) DynamicsList(ctx context.Context, req *model.CtrContractDynamicsListReq) (int, interface{}, error) {
  100. dao := &s.DynamicsDao.CtrContractDynamicsDao
  101. if req.SearchText != "" {
  102. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  103. dao = dao.Where("(opn_people LIKE ? || opn_content LIKE ?)", likestr, likestr)
  104. }
  105. if req.ContractId != 0 {
  106. dao = dao.Where("contract_id = ?", req.ContractId)
  107. }
  108. if req.OpnPeopleId != 0 {
  109. dao = dao.Where("opn_people_id = ?", req.OpnPeopleId)
  110. }
  111. if req.OpnPeople != "" {
  112. likestr := fmt.Sprintf("%%%s%%", req.OpnPeople)
  113. dao = dao.Where("opn_people like ?", likestr)
  114. }
  115. if req.OpnType != "" {
  116. dao = dao.Where("opn_type = ?", req.OpnType)
  117. }
  118. // if req.OpnContent != "" {
  119. // likestr := fmt.Sprintf("%%%s%%", req.OpnContent)
  120. // dao = dao.Where("opn_content like ?", likestr)
  121. // }
  122. if req.BeginTime != "" {
  123. dao = dao.Where("created_time > ?", req.BeginTime)
  124. }
  125. if req.EndTime != "" {
  126. dao = dao.Where("created_time < ?", req.EndTime)
  127. }
  128. total, err := dao.Count()
  129. if err != nil {
  130. return 0, nil, err
  131. }
  132. if req.PageNum != 0 {
  133. dao = dao.Page(req.GetPage())
  134. }
  135. orderby := "created_time desc"
  136. if req.OrderBy != "" {
  137. orderby = req.OrderBy
  138. }
  139. dao = dao.Order(orderby)
  140. ents := []*model.CtrContractDynamics{}
  141. err = dao.Structs(&ents)
  142. if err != nil && err != sql.ErrNoRows {
  143. return 0, nil, err
  144. }
  145. ret := map[string][]*model.CtrContractDynamics{}
  146. for _, ent := range ents {
  147. date := ent.OpnDate.Format("Y-m-d")
  148. ret[date] = append(ret[date], ent)
  149. }
  150. return total, ret, err
  151. }
  152. func (s CtrContractService) List(ctx context.Context, req *model.CtrContractListReq) (int, []*model.CtrContractListRsp, error) {
  153. ctx = context.WithValue(ctx, "contextService", s)
  154. dao := s.Dao.DataScope(ctx, "incharge_id").As("a")
  155. if req.SearchText != "" {
  156. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  157. dao = dao.Where("(a.contract_code LIKE ? || a.contract_name LIKE ? || a.cust_name LIKE ? || a.nbo_name LIKE ?)", likestr, likestr, likestr, likestr)
  158. }
  159. if req.ContractCode != "" {
  160. likestr := fmt.Sprintf("%%%s%%", req.ContractCode)
  161. dao = dao.Where("a.contract_code like ?", likestr)
  162. }
  163. if req.ContractName != "" {
  164. likestr := fmt.Sprintf("%%%s%%", req.ContractName)
  165. dao = dao.Where("a.contract_name like ?", likestr)
  166. }
  167. if req.CustId != 0 {
  168. dao = dao.Where("a.cust_id = ?", req.CustId)
  169. }
  170. if req.CustName != "" {
  171. likestr := fmt.Sprintf("%%%s%%", req.CustName)
  172. dao = dao.Where("a.cust_name like ?", likestr)
  173. }
  174. if req.NboId != 0 {
  175. dao = dao.Where("a.nbo_id = ?", req.NboId)
  176. }
  177. if req.NboName != "" {
  178. likestr := fmt.Sprintf("%%%s%%", req.NboName)
  179. dao = dao.Where("a.nbo_name like ?", likestr)
  180. }
  181. if req.ApproStatus != "" {
  182. dao = dao.Where("a.appro_status = ?", req.ApproStatus)
  183. }
  184. if req.ContractType != "" {
  185. dao = dao.Where("a.contract_type = ?", req.ContractType)
  186. }
  187. // if req.ContractStartTime != nil {
  188. // dao = dao.Where("a.contract_start_time > ?", req.ContractStartTime)
  189. // }
  190. // if req.ContractEndTime != nil {
  191. // dao = dao.Where("a.contract_end_time < ?", req.ContractEndTime)
  192. // }
  193. if req.InchargeId != 0 {
  194. dao = dao.Where("a.incharge_id = ?", req.InchargeId)
  195. }
  196. if req.InchargeName != "" {
  197. likestr := fmt.Sprintf("%%%s%%", req.InchargeName)
  198. dao = dao.Where("a.incharge_name like ?", likestr)
  199. }
  200. if req.SignatoryId != 0 {
  201. dao = dao.Where("a.signatory_id = ?", req.SignatoryId)
  202. }
  203. if req.SignatoryName != "" {
  204. likestr := fmt.Sprintf("%%%s%%", req.SignatoryName)
  205. dao = dao.Where("a.signatory_name like ?", likestr)
  206. }
  207. if req.DistributorId != 0 {
  208. dao = dao.Where("a.distributor_id = ?", req.DistributorId)
  209. }
  210. if req.DistributorName != "" {
  211. likestr := fmt.Sprintf("%%%s%%", req.DistributorName)
  212. dao = dao.Where("a.distributor_name like ?", likestr)
  213. }
  214. if req.BeginTime != "" {
  215. dao = dao.Where("a.created_time > ?", req.BeginTime)
  216. }
  217. if req.EndTime != "" {
  218. dao = dao.Where("a.created_time < ?", req.EndTime)
  219. }
  220. total, err := dao.Count()
  221. if err != nil {
  222. return 0, nil, err
  223. }
  224. if req.PageNum != 0 {
  225. dao = dao.Page(req.GetPage())
  226. }
  227. orderby := "a.created_time desc"
  228. if req.OrderBy != "" {
  229. orderby = req.OrderBy
  230. }
  231. dao = dao.Order(orderby)
  232. ents := []*model.CtrContractListRsp{}
  233. err = dao.Structs(&ents)
  234. if err != nil && err != sql.ErrNoRows {
  235. return 0, nil, err
  236. }
  237. return total, ents, err
  238. }
  239. func (s CtrContractService) BindProduct(tx *gdb.TX, id int, code string, product []model.CtrAddProduct) error {
  240. var amount float64
  241. for _, p := range product {
  242. amount += (p.TranPrice * float64(p.ProdNum))
  243. }
  244. _, err := tx.Delete("ctr_contract_product", "contract_id = ?", id)
  245. if err != nil {
  246. return err
  247. }
  248. tocreate := []model.CtrContractProduct{}
  249. for _, p := range product {
  250. product, err := s.ProductDao.Where("id = ?", p.ProdId).One()
  251. if err != nil {
  252. return err
  253. }
  254. if product == nil {
  255. return myerrors.TipsError(fmt.Sprintf("产品: %d 不存在", p.ProdId))
  256. }
  257. tocreate = append(tocreate, model.CtrContractProduct{
  258. ContractId: id,
  259. ContractCode: code,
  260. ProdId: p.ProdId,
  261. ProdCode: product.ProdCode,
  262. ProdName: product.ProdName,
  263. ProdClass: product.ProdClass,
  264. ProdNum: p.ProdNum,
  265. MaintTerm: p.MaintTerm,
  266. SugSalesPrice: p.SugSalesPrice,
  267. TranPrice: p.TranPrice,
  268. ContractPrive: amount,
  269. Remark: p.Remark,
  270. CreatedBy: int(s.userInfo.Id),
  271. CreatedName: s.userInfo.NickName,
  272. CreatedTime: gtime.Now(),
  273. UpdatedBy: int(s.userInfo.Id),
  274. UpdatedName: s.userInfo.NickName,
  275. UpdatedTime: gtime.Now(),
  276. })
  277. }
  278. if len(tocreate) != 0 {
  279. _, err = tx.Insert("ctr_contract_product", tocreate)
  280. if err != nil {
  281. return err
  282. }
  283. }
  284. return nil
  285. }
  286. func (s CtrContractService) AddDynamicsByCurrentUser(tx *gdb.TX, contractId int, opnType string, content map[string]interface{}) error {
  287. contentByte, err := json.Marshal(content)
  288. if err != nil {
  289. return err
  290. }
  291. _, err = tx.InsertAndGetId("ctr_contract_dynamics", model.CtrContractDynamics{
  292. ContractId: contractId,
  293. OpnPeopleId: s.userInfo.Id,
  294. OpnPeople: s.userInfo.NickName,
  295. OpnDate: gtime.Now(),
  296. OpnType: opnType,
  297. OpnContent: string(contentByte),
  298. Remark: "",
  299. CreatedBy: s.userInfo.Id,
  300. CreatedName: s.userInfo.NickName,
  301. CreatedTime: gtime.Now(),
  302. UpdatedBy: s.userInfo.Id,
  303. UpdatedName: s.userInfo.NickName,
  304. UpdatedTime: gtime.Now(),
  305. })
  306. return err
  307. }
  308. func (s CtrContractService) Add(ctx context.Context, req *model.CtrContractAddReq) (int, error) {
  309. validErr := gvalid.CheckStruct(ctx, req, nil)
  310. if validErr != nil {
  311. return 0, myerrors.TipsError(validErr.Current().Error())
  312. }
  313. if len(req.Product) == 0 {
  314. return 0, myerrors.TipsError("产品不能为空")
  315. }
  316. for _, p := range req.Product {
  317. if p.ProdNum < 1 {
  318. return 0, myerrors.TipsError("产品数量必须大于 0")
  319. }
  320. }
  321. c, err := s.Dao.Where("contract_name = ?", req.ContractName).One()
  322. if err != nil {
  323. return 0, err
  324. }
  325. if c != nil {
  326. return 0, myerrors.TipsError(fmt.Sprintf("合同名称:%s 已存在", req.ContractName))
  327. }
  328. nbo, err := s.ProjBusinessDao.Where("id = ?", req.NboId).One()
  329. if err != nil {
  330. return 0, err
  331. }
  332. if nbo == nil {
  333. return 0, myerrors.TipsError("项目不存在")
  334. }
  335. // c, err = s.Dao.Where("nbo_id = ?", req.NboId).One()
  336. // if err != nil {
  337. // return 0, err
  338. // }
  339. // if c != nil {
  340. // return 0, myerrors.TipsError("所选项目已添加合同")
  341. // }
  342. sequence, err := service.Sequence(s.Dao.DB, "contract_code")
  343. if err != nil {
  344. return 0, err
  345. }
  346. if req.ContractCode == "" {
  347. req.ContractCode = fmt.Sprintf("DS%s%s%s", req.ContractType, time.Now().Format("0601"), sequence)
  348. }
  349. c, err = s.Dao.Where("contract_code = ?", req.ContractCode).One()
  350. if err != nil {
  351. return 0, err
  352. }
  353. if c != nil {
  354. return 0, myerrors.TipsError(fmt.Sprintf("合同编号:%s 已存在", req.ContractCode))
  355. }
  356. var contractAmount float64
  357. for _, p := range req.Product {
  358. contractAmount += (p.TranPrice * float64(p.ProdNum))
  359. }
  360. ctr := model.CtrContract{
  361. ContractCode: req.ContractCode,
  362. ContractName: req.ContractName,
  363. CustId: nbo.CustId,
  364. CustName: nbo.CustName,
  365. NboId: nbo.Id,
  366. NboName: nbo.NboName,
  367. IsBig: nbo.IsBig,
  368. ProductLine: nbo.ProductLine,
  369. CustProvinceId: nbo.CustProvinceId,
  370. CustProvince: nbo.CustProvince,
  371. CustCityId: nbo.CustCityId,
  372. CustCity: nbo.CustCity,
  373. ApproStatus: "10",
  374. ContractType: req.ContractType,
  375. ContractAmount: contractAmount,
  376. InvoiceAmount: 0,
  377. CollectedAmount: 0,
  378. ContractStartTime: req.ContractStartTime,
  379. ContractEndTime: req.ContractEndTime,
  380. ContractSignTime: req.ContractSignTime,
  381. InchargeId: req.InchargeId,
  382. InchargeName: req.InchargeName,
  383. SignatoryId: req.SignatoryId,
  384. SignatoryName: req.SignatoryName,
  385. SignatoryType: req.SignatoryType,
  386. SignatoryUnit: req.SignatoryUnit,
  387. EarnestMoney: req.EarnestMoney,
  388. CustSignatoryId: req.CustSignatoryId,
  389. CustSignatoryName: req.CustSignatoryName,
  390. DistributorId: req.DistributorId,
  391. DistributorName: req.DistributorName,
  392. Remark: req.Remark,
  393. ServiceFeeAgreement: req.ServiceFeeAgreement,
  394. CreatedBy: int(s.userInfo.Id),
  395. CreatedName: s.userInfo.NickName,
  396. CreatedTime: gtime.Now(),
  397. UpdatedBy: int(s.userInfo.Id),
  398. UpdatedName: s.userInfo.NickName,
  399. UpdatedTime: gtime.Now(),
  400. }
  401. var id int
  402. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  403. ctrid, err := tx.InsertAndGetId("ctr_contract", ctr)
  404. if err != nil {
  405. return err
  406. }
  407. err = s.BindProduct(tx, int(ctrid), ctr.ContractCode, req.Product)
  408. if err != nil {
  409. return err
  410. }
  411. err = s.AddDynamicsByCurrentUser(tx, int(ctrid), "创建合同", map[string]interface{}{})
  412. if err != nil {
  413. return err
  414. }
  415. _, err = tx.Update("proj_business", map[string]interface{}{
  416. "nbo_type": projsrv.StatusDeal,
  417. }, "id = ?", nbo.Id)
  418. if err != nil {
  419. return err
  420. }
  421. id = int(ctrid)
  422. return nil
  423. })
  424. return id, txerr
  425. }
  426. var ContractApplyProcessCode = "PROC-7057E20A-2066-4644-9B35-9331E4DA912C" // 创建合同
  427. func (s CtrContractService) Commit(ctx context.Context, req *model.CtrContractCommitReq) (int64, error) {
  428. validErr := gvalid.CheckStruct(ctx, req, nil)
  429. if validErr != nil {
  430. return 0, myerrors.TipsError(validErr.Current().Error())
  431. }
  432. if !(req.ContractModel == "大数模板" || req.ContractModel == "客户模板") {
  433. return 0, myerrors.TipsError("合同模板不合法")
  434. }
  435. if !(req.Terms == "接纳全部条款" || req.Terms == "不接纳全部条款") {
  436. return 0, myerrors.TipsError("条款情况不合法")
  437. }
  438. if req.PayTerms == "" {
  439. return 0, myerrors.TipsError("付款条件不能为空")
  440. }
  441. if len(req.File) == 0 {
  442. return 0, myerrors.TipsError("附件不能为空")
  443. }
  444. ent, err := s.Dao.Where("id = ?", req.Id).One()
  445. if err != nil {
  446. return 0, err
  447. }
  448. if ent == nil {
  449. return 0, myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  450. }
  451. fileinfoByte, err := json.Marshal(req.File)
  452. if err != nil {
  453. return 0, err
  454. }
  455. workflowSrv, err := workflowService.NewFlowService(ctx)
  456. if err != nil {
  457. return 0, err
  458. }
  459. bizCode := strconv.Itoa(ent.Id)
  460. workflowId, err := workflowSrv.StartProcessInstance(bizCode, "30", "", &workflow.StartProcessInstanceRequest{
  461. ProcessCode: &ContractApplyProcessCode,
  462. FormComponentValues: []*workflow.StartProcessInstanceRequestFormComponentValues{
  463. {
  464. Id: utils.String("DDSelectField_ESX8H30W3VK0"),
  465. Name: utils.String("合同模板"),
  466. Value: utils.String(req.ContractModel),
  467. },
  468. {
  469. Id: utils.String("DDSelectField_13IQX96C2KAK0"),
  470. Name: utils.String("条款情况"),
  471. Value: utils.String(req.Terms),
  472. },
  473. {
  474. Id: utils.String("TextField_1A5SA7VOG5TS0"),
  475. Name: utils.String("合同编号"),
  476. Value: utils.String(ent.ContractCode),
  477. },
  478. {
  479. Id: utils.String("TextField_1EX61DPS3LA80"),
  480. Name: utils.String("客户名称"),
  481. Value: utils.String(ent.CustName),
  482. },
  483. {
  484. Id: utils.String("MoneyField_X1XV4KIR0GW0"),
  485. Name: utils.String("合同金额(元)"),
  486. Value: utils.String(strconv.FormatFloat(ent.ContractAmount, 'f', 2, 64)),
  487. },
  488. {
  489. Id: utils.String("TextareaField_1WZ5ILKBUVSW0"),
  490. Name: utils.String("付款条件"),
  491. Value: utils.String(req.PayTerms),
  492. },
  493. {
  494. Id: utils.String("DDAttachment_1051KJYC3MBK0"),
  495. Name: utils.String("附件"),
  496. // Details: productForm,
  497. Value: utils.String(string(fileinfoByte)),
  498. },
  499. },
  500. })
  501. if err != nil {
  502. return 0, err
  503. }
  504. _, err = s.Dao.Where("id = ?", ent.Id).Data(map[string]interface{}{
  505. "appro_status": 20,
  506. }).Update()
  507. return workflowId, err
  508. }
  509. // var spaceId = "21042518430"
  510. var spaceId = "21077726250"
  511. func (s CtrContractService) CommitWithFile(ctx context.Context, formData *multipart.Form) error {
  512. if s.userInfo.DingtalkUid == "" {
  513. return fmt.Errorf("该用户钉钉 uid 为空")
  514. }
  515. if len(formData.File) == 0 {
  516. return myerrors.TipsError("文件不能为空")
  517. }
  518. if _, ok := formData.File["file"]; !ok {
  519. return myerrors.TipsError("文件不能为空")
  520. }
  521. if formData.File["file"].FileName == "" {
  522. return fmt.Errorf("文件名称不能为空")
  523. }
  524. if formData.File["file"].File == nil {
  525. return fmt.Errorf("文件不能为空")
  526. }
  527. if formData.File["file"].File.Name() == "" {
  528. return fmt.Errorf("文件路径不能为空")
  529. }
  530. contractId, err := strconv.Atoi(formData.Value["contractId"])
  531. if err != nil {
  532. return fmt.Errorf("合同 Id 不合法 %s", formData.Value["contractId"])
  533. }
  534. //fmt.Println(args.File.Name(), args.FileName, args.FileSize, args.Meta)
  535. //fmt.Println(spaceId, s.userInfo.DingtalkId, args.FileName, args.File.Name())
  536. // resp, err := s.UploadFile("21042518430", "8xljy04PZiS9iPxp5PhDnUzQiEiE", "引物导入模板-000000.xlsx", "/Users/chengjian/Downloads/引物导入模板.xlsx")
  537. resp, err := dingtalk.Client.GetStorage().UploadFile(spaceId, s.userInfo.DingtalkId, formData.File["file"].FileName, formData.File["file"].File.Name())
  538. if err != nil {
  539. return fmt.Errorf("钉钉上传文件异常 %s", err.Error())
  540. }
  541. _, err = s.Commit(ctx, &model.CtrContractCommitReq{
  542. Id: contractId,
  543. ContractModel: formData.Value["contractModel"],
  544. Terms: formData.Value["terms"],
  545. PayTerms: formData.Value["payTerms"],
  546. File: []model.DingFileInfo{
  547. {
  548. SpaceId: resp.Dentry.SpaceId,
  549. FileId: resp.Dentry.Id,
  550. FileName: resp.Dentry.Name,
  551. FileSize: resp.Dentry.Size,
  552. FileType: resp.Dentry.Extension,
  553. },
  554. },
  555. })
  556. if err != nil {
  557. return err
  558. }
  559. // workflow, err := s.WorkflowDao.Where("id = ?", workflowId).One()
  560. // if err != nil {
  561. // return err
  562. // }
  563. // instance, err := dingtalk.Client.GetWorkflow().QueryProcessInstanceDetail(workflow.ProcessInstId)
  564. // if err != nil {
  565. // return fmt.Errorf("查询审批实例详情错误: %s", err.Error())
  566. // }
  567. // fmt.Println(workflow.ProcessInstId, instance.Result.ApproverUserIds)
  568. // approverUserIds := g.Config().GetStrings("dingtalk.approver-user-ids")
  569. // fmt.Println(approverUserIds)
  570. // for _, uid := range approverUserIds {
  571. // resp, err := dingtalk.Client.GetStorage().AddPermission(
  572. // dingtalk.Client.Context.CorpId, spaceId, uid, "DOWNLOADER", "USER")
  573. // if err != nil {
  574. // return fmt.Errorf("添加审核附件权限异常: %s", err.Error())
  575. // }
  576. // fmt.Println(uid, resp)
  577. // }
  578. appendSrv, err := NewCtrContractAppendService(ctx)
  579. if err != nil {
  580. return err
  581. }
  582. _, err = appendSrv.Add(ctx, &model.CtrContractAppendAddReq{
  583. ContractId: contractId,
  584. FileName: resp.Dentry.Name,
  585. FileType: resp.Dentry.Extension,
  586. FileUrl: strings.Join([]string{"dingtalk", resp.Dentry.SpaceId, resp.Dentry.Id}, ":"),
  587. Remark: "",
  588. })
  589. if err != nil {
  590. return err
  591. }
  592. return nil
  593. }
  594. func (s CtrContractService) DownloadDingtalkFile(ctx context.Context, id int) (string, error) {
  595. ent, err := s.AppendDao.Where("id= ?", id).One()
  596. if err != nil {
  597. return "", err
  598. }
  599. if ent == nil {
  600. return "", myerrors.TipsError("附件不存在")
  601. }
  602. if !strings.HasPrefix(ent.FileUrl, "dingtalk") {
  603. return "", myerrors.TipsError("此附件不是钉钉附件")
  604. }
  605. fileInfo := strings.Split(ent.FileUrl, ":")
  606. if len(fileInfo) != 3 {
  607. return "", myerrors.TipsError("钉钉附件地址不合法")
  608. }
  609. spaceId := fileInfo[1]
  610. fileId := fileInfo[2]
  611. // res, err := dingtalk.Client.GetStorage().AddPermission(dingtalk.Client.Context.CorpId, spaceId, s.userInfo.DingtalkId, "EDITOR", "USER")
  612. // fmt.Println(res, err)
  613. // if err != nil {
  614. // return "", fmt.Errorf("设置权限异常 %s", err.Error())
  615. // }
  616. resp, err := dingtalk.Client.GetStorage().QueryFileDownloadInfo(spaceId, fileId, s.userInfo.DingtalkId)
  617. if err != nil {
  618. return "", myerrors.TipsError("获取文件下载信息异常")
  619. }
  620. fmt.Println(resp, err)
  621. req, err := http.NewRequest("GET", resp.HeaderSignatureInfo.ResourceUrls[0], nil)
  622. if err != nil {
  623. return "", fmt.Errorf("构建文件下载请求异常 %s", err.Error())
  624. }
  625. for k, v := range resp.HeaderSignatureInfo.Headers {
  626. req.Header.Add(k, v)
  627. }
  628. fileresp, err := http.DefaultClient.Do(req)
  629. if err != nil {
  630. return "", fmt.Errorf("文件下载异常 %s", err.Error())
  631. }
  632. data, err := io.ReadAll(fileresp.Body)
  633. if err != nil {
  634. return "", fmt.Errorf("读取下载内容异常 %s", err.Error())
  635. }
  636. return base64.StdEncoding.EncodeToString(data), nil
  637. }
  638. func ContractApplyApproval(ctx context.Context, flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
  639. tenant, err := micro_srv.GetTenant(ctx)
  640. if err != nil {
  641. return fmt.Errorf("获取租户码异常:%s", err.Error())
  642. }
  643. contractDao := dao.NewCtrContractDao(tenant)
  644. contractId, err := strconv.Atoi(flow.BizCode)
  645. if err != nil {
  646. return fmt.Errorf("创建合同审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  647. }
  648. contract, err := contractDao.Where("id = ?", contractId).One()
  649. if err != nil {
  650. return err
  651. }
  652. if contract == nil {
  653. return fmt.Errorf("合同不存在:%s Id: %d", flow.BizCode, flow.Id)
  654. }
  655. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  656. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  657. }
  658. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  659. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  660. }
  661. if msg.ProcessType == "terminate" {
  662. _, err = contractDao.Where("id = ?", contractId).Data(map[string]interface{}{
  663. "appro_status": "50",
  664. }).Update()
  665. return err
  666. }
  667. pass := msg.Result == "agree"
  668. if !pass {
  669. _, err = contractDao.Where("id = ?", contractId).Data(map[string]interface{}{
  670. "appro_status": "40",
  671. }).Update()
  672. return err
  673. }
  674. _, err = contractDao.Where("id = ?", contractId).Data(map[string]interface{}{
  675. "appro_status": "30",
  676. }).Update()
  677. return err
  678. }
  679. func (s CtrContractService) Update(ctx context.Context, req *model.CtrContractUpdateReq) error {
  680. validErr := gvalid.CheckStruct(ctx, req, nil)
  681. if validErr != nil {
  682. return myerrors.TipsError(validErr.Current().Error())
  683. }
  684. ent, err := s.Dao.Where("id = ?", req.Id).One()
  685. if err != nil {
  686. return err
  687. }
  688. if ent == nil {
  689. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  690. }
  691. // if req.ContractCode != "" {
  692. // exist, err := s.Dao.Where("contract_code = ?", req.ContractCode).One()
  693. // if err != nil {
  694. // return err
  695. // }
  696. // if exist != nil && exist.Id != req.Id {
  697. // return myerrors.NewMsgError(nil, fmt.Sprintf("合同编号:%s 已存在", req.ContractCode))
  698. // }
  699. // }
  700. if req.ContractName != "" {
  701. exist, err := s.Dao.Where("contract_name = ?", req.ContractName).One()
  702. if err != nil {
  703. return err
  704. }
  705. if exist != nil && exist.Id != req.Id {
  706. return myerrors.TipsError(fmt.Sprintf("合同名称:%s 已存在", req.ContractName))
  707. }
  708. }
  709. var nbo *proj.ProjBusiness
  710. if req.NboId != 0 {
  711. nbo, err = s.ProjBusinessDao.Where("id = ?", req.NboId).One()
  712. if err != nil {
  713. return err
  714. }
  715. if nbo == nil {
  716. return myerrors.TipsError("项目不存在")
  717. }
  718. }
  719. toupdate := map[string]interface{}{}
  720. // if req.ContractCode != "" {
  721. // toupdate["contract_code"] = req.ContractCode
  722. // }
  723. if req.ContractName != "" {
  724. toupdate["contract_name"] = req.ContractName
  725. }
  726. if req.NboId != 0 {
  727. toupdate["cust_id"] = nbo.CustId
  728. toupdate["cust_name"] = nbo.CustName
  729. toupdate["nbo_id"] = nbo.Id
  730. toupdate["nbo_name"] = nbo.NboName
  731. toupdate["is_big"] = nbo.IsBig
  732. toupdate["product_line"] = nbo.ProductLine
  733. toupdate["cust_province_id"] = nbo.CustProvinceId
  734. toupdate["cust_province"] = nbo.CustProvince
  735. toupdate["cust_city_id"] = nbo.CustCityId
  736. toupdate["cust_city"] = nbo.CustCity
  737. }
  738. // if req.ApproStatus != "" {
  739. // toupdate["appro_status"] = req.ApproStatus
  740. // }
  741. if req.ContractType != "" {
  742. toupdate["contract_type"] = req.ContractType
  743. }
  744. // if req.ContractAmount != 0 {
  745. // toupdate["contract_amount"] = req.ContractAmount
  746. // }
  747. // if req.InvoiceAmount != 0 {
  748. // toupdate["invoice_amount"] = req.InvoiceAmount
  749. // }
  750. // if req.CollectedAmount != 0 {
  751. // toupdate["collected_amount"] = req.CollectedAmount
  752. // }
  753. if req.ContractStartTime != nil {
  754. toupdate["contract_start_time"] = req.ContractStartTime
  755. }
  756. if req.ContractEndTime != nil {
  757. toupdate["contract_end_time"] = req.ContractEndTime
  758. }
  759. if req.ContractSignTime != nil {
  760. toupdate["contract_sign_time"] = req.ContractSignTime
  761. }
  762. //if req.InchargeId != 0 {
  763. // toupdate["incharge_id"] = req.InchargeId
  764. //}
  765. //if req.InchargeName != "" {
  766. // toupdate["incharge_name"] = req.InchargeName
  767. //}
  768. if req.SignatoryId != 0 {
  769. toupdate["signatory_id"] = req.SignatoryId
  770. }
  771. if req.SignatoryName != "" {
  772. toupdate["signatory_name"] = req.SignatoryName
  773. }
  774. if req.SignatoryType != "" {
  775. toupdate["signatory_type"] = req.SignatoryType
  776. }
  777. if req.SignatoryUnit != "" {
  778. toupdate["signatory_unit"] = req.SignatoryUnit
  779. }
  780. if req.EarnestMoney != nil {
  781. toupdate["earnest_money"] = req.EarnestMoney
  782. }
  783. if req.CustSignatoryId != 0 {
  784. toupdate["cust_signatory_id"] = req.CustSignatoryId
  785. }
  786. if req.CustSignatoryName != "" {
  787. toupdate["cust_signatory_name"] = req.CustSignatoryName
  788. }
  789. if req.DistributorId != 0 {
  790. toupdate["distributor_id"] = req.DistributorId
  791. }
  792. if req.DistributorName != "" {
  793. toupdate["distributor_name"] = req.DistributorName
  794. }
  795. if req.Remark != nil {
  796. toupdate["remark"] = *req.Remark
  797. }
  798. if req.Product != nil {
  799. var contractAmount float64
  800. for _, p := range *req.Product {
  801. contractAmount += (p.TranPrice * float64(p.ProdNum))
  802. }
  803. toupdate["contract_amount"] = contractAmount
  804. }
  805. if len(toupdate) != 0 {
  806. toupdate["updated_by"] = int(s.userInfo.Id)
  807. toupdate["updated_name"] = s.userInfo.NickName
  808. toupdate["updated_time"] = gtime.Now()
  809. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  810. _, err = tx.Update("ctr_contract", toupdate, "id = ?", req.Id)
  811. if err != nil {
  812. return err
  813. }
  814. if req.Product != nil {
  815. err = s.BindProduct(tx, req.Id, ent.ContractCode, *req.Product)
  816. if err != nil {
  817. return err
  818. }
  819. }
  820. return nil
  821. })
  822. if txerr != nil {
  823. return txerr
  824. }
  825. }
  826. return nil
  827. }
  828. func (s CtrContractService) UpdateProduct(ctx context.Context, req *model.CtrContractUpdateProductReq) error {
  829. validErr := gvalid.CheckStruct(ctx, req, nil)
  830. if validErr != nil {
  831. return myerrors.TipsError(validErr.Current().Error())
  832. }
  833. ent, err := s.CtrProductDao.Where("id = ?", req.Id).One()
  834. if err != nil {
  835. return err
  836. }
  837. if ent == nil {
  838. return myerrors.TipsError(fmt.Sprintf("合同产品记录不存在: %d", req.Id))
  839. }
  840. toupdate := map[string]interface{}{}
  841. if req.MaintainPeriod != nil {
  842. toupdate["maintain_period"] = req.MaintainPeriod
  843. }
  844. if req.WarrantPeriod != nil {
  845. toupdate["warrant_period"] = req.WarrantPeriod
  846. }
  847. if req.MaintainStartTime != nil {
  848. toupdate["maintain_start_time"] = req.MaintainStartTime
  849. }
  850. if req.MaintainRemark != nil {
  851. toupdate["maintain_remark"] = req.MaintainRemark
  852. }
  853. if req.AcceptTime != nil {
  854. toupdate["accept_time"] = req.AcceptTime
  855. }
  856. if req.PurchaseCost != nil {
  857. toupdate["purchase_cost"] = req.PurchaseCost
  858. }
  859. if req.DevCost != nil {
  860. toupdate["dev_cost"] = req.DevCost
  861. }
  862. if req.MaintainCost != nil {
  863. toupdate["maintain_cost"] = req.MaintainCost
  864. }
  865. if req.DirectCost != nil {
  866. toupdate["direct_cost"] = req.DirectCost
  867. }
  868. if len(toupdate) != 0 {
  869. toupdate["updated_by"] = int(s.userInfo.Id)
  870. toupdate["updated_name"] = s.userInfo.NickName
  871. toupdate["updated_time"] = gtime.Now()
  872. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  873. _, err = tx.Update("ctr_contract_product", toupdate, "id = ?", req.Id)
  874. if err != nil {
  875. return err
  876. }
  877. err = s.AddDynamicsByCurrentUser(tx, ent.ContractId, "更新合同产品信息", toupdate)
  878. if err != nil {
  879. return err
  880. }
  881. return nil
  882. })
  883. if txerr != nil {
  884. return txerr
  885. }
  886. }
  887. return nil
  888. }
  889. func (s CtrContractService) Transfer(ctx context.Context, req *model.CtrContractTransferReq) error {
  890. if len(req.Id) == 0 {
  891. return nil
  892. }
  893. ents := map[int]*model.CtrContract{}
  894. for _, i := range req.Id {
  895. ent, err := s.Dao.Where("id = ?", i).One()
  896. if err != nil {
  897. return err
  898. }
  899. if ent == nil {
  900. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  901. }
  902. ents[ent.Id] = ent
  903. }
  904. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  905. toupdate := map[string]interface{}{
  906. "incharge_id": req.InchargeId,
  907. "incharge_name": req.InchargeName,
  908. }
  909. _, err := tx.Update("ctr_contract", toupdate, "id in (?)", req.Id)
  910. if err != nil {
  911. return err
  912. }
  913. for _, ent := range ents {
  914. err = s.AddDynamicsByCurrentUser(tx, ent.Id, "转移合同", map[string]interface{}{
  915. "toInchargeId": req.InchargeId,
  916. "toInchargeName": req.InchargeName,
  917. "fromInchargeId": ent.InchargeId,
  918. "fromInchargeName": ent.InchargeName,
  919. "operatedId": s.userInfo.Id,
  920. "operatedName": s.userInfo.NickName,
  921. })
  922. if err != nil {
  923. return err
  924. }
  925. }
  926. return nil
  927. })
  928. if txerr != nil {
  929. return txerr
  930. }
  931. return nil
  932. }
  933. func (s CtrContractService) UpdateInvoiceAmount(tx *gdb.TX, id int) error {
  934. ctr := model.CtrContract{}
  935. err := tx.GetStruct(&ctr, "select * from ctr_contract where id = ?", id)
  936. if err == sql.ErrNoRows {
  937. return myerrors.TipsError(fmt.Sprintf("合同不存在 %d", id))
  938. }
  939. if err != nil {
  940. return err
  941. }
  942. v, err := tx.GetValue("select sum(invoice_amount) from ctr_contract_invoice where contract_id=? and appro_status='30' and deleted_time is null", id)
  943. if err != nil {
  944. return err
  945. }
  946. amount := v.Float64()
  947. _, err = tx.Update("ctr_contract",
  948. map[string]interface{}{
  949. "invoice_amount": amount,
  950. }, "id = ?", id)
  951. if err != nil {
  952. return err
  953. }
  954. return nil
  955. }
  956. func (s CtrContractService) UpdateCollectedAmount(tx *gdb.TX, id int) error {
  957. ctr := model.CtrContract{}
  958. err := tx.GetStruct(&ctr, "select * from ctr_contract where id = ?", id)
  959. if err == sql.ErrNoRows {
  960. return myerrors.TipsError(fmt.Sprintf("合同不存在 %d", id))
  961. }
  962. if err != nil {
  963. return err
  964. }
  965. v, err := tx.GetValue("select sum(collection_amount) from ctr_contract_collection where contract_id=? and appro_status='20' and deleted_time is null", id)
  966. if err != nil {
  967. return err
  968. }
  969. amount := v.Float64()
  970. _, err = tx.Update("ctr_contract",
  971. map[string]interface{}{
  972. "collected_amount": amount,
  973. }, "id = ?", id)
  974. if err != nil {
  975. return err
  976. }
  977. return nil
  978. }
  979. func (s CtrContractService) Delete(ctx context.Context, id []int) error {
  980. if len(id) == 0 {
  981. return nil
  982. }
  983. _, err := s.Dao.Where("Id IN (?)", id).Delete()
  984. return err
  985. }
  986. func init() {
  987. tenant := g.Config().GetString("micro_srv.tenant")
  988. if tenant == "" {
  989. panic("定时任务租户码未设置,请前往配置")
  990. }
  991. contractDao := dao.NewCtrContractDao(tenant)
  992. produceDao := dao.NewCtrContractProductDao(tenant)
  993. job := func() {
  994. alert := map[int]*[]model.CtrContractProduct{
  995. 180: {},
  996. 90: {},
  997. 30: {},
  998. 10: {},
  999. // 7: {},
  1000. }
  1001. where := `DATE_FORMAT(DATE_ADD(maintain_start_time, INTERVAL ? day), "%Y-%m-%d") = DATE_FORMAT(NOW(), "%Y-%m-%d")`
  1002. for day, p := range alert {
  1003. err := produceDao.Where(where, day).Structs(p)
  1004. if err != nil {
  1005. glog.Error(err)
  1006. }
  1007. glog.Infof("运维期到期 %d 天提醒,产品个数 %d", day, len(*p))
  1008. }
  1009. for day, p := range alert {
  1010. for _, i := range *p {
  1011. ctr, err := contractDao.Where("id = ?", i.ContractId).One()
  1012. if err != nil {
  1013. glog.Error(err)
  1014. }
  1015. text := fmt.Sprintf("合同:%s-%s 中的产品:%s 距离运维到期还有 %d 天",
  1016. ctr.ContractCode, ctr.ContractName, i.ProdName, day)
  1017. msg := g.MapStrStr{
  1018. "msgTitle": "运维期到期提醒",
  1019. "msgContent": text,
  1020. "msgType": "20",
  1021. "recvUserIds": strconv.Itoa(ctr.InchargeId),
  1022. "msgStatus": "10",
  1023. "sendType": "10",
  1024. }
  1025. if err := service.CreateSystemMessage(msg); err != nil {
  1026. glog.Error("消息提醒异常:", err)
  1027. }
  1028. glog.Infof("%s", text)
  1029. }
  1030. }
  1031. }
  1032. // 每天凌晨2点执行
  1033. gcron.AddSingleton("0 0 2 * * *", job)
  1034. // job()
  1035. }