ctr_contract.go 59 KB

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