ctr_contract.go 57 KB

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