ctr_contract.go 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783
  1. package service
  2. import (
  3. "context"
  4. worksrv "dashoo.cn/micro/app/service/work"
  5. "database/sql"
  6. "encoding/base64"
  7. "encoding/json"
  8. "fmt"
  9. "github.com/gogf/gf/util/gconv"
  10. "io"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. basedao "dashoo.cn/micro/app/dao/base"
  17. dao "dashoo.cn/micro/app/dao/contract"
  18. custdao "dashoo.cn/micro/app/dao/cust"
  19. projdao "dashoo.cn/micro/app/dao/proj"
  20. workflowdao "dashoo.cn/micro/app/dao/workflow"
  21. model "dashoo.cn/micro/app/model/contract"
  22. proj "dashoo.cn/micro/app/model/proj"
  23. workflowModel "dashoo.cn/micro/app/model/workflow"
  24. "dashoo.cn/micro/app/service"
  25. baseService "dashoo.cn/micro/app/service/base"
  26. projsrv "dashoo.cn/micro/app/service/proj"
  27. workflowService "dashoo.cn/micro/app/service/workflow"
  28. "dashoo.cn/opms_libary/micro_srv"
  29. "dashoo.cn/opms_libary/multipart"
  30. "dashoo.cn/opms_libary/myerrors"
  31. "dashoo.cn/opms_libary/plugin/dingtalk"
  32. "dashoo.cn/opms_libary/plugin/dingtalk/message"
  33. "dashoo.cn/opms_libary/plugin/dingtalk/workflow"
  34. "dashoo.cn/opms_libary/request"
  35. "dashoo.cn/opms_libary/utils"
  36. "github.com/gogf/gf/database/gdb"
  37. "github.com/gogf/gf/frame/g"
  38. "github.com/gogf/gf/os/gcron"
  39. "github.com/gogf/gf/os/glog"
  40. "github.com/gogf/gf/os/gtime"
  41. "github.com/gogf/gf/util/gvalid"
  42. )
  43. type CtrContractService struct {
  44. Dao *dao.CtrContractDao
  45. ProjBusinessDao *projdao.ProjBusinessDao
  46. CustomerDao *custdao.CustCustomerDao
  47. CtrProductDao *dao.CtrContractProductDao
  48. ProductDao *basedao.BaseProductDao
  49. DynamicsDao *dao.CtrContractDynamicsDao
  50. WorkflowDao *workflowdao.PlatWorkflowDao
  51. AppendDao *dao.CtrContractAppendDao
  52. GoalDao *dao.CtrContractGoalDao
  53. ShareDao *dao.CtrContractShareDao
  54. TargetDao *dao.CtrContractSaleTargetDao
  55. Tenant string
  56. userInfo request.UserInfo
  57. DataScope g.Map `json:"dataScope"`
  58. }
  59. var mtx sync.Mutex
  60. func NewCtrContractService(ctx context.Context) (*CtrContractService, error) {
  61. tenant, err := micro_srv.GetTenant(ctx)
  62. if err != nil {
  63. err = myerrors.TipsError(fmt.Sprintf("获取租户码异常:%s", err.Error()))
  64. return nil, err //fmt.Errorf("获取租户码异常:%s", err.Error())
  65. }
  66. // 获取用户信息
  67. userInfo, err := micro_srv.GetUserInfo(ctx)
  68. if err != nil {
  69. return nil, fmt.Errorf("获取用户信息异常:%s", err.Error())
  70. }
  71. return &CtrContractService{
  72. Dao: dao.NewCtrContractDao(tenant),
  73. ProjBusinessDao: projdao.NewProjBusinessDao(tenant),
  74. CustomerDao: custdao.NewCustCustomerDao(tenant),
  75. CtrProductDao: dao.NewCtrContractProductDao(tenant),
  76. ProductDao: basedao.NewBaseProductDao(tenant),
  77. DynamicsDao: dao.NewCtrContractDynamicsDao(tenant),
  78. WorkflowDao: workflowdao.NewPlatWorkflowDao(tenant),
  79. AppendDao: dao.NewCtrContractAppendDao(tenant),
  80. GoalDao: dao.NewCtrContractGoalDao(tenant),
  81. ShareDao: dao.NewCtrContractShareDao(tenant),
  82. TargetDao: dao.NewCtrContractSaleTargetDao(tenant),
  83. Tenant: tenant,
  84. userInfo: userInfo,
  85. DataScope: userInfo.DataScope,
  86. }, nil
  87. }
  88. func (s CtrContractService) Get(ctx context.Context, id int) (*model.CtrContractGetRsp, error) {
  89. ent, err := s.Dao.Where("Id = ?", id).One()
  90. if err != nil {
  91. return nil, err
  92. }
  93. if ent == nil {
  94. return nil, myerrors.TipsError("合同不存在")
  95. }
  96. product, err := s.CtrProductDao.Where("contract_id = ?", id).All()
  97. if err != nil {
  98. return nil, err
  99. }
  100. if product == nil {
  101. product = []*model.CtrContractProduct{}
  102. }
  103. return &model.CtrContractGetRsp{
  104. CtrContract: *ent,
  105. Product: product,
  106. }, nil
  107. }
  108. func (s CtrContractService) DynamicsList(ctx context.Context, req *model.CtrContractDynamicsListReq) (int, interface{}, error) {
  109. dao := &s.DynamicsDao.CtrContractDynamicsDao
  110. if req.SearchText != "" {
  111. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  112. dao = dao.Where("(opn_people LIKE ? || opn_content LIKE ?)", likestr, likestr)
  113. }
  114. if req.ContractId != 0 {
  115. dao = dao.Where("contract_id = ?", req.ContractId)
  116. }
  117. if req.OpnPeopleId != 0 {
  118. dao = dao.Where("opn_people_id = ?", req.OpnPeopleId)
  119. }
  120. if req.OpnPeople != "" {
  121. likestr := fmt.Sprintf("%%%s%%", req.OpnPeople)
  122. dao = dao.Where("opn_people like ?", likestr)
  123. }
  124. if req.OpnType != "" {
  125. dao = dao.Where("opn_type = ?", req.OpnType)
  126. }
  127. // if req.OpnContent != "" {
  128. // likestr := fmt.Sprintf("%%%s%%", req.OpnContent)
  129. // dao = dao.Where("opn_content like ?", likestr)
  130. // }
  131. if req.BeginTime != "" {
  132. dao = dao.Where("created_time > ?", req.BeginTime)
  133. }
  134. if req.EndTime != "" {
  135. dao = dao.Where("created_time < ?", req.EndTime)
  136. }
  137. total, err := dao.Count()
  138. if err != nil {
  139. return 0, nil, err
  140. }
  141. if req.PageNum != 0 {
  142. dao = dao.Page(req.GetPage())
  143. }
  144. orderby := "created_time desc"
  145. if req.OrderBy != "" {
  146. orderby = req.OrderBy
  147. }
  148. dao = dao.Order(orderby)
  149. ents := []*model.CtrContractDynamics{}
  150. err = dao.Structs(&ents)
  151. if err != nil && err != sql.ErrNoRows {
  152. return 0, nil, err
  153. }
  154. ret := map[string][]*model.CtrContractDynamics{}
  155. for _, ent := range ents {
  156. date := ent.OpnDate.Format("Y-m-d")
  157. ret[date] = append(ret[date], ent)
  158. }
  159. return total, ret, err
  160. }
  161. func (s CtrContractService) List(ctx context.Context, req *model.CtrContractListReq) (int, []*model.CtrContractListRsp, error) {
  162. ctx = context.WithValue(ctx, "contextService", s)
  163. dao := s.Dao.DataScope(ctx, "incharge_id").As("a")
  164. if req.SearchText != "" {
  165. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  166. dao = dao.Where("(a.contract_code LIKE ? || a.contract_name LIKE ? || a.cust_name LIKE ? || a.nbo_name LIKE ?)", likestr, likestr, likestr, likestr)
  167. }
  168. if req.ContractCode != "" {
  169. likestr := fmt.Sprintf("%%%s%%", req.ContractCode)
  170. dao = dao.Where("a.contract_code like ?", likestr)
  171. }
  172. if req.ContractName != "" {
  173. likestr := fmt.Sprintf("%%%s%%", req.ContractName)
  174. dao = dao.Where("a.contract_name like ?", likestr)
  175. }
  176. if req.CustId != 0 {
  177. dao = dao.Where("a.cust_id = ?", req.CustId)
  178. }
  179. if req.CustName != "" {
  180. likestr := fmt.Sprintf("%%%s%%", req.CustName)
  181. dao = dao.Where("a.cust_name like ?", likestr)
  182. }
  183. if req.NboId != 0 {
  184. dao = dao.Where("a.nbo_id = ?", req.NboId)
  185. }
  186. if req.NboName != "" {
  187. likestr := fmt.Sprintf("%%%s%%", req.NboName)
  188. dao = dao.Where("a.nbo_name like ?", likestr)
  189. }
  190. if req.ApproStatus != "" {
  191. dao = dao.Where("a.appro_status = ?", req.ApproStatus)
  192. }
  193. if req.ContractType != "" {
  194. dao = dao.Where("a.contract_type = ?", req.ContractType)
  195. }
  196. // if req.ContractStartTime != nil {
  197. // dao = dao.Where("a.contract_start_time > ?", req.ContractStartTime)
  198. // }
  199. // if req.ContractEndTime != nil {
  200. // dao = dao.Where("a.contract_end_time < ?", req.ContractEndTime)
  201. // }
  202. if req.InchargeId != 0 {
  203. dao = dao.Where("a.incharge_id = ?", req.InchargeId)
  204. }
  205. if req.InchargeName != "" {
  206. likestr := fmt.Sprintf("%%%s%%", req.InchargeName)
  207. dao = dao.Where("a.incharge_name like ?", likestr)
  208. }
  209. if req.SignatoryId != 0 {
  210. dao = dao.Where("a.signatory_id = ?", req.SignatoryId)
  211. }
  212. if req.SignatoryName != "" {
  213. likestr := fmt.Sprintf("%%%s%%", req.SignatoryName)
  214. dao = dao.Where("a.signatory_name like ?", likestr)
  215. }
  216. if req.DistributorId != 0 {
  217. dao = dao.Where("a.distributor_id = ?", req.DistributorId)
  218. }
  219. if req.DistributorName != "" {
  220. likestr := fmt.Sprintf("%%%s%%", req.DistributorName)
  221. dao = dao.Where("a.distributor_name like ?", likestr)
  222. }
  223. if req.BeginTime != "" {
  224. dao = dao.Where("a.created_time > ?", req.BeginTime)
  225. }
  226. if req.EndTime != "" {
  227. dao = dao.Where("a.created_time < ?", req.EndTime)
  228. }
  229. if req.ContractEndTimeStart != "" {
  230. dao = dao.Where("a.contract_end_time >= ?", req.ContractEndTimeStart)
  231. }
  232. if req.ContractEndTimeEnd != "" {
  233. dao = dao.Where("a.contract_end_time <= ?", req.ContractEndTimeEnd)
  234. }
  235. if req.ContractSignTimeStart != "" {
  236. dao = dao.Where("a.contract_sign_time >= ?", req.ContractSignTimeStart)
  237. }
  238. if req.ContractSignTimeEnd != "" {
  239. dao = dao.Where("a.contract_sign_time <= ?", req.ContractSignTimeEnd)
  240. }
  241. if req.CustProvinceId != 0 {
  242. dao = dao.Where("a.cust_province_id = ?", req.CustProvinceId)
  243. }
  244. if req.CustCityId != 0 {
  245. dao = dao.Where("a.cust_city_id = ?", req.CustCityId)
  246. }
  247. if req.ProductLine != "" {
  248. dao = dao.Where("a.product_line = ?", req.ProductLine)
  249. }
  250. if req.SoftwareMaintenanceBeginTimeStart != nil {
  251. dao = dao.Where("DATE(a.software_maintenance_begin_time) >= DATE(?)", req.SoftwareMaintenanceBeginTimeStart)
  252. }
  253. if req.SoftwareMaintenanceBeginTimeEnd != nil {
  254. dao = dao.Where("DATE(a.software_maintenance_begin_time) <= DATE(?)", req.SoftwareMaintenanceBeginTimeEnd)
  255. }
  256. if req.SoftwareMaintenanceEndTimeStart != nil {
  257. dao = dao.Where("DATE(a.software_maintenance_end_time) >= DATE(?)", req.SoftwareMaintenanceEndTimeStart)
  258. }
  259. if req.SoftwareMaintenanceEndTimeEnd != nil {
  260. dao = dao.Where("DATE(a.software_maintenance_end_time) <= DATE(?)", req.SoftwareMaintenanceEndTimeEnd)
  261. }
  262. if req.HardwareMaintenanceBeginTimeStart != nil {
  263. dao = dao.Where("DATE(a.hardware_maintenance_begin_time) >= DATE(?)", req.HardwareMaintenanceBeginTimeStart)
  264. }
  265. if req.HardwareMaintenanceBeginTimeEnd != nil {
  266. dao = dao.Where("DATE(a.hardware_maintenance_begin_time) <= DATE(?)", req.HardwareMaintenanceBeginTimeEnd)
  267. }
  268. if req.HardwareMaintenanceEndTimeStart != nil {
  269. dao = dao.Where("DATE(a.hardware_maintenance_end_time) >= DATE(?)", req.HardwareMaintenanceEndTimeStart)
  270. }
  271. if req.HardwareMaintenanceEndTimeEnd != nil {
  272. dao = dao.Where("DATE(a.hardware_maintenance_end_time) <= DATE(?)", req.HardwareMaintenanceEndTimeEnd)
  273. }
  274. if req.IsNotMaintenanceContract == "10" {
  275. dao = dao.Where("a.contract_id = 0 or a.contract_id is NULL")
  276. }
  277. total, err := dao.Count()
  278. if err != nil {
  279. return 0, nil, err
  280. }
  281. if req.PageNum != 0 {
  282. dao = dao.Page(req.GetPage())
  283. }
  284. orderby := "a.contract_sign_time desc"
  285. if req.OrderBy != "" {
  286. orderby = req.OrderBy
  287. }
  288. dao = dao.Order(orderby)
  289. ents := []*model.CtrContractListRsp{}
  290. err = dao.Structs(&ents)
  291. if err != nil && err != sql.ErrNoRows {
  292. return 0, nil, err
  293. }
  294. return total, ents, err
  295. }
  296. func (s CtrContractService) RenewList(ctx context.Context, req *model.CtrRenewContractListReq) ([]*model.CtrContractListRsp, error) {
  297. ctx = context.WithValue(ctx, "contextService", s)
  298. dao := s.Dao.DataScope(ctx, "incharge_id").As("a").Where("contract_id=?", req.ContractId)
  299. if req.SearchText != "" {
  300. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  301. dao = dao.Where("(a.contract_code LIKE ? || a.contract_name LIKE ? || a.cust_name LIKE ? || a.nbo_name LIKE ?)", likestr, likestr, likestr, likestr)
  302. }
  303. orderby := "a.contract_sign_time desc"
  304. dao = dao.Order(orderby)
  305. ents := []*model.CtrContractListRsp{}
  306. err := dao.Structs(&ents)
  307. if err != nil && err != sql.ErrNoRows {
  308. return nil, err
  309. }
  310. return ents, err
  311. }
  312. func (s CtrContractService) BindProduct(tx *gdb.TX, id int, code string, product []model.CtrAddProduct) error {
  313. var amount float64
  314. for _, p := range product {
  315. amount += (p.TranPrice * float64(p.ProdNum))
  316. }
  317. _, err := tx.Delete("ctr_contract_product", "contract_id = ?", id)
  318. if err != nil {
  319. return err
  320. }
  321. tocreate := []model.CtrContractProduct{}
  322. for _, p := range product {
  323. product, err := s.ProductDao.Where("id = ?", p.ProdId).One()
  324. if err != nil {
  325. return err
  326. }
  327. if product == nil {
  328. return myerrors.TipsError(fmt.Sprintf("产品: %d 不存在", p.ProdId))
  329. }
  330. tocreate = append(tocreate, model.CtrContractProduct{
  331. ContractId: id,
  332. ContractCode: code,
  333. ProdId: p.ProdId,
  334. ProdCode: product.ProdCode,
  335. ProdName: product.ProdName,
  336. ProdClass: product.ProdClass,
  337. ProdNum: p.ProdNum,
  338. MaintTerm: p.MaintTerm,
  339. SugSalesPrice: p.SugSalesPrice,
  340. TranPrice: p.TranPrice,
  341. ContractPrive: amount,
  342. Remark: p.Remark,
  343. CreatedBy: int(s.userInfo.Id),
  344. CreatedName: s.userInfo.NickName,
  345. CreatedTime: gtime.Now(),
  346. UpdatedBy: int(s.userInfo.Id),
  347. UpdatedName: s.userInfo.NickName,
  348. UpdatedTime: gtime.Now(),
  349. })
  350. }
  351. if len(tocreate) != 0 {
  352. _, err = tx.Insert("ctr_contract_product", tocreate)
  353. if err != nil {
  354. return err
  355. }
  356. }
  357. return nil
  358. }
  359. func (s CtrContractService) AddDynamicsByCurrentUser(tx *gdb.TX, contractId int, opnType string, content map[string]interface{}) error {
  360. contentByte, err := json.Marshal(content)
  361. if err != nil {
  362. return err
  363. }
  364. _, err = tx.InsertAndGetId("ctr_contract_dynamics", model.CtrContractDynamics{
  365. ContractId: contractId,
  366. OpnPeopleId: s.userInfo.Id,
  367. OpnPeople: s.userInfo.NickName,
  368. OpnDate: gtime.Now(),
  369. OpnType: opnType,
  370. OpnContent: string(contentByte),
  371. Remark: "",
  372. CreatedBy: s.userInfo.Id,
  373. CreatedName: s.userInfo.NickName,
  374. CreatedTime: gtime.Now(),
  375. UpdatedBy: s.userInfo.Id,
  376. UpdatedName: s.userInfo.NickName,
  377. UpdatedTime: gtime.Now(),
  378. })
  379. return err
  380. }
  381. func (s CtrContractService) Add(ctx context.Context, req *model.CtrContractAddReq) (int, error) {
  382. validErr := gvalid.CheckStruct(ctx, req, nil)
  383. if validErr != nil {
  384. return 0, myerrors.TipsError(validErr.Current().Error())
  385. }
  386. if len(req.Product) == 0 {
  387. return 0, myerrors.TipsError("产品不能为空")
  388. }
  389. for _, p := range req.Product {
  390. if p.ProdNum < 1 {
  391. return 0, myerrors.TipsError("产品数量必须大于 0")
  392. }
  393. }
  394. // c, err := s.Dao.Where("contract_name = ?", req.ContractName).One()
  395. // if err != nil {
  396. // return 0, err
  397. // }
  398. // if c != nil {
  399. // return 0, myerrors.TipsError(fmt.Sprintf("合同名称:%s 已存在", req.ContractName))
  400. // }
  401. nbo, err := s.ProjBusinessDao.Where("id = ?", req.NboId).One()
  402. if err != nil {
  403. return 0, err
  404. }
  405. if nbo == nil {
  406. return 0, myerrors.TipsError("项目不存在")
  407. }
  408. // c, err = s.Dao.Where("nbo_id = ?", req.NboId).One()
  409. // if err != nil {
  410. // return 0, err
  411. // }
  412. // if c != nil {
  413. // return 0, myerrors.TipsError("所选项目已添加合同")
  414. // }
  415. var sequence int
  416. if req.ContractType == "XS" { // 销售合同
  417. sequence, err = service.SequenceYearRest(s.Dao.DB, "contract_code_xs")
  418. if err != nil {
  419. return 0, err
  420. }
  421. } else if req.ContractType == "JS" { // 技术合同
  422. sequence, err = service.SequenceYearRest(s.Dao.DB, "contract_code_js")
  423. if err != nil {
  424. return 0, err
  425. }
  426. } else {
  427. return 0, myerrors.TipsError("不支持的合同类型")
  428. }
  429. if req.ContractCode == "" {
  430. req.ContractCode = fmt.Sprintf("DH%s%s-%03d", req.ContractType, time.Now().Format("0601"), sequence)
  431. }
  432. c, err := s.Dao.Where("contract_code = ?", req.ContractCode).One()
  433. if err != nil {
  434. return 0, err
  435. }
  436. if c != nil {
  437. return 0, myerrors.TipsError(fmt.Sprintf("合同编号:%s 已存在", req.ContractCode))
  438. }
  439. var contractAmount float64
  440. for _, p := range req.Product {
  441. contractAmount += (p.TranPrice * float64(p.ProdNum))
  442. }
  443. ctr := model.CtrContract{
  444. ContractCode: req.ContractCode,
  445. ContractName: req.ContractName,
  446. CustId: nbo.CustId,
  447. CustName: nbo.CustName,
  448. NboId: nbo.Id,
  449. NboName: nbo.NboName,
  450. IsBig: nbo.IsBig,
  451. ProductLine: nbo.ProductLine,
  452. CustProvinceId: nbo.CustProvinceId,
  453. CustProvince: nbo.CustProvince,
  454. CustCityId: nbo.CustCityId,
  455. CustCity: nbo.CustCity,
  456. ApproStatus: "10",
  457. ContractType: req.ContractType,
  458. ContractAmount: contractAmount,
  459. InvoiceAmount: 0,
  460. CollectedAmount: 0,
  461. ContractStartTime: req.ContractStartTime,
  462. ContractEndTime: req.ContractEndTime,
  463. ContractSignTime: req.ContractSignTime,
  464. InchargeId: req.InchargeId,
  465. InchargeName: req.InchargeName,
  466. SignatoryId: req.SignatoryId,
  467. SignatoryName: req.SignatoryName,
  468. SignatoryType: req.SignatoryType,
  469. SignatoryUnit: req.SignatoryUnit,
  470. EarnestMoney: req.EarnestMoney,
  471. CustSignatoryId: req.CustSignatoryId,
  472. CustSignatoryName: req.CustSignatoryName,
  473. DistributorId: req.DistributorId,
  474. DistributorName: req.DistributorName,
  475. Remark: req.Remark,
  476. ServiceFeeAgreement: req.ServiceFeeAgreement,
  477. SoftwareMaintenanceLimit: req.SoftwareMaintenanceLimit,
  478. HardwareMaintenanceLimit: req.HardwareMaintenanceLimit,
  479. MaintenanceClause: req.MaintenanceClause,
  480. CreatedBy: s.userInfo.Id,
  481. CreatedName: s.userInfo.NickName,
  482. CreatedTime: gtime.Now(),
  483. UpdatedBy: s.userInfo.Id,
  484. UpdatedName: s.userInfo.NickName,
  485. UpdatedTime: gtime.Now(),
  486. }
  487. var id int
  488. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  489. ctrid, err := tx.InsertAndGetId("ctr_contract", ctr)
  490. if err != nil {
  491. return err
  492. }
  493. err = s.BindProduct(tx, int(ctrid), ctr.ContractCode, req.Product)
  494. if err != nil {
  495. return err
  496. }
  497. err = s.AddDynamicsByCurrentUser(tx, int(ctrid), "创建合同", map[string]interface{}{})
  498. if err != nil {
  499. return err
  500. }
  501. _, err = tx.Update("proj_business", map[string]interface{}{
  502. "nbo_type": projsrv.StatusDeal,
  503. }, "id = ?", nbo.Id)
  504. if err != nil {
  505. return err
  506. }
  507. id = int(ctrid)
  508. return nil
  509. })
  510. return id, txerr
  511. }
  512. func (s CtrContractService) ReNew(ctx context.Context, req *model.CtrContractReNewReq) (int, error) {
  513. validErr := gvalid.CheckStruct(ctx, req, nil)
  514. if validErr != nil {
  515. return 0, myerrors.TipsError(validErr.Current().Error())
  516. }
  517. if len(req.Product) == 0 {
  518. return 0, myerrors.TipsError("产品不能为空")
  519. }
  520. for _, p := range req.Product {
  521. if p.ProdNum < 1 {
  522. return 0, myerrors.TipsError("产品数量必须大于 0")
  523. }
  524. }
  525. nbo, err := s.ProjBusinessDao.Where("id = ?", req.NboId).One()
  526. if err != nil {
  527. return 0, err
  528. }
  529. if nbo == nil {
  530. return 0, myerrors.TipsError("项目不存在")
  531. }
  532. oldContract, err := s.Dao.Where("id = ?", req.ContractId).One()
  533. if err != nil {
  534. return 0, err
  535. }
  536. if oldContract == nil {
  537. return 0, myerrors.TipsError("合同不存在")
  538. }
  539. var sequence int
  540. if req.ContractType == "XS" { // 销售合同
  541. sequence, err = service.SequenceYearRest(s.Dao.DB, "contract_code_xs")
  542. if err != nil {
  543. return 0, err
  544. }
  545. } else if req.ContractType == "JS" { // 技术合同
  546. sequence, err = service.SequenceYearRest(s.Dao.DB, "contract_code_js")
  547. if err != nil {
  548. return 0, err
  549. }
  550. } else {
  551. return 0, myerrors.TipsError("不支持的合同类型")
  552. }
  553. if req.ContractCode == "" {
  554. req.ContractCode = fmt.Sprintf("DH%s%s-%03d", req.ContractType, time.Now().Format("0601"), sequence)
  555. }
  556. c, err := s.Dao.Where("contract_code = ?", req.ContractCode).One()
  557. if err != nil {
  558. return 0, err
  559. }
  560. if c != nil {
  561. return 0, myerrors.TipsError(fmt.Sprintf("合同编号:%s 已存在", req.ContractCode))
  562. }
  563. var contractAmount float64
  564. for _, p := range req.Product {
  565. contractAmount += (p.TranPrice * float64(p.ProdNum))
  566. }
  567. softSub := req.SoftwareMaintenanceEndTime.Sub(req.SoftwareMaintenanceBeginTime).Hours() / 24 / 365
  568. req.SoftwareMaintenanceLimit = int(softSub)
  569. hardSub := req.HardwareMaintenanceEndTime.Sub(req.HardwareMaintenanceBeginTime).Hours() / 24 / 365
  570. req.HardwareMaintenanceLimit = int(hardSub)
  571. ctr := model.CtrContract{
  572. ContractCode: req.ContractCode,
  573. ContractName: req.ContractName,
  574. CustId: nbo.CustId,
  575. CustName: nbo.CustName,
  576. ContractId: req.ContractId,
  577. NboId: nbo.Id,
  578. NboName: nbo.NboName,
  579. IsBig: nbo.IsBig,
  580. ProductLine: nbo.ProductLine,
  581. CustProvinceId: nbo.CustProvinceId,
  582. CustProvince: nbo.CustProvince,
  583. CustCityId: nbo.CustCityId,
  584. CustCity: nbo.CustCity,
  585. ApproStatus: "10",
  586. ContractType: req.ContractType,
  587. ContractAmount: contractAmount,
  588. InvoiceAmount: 0,
  589. CollectedAmount: 0,
  590. ContractStartTime: req.ContractStartTime,
  591. ContractEndTime: req.ContractEndTime,
  592. ContractSignTime: req.ContractSignTime,
  593. InchargeId: req.InchargeId,
  594. InchargeName: req.InchargeName,
  595. SignatoryId: req.SignatoryId,
  596. SignatoryName: req.SignatoryName,
  597. SignatoryType: req.SignatoryType,
  598. SignatoryUnit: req.SignatoryUnit,
  599. EarnestMoney: req.EarnestMoney,
  600. CustSignatoryId: req.CustSignatoryId,
  601. CustSignatoryName: req.CustSignatoryName,
  602. DistributorId: req.DistributorId,
  603. DistributorName: req.DistributorName,
  604. Remark: req.Remark,
  605. ServiceFeeAgreement: req.ServiceFeeAgreement,
  606. SoftwareMaintenanceBeginTime: req.SoftwareMaintenanceBeginTime,
  607. SoftwareMaintenanceEndTime: req.SoftwareMaintenanceEndTime,
  608. HardwareMaintenanceBeginTime: req.HardwareMaintenanceBeginTime,
  609. HardwareMaintenanceEndTime: req.HardwareMaintenanceEndTime,
  610. SoftwareMaintenanceLimit: req.SoftwareMaintenanceLimit,
  611. HardwareMaintenanceLimit: req.HardwareMaintenanceLimit,
  612. MaintenanceClause: req.MaintenanceClause,
  613. CreatedBy: s.userInfo.Id,
  614. CreatedName: s.userInfo.NickName,
  615. CreatedTime: gtime.Now(),
  616. UpdatedBy: s.userInfo.Id,
  617. UpdatedName: s.userInfo.NickName,
  618. UpdatedTime: gtime.Now(),
  619. }
  620. var id int
  621. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  622. ctrid, err := tx.InsertAndGetId("ctr_contract", ctr)
  623. if err != nil {
  624. return err
  625. }
  626. err = s.BindProduct(tx, int(ctrid), ctr.ContractCode, req.Product)
  627. if err != nil {
  628. return err
  629. }
  630. //ContractApplyApproval
  631. err = s.AddDynamicsByCurrentUser(tx, int(ctrid), "创建合同", map[string]interface{}{})
  632. if err != nil {
  633. return err
  634. }
  635. _, err = tx.Update("proj_business", map[string]interface{}{
  636. "nbo_type": projsrv.StatusDeal,
  637. }, "id = ?", nbo.Id)
  638. if err != nil {
  639. return err
  640. }
  641. err = s.AddDynamicsByCurrentUser(tx, int(req.ContractId), "创建续签合同", map[string]interface{}{
  642. "contractName": req.ContractName,
  643. })
  644. if err != nil {
  645. return err
  646. }
  647. id = int(ctrid)
  648. return nil
  649. })
  650. return id, txerr
  651. }
  652. func (s CtrContractService) UpdateReNew(ctx context.Context, req *model.CtrContractUpdateReNewReq) error {
  653. validErr := gvalid.CheckStruct(ctx, req, nil)
  654. if validErr != nil {
  655. return myerrors.TipsError(validErr.Current().Error())
  656. }
  657. ent, err := s.Dao.Where("id = ?", req.Id).One()
  658. if err != nil {
  659. return err
  660. }
  661. if ent == nil {
  662. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  663. }
  664. //if req.ContractName != "" {
  665. // exist, err := s.Dao.Where("contract_name = ?", req.ContractName).One()
  666. // if err != nil {
  667. // return err
  668. // }
  669. // if exist != nil && exist.Id != req.Id {
  670. // return myerrors.TipsError(fmt.Sprintf("合同名称:%s 已存在", req.ContractName))
  671. // }
  672. //}
  673. var nbo *proj.ProjBusiness
  674. if req.NboId != 0 {
  675. nbo, err = s.ProjBusinessDao.Where("id = ?", req.NboId).One()
  676. if err != nil {
  677. return err
  678. }
  679. if nbo == nil {
  680. return myerrors.TipsError("项目不存在")
  681. }
  682. }
  683. toupdate := map[string]interface{}{}
  684. if req.ContractName != "" {
  685. toupdate["contract_name"] = req.ContractName
  686. }
  687. if req.NboId != 0 {
  688. toupdate["cust_id"] = nbo.CustId
  689. toupdate["cust_name"] = nbo.CustName
  690. toupdate["nbo_id"] = nbo.Id
  691. toupdate["nbo_name"] = nbo.NboName
  692. toupdate["is_big"] = nbo.IsBig
  693. toupdate["product_line"] = nbo.ProductLine
  694. toupdate["cust_province_id"] = nbo.CustProvinceId
  695. toupdate["cust_province"] = nbo.CustProvince
  696. toupdate["cust_city_id"] = nbo.CustCityId
  697. toupdate["cust_city"] = nbo.CustCity
  698. }
  699. if req.ContractType != "" {
  700. toupdate["contract_type"] = req.ContractType
  701. }
  702. if req.ContractStartTime != nil {
  703. toupdate["contract_start_time"] = req.ContractStartTime
  704. }
  705. if req.ContractEndTime != nil {
  706. toupdate["contract_end_time"] = req.ContractEndTime
  707. }
  708. if req.ContractSignTime != nil {
  709. toupdate["contract_sign_time"] = req.ContractSignTime
  710. }
  711. if req.SignatoryId != 0 {
  712. toupdate["signatory_id"] = req.SignatoryId
  713. }
  714. if req.SignatoryName != "" {
  715. toupdate["signatory_name"] = req.SignatoryName
  716. }
  717. if req.SignatoryType != "" {
  718. toupdate["signatory_type"] = req.SignatoryType
  719. }
  720. if req.SignatoryUnit != "" {
  721. toupdate["signatory_unit"] = req.SignatoryUnit
  722. }
  723. if req.EarnestMoney != 0 {
  724. toupdate["earnest_money"] = req.EarnestMoney
  725. }
  726. if req.CustSignatoryId != 0 {
  727. toupdate["cust_signatory_id"] = req.CustSignatoryId
  728. }
  729. if req.CustSignatoryName != "" {
  730. toupdate["cust_signatory_name"] = req.CustSignatoryName
  731. }
  732. if req.DistributorId != 0 {
  733. toupdate["distributor_id"] = req.DistributorId
  734. }
  735. if req.DistributorName != "" {
  736. toupdate["distributor_name"] = req.DistributorName
  737. }
  738. if req.SoftwareMaintenanceBeginTime != nil {
  739. toupdate["software_maintenance_begin_time"] = req.SoftwareMaintenanceBeginTime
  740. }
  741. if req.SoftwareMaintenanceEndTime != nil {
  742. toupdate["software_maintenance_end_time"] = req.SoftwareMaintenanceEndTime
  743. }
  744. if req.HardwareMaintenanceBeginTime != nil {
  745. toupdate["hardware_maintenance_begin_time"] = req.HardwareMaintenanceBeginTime
  746. }
  747. if req.HardwareMaintenanceEndTime != nil {
  748. toupdate["hardware_maintenance_end_time"] = req.HardwareMaintenanceEndTime
  749. }
  750. softSub := req.SoftwareMaintenanceEndTime.Sub(req.SoftwareMaintenanceBeginTime).Hours() / 24 / 365
  751. req.SoftwareMaintenanceLimit = int(softSub)
  752. hardSub := req.HardwareMaintenanceEndTime.Sub(req.HardwareMaintenanceBeginTime).Hours() / 24 / 365
  753. req.HardwareMaintenanceLimit = int(hardSub)
  754. if req.SoftwareMaintenanceLimit != 0 {
  755. toupdate["software_maintenance_limit"] = req.SoftwareMaintenanceLimit
  756. }
  757. if req.HardwareMaintenanceLimit != 0 {
  758. toupdate["hardware_maintenance_limit"] = req.HardwareMaintenanceLimit
  759. }
  760. if req.Remark != "" {
  761. toupdate["remark"] = req.Remark
  762. }
  763. if req.Product != nil {
  764. var contractAmount float64
  765. for _, p := range req.Product {
  766. contractAmount += (p.TranPrice * float64(p.ProdNum))
  767. }
  768. toupdate["contract_amount"] = contractAmount
  769. }
  770. if len(toupdate) != 0 {
  771. toupdate["updated_by"] = int(s.userInfo.Id)
  772. toupdate["updated_name"] = s.userInfo.NickName
  773. toupdate["updated_time"] = gtime.Now()
  774. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  775. _, err = tx.Update("ctr_contract", toupdate, "id = ?", req.Id)
  776. if err != nil {
  777. return err
  778. }
  779. if req.Product != nil {
  780. err = s.BindProduct(tx, req.Id, ent.ContractCode, req.Product)
  781. if err != nil {
  782. return err
  783. }
  784. }
  785. return nil
  786. })
  787. if txerr != nil {
  788. return txerr
  789. }
  790. }
  791. return nil
  792. }
  793. var ContractApplyProcessCode = "PROC-7057E20A-2066-4644-9B35-9331E4DA912C" // 创建合同
  794. func (s CtrContractService) Commit(ctx context.Context, req *model.CtrContractCommitReq) error {
  795. validErr := gvalid.CheckStruct(ctx, req, nil)
  796. if validErr != nil {
  797. return myerrors.TipsError(validErr.Current().Error())
  798. }
  799. if !(req.ContractModel == "大数模板" || req.ContractModel == "客户模板") {
  800. return myerrors.TipsError("合同模板不合法")
  801. }
  802. if !(req.Terms == "接纳全部条款" || req.Terms == "不接纳全部条款") {
  803. return myerrors.TipsError("条款情况不合法")
  804. }
  805. if req.PayTerms == "" {
  806. return myerrors.TipsError("付款条件不能为空")
  807. }
  808. if len(req.File) == 0 {
  809. return myerrors.TipsError("附件不能为空")
  810. }
  811. ent, err := s.Dao.Where("id = ?", req.Id).One()
  812. if err != nil {
  813. return err
  814. }
  815. if ent == nil {
  816. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  817. }
  818. fileinfoByte, err := json.Marshal(req.File)
  819. if err != nil {
  820. return err
  821. }
  822. workflowSrv, err := workflowService.NewFlowService(ctx)
  823. if err != nil {
  824. return err
  825. }
  826. bizCode := strconv.Itoa(ent.Id)
  827. _, err = workflowSrv.StartProcessInstance(bizCode, "30", "", &workflow.StartProcessInstanceRequest{
  828. ProcessCode: &ContractApplyProcessCode,
  829. FormComponentValues: []*workflow.StartProcessInstanceRequestFormComponentValues{
  830. {
  831. Id: utils.String("DDSelectField_ESX8H30W3VK0"),
  832. Name: utils.String("合同模板"),
  833. Value: utils.String(req.ContractModel),
  834. },
  835. {
  836. Id: utils.String("DDSelectField_13IQX96C2KAK0"),
  837. Name: utils.String("条款情况"),
  838. Value: utils.String(req.Terms),
  839. },
  840. {
  841. Id: utils.String("TextField_1A5SA7VOG5TS0"),
  842. Name: utils.String("合同编号"),
  843. Value: utils.String(ent.ContractCode),
  844. },
  845. {
  846. Id: utils.String("TextField_1EX61DPS3LA80"),
  847. Name: utils.String("客户名称"),
  848. Value: utils.String(ent.CustName),
  849. },
  850. {
  851. Id: utils.String("MoneyField_X1XV4KIR0GW0"),
  852. Name: utils.String("合同金额(元)"),
  853. Value: utils.String(strconv.FormatFloat(ent.ContractAmount, 'f', 2, 64)),
  854. },
  855. {
  856. Id: utils.String("TextareaField_1WZ5ILKBUVSW0"),
  857. Name: utils.String("付款条件"),
  858. Value: utils.String(req.PayTerms),
  859. },
  860. {
  861. Id: utils.String("DDAttachment_1051KJYC3MBK0"),
  862. Name: utils.String("附件"),
  863. // Details: productForm,
  864. Value: utils.String(string(fileinfoByte)),
  865. },
  866. },
  867. })
  868. if err != nil {
  869. return err
  870. }
  871. _, err = s.Dao.Where("id = ?", ent.Id).Data(map[string]interface{}{
  872. "appro_status": 20,
  873. }).Update()
  874. return err
  875. }
  876. // var spaceId = "21042518430"
  877. var spaceId = "21077726250"
  878. func (s CtrContractService) CommitWithFile(ctx context.Context, formData *multipart.Form) error {
  879. if s.userInfo.DingtalkUid == "" {
  880. return fmt.Errorf("该用户钉钉 uid 为空")
  881. }
  882. if len(formData.File) == 0 {
  883. return myerrors.TipsError("文件不能为空")
  884. }
  885. if _, ok := formData.File["file"]; !ok {
  886. return myerrors.TipsError("文件不能为空")
  887. }
  888. if formData.File["file"].FileName == "" {
  889. return fmt.Errorf("文件名称不能为空")
  890. }
  891. if formData.File["file"].File == nil {
  892. return fmt.Errorf("文件不能为空")
  893. }
  894. if formData.File["file"].File.Name() == "" {
  895. return fmt.Errorf("文件路径不能为空")
  896. }
  897. contractId, err := strconv.Atoi(formData.Value["contractId"])
  898. if err != nil {
  899. return fmt.Errorf("合同 Id 不合法 %s", formData.Value["contractId"])
  900. }
  901. //fmt.Println(args.File.Name(), args.FileName, args.FileSize, args.Meta)
  902. //fmt.Println(spaceId, s.userInfo.DingtalkId, args.FileName, args.File.Name())
  903. // resp, err := s.UploadFile("21042518430", "8xljy04PZiS9iPxp5PhDnUzQiEiE", "引物导入模板-000000.xlsx", "/Users/chengjian/Downloads/引物导入模板.xlsx")
  904. resp, err := dingtalk.Client.GetStorage().UploadFile(spaceId, s.userInfo.DingtalkId, formData.File["file"].FileName, formData.File["file"].File.Name())
  905. if err != nil {
  906. return fmt.Errorf("钉钉上传文件异常 %s", err.Error())
  907. }
  908. err = s.Commit(ctx, &model.CtrContractCommitReq{
  909. Id: contractId,
  910. ContractModel: formData.Value["contractModel"],
  911. Terms: formData.Value["terms"],
  912. PayTerms: formData.Value["payTerms"],
  913. File: []model.DingFileInfo{
  914. {
  915. SpaceId: resp.Dentry.SpaceId,
  916. FileId: resp.Dentry.Id,
  917. FileName: resp.Dentry.Name,
  918. FileSize: resp.Dentry.Size,
  919. FileType: resp.Dentry.Extension,
  920. },
  921. },
  922. })
  923. if err != nil {
  924. return err
  925. }
  926. // workflow, err := s.WorkflowDao.Where("id = ?", workflowId).One()
  927. // if err != nil {
  928. // return err
  929. // }
  930. // instance, err := dingtalk.Client.GetWorkflow().QueryProcessInstanceDetail(workflow.ProcessInstId)
  931. // if err != nil {
  932. // return fmt.Errorf("查询审批实例详情错误: %s", err.Error())
  933. // }
  934. // fmt.Println(workflow.ProcessInstId, instance.Result.ApproverUserIds)
  935. // approverUserIds := g.Config().GetStrings("dingtalk.approver-user-ids")
  936. // fmt.Println(approverUserIds)
  937. // for _, uid := range approverUserIds {
  938. // resp, err := dingtalk.Client.GetStorage().AddPermission(
  939. // dingtalk.Client.Context.CorpId, spaceId, uid, "DOWNLOADER", "USER")
  940. // if err != nil {
  941. // return fmt.Errorf("添加审核附件权限异常: %s", err.Error())
  942. // }
  943. // fmt.Println(uid, resp)
  944. // }
  945. appendSrv, err := NewCtrContractAppendService(ctx)
  946. if err != nil {
  947. return err
  948. }
  949. _, err = appendSrv.Add(ctx, &model.CtrContractAppendAddReq{
  950. ContractId: contractId,
  951. FileName: resp.Dentry.Name,
  952. FileType: resp.Dentry.Extension,
  953. FileUrl: strings.Join([]string{"dingtalk", resp.Dentry.SpaceId, resp.Dentry.Id}, ":"),
  954. Remark: "",
  955. })
  956. if err != nil {
  957. return err
  958. }
  959. return nil
  960. }
  961. func (s CtrContractService) CommitWithFileUrl(ctx context.Context, req *model.CtrContractCommitWithFileUrlReq) error {
  962. // 数据校验
  963. validErr := gvalid.CheckStruct(ctx, req, nil)
  964. if validErr != nil {
  965. return myerrors.TipsError(validErr.Current().Error())
  966. }
  967. // 校验销售分成数据
  968. if len(req.Shares) == 0 {
  969. return myerrors.TipsError("销售分成信息不能为空")
  970. }
  971. fileinfoByte, err := baseService.UploadDingtalk(s.userInfo.DingtalkId, req.FileUrl, req.FileName)
  972. if err != nil {
  973. return err
  974. }
  975. var fileinfo = []model.DingFileInfo{}
  976. err = json.Unmarshal(fileinfoByte, &fileinfo)
  977. if err != nil {
  978. return err
  979. }
  980. err = s.Commit(ctx, &model.CtrContractCommitReq{
  981. Id: req.Id,
  982. ContractModel: req.ContractModel,
  983. Terms: req.Terms,
  984. PayTerms: req.PayTerms,
  985. File: fileinfo,
  986. })
  987. if err != nil {
  988. return err
  989. }
  990. appendSrv, err := NewCtrContractAppendService(ctx)
  991. if err != nil {
  992. return err
  993. }
  994. _, err = appendSrv.Add(ctx, &model.CtrContractAppendAddReq{
  995. ContractId: req.Id,
  996. FileName: fileinfo[0].FileName,
  997. FileType: fileinfo[0].FileType,
  998. FileUrl: strings.Join([]string{"dingtalk", fileinfo[0].SpaceId, fileinfo[0].FileId}, ":"),
  999. Remark: "",
  1000. })
  1001. if err != nil {
  1002. return err
  1003. }
  1004. // 保存销售分成信息
  1005. if len(req.Shares) > 0 {
  1006. saleIds := ""
  1007. amountMap := make(map[int]float64)
  1008. for _, share := range req.Shares {
  1009. share.CreatedBy = s.userInfo.Id
  1010. share.CreatedName = s.userInfo.NickName
  1011. share.CreatedTime = gtime.Now()
  1012. share.UpdatedBy = s.userInfo.Id
  1013. share.UpdatedName = s.userInfo.NickName
  1014. share.UpdatedTime = gtime.Now()
  1015. amountMap[share.SaleId] += share.ShareAmount
  1016. if saleIds == "" {
  1017. saleIds += gconv.String(share.SaleId)
  1018. } else {
  1019. saleIds += "," + gconv.String(share.SaleId)
  1020. }
  1021. }
  1022. year := req.Shares[0].ContractSignTime.Format("Y")
  1023. month := req.Shares[0].ContractSignTime.Format("m")
  1024. // 查询需要更新的销售签约指标
  1025. if saleIds != "" {
  1026. targets, err := s.TargetDao.Where(fmt.Sprintf("sale_id IN (%v) AND year='%v'", saleIds, year)).FindAll()
  1027. if err != nil {
  1028. return err
  1029. }
  1030. // 更新数据
  1031. for _, target := range targets {
  1032. switch month {
  1033. case "01":
  1034. target.Complete1 += amountMap[target.SaleId]
  1035. target.QuarterComplete1 = target.Complete1 + target.Complete2 + target.Complete3
  1036. if target.QuarterPlan1 != 0 {
  1037. target.QuarterCompleteRatio1 = target.QuarterComplete1 / target.QuarterPlan1 * 100
  1038. }
  1039. break
  1040. case "02":
  1041. target.Complete2 += amountMap[target.SaleId]
  1042. target.QuarterComplete1 = target.Complete1 + target.Complete2 + target.Complete3
  1043. if target.QuarterPlan1 != 0 {
  1044. target.QuarterCompleteRatio1 = target.QuarterComplete1 / target.QuarterPlan1 * 100
  1045. }
  1046. break
  1047. case "03":
  1048. target.Complete3 += amountMap[target.SaleId]
  1049. target.QuarterComplete1 = target.Complete1 + target.Complete2 + target.Complete3
  1050. if target.QuarterPlan1 != 0 {
  1051. target.QuarterCompleteRatio1 = target.QuarterComplete1 / target.QuarterPlan1 * 100
  1052. }
  1053. break
  1054. case "04":
  1055. target.Complete4 += amountMap[target.SaleId]
  1056. target.QuarterComplete2 = target.Complete4 + target.Complete5 + target.Complete6
  1057. if target.QuarterPlan2 != 0 {
  1058. target.QuarterCompleteRatio2 = target.QuarterComplete2 / target.QuarterPlan2 * 100
  1059. }
  1060. break
  1061. case "05":
  1062. target.Complete5 += amountMap[target.SaleId]
  1063. target.QuarterComplete2 = target.Complete4 + target.Complete5 + target.Complete6
  1064. if target.QuarterPlan2 != 0 {
  1065. target.QuarterCompleteRatio2 = target.QuarterComplete2 / target.QuarterPlan2 * 100
  1066. }
  1067. break
  1068. case "06":
  1069. target.Complete6 += amountMap[target.SaleId]
  1070. target.QuarterComplete2 = target.Complete4 + target.Complete5 + target.Complete6
  1071. if target.QuarterPlan2 != 0 {
  1072. target.QuarterCompleteRatio2 = target.QuarterComplete2 / target.QuarterPlan2 * 100
  1073. }
  1074. break
  1075. case "07":
  1076. target.Complete7 += amountMap[target.SaleId]
  1077. target.QuarterComplete3 = target.Complete7 + target.Complete8 + target.Complete9
  1078. if target.QuarterPlan3 != 0 {
  1079. target.QuarterCompleteRatio3 = target.QuarterComplete3 / target.QuarterPlan3 * 100
  1080. }
  1081. break
  1082. case "08":
  1083. target.Complete8 += amountMap[target.SaleId]
  1084. target.QuarterComplete3 = target.Complete7 + target.Complete8 + target.Complete9
  1085. if target.QuarterPlan3 != 0 {
  1086. target.QuarterCompleteRatio3 = target.QuarterComplete3 / target.QuarterPlan3 * 100
  1087. }
  1088. break
  1089. case "09":
  1090. target.Complete9 += amountMap[target.SaleId]
  1091. target.QuarterComplete3 = target.Complete7 + target.Complete8 + target.Complete9
  1092. if target.QuarterPlan3 != 0 {
  1093. target.QuarterCompleteRatio3 = target.QuarterComplete3 / target.QuarterPlan3 * 100
  1094. }
  1095. break
  1096. case "10":
  1097. target.Complete10 += amountMap[target.SaleId]
  1098. break
  1099. case "11":
  1100. target.Complete11 += amountMap[target.SaleId]
  1101. break
  1102. case "12":
  1103. target.Complete12 += amountMap[target.SaleId]
  1104. break
  1105. }
  1106. target.UpdatedTime = gtime.Now()
  1107. target.UpdatedBy = s.userInfo.Id
  1108. target.UpdatedName = s.userInfo.NickName
  1109. // 年度数据
  1110. target.YearComplete = target.QuarterComplete1 + target.QuarterComplete2 + target.QuarterComplete3 + target.Complete10 + target.Complete11 + target.Complete12
  1111. if target.YearPlan != 0 {
  1112. target.YearCompleteRatio = target.YearComplete / target.YearPlan * 100
  1113. }
  1114. }
  1115. // 保存销售签约指标数据
  1116. if len(targets) > 0 {
  1117. _, err = s.TargetDao.Save(targets)
  1118. if err != nil {
  1119. return err
  1120. }
  1121. }
  1122. }
  1123. // 保存分成数据
  1124. _, err = s.ShareDao.Save(req.Shares)
  1125. if err != nil {
  1126. return err
  1127. }
  1128. }
  1129. return nil
  1130. }
  1131. func (s CtrContractService) DownloadDingtalkFile(ctx context.Context, id int) (string, error) {
  1132. ent, err := s.AppendDao.Where("id= ?", id).One()
  1133. if err != nil {
  1134. return "", err
  1135. }
  1136. if ent == nil {
  1137. return "", myerrors.TipsError("附件不存在")
  1138. }
  1139. if !strings.HasPrefix(ent.FileUrl, "dingtalk") {
  1140. return "", myerrors.TipsError("此附件不是钉钉附件")
  1141. }
  1142. fileInfo := strings.Split(ent.FileUrl, ":")
  1143. if len(fileInfo) != 3 {
  1144. return "", myerrors.TipsError("钉钉附件地址不合法")
  1145. }
  1146. spaceId := fileInfo[1]
  1147. fileId := fileInfo[2]
  1148. // res, err := dingtalk.Client.GetStorage().AddPermission(dingtalk.Client.Context.CorpId, spaceId, s.userInfo.DingtalkId, "EDITOR", "USER")
  1149. // fmt.Println(res, err)
  1150. // if err != nil {
  1151. // return "", fmt.Errorf("设置权限异常 %s", err.Error())
  1152. // }
  1153. resp, err := dingtalk.Client.GetStorage().QueryFileDownloadInfo(spaceId, fileId, s.userInfo.DingtalkId)
  1154. if err != nil {
  1155. return "", myerrors.TipsError("获取文件下载信息异常")
  1156. }
  1157. fmt.Println(resp, err)
  1158. req, err := http.NewRequest("GET", resp.HeaderSignatureInfo.ResourceUrls[0], nil)
  1159. if err != nil {
  1160. return "", fmt.Errorf("构建文件下载请求异常 %s", err.Error())
  1161. }
  1162. for k, v := range resp.HeaderSignatureInfo.Headers {
  1163. req.Header.Add(k, v)
  1164. }
  1165. fileresp, err := http.DefaultClient.Do(req)
  1166. if err != nil {
  1167. return "", fmt.Errorf("文件下载异常 %s", err.Error())
  1168. }
  1169. data, err := io.ReadAll(fileresp.Body)
  1170. if err != nil {
  1171. return "", fmt.Errorf("读取下载内容异常 %s", err.Error())
  1172. }
  1173. return base64.StdEncoding.EncodeToString(data), nil
  1174. }
  1175. func ContractApplyApproval(ctx context.Context, flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
  1176. mtx.Lock()
  1177. defer mtx.Unlock()
  1178. tenant, err := micro_srv.GetTenant(ctx)
  1179. if err != nil {
  1180. return fmt.Errorf("获取租户码异常:%s", err.Error())
  1181. }
  1182. contractDao := dao.NewCtrContractDao(tenant)
  1183. contractId, err := strconv.Atoi(flow.BizCode)
  1184. if err != nil {
  1185. return fmt.Errorf("创建合同审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  1186. }
  1187. contract, err := contractDao.Where("id = ?", contractId).One()
  1188. if err != nil {
  1189. return err
  1190. }
  1191. if contract == nil {
  1192. return fmt.Errorf("合同不存在:%s Id: %d", flow.BizCode, flow.Id)
  1193. }
  1194. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  1195. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  1196. }
  1197. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  1198. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  1199. }
  1200. var status string
  1201. if msg.ProcessType == "terminate" {
  1202. status = "50"
  1203. } else {
  1204. pass := msg.Result == "agree"
  1205. if !pass {
  1206. status = "40"
  1207. } else {
  1208. status = "30"
  1209. }
  1210. }
  1211. _, err = contractDao.Where("id = ?", contractId).Data(map[string]interface{}{
  1212. "appro_status": status,
  1213. }).Update()
  1214. if err != nil {
  1215. return err
  1216. }
  1217. if status != "30" {
  1218. return nil
  1219. }
  1220. return contractDao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  1221. // 交付状态(0发起 10项目立项 15进行中 20 完成 30审批拒绝40关闭)
  1222. _, err = worksrv.DeliverOrderAdd(tx, contractId, request.UserInfo{}, nil, "10")
  1223. if err != nil {
  1224. return err
  1225. }
  1226. if contract.ContractId != 0 {
  1227. oldContract, err := contractDao.TX(tx).Where("id = ?", contract.ContractId).One()
  1228. if err != nil {
  1229. return err
  1230. }
  1231. softSub := contract.SoftwareMaintenanceEndTime.Sub(oldContract.SoftwareMaintenanceBeginTime).Hours() / 24 / 365
  1232. SoftwareMaintenanceLimit := int(softSub)
  1233. hardSub := contract.HardwareMaintenanceEndTime.Sub(oldContract.HardwareMaintenanceBeginTime).Hours() / 24 / 365
  1234. HardwareMaintenanceLimit := int(hardSub)
  1235. opnContent := map[string]interface{}{
  1236. "contractId": contract.ContractId,
  1237. "contractName": contract.ContractName,
  1238. "contractCode": contract.ContractCode,
  1239. "oldSoftwareMaintenanceBeginTime": oldContract.SoftwareMaintenanceBeginTime,
  1240. "oldSoftwareMaintenanceEndTime": oldContract.SoftwareMaintenanceEndTime,
  1241. "oldHardwareMaintenanceBeginTime": oldContract.HardwareMaintenanceBeginTime,
  1242. "oldHardwareMaintenanceEndTime": oldContract.HardwareMaintenanceEndTime,
  1243. "newSoftwareMaintenanceBeginTime": contract.SoftwareMaintenanceBeginTime,
  1244. "newSoftwareMaintenanceEndTime": contract.SoftwareMaintenanceEndTime,
  1245. "newHardwareMaintenanceBeginTime": contract.HardwareMaintenanceBeginTime,
  1246. "newHardwareMaintenanceEndTime": contract.HardwareMaintenanceEndTime,
  1247. }
  1248. dynamics := model.CtrContractDynamics{
  1249. ContractId: contract.ContractId,
  1250. OpnPeople: "系统自动创建",
  1251. OpnDate: gtime.Now(),
  1252. OpnType: "续签合同审批通过",
  1253. OpnContent: gconv.String(opnContent),
  1254. }
  1255. _, err = contractDao.DB.Model("ctr_contract_dynamics").TX(tx).Data(dynamics).InsertAndGetId()
  1256. if err != nil {
  1257. return err
  1258. }
  1259. _, err = contractDao.TX(tx).Where("id = ?", contract.ContractId).Data(map[string]interface{}{
  1260. "software_maintenance_end_time": contract.SoftwareMaintenanceEndTime,
  1261. "hardware_maintenance_end_time": contract.HardwareMaintenanceEndTime,
  1262. "software_maintenance_limit": SoftwareMaintenanceLimit,
  1263. "hardware_maintenance_limit": HardwareMaintenanceLimit,
  1264. }).Update()
  1265. if err != nil {
  1266. return err
  1267. }
  1268. }
  1269. return nil
  1270. })
  1271. }
  1272. func (s CtrContractService) Update(ctx context.Context, req *model.CtrContractUpdateReq) error {
  1273. validErr := gvalid.CheckStruct(ctx, req, nil)
  1274. if validErr != nil {
  1275. return myerrors.TipsError(validErr.Current().Error())
  1276. }
  1277. ent, err := s.Dao.Where("id = ?", req.Id).One()
  1278. if err != nil {
  1279. return err
  1280. }
  1281. if ent == nil {
  1282. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  1283. }
  1284. // if req.ContractCode != "" {
  1285. // exist, err := s.Dao.Where("contract_code = ?", req.ContractCode).One()
  1286. // if err != nil {
  1287. // return err
  1288. // }
  1289. // if exist != nil && exist.Id != req.Id {
  1290. // return myerrors.NewMsgError(nil, fmt.Sprintf("合同编号:%s 已存在", req.ContractCode))
  1291. // }
  1292. // }
  1293. //if req.ContractName != "" {
  1294. // exist, err := s.Dao.Where("contract_name = ?", req.ContractName).One()
  1295. // if err != nil {
  1296. // return err
  1297. // }
  1298. // if exist != nil && exist.Id != req.Id {
  1299. // return myerrors.TipsError(fmt.Sprintf("合同名称:%s 已存在", req.ContractName))
  1300. // }
  1301. //}
  1302. var nbo *proj.ProjBusiness
  1303. if req.NboId != 0 {
  1304. nbo, err = s.ProjBusinessDao.Where("id = ?", req.NboId).One()
  1305. if err != nil {
  1306. return err
  1307. }
  1308. if nbo == nil {
  1309. return myerrors.TipsError("项目不存在")
  1310. }
  1311. }
  1312. toupdate := map[string]interface{}{}
  1313. // if req.ContractCode != "" {
  1314. // toupdate["contract_code"] = req.ContractCode
  1315. // }
  1316. if req.ContractName != "" {
  1317. toupdate["contract_name"] = req.ContractName
  1318. }
  1319. if req.NboId != 0 {
  1320. toupdate["cust_id"] = nbo.CustId
  1321. toupdate["cust_name"] = nbo.CustName
  1322. toupdate["nbo_id"] = nbo.Id
  1323. toupdate["nbo_name"] = nbo.NboName
  1324. toupdate["is_big"] = nbo.IsBig
  1325. toupdate["product_line"] = nbo.ProductLine
  1326. toupdate["cust_province_id"] = nbo.CustProvinceId
  1327. toupdate["cust_province"] = nbo.CustProvince
  1328. toupdate["cust_city_id"] = nbo.CustCityId
  1329. toupdate["cust_city"] = nbo.CustCity
  1330. }
  1331. // if req.ApproStatus != "" {
  1332. // toupdate["appro_status"] = req.ApproStatus
  1333. // }
  1334. if req.ContractType != "" {
  1335. toupdate["contract_type"] = req.ContractType
  1336. }
  1337. // if req.ContractAmount != 0 {
  1338. // toupdate["contract_amount"] = req.ContractAmount
  1339. // }
  1340. // if req.InvoiceAmount != 0 {
  1341. // toupdate["invoice_amount"] = req.InvoiceAmount
  1342. // }
  1343. // if req.CollectedAmount != 0 {
  1344. // toupdate["collected_amount"] = req.CollectedAmount
  1345. // }
  1346. if req.ContractStartTime != nil {
  1347. toupdate["contract_start_time"] = req.ContractStartTime
  1348. }
  1349. if req.ContractEndTime != nil {
  1350. toupdate["contract_end_time"] = req.ContractEndTime
  1351. }
  1352. if req.ContractSignTime != nil {
  1353. toupdate["contract_sign_time"] = req.ContractSignTime
  1354. }
  1355. //if req.InchargeId != 0 {
  1356. // toupdate["incharge_id"] = req.InchargeId
  1357. //}
  1358. //if req.InchargeName != "" {
  1359. // toupdate["incharge_name"] = req.InchargeName
  1360. //}
  1361. if req.SignatoryId != 0 {
  1362. toupdate["signatory_id"] = req.SignatoryId
  1363. }
  1364. if req.SignatoryName != "" {
  1365. toupdate["signatory_name"] = req.SignatoryName
  1366. }
  1367. if req.SignatoryType != "" {
  1368. toupdate["signatory_type"] = req.SignatoryType
  1369. }
  1370. if req.SignatoryUnit != "" {
  1371. toupdate["signatory_unit"] = req.SignatoryUnit
  1372. }
  1373. if req.EarnestMoney != nil {
  1374. toupdate["earnest_money"] = req.EarnestMoney
  1375. }
  1376. if req.CustSignatoryId != 0 {
  1377. toupdate["cust_signatory_id"] = req.CustSignatoryId
  1378. }
  1379. if req.CustSignatoryName != "" {
  1380. toupdate["cust_signatory_name"] = req.CustSignatoryName
  1381. }
  1382. if req.DistributorId != 0 {
  1383. toupdate["distributor_id"] = req.DistributorId
  1384. }
  1385. if req.DistributorName != "" {
  1386. toupdate["distributor_name"] = req.DistributorName
  1387. }
  1388. if req.Remark != nil {
  1389. toupdate["remark"] = *req.Remark
  1390. }
  1391. if req.Product != nil {
  1392. var contractAmount float64
  1393. for _, p := range *req.Product {
  1394. contractAmount += (p.TranPrice * float64(p.ProdNum))
  1395. }
  1396. toupdate["contract_amount"] = contractAmount
  1397. }
  1398. if len(toupdate) != 0 {
  1399. toupdate["updated_by"] = int(s.userInfo.Id)
  1400. toupdate["updated_name"] = s.userInfo.NickName
  1401. toupdate["updated_time"] = gtime.Now()
  1402. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  1403. _, err = tx.Update("ctr_contract", toupdate, "id = ?", req.Id)
  1404. if err != nil {
  1405. return err
  1406. }
  1407. if req.Product != nil {
  1408. err = s.BindProduct(tx, req.Id, ent.ContractCode, *req.Product)
  1409. if err != nil {
  1410. return err
  1411. }
  1412. }
  1413. return nil
  1414. })
  1415. if txerr != nil {
  1416. return txerr
  1417. }
  1418. }
  1419. return nil
  1420. }
  1421. func (s CtrContractService) UpdateProduct(ctx context.Context, req *model.CtrContractUpdateProductReq) error {
  1422. validErr := gvalid.CheckStruct(ctx, req, nil)
  1423. if validErr != nil {
  1424. return myerrors.TipsError(validErr.Current().Error())
  1425. }
  1426. ent, err := s.CtrProductDao.Where("id = ?", req.Id).One()
  1427. if err != nil {
  1428. return err
  1429. }
  1430. if ent == nil {
  1431. return myerrors.TipsError(fmt.Sprintf("合同产品记录不存在: %d", req.Id))
  1432. }
  1433. toupdate := map[string]interface{}{}
  1434. if req.MaintainPeriod != nil {
  1435. toupdate["maintain_period"] = req.MaintainPeriod
  1436. }
  1437. if req.WarrantPeriod != nil {
  1438. toupdate["warrant_period"] = req.WarrantPeriod
  1439. }
  1440. if req.MaintainStartTime != nil {
  1441. toupdate["maintain_start_time"] = req.MaintainStartTime
  1442. }
  1443. if req.MaintainRemark != nil {
  1444. toupdate["maintain_remark"] = req.MaintainRemark
  1445. }
  1446. if req.AcceptTime != nil {
  1447. toupdate["accept_time"] = req.AcceptTime
  1448. }
  1449. if req.PurchaseCost != nil {
  1450. toupdate["purchase_cost"] = req.PurchaseCost
  1451. }
  1452. if req.DevCost != nil {
  1453. toupdate["dev_cost"] = req.DevCost
  1454. }
  1455. if req.MaintainCost != nil {
  1456. toupdate["maintain_cost"] = req.MaintainCost
  1457. }
  1458. if req.DirectCost != nil {
  1459. toupdate["direct_cost"] = req.DirectCost
  1460. }
  1461. if len(toupdate) != 0 {
  1462. toupdate["updated_by"] = int(s.userInfo.Id)
  1463. toupdate["updated_name"] = s.userInfo.NickName
  1464. toupdate["updated_time"] = gtime.Now()
  1465. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  1466. _, err = tx.Update("ctr_contract_product", toupdate, "id = ?", req.Id)
  1467. if err != nil {
  1468. return err
  1469. }
  1470. err = s.AddDynamicsByCurrentUser(tx, ent.ContractId, "更新合同产品信息", toupdate)
  1471. if err != nil {
  1472. return err
  1473. }
  1474. return nil
  1475. })
  1476. if txerr != nil {
  1477. return txerr
  1478. }
  1479. }
  1480. return nil
  1481. }
  1482. func (s CtrContractService) Transfer(ctx context.Context, req *model.CtrContractTransferReq) error {
  1483. if len(req.Id) == 0 {
  1484. return nil
  1485. }
  1486. ents := map[int]*model.CtrContract{}
  1487. for _, i := range req.Id {
  1488. ent, err := s.Dao.Where("id = ?", i).One()
  1489. if err != nil {
  1490. return err
  1491. }
  1492. if ent == nil {
  1493. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  1494. }
  1495. ents[ent.Id] = ent
  1496. }
  1497. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  1498. toupdate := map[string]interface{}{
  1499. "incharge_id": req.InchargeId,
  1500. "incharge_name": req.InchargeName,
  1501. }
  1502. _, err := tx.Update("ctr_contract", toupdate, "id in (?)", req.Id)
  1503. if err != nil {
  1504. return err
  1505. }
  1506. for _, ent := range ents {
  1507. err = s.AddDynamicsByCurrentUser(tx, ent.Id, "转移合同", map[string]interface{}{
  1508. "toInchargeId": req.InchargeId,
  1509. "toInchargeName": req.InchargeName,
  1510. "fromInchargeId": ent.InchargeId,
  1511. "fromInchargeName": ent.InchargeName,
  1512. "operatedId": s.userInfo.Id,
  1513. "operatedName": s.userInfo.NickName,
  1514. })
  1515. if err != nil {
  1516. return err
  1517. }
  1518. }
  1519. return nil
  1520. })
  1521. if txerr != nil {
  1522. return txerr
  1523. }
  1524. return nil
  1525. }
  1526. func (s CtrContractService) UpdateInvoiceAmount(tx *gdb.TX, id int) error {
  1527. ctr := model.CtrContract{}
  1528. err := tx.GetStruct(&ctr, "select * from ctr_contract where id = ?", id)
  1529. if err == sql.ErrNoRows {
  1530. return myerrors.TipsError(fmt.Sprintf("合同不存在 %d", id))
  1531. }
  1532. if err != nil {
  1533. return err
  1534. }
  1535. 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)
  1536. if err != nil {
  1537. return err
  1538. }
  1539. amount := v.Float64()
  1540. _, err = tx.Update("ctr_contract",
  1541. map[string]interface{}{
  1542. "invoice_amount": amount,
  1543. }, "id = ?", id)
  1544. if err != nil {
  1545. return err
  1546. }
  1547. return nil
  1548. }
  1549. func (s CtrContractService) UpdateCollectedAmount(tx *gdb.TX, id int) error {
  1550. ctr := model.CtrContract{}
  1551. err := tx.GetStruct(&ctr, "select * from ctr_contract where id = ?", id)
  1552. if err == sql.ErrNoRows {
  1553. return myerrors.TipsError(fmt.Sprintf("合同不存在 %d", id))
  1554. }
  1555. if err != nil {
  1556. return err
  1557. }
  1558. 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)
  1559. if err != nil {
  1560. return err
  1561. }
  1562. amount := v.Float64()
  1563. _, err = tx.Update("ctr_contract",
  1564. map[string]interface{}{
  1565. "collected_amount": amount,
  1566. }, "id = ?", id)
  1567. if err != nil {
  1568. return err
  1569. }
  1570. return nil
  1571. }
  1572. func (s CtrContractService) Delete(ctx context.Context, id []int) error {
  1573. if len(id) == 0 {
  1574. return nil
  1575. }
  1576. _, err := s.Dao.Where("Id IN (?)", id).Delete()
  1577. return err
  1578. }
  1579. // GetShares 获取销售分成数据
  1580. func (s CtrContractService) GetShares(ctx context.Context, req *model.GetContractShareReq) ([]*model.CtrContractShare, error) {
  1581. validErr := gvalid.CheckStruct(ctx, req, nil)
  1582. if validErr != nil {
  1583. return nil, myerrors.TipsError(validErr.Current().Error())
  1584. }
  1585. return s.ShareDao.Where("contract_id=?", req.ContractId).FindAll()
  1586. }
  1587. func init() {
  1588. tenant := g.Config().GetString("micro_srv.tenant")
  1589. if tenant == "" {
  1590. panic("定时任务租户码未设置,请前往配置")
  1591. }
  1592. contractDao := dao.NewCtrContractDao(tenant)
  1593. produceDao := dao.NewCtrContractProductDao(tenant)
  1594. job := func() {
  1595. alert := map[int]*[]model.CtrContractProduct{
  1596. 180: {},
  1597. 90: {},
  1598. 30: {},
  1599. 10: {},
  1600. // 7: {},
  1601. }
  1602. where := `DATE_FORMAT(DATE_ADD(maintain_start_time, INTERVAL ? day), "%Y-%m-%d") = DATE_FORMAT(NOW(), "%Y-%m-%d")`
  1603. for day, p := range alert {
  1604. err := produceDao.Where(where, day).Structs(p)
  1605. if err != nil {
  1606. glog.Error(err)
  1607. }
  1608. glog.Infof("运维期到期 %d 天提醒,产品个数 %d", day, len(*p))
  1609. }
  1610. for day, p := range alert {
  1611. for _, i := range *p {
  1612. ctr, err := contractDao.Where("id = ?", i.ContractId).One()
  1613. if err != nil {
  1614. glog.Error(err)
  1615. }
  1616. text := fmt.Sprintf("合同:%s-%s 中的产品:%s 距离运维到期还有 %d 天",
  1617. ctr.ContractCode, ctr.ContractName, i.ProdName, day)
  1618. msg := g.MapStrStr{
  1619. "msgTitle": "运维期到期提醒",
  1620. "msgContent": text,
  1621. "msgType": "20",
  1622. "recvUserIds": strconv.Itoa(ctr.InchargeId),
  1623. "msgStatus": "10",
  1624. "sendType": "10",
  1625. }
  1626. if err := service.CreateSystemMessage(msg); err != nil {
  1627. glog.Error("消息提醒异常:", err)
  1628. }
  1629. glog.Infof("%s", text)
  1630. }
  1631. }
  1632. }
  1633. // 每天凌晨2点执行
  1634. gcron.AddSingleton("0 0 2 * * *", job)
  1635. // job()
  1636. }
  1637. func (s CtrContractService) CtrContractMaintenanceExport(ctx context.Context, req *model.CtrContractListReq) (path string, err error) {
  1638. req.PageNum = 0
  1639. _, list, err := s.List(ctx, req)
  1640. if err != nil {
  1641. return path, err
  1642. }
  1643. exportsData := make([]*model.CtrContractMaintenanceExport, 0)
  1644. if err = gconv.Struct(&list, &exportsData); err != nil {
  1645. return
  1646. }
  1647. path, err = service.CommonExportExcel(ctx, "项目运维信息", model.CtrContractMaintenanceExport{}, gconv.Maps(exportsData), func(item map[string]interface{}, header string) interface{} {
  1648. if header == "softwareMaintenanceBeginTime" {
  1649. return gconv.GTime(item[header]).Format("Y-m-d")
  1650. }
  1651. if header == "softwareMaintenanceEndTime" {
  1652. return gconv.GTime(item[header]).Format("Y-m-d")
  1653. }
  1654. if header == "hardwareMaintenanceBeginTime" {
  1655. return gconv.GTime(item[header]).Format("Y-m-d")
  1656. }
  1657. if header == "hardwareMaintenanceEndTime" {
  1658. return gconv.GTime(item[header]).Format("Y-m-d")
  1659. }
  1660. return item[header]
  1661. })
  1662. if err != nil {
  1663. return path, err
  1664. }
  1665. return path, nil
  1666. }