ctr_contract.go 32 KB

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