ctr_contract.go 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  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. if ent.InchargeId != req.InchargeId {
  1358. toupdate["orig_incharge_id"] = ent.InchargeId
  1359. }
  1360. }
  1361. if req.InchargeName != "" {
  1362. toupdate["incharge_name"] = req.InchargeName
  1363. if ent.InchargeName != req.InchargeName {
  1364. toupdate["orig_incharge_name"] = ent.InchargeName
  1365. }
  1366. }
  1367. if req.SignatoryId != 0 {
  1368. toupdate["signatory_id"] = req.SignatoryId
  1369. }
  1370. if req.SignatoryName != "" {
  1371. toupdate["signatory_name"] = req.SignatoryName
  1372. }
  1373. if req.SignatoryType != "" {
  1374. toupdate["signatory_type"] = req.SignatoryType
  1375. }
  1376. if req.SignatoryUnit != "" {
  1377. toupdate["signatory_unit"] = req.SignatoryUnit
  1378. }
  1379. if req.EarnestMoney != nil {
  1380. toupdate["earnest_money"] = req.EarnestMoney
  1381. }
  1382. if req.CustSignatoryId != 0 {
  1383. toupdate["cust_signatory_id"] = req.CustSignatoryId
  1384. }
  1385. if req.CustSignatoryName != "" {
  1386. toupdate["cust_signatory_name"] = req.CustSignatoryName
  1387. }
  1388. if req.DistributorId != 0 {
  1389. toupdate["distributor_id"] = req.DistributorId
  1390. }
  1391. if req.DistributorName != "" {
  1392. toupdate["distributor_name"] = req.DistributorName
  1393. }
  1394. if req.Remark != nil {
  1395. toupdate["remark"] = *req.Remark
  1396. }
  1397. if req.Product != nil {
  1398. var contractAmount float64
  1399. for _, p := range *req.Product {
  1400. contractAmount += (p.TranPrice * float64(p.ProdNum))
  1401. }
  1402. toupdate["contract_amount"] = contractAmount
  1403. }
  1404. if len(toupdate) != 0 {
  1405. toupdate["updated_by"] = int(s.userInfo.Id)
  1406. toupdate["updated_name"] = s.userInfo.NickName
  1407. toupdate["updated_time"] = gtime.Now()
  1408. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  1409. _, err = tx.Update("ctr_contract", toupdate, "id = ?", req.Id)
  1410. if err != nil {
  1411. return err
  1412. }
  1413. if req.Product != nil {
  1414. err = s.BindProduct(tx, req.Id, ent.ContractCode, *req.Product)
  1415. if err != nil {
  1416. return err
  1417. }
  1418. }
  1419. _ = s.AddDynamicsByCurrentUser(tx, ent.Id, "更新合同信息", toupdate)
  1420. return nil
  1421. })
  1422. if txerr != nil {
  1423. return txerr
  1424. }
  1425. }
  1426. return nil
  1427. }
  1428. func (s CtrContractService) UpdateProduct(ctx context.Context, req *model.CtrContractUpdateProductReq) error {
  1429. validErr := gvalid.CheckStruct(ctx, req, nil)
  1430. if validErr != nil {
  1431. return myerrors.TipsError(validErr.Current().Error())
  1432. }
  1433. ent, err := s.CtrProductDao.Where("id = ?", req.Id).One()
  1434. if err != nil {
  1435. return err
  1436. }
  1437. if ent == nil {
  1438. return myerrors.TipsError(fmt.Sprintf("合同产品记录不存在: %d", req.Id))
  1439. }
  1440. toupdate := map[string]interface{}{}
  1441. if req.MaintainPeriod != nil {
  1442. toupdate["maintain_period"] = req.MaintainPeriod
  1443. }
  1444. if req.WarrantPeriod != nil {
  1445. toupdate["warrant_period"] = req.WarrantPeriod
  1446. }
  1447. if req.MaintainStartTime != nil {
  1448. toupdate["maintain_start_time"] = req.MaintainStartTime
  1449. }
  1450. if req.MaintainRemark != nil {
  1451. toupdate["maintain_remark"] = req.MaintainRemark
  1452. }
  1453. if req.AcceptTime != nil {
  1454. toupdate["accept_time"] = req.AcceptTime
  1455. }
  1456. if req.PurchaseCost != nil {
  1457. toupdate["purchase_cost"] = req.PurchaseCost
  1458. }
  1459. if req.DevCost != nil {
  1460. toupdate["dev_cost"] = req.DevCost
  1461. }
  1462. if req.MaintainCost != nil {
  1463. toupdate["maintain_cost"] = req.MaintainCost
  1464. }
  1465. if req.DirectCost != nil {
  1466. toupdate["direct_cost"] = req.DirectCost
  1467. }
  1468. if len(toupdate) != 0 {
  1469. toupdate["updated_by"] = int(s.userInfo.Id)
  1470. toupdate["updated_name"] = s.userInfo.NickName
  1471. toupdate["updated_time"] = gtime.Now()
  1472. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  1473. _, err = tx.Update("ctr_contract_product", toupdate, "id = ?", req.Id)
  1474. if err != nil {
  1475. return err
  1476. }
  1477. err = s.AddDynamicsByCurrentUser(tx, ent.ContractId, "更新合同产品信息", toupdate)
  1478. if err != nil {
  1479. return err
  1480. }
  1481. return nil
  1482. })
  1483. if txerr != nil {
  1484. return txerr
  1485. }
  1486. }
  1487. return nil
  1488. }
  1489. func (s CtrContractService) Transfer(ctx context.Context, req *model.CtrContractTransferReq) error {
  1490. if len(req.Id) == 0 {
  1491. return nil
  1492. }
  1493. ents := map[int]*model.CtrContract{}
  1494. for _, i := range req.Id {
  1495. ent, err := s.Dao.Where("id = ?", i).One()
  1496. if err != nil {
  1497. return err
  1498. }
  1499. if ent == nil {
  1500. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  1501. }
  1502. ents[ent.Id] = ent
  1503. }
  1504. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  1505. toupdate := map[string]interface{}{
  1506. "incharge_id": req.InchargeId,
  1507. "incharge_name": req.InchargeName,
  1508. }
  1509. _, err := tx.Update("ctr_contract", toupdate, "id in (?)", req.Id)
  1510. if err != nil {
  1511. return err
  1512. }
  1513. for _, ent := range ents {
  1514. err = s.AddDynamicsByCurrentUser(tx, ent.Id, "转移合同", map[string]interface{}{
  1515. "toInchargeId": req.InchargeId,
  1516. "toInchargeName": req.InchargeName,
  1517. "fromInchargeId": ent.InchargeId,
  1518. "fromInchargeName": ent.InchargeName,
  1519. "operatedId": s.userInfo.Id,
  1520. "operatedName": s.userInfo.NickName,
  1521. })
  1522. if err != nil {
  1523. return err
  1524. }
  1525. }
  1526. return nil
  1527. })
  1528. if txerr != nil {
  1529. return txerr
  1530. }
  1531. return nil
  1532. }
  1533. func (s CtrContractService) UpdateInvoiceAmount(tx *gdb.TX, id int) error {
  1534. ctr := model.CtrContract{}
  1535. err := tx.GetStruct(&ctr, "select * from ctr_contract where id = ?", id)
  1536. if err == sql.ErrNoRows {
  1537. return myerrors.TipsError(fmt.Sprintf("合同不存在 %d", id))
  1538. }
  1539. if err != nil {
  1540. return err
  1541. }
  1542. 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)
  1543. if err != nil {
  1544. return err
  1545. }
  1546. amount := v.Float64()
  1547. _, err = tx.Update("ctr_contract",
  1548. map[string]interface{}{
  1549. "invoice_amount": amount,
  1550. }, "id = ?", id)
  1551. if err != nil {
  1552. return err
  1553. }
  1554. return nil
  1555. }
  1556. func (s CtrContractService) UpdateCollectedAmount(tx *gdb.TX, id int) error {
  1557. ctr := model.CtrContract{}
  1558. err := tx.GetStruct(&ctr, "select * from ctr_contract where id = ?", id)
  1559. if err == sql.ErrNoRows {
  1560. return myerrors.TipsError(fmt.Sprintf("合同不存在 %d", id))
  1561. }
  1562. if err != nil {
  1563. return err
  1564. }
  1565. 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)
  1566. if err != nil {
  1567. return err
  1568. }
  1569. amount := v.Float64()
  1570. _, err = tx.Update("ctr_contract",
  1571. map[string]interface{}{
  1572. "collected_amount": amount,
  1573. }, "id = ?", id)
  1574. if err != nil {
  1575. return err
  1576. }
  1577. return nil
  1578. }
  1579. func (s CtrContractService) Delete(ctx context.Context, id []int) error {
  1580. if len(id) == 0 {
  1581. return nil
  1582. }
  1583. _, err := s.Dao.Where("Id IN (?)", id).Delete()
  1584. return err
  1585. }
  1586. // GetShares 获取销售分成数据
  1587. func (s CtrContractService) GetShares(ctx context.Context, req *model.GetContractShareReq) ([]*model.CtrContractShare, error) {
  1588. validErr := gvalid.CheckStruct(ctx, req, nil)
  1589. if validErr != nil {
  1590. return nil, myerrors.TipsError(validErr.Current().Error())
  1591. }
  1592. return s.ShareDao.Where("contract_id=?", req.ContractId).FindAll()
  1593. }
  1594. func init() {
  1595. tenant := g.Config().GetString("micro_srv.tenant")
  1596. if tenant == "" {
  1597. panic("定时任务租户码未设置,请前往配置")
  1598. }
  1599. contractDao := dao.NewCtrContractDao(tenant)
  1600. produceDao := dao.NewCtrContractProductDao(tenant)
  1601. job := func() {
  1602. alert := map[int]*[]model.CtrContractProduct{
  1603. 180: {},
  1604. 90: {},
  1605. 30: {},
  1606. 10: {},
  1607. // 7: {},
  1608. }
  1609. where := `DATE_FORMAT(DATE_ADD(maintain_start_time, INTERVAL ? day), "%Y-%m-%d") = DATE_FORMAT(NOW(), "%Y-%m-%d")`
  1610. for day, p := range alert {
  1611. err := produceDao.Where(where, day).Structs(p)
  1612. if err != nil {
  1613. glog.Error(err)
  1614. }
  1615. glog.Infof("运维期到期 %d 天提醒,产品个数 %d", day, len(*p))
  1616. }
  1617. for day, p := range alert {
  1618. for _, i := range *p {
  1619. ctr, err := contractDao.Where("id = ?", i.ContractId).One()
  1620. if err != nil {
  1621. glog.Error(err)
  1622. }
  1623. text := fmt.Sprintf("合同:%s-%s 中的产品:%s 距离运维到期还有 %d 天",
  1624. ctr.ContractCode, ctr.ContractName, i.ProdName, day)
  1625. msg := g.MapStrStr{
  1626. "msgTitle": "运维期到期提醒",
  1627. "msgContent": text,
  1628. "msgType": "20",
  1629. "recvUserIds": strconv.Itoa(ctr.InchargeId),
  1630. "msgStatus": "10",
  1631. "sendType": "10",
  1632. }
  1633. if err := service.CreateSystemMessage(msg); err != nil {
  1634. glog.Error("消息提醒异常:", err)
  1635. }
  1636. glog.Infof("%s", text)
  1637. }
  1638. }
  1639. }
  1640. // 每天凌晨2点执行
  1641. gcron.AddSingleton("0 0 2 * * *", job)
  1642. // job()
  1643. }
  1644. func (s CtrContractService) CtrContractMaintenanceExport(ctx context.Context, req *model.CtrContractListReq) (path string, err error) {
  1645. req.PageNum = 0
  1646. _, list, err := s.List(ctx, req)
  1647. if err != nil {
  1648. return path, err
  1649. }
  1650. exportsData := make([]*model.CtrContractMaintenanceExport, 0)
  1651. if err = gconv.Struct(&list, &exportsData); err != nil {
  1652. return
  1653. }
  1654. path, err = service.CommonExportExcel(ctx, "项目运维信息", model.CtrContractMaintenanceExport{}, gconv.Maps(exportsData), func(item map[string]interface{}, header string) interface{} {
  1655. if header == "softwareMaintenanceBeginTime" {
  1656. return gconv.GTime(item[header]).Format("Y-m-d")
  1657. }
  1658. if header == "softwareMaintenanceEndTime" {
  1659. return gconv.GTime(item[header]).Format("Y-m-d")
  1660. }
  1661. if header == "hardwareMaintenanceBeginTime" {
  1662. return gconv.GTime(item[header]).Format("Y-m-d")
  1663. }
  1664. if header == "hardwareMaintenanceEndTime" {
  1665. return gconv.GTime(item[header]).Format("Y-m-d")
  1666. }
  1667. return item[header]
  1668. })
  1669. if err != nil {
  1670. return path, err
  1671. }
  1672. return path, nil
  1673. }