register.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. package contract
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "github.com/go-playground/validator/v10"
  8. "github.com/tealeg/xlsx"
  9. "hongze/fms_api/controller/resp"
  10. "hongze/fms_api/global"
  11. "hongze/fms_api/models/base"
  12. "hongze/fms_api/models/crm"
  13. "hongze/fms_api/models/fms"
  14. "hongze/fms_api/models/system"
  15. fmsService "hongze/fms_api/services/fms"
  16. "hongze/fms_api/utils"
  17. "net/http"
  18. "time"
  19. )
  20. // RegisterController 合同登记
  21. type RegisterController struct{}
  22. // List
  23. // @Title 合同登记列表
  24. // @Description 合同登记列表
  25. // @Param Keyword query string false "关键词"
  26. // @Param StartDate query string false "合同开始日期"
  27. // @Param EndDate query string false "合同结束日期"
  28. // @Param ServiceType query int false "套餐类型"
  29. // @Param ContractType query int false "合同类型"
  30. // @Param RegisterStatus query int false "登记状态"
  31. // @Success 200 {object} fms.ContractRegisterItem
  32. // @router /contract/register/list [get]
  33. func (rg *RegisterController) List(c *gin.Context) {
  34. var req fms.ContractRegisterListReq
  35. if e := c.BindQuery(&req); e != nil {
  36. err, ok := e.(validator.ValidationErrors)
  37. if !ok {
  38. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  39. return
  40. }
  41. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  42. return
  43. }
  44. // TODO:代付方
  45. cond := `1 = 1`
  46. pars := make([]interface{}, 0)
  47. if req.Keyword != "" {
  48. kw := "%" + req.Keyword + "%"
  49. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ?)`
  50. pars = append(pars, kw, kw, kw)
  51. }
  52. if req.StartDate != "" && req.EndDate != "" {
  53. st := fmt.Sprint(req.StartDate, " 00:00:00")
  54. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  55. cond += ` AND (create_time BETWEEN ? AND ?)`
  56. pars = append(pars, st, ed)
  57. }
  58. if req.ContractType != 0 {
  59. cond += ` AND contract_type = ?`
  60. pars = append(pars, req.ContractType)
  61. }
  62. if req.RegisterStatus != 0 {
  63. cond += ` AND register_status = ?`
  64. pars = append(pars, req.RegisterStatus)
  65. }
  66. // 套餐筛选
  67. if req.ServiceType != 0 {
  68. registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
  69. if e != nil {
  70. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  71. return
  72. }
  73. if len(registerIds) > 0 {
  74. cond += ` AND contract_register_id IN ?`
  75. pars = append(pars, registerIds)
  76. } else {
  77. cond += ` AND 1 = 2`
  78. }
  79. }
  80. page := new(base.Page)
  81. page.SetPageSize(req.PageSize)
  82. page.SetCurrent(req.Current)
  83. page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: false})
  84. total, list, e := fms.GetContractRegisterItemPageList(page, cond, pars)
  85. if e != nil {
  86. resp.FailMsg("获取失败", "获取合同登记列表失败, Err: "+e.Error(), c)
  87. return
  88. }
  89. registerIds := make([]int, 0)
  90. for i := range list {
  91. registerIds = append(registerIds, list[i].ContractRegisterId)
  92. }
  93. serviceMap := make(map[int]string, 0)
  94. invoiceMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  95. paymentMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  96. if len(registerIds) > 0 {
  97. // 获取服务套餐
  98. servicesNameList, e := fms.GetContractRegisterServicesNameByRegisterIds(registerIds)
  99. if e != nil {
  100. resp.FailMsg("获取失败", "获取套餐拼接字符串失败, Err: "+e.Error(), c)
  101. return
  102. }
  103. for i := range servicesNameList {
  104. serviceMap[servicesNameList[i].ContractRegisterId] = servicesNameList[i].ServicesName
  105. }
  106. // 获取开票/到款列表
  107. invoiceCond := `contract_register_id IN ?`
  108. invoicePars := make([]interface{}, 0)
  109. invoicePars = append(invoicePars, registerIds)
  110. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  111. if e != nil {
  112. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  113. return
  114. }
  115. for i := range invoiceList {
  116. if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  117. invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  118. }
  119. if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  120. paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  121. }
  122. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  123. invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  124. }
  125. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  126. paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  127. }
  128. }
  129. }
  130. respList := make([]*fms.ContractRegisterList, 0)
  131. for i := range list {
  132. v := new(fms.ContractRegisterList)
  133. v.ContractRegisterItem = list[i]
  134. v.ServicesName = serviceMap[list[i].ContractRegisterId]
  135. v.InvoiceList = invoiceMap[list[i].ContractRegisterId]
  136. v.PaymentList = paymentMap[list[i].ContractRegisterId]
  137. respList = append(respList, v)
  138. }
  139. page.SetTotal(total)
  140. baseData := new(base.BaseData)
  141. baseData.SetPage(page)
  142. baseData.SetList(respList)
  143. resp.OkData("获取成功", baseData, c)
  144. }
  145. // Add
  146. // @Title 新增合同登记
  147. // @Description 新增合同登记
  148. // @Param request body fms.ContractRegisterAddReq true "type json string"
  149. // @Success 200 string "操作成功"
  150. // @router /contract/register/add [post]
  151. func (rg *RegisterController) Add(c *gin.Context) {
  152. req := new(fms.ContractRegisterAddReq)
  153. err := c.ShouldBind(&req)
  154. if err != nil {
  155. errs, ok := err.(validator.ValidationErrors)
  156. if !ok {
  157. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  158. return
  159. }
  160. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  161. return
  162. }
  163. claims, _ := c.Get("adminInfo")
  164. adminInfo := claims.(*system.SysAdmin)
  165. // 日期校验
  166. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  167. if e != nil {
  168. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  169. return
  170. }
  171. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  172. if e != nil {
  173. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  174. return
  175. }
  176. signDate, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  177. if e != nil {
  178. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  179. return
  180. }
  181. // 是否存在相同合同编号的登记
  182. ob := new(fms.ContractRegister)
  183. existCond := `contract_code = ?`
  184. existPars := make([]interface{}, 0)
  185. existPars = append(existPars, req.ContractCode)
  186. exist, e := ob.FetchByCondition(existCond, existPars)
  187. if e != nil && e != utils.ErrNoRow {
  188. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  189. return
  190. }
  191. if exist != nil && exist.ContractRegisterId > 0 {
  192. resp.Fail("合同编号已存在", c)
  193. return
  194. }
  195. // TODO:代付、补充协议
  196. nowTime := time.Now().Local()
  197. ob.ContractCode = req.ContractCode
  198. ob.CrmContractId = req.CrmContractId
  199. ob.ContractSource = req.ContractSource
  200. ob.CompanyName = req.CompanyName
  201. ob.ProductId = req.ProductId
  202. ob.SellerId = req.SellerId
  203. ob.SellerName = req.SellerName
  204. ob.ContractType = req.ContractType
  205. ob.ContractAmount = req.ContractAmount
  206. ob.StartDate = startDate
  207. ob.EndDate = endDate
  208. ob.SignDate = signDate
  209. ob.AgreedPayTime = req.AgreedPayTime
  210. ob.ContractStatus = req.ContractStatus
  211. ob.RegisterStatus = fms.ContractRegisterStatusIng
  212. ob.Remark = req.Remark
  213. ob.Set()
  214. // 套餐信息
  215. serviceList, e := fmsService.HandleContractServiceAndDetail(req.ProductId, req.Services, true)
  216. if e != nil {
  217. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  218. return
  219. }
  220. // 新增合同及套餐
  221. if e = fms.CreateContractRegisterAndServices(ob, serviceList); e != nil {
  222. resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
  223. return
  224. }
  225. // 操作日志
  226. go func() {
  227. opData := ""
  228. opDataByte, e := json.Marshal(req)
  229. if e != nil {
  230. return
  231. }
  232. opData = string(opDataByte)
  233. logItem := new(fms.ContractRegisterLog)
  234. logItem.ContractRegisterId = ob.ContractRegisterId
  235. logItem.AdminId = int(adminInfo.AdminId)
  236. logItem.AdminName = adminInfo.RealName
  237. logItem.OpData = opData
  238. logItem.OpType = fms.ContractRegisterOpTypeSave
  239. logItem.CreateTime = nowTime
  240. if e = logItem.Create(); e != nil {
  241. return
  242. }
  243. }()
  244. resp.Ok("操作成功", c)
  245. }
  246. // Edit
  247. // @Title 编辑合同登记
  248. // @Description 编辑合同登记
  249. // @Param request body fms.ContractRegisterEditReq true "type json string"
  250. // @Success 200 string "操作成功"
  251. // @router /contract/register/edit [post]
  252. func (rg *RegisterController) Edit(c *gin.Context) {
  253. req := new(fms.ContractRegisterEditReq)
  254. err := c.ShouldBind(&req)
  255. if err != nil {
  256. errs, ok := err.(validator.ValidationErrors)
  257. if !ok {
  258. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  259. return
  260. }
  261. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  262. return
  263. }
  264. claims, _ := c.Get("adminInfo")
  265. adminInfo := claims.(*system.SysAdmin)
  266. // 日期校验
  267. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  268. if e != nil {
  269. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  270. return
  271. }
  272. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  273. if e != nil {
  274. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  275. return
  276. }
  277. signDate, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  278. if e != nil {
  279. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  280. return
  281. }
  282. ob := new(fms.ContractRegister)
  283. item, e := ob.Fetch(req.ContractRegisterId)
  284. if e != nil {
  285. if e == utils.ErrNoRow {
  286. resp.Fail("登记记录不存在或已被删除", c)
  287. return
  288. }
  289. resp.FailMsg("操作失败", "获取合同登记信息失败, Err:"+e.Error(), c)
  290. return
  291. }
  292. // 是否存在相同合同编号的登记
  293. existCond := `contract_code = ?`
  294. existPars := make([]interface{}, 0)
  295. existPars = append(existPars, req.ContractCode)
  296. exist, e := ob.FetchByCondition(existCond, existPars)
  297. if e != nil && e != utils.ErrNoRow {
  298. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  299. return
  300. }
  301. if exist != nil && exist.ContractRegisterId > 0 && exist.ContractRegisterId != item.ContractRegisterId {
  302. resp.Fail("合同编号已存在", c)
  303. return
  304. }
  305. nowTime := time.Now().Local()
  306. item.ContractCode = req.ContractCode
  307. item.CrmContractId = req.CrmContractId
  308. item.ContractSource = req.ContractSource
  309. item.CompanyName = req.CompanyName
  310. item.SellerId = req.SellerId
  311. item.SellerName = req.SellerName
  312. item.ContractType = req.ContractType
  313. item.ContractAmount = req.ContractAmount
  314. item.StartDate = startDate
  315. item.EndDate = endDate
  316. item.SignDate = signDate
  317. item.AgreedPayTime = req.AgreedPayTime
  318. item.ContractStatus = req.ContractStatus
  319. item.RegisterStatus = fms.ContractRegisterStatusIng
  320. item.Remark = req.Remark
  321. item.ModifyTime = nowTime
  322. updateCols := []string{
  323. "ContractCode", "CrmContractId", "ContractSource", "CompanyName", "SellerId", "SellerName",
  324. "ContractType", "ContractAmount", "StartDate", "EndDate", "SignDate", "AgreedPayTime", "ContractStatus",
  325. "RegisterStatus", "Remark", "ModifyTime",
  326. }
  327. // 套餐信息
  328. serviceList, e := fmsService.HandleContractServiceAndDetail(req.ProductId, req.Services, true)
  329. if e != nil {
  330. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  331. return
  332. }
  333. // 更新合同及套餐
  334. if e = fms.UpdateContractRegisterAndServices(item, updateCols, serviceList); e != nil {
  335. resp.FailMsg("操作失败", "更新合同及套餐失败, Err: "+e.Error(), c)
  336. return
  337. }
  338. // 校验金额-是否修改状态
  339. go fmsService.CheckContractRegisterAmount(item.ContractRegisterId)
  340. // 操作日志
  341. go func() {
  342. opData := ""
  343. opDataByte, e := json.Marshal(req)
  344. if e != nil {
  345. return
  346. }
  347. opData = string(opDataByte)
  348. logItem := new(fms.ContractRegisterLog)
  349. logItem.ContractRegisterId = item.ContractRegisterId
  350. logItem.AdminId = int(adminInfo.AdminId)
  351. logItem.AdminName = adminInfo.RealName
  352. logItem.OpData = opData
  353. logItem.OpType = fms.ContractRegisterOpTypeEdit
  354. logItem.CreateTime = nowTime
  355. if e = logItem.Create(); e != nil {
  356. return
  357. }
  358. }()
  359. resp.Ok("操作成功", c)
  360. }
  361. // Del
  362. // @Title 删除合同登记
  363. // @Description 删除合同登记
  364. // @Param request body fms.ContractRegisterDelReq true "type json string"
  365. // @Success 200 string "操作成功"
  366. // @router /contract/register/del [post]
  367. func (rg *RegisterController) Del(c *gin.Context) {
  368. req := new(fms.ContractRegisterDelReq)
  369. err := c.ShouldBind(&req)
  370. if err != nil {
  371. errs, ok := err.(validator.ValidationErrors)
  372. if !ok {
  373. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  374. return
  375. }
  376. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  377. return
  378. }
  379. claims, _ := c.Get("adminInfo")
  380. adminInfo := claims.(*system.SysAdmin)
  381. ob := new(fms.ContractRegister)
  382. item, e := ob.Fetch(req.ContractRegisterId)
  383. if e != nil {
  384. if e == utils.ErrNoRow {
  385. resp.Fail("合同登记不存在或已被删除", c)
  386. return
  387. }
  388. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  389. return
  390. }
  391. nowTime := time.Now().Local()
  392. item.IsDeleted = 1
  393. item.ModifyTime = nowTime
  394. updateCols := []string{"IsDeleted", "ModifyTime"}
  395. if e = item.Update(updateCols); e != nil {
  396. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  397. return
  398. }
  399. // 操作日志
  400. go func() {
  401. opData := ""
  402. opDataByte, e := json.Marshal(req)
  403. if e != nil {
  404. return
  405. }
  406. opData = string(opDataByte)
  407. logItem := new(fms.ContractRegisterLog)
  408. logItem.ContractRegisterId = req.ContractRegisterId
  409. logItem.AdminId = int(adminInfo.AdminId)
  410. logItem.AdminName = adminInfo.RealName
  411. logItem.OpData = opData
  412. logItem.OpType = fms.ContractRegisterOpTypeDel
  413. logItem.CreateTime = nowTime
  414. if e = logItem.Create(); e != nil {
  415. return
  416. }
  417. }()
  418. resp.Ok("操作成功", c)
  419. }
  420. // Detail
  421. // @Title 合同登记详情
  422. // @Description 合同登记详情
  423. // @Param ContractRegisterId query int false "合同登记ID"
  424. // @Success 200 {object} fms.ContractRegisterDetail
  425. // @router /contract/register/detail [get]
  426. func (rg *RegisterController) Detail(c *gin.Context) {
  427. var req fms.ContractRegisterDetailReq
  428. if e := c.BindQuery(&req); e != nil {
  429. err, ok := e.(validator.ValidationErrors)
  430. if !ok {
  431. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  432. return
  433. }
  434. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  435. return
  436. }
  437. result := new(fms.ContractRegisterDetail)
  438. // 合同登记信息
  439. item, e := fms.GetContractRegisterItemById(req.ContractRegisterId)
  440. if e != nil {
  441. resp.FailData("获取失败", "获取合同登记详情失败, Err:"+e.Error(), c)
  442. return
  443. }
  444. result.ContractRegisterItem = item
  445. // 套餐信息
  446. serviceList, e := fmsService.GetContractServiceAndDetail(req.ContractRegisterId)
  447. if e != nil {
  448. resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
  449. return
  450. }
  451. result.ServiceList = serviceList
  452. // 开票/到款信息
  453. invoiceCond := `contract_register_id = ?`
  454. invoicePars := make([]interface{}, 0)
  455. invoicePars = append(invoicePars, req.ContractRegisterId)
  456. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  457. if e != nil {
  458. resp.FailData("获取失败", "获取合同开票/到款信息失败, Err: "+e.Error(), c)
  459. return
  460. }
  461. result.InvoiceList = make([]*fms.ContractInvoiceItem, 0)
  462. result.PaymentList = make([]*fms.ContractInvoiceItem, 0)
  463. for i := range invoiceList {
  464. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  465. result.InvoiceList = append(result.InvoiceList, invoiceList[i])
  466. continue
  467. }
  468. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  469. result.PaymentList = append(result.PaymentList, invoiceList[i])
  470. }
  471. }
  472. // 合同登记进度
  473. logCond := `contract_register_id = ?`
  474. logPars := make([]interface{}, 0)
  475. logPars = append(logPars, req.ContractRegisterId)
  476. logList, e := fms.GetContractRegisterLogItemList(logCond, logPars)
  477. if e != nil {
  478. resp.FailData("获取失败", "获取合同登记进度失败, Err: "+e.Error(), c)
  479. return
  480. }
  481. result.Logs = logList
  482. resp.OkData("获取成功", result, c)
  483. }
  484. // UpdateStatus
  485. // @Title 修改合同状态
  486. // @Description 修改合同状态
  487. // @Param request body fms.ContractRegisterUpdateStatusReq true "type json string"
  488. // @Success 200 string "操作成功"
  489. // @router /contract/register/update_status [post]
  490. func (rg *RegisterController) UpdateStatus(c *gin.Context) {
  491. req := new(fms.ContractRegisterUpdateStatusReq)
  492. err := c.ShouldBind(&req)
  493. if err != nil {
  494. errs, ok := err.(validator.ValidationErrors)
  495. if !ok {
  496. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  497. return
  498. }
  499. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  500. return
  501. }
  502. claims, _ := c.Get("adminInfo")
  503. adminInfo := claims.(*system.SysAdmin)
  504. ob := new(fms.ContractRegister)
  505. item, e := ob.Fetch(req.ContractRegisterId)
  506. if e != nil {
  507. if e == utils.ErrNoRow {
  508. resp.Fail("合同登记不存在或已被删除", c)
  509. return
  510. }
  511. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  512. return
  513. }
  514. nowTime := time.Now().Local()
  515. item.ContractStatus = req.ContractStatus
  516. item.ModifyTime = nowTime
  517. updateCols := []string{"ContractStatus", "ModifyTime"}
  518. if e = item.Update(updateCols); e != nil {
  519. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  520. return
  521. }
  522. // 校验金额-是否修改状态
  523. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  524. // 操作日志
  525. go func() {
  526. opData := ""
  527. opDataByte, e := json.Marshal(req)
  528. if e != nil {
  529. return
  530. }
  531. opData = string(opDataByte)
  532. logItem := new(fms.ContractRegisterLog)
  533. logItem.ContractRegisterId = req.ContractRegisterId
  534. logItem.AdminId = int(adminInfo.AdminId)
  535. logItem.AdminName = adminInfo.RealName
  536. logItem.OpData = opData
  537. logItem.OpType = fms.ContractRegisterOpTypeStatus
  538. logItem.CreateTime = nowTime
  539. if e = logItem.Create(); e != nil {
  540. return
  541. }
  542. }()
  543. resp.Ok("操作成功", c)
  544. }
  545. // Invoice
  546. // @Title 开票/到款登记
  547. // @Description 开票/到款登记
  548. // @Param request body fms.ContractInvoiceSaveReq true "type json string"
  549. // @Success 200 string "操作成功"
  550. // @router /contract/register/invoice [post]
  551. func (rg *RegisterController) Invoice(c *gin.Context) {
  552. req := new(fms.ContractInvoiceSaveReq)
  553. err := c.ShouldBind(&req)
  554. if err != nil {
  555. errs, ok := err.(validator.ValidationErrors)
  556. if !ok {
  557. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  558. return
  559. }
  560. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  561. return
  562. }
  563. claims, _ := c.Get("adminInfo")
  564. adminInfo := claims.(*system.SysAdmin)
  565. newInvoice := make([]*fms.ContractInvoice, 0)
  566. if len(req.AmountList) > 0 {
  567. for i := range req.AmountList {
  568. if req.AmountList[i].Amount <= 0 {
  569. resp.Fail("登记金额有误", c)
  570. return
  571. }
  572. if req.AmountList[i].InvoiceDate == "" {
  573. resp.Fail("请选择日期", c)
  574. return
  575. }
  576. t, e := time.ParseInLocation(utils.FormatDate, req.AmountList[i].InvoiceDate, time.Local)
  577. if e != nil {
  578. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  579. return
  580. }
  581. v := &fms.ContractInvoice{
  582. ContractRegisterId: req.ContractRegisterId,
  583. Amount: req.AmountList[i].Amount,
  584. InvoiceType: req.InvoiceType,
  585. InvoiceDate: t,
  586. AdminId: int(adminInfo.AdminId),
  587. AdminName: adminInfo.RealName,
  588. }
  589. v.Set()
  590. newInvoice = append(newInvoice, v)
  591. }
  592. }
  593. // 删除并新增登记
  594. ob := new(fms.ContractInvoice)
  595. if e := ob.DeleteAndCreateNewInvoice(req.ContractRegisterId, req.InvoiceType, newInvoice); e != nil {
  596. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  597. return
  598. }
  599. // 校验金额-是否修改状态
  600. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  601. // 操作日志
  602. go func() {
  603. opData := ""
  604. opDataByte, e := json.Marshal(req)
  605. if e != nil {
  606. return
  607. }
  608. opData = string(opDataByte)
  609. opType := fms.ContractRegisterOpTypeInvoice
  610. if req.InvoiceType == fms.ContractInvoiceTypePay {
  611. opType = fms.ContractRegisterOpTypePayment
  612. }
  613. logItem := new(fms.ContractRegisterLog)
  614. logItem.ContractRegisterId = req.ContractRegisterId
  615. logItem.AdminId = int(adminInfo.AdminId)
  616. logItem.AdminName = adminInfo.RealName
  617. logItem.OpData = opData
  618. logItem.OpType = opType
  619. logItem.CreateTime = time.Now().Local()
  620. if e = logItem.Create(); e != nil {
  621. return
  622. }
  623. }()
  624. resp.Ok("操作成功", c)
  625. }
  626. // Export
  627. // @Title 合同登记-导出
  628. // @Description 合同登记-导出
  629. // @Param Keyword query string false "关键词"
  630. // @Param StartDate query string false "合同开始日期"
  631. // @Param EndDate query string false "合同结束日期"
  632. // @Param ServiceType query int false "套餐类型"
  633. // @Param ContractType query int false "合同类型"
  634. // @Param RegisterStatus query int false "登记状态"
  635. // @Success 200 string "操作成功"
  636. // @router /contract/register/export [get]
  637. func (rg *RegisterController) Export(c *gin.Context) {
  638. var req fms.ContractRegisterListReq
  639. if e := c.BindQuery(&req); e != nil {
  640. err, ok := e.(validator.ValidationErrors)
  641. if !ok {
  642. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  643. return
  644. }
  645. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  646. return
  647. }
  648. cond := `1 = 1`
  649. pars := make([]interface{}, 0)
  650. if req.Keyword != "" {
  651. kw := "%" + req.Keyword + "%"
  652. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ?)`
  653. pars = append(pars, kw, kw, kw)
  654. }
  655. if req.StartDate != "" && req.EndDate != "" {
  656. st := fmt.Sprint(req.StartDate, " 00:00:00")
  657. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  658. cond += ` AND (create_time BETWEEN ? AND ?)`
  659. pars = append(pars, st, ed)
  660. }
  661. if req.ContractType != 0 {
  662. cond += ` AND contract_type = ?`
  663. pars = append(pars, req.ContractType)
  664. }
  665. if req.RegisterStatus != 0 {
  666. cond += ` AND register_status = ?`
  667. pars = append(pars, req.RegisterStatus)
  668. }
  669. if req.ServiceType != 0 {
  670. registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
  671. if e != nil {
  672. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  673. return
  674. }
  675. if len(registerIds) > 0 {
  676. cond += ` AND contract_register_id IN ?`
  677. pars = append(pars, registerIds)
  678. } else {
  679. cond += ` AND 1 = 2`
  680. }
  681. }
  682. // 获取列表数据
  683. cr := new(fms.ContractRegister)
  684. list, e := cr.List(cond, pars)
  685. if e != nil {
  686. resp.FailData("获取合同列表失败", "Err:"+e.Error(), c)
  687. return
  688. }
  689. if len(list) == 0 {
  690. resp.Fail("无有效数据可导出", c)
  691. return
  692. }
  693. registerIds := make([]int, 0)
  694. for i := range list {
  695. registerIds = append(registerIds, list[i].ContractRegisterId)
  696. }
  697. // 获取小套餐品种
  698. cpCond := `product_id = ? AND permission_name <> ?`
  699. cpPars := make([]interface{}, 0)
  700. cpPars = append(cpPars, crm.CompanyProductFicc, crm.ChartPermissionStrategyName)
  701. cp := new(crm.ChartPermission)
  702. permissionList, e := cp.List(cpCond, cpPars)
  703. if e != nil {
  704. resp.FailData("获取小套餐品种失败", "Err:"+e.Error(), c)
  705. return
  706. }
  707. permissionLen := len(permissionList)
  708. permissionNameIdMap := make(map[string]int)
  709. for i := range permissionList {
  710. permissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  711. }
  712. // 获取套餐服务
  713. //serviceList, e := fms.GetContractServiceTemplateMapByProductId(crm.CompanyProductFicc)
  714. //if e != nil {
  715. // resp.FailData("获取套餐服务失败", "Err:"+e.Error(), c)
  716. // return
  717. //}
  718. // 套餐/开票/到款列表
  719. serviceMap := make(map[int][]*fms.ContractService)
  720. serviceChartPermissionsMap := make(map[int][]int)
  721. invoiceMap := make(map[int][]*fms.ContractInvoice)
  722. paymentMap := make(map[int][]*fms.ContractInvoice)
  723. maxInvoice := 0
  724. maxPayment := 0
  725. if len(registerIds) > 0 {
  726. // 获取套餐信息
  727. csCond := `contract_register_id IN ?`
  728. csPars := make([]interface{}, 0)
  729. csPars = append(csPars, registerIds)
  730. cs := new(fms.ContractService)
  731. serviceList, e := cs.List(csCond, csPars)
  732. if e != nil {
  733. resp.FailData("获取合同套餐列表失败", "Err:"+e.Error(), c)
  734. return
  735. }
  736. for i := range serviceList {
  737. cid := serviceList[i].ContractRegisterId
  738. if serviceMap[cid] == nil {
  739. serviceMap[cid] = make([]*fms.ContractService, 0)
  740. }
  741. serviceMap[cid] = append(serviceMap[cid], serviceList[i])
  742. // 小套餐权限
  743. if serviceChartPermissionsMap[cid] == nil {
  744. serviceChartPermissionsMap[cid] = make([]int, 0)
  745. }
  746. if serviceList[i].ChartPermissionIds != "" {
  747. ids := utils.JoinStr2IntArr(serviceList[i].ChartPermissionIds, ",")
  748. serviceChartPermissionsMap[cid] = append(serviceChartPermissionsMap[cid], ids...)
  749. }
  750. }
  751. // 获取开票/到款详情, 并取最大的开票/到款数(用于动态扩展第二列表头)
  752. ci := new(fms.ContractInvoice)
  753. invoiceList, e := ci.List(csCond, csPars)
  754. if e != nil {
  755. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  756. return
  757. }
  758. for k := range invoiceList {
  759. cid := invoiceList[k].ContractRegisterId
  760. if invoiceMap[cid] == nil {
  761. invoiceMap[cid] = make([]*fms.ContractInvoice, 0)
  762. }
  763. if paymentMap[cid] == nil {
  764. paymentMap[cid] = make([]*fms.ContractInvoice, 0)
  765. }
  766. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypeMake {
  767. invoiceMap[cid] = append(invoiceMap[cid], invoiceList[k])
  768. continue
  769. }
  770. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypePay {
  771. paymentMap[cid] = append(paymentMap[cid], invoiceList[k])
  772. continue
  773. }
  774. }
  775. // 取最大开票/到款数
  776. for j := range invoiceMap {
  777. if len(invoiceMap[j]) > maxInvoice {
  778. maxInvoice = len(invoiceMap[j])
  779. }
  780. }
  781. for p := range paymentMap {
  782. if len(paymentMap[p]) > maxPayment {
  783. maxPayment = len(paymentMap[p])
  784. }
  785. }
  786. }
  787. // 生成Excel文件
  788. //dir, err := os.Executable()
  789. //exPath := filepath.Dir(dir)
  790. //filePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  791. xlsxFile := xlsx.NewFile()
  792. //if err != nil {
  793. // resp.FailData("生成文件失败", "Err:"+err.Error(), c)
  794. // return
  795. //}
  796. style := xlsx.NewStyle()
  797. alignment := xlsx.Alignment{
  798. Horizontal: "center",
  799. Vertical: "center",
  800. WrapText: true,
  801. }
  802. style.Alignment = alignment
  803. style.ApplyAlignment = true
  804. sheet, err := xlsxFile.AddSheet("合同登记")
  805. if err != nil {
  806. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  807. return
  808. }
  809. //_ = sheet.SetColWidth(0, 0, 60)
  810. //_ = sheet.SetColWidth(4, 10, 60)
  811. // 1行表头
  812. titleRow := sheet.AddRow()
  813. titleRow.SetHeight(40)
  814. // 1行1列-右合并两格
  815. cell1 := titleRow.AddCell()
  816. cell1.HMerge = 2
  817. cell1.SetValue("FICC客户签约表 2022")
  818. cell1.SetStyle(style)
  819. // 右增两列空白格用于第一列合并, 否则后续单元格合并会有问题
  820. titleRow.AddCell().SetValue("")
  821. titleRow.AddCell().SetValue("")
  822. // 1行2列
  823. cell2 := titleRow.AddCell()
  824. cell2.SetValue("FICC大套餐")
  825. cell2.SetStyle(style)
  826. // 1行3列-右合并小套餐数
  827. if permissionLen >= 1 {
  828. cell3 := titleRow.AddCell()
  829. cell3.HMerge = permissionLen - 1
  830. cell3.SetValue("FICC小套餐")
  831. cell3.SetStyle(style)
  832. // 同上右增单元格小套餐数-1的空白单元格用于合并
  833. for i := 0; i < permissionLen-1; i++ {
  834. titleRow.AddCell().SetValue("")
  835. }
  836. }
  837. cell4 := titleRow.AddCell()
  838. cell4.SetValue("市场策略")
  839. cell4.SetStyle(style)
  840. cell5 := titleRow.AddCell()
  841. cell5.SetValue("财富管理")
  842. cell5.SetStyle(style)
  843. // 第二行表头
  844. titleRow2 := sheet.AddRow()
  845. titleRow2.SetHeight(60)
  846. row2Title := make([]string, 0)
  847. row2Title = append(row2Title, "客户名称", "续约-0\n新增-1", "销售", "FICC大套餐")
  848. for i := range permissionList {
  849. row2Title = append(row2Title, permissionList[i].PermissionName)
  850. }
  851. row2Title = append(row2Title, "市场策略", "财富管理", "开始时间", "到期时间", "2022年合同金额", "约定付款时间", "签订日",
  852. "签订月", "合同状态", "合同编号", "备注")
  853. for i := range row2Title {
  854. v := titleRow2.AddCell()
  855. v.SetValue(row2Title[i])
  856. v.SetStyle(style)
  857. }
  858. // 第二行表头-开票/收款(动态添加)
  859. for i := 0; i < maxInvoice; i++ {
  860. n := i + 1
  861. c1 := titleRow2.AddCell()
  862. t1 := fmt.Sprintf("%s%d", "开票日", n)
  863. c1.SetValue(t1)
  864. c1.SetStyle(style)
  865. c2 := titleRow2.AddCell()
  866. t2 := fmt.Sprintf("%s%d", "开票金额", n)
  867. c2.SetValue(t2)
  868. c2.SetStyle(style)
  869. row2Title = append(row2Title, t1, t2)
  870. }
  871. for i := 0; i < maxPayment; i++ {
  872. n := i + 1
  873. c1 := titleRow2.AddCell()
  874. t1 := fmt.Sprintf("%s%d", "收款日", n)
  875. c1.SetValue(t1)
  876. c1.SetStyle(style)
  877. c2 := titleRow2.AddCell()
  878. t2 := fmt.Sprintf("%s%d", "收款金额", n)
  879. c2.SetValue(t2)
  880. c2.SetStyle(style)
  881. row2Title = append(row2Title, t1, t2)
  882. }
  883. // 此处取第二行标题NameKeyMap, 后面的动态匹配
  884. row2NameKeyMap := make(map[string]int)
  885. for i := range row2Title {
  886. row2NameKeyMap[row2Title[i]] = i
  887. }
  888. contractTMap := map[int]int{
  889. fms.ContractTypeNew: 1,
  890. fms.ContractTypeRenew: 0,
  891. }
  892. for _, v := range list {
  893. k := -1
  894. dataRow := sheet.AddRow()
  895. dataRow.SetHeight(20)
  896. k += 3
  897. dataRow.AddCell().SetString(v.CompanyName)
  898. dataRow.AddCell().SetString(fmt.Sprint(contractTMap[v.ContractType]))
  899. dataRow.AddCell().SetString(v.SellerName)
  900. // 大套餐
  901. k += 1
  902. col4Name := row2Title[k]
  903. svList := serviceMap[v.ContractRegisterId]
  904. col4 := ""
  905. if svList != nil && len(svList) > 0 {
  906. for isv := range svList {
  907. if svList[isv].Title == col4Name {
  908. col4 = "是"
  909. break
  910. }
  911. }
  912. }
  913. dataRow.AddCell().SetString(col4)
  914. // 小套餐
  915. serviceChartPermissionIds := serviceChartPermissionsMap[v.ContractRegisterId]
  916. for i := 0; i < permissionLen; i++ {
  917. k += 1
  918. colName := row2Title[k]
  919. chartPermissionId := permissionNameIdMap[colName]
  920. if utils.InArray(chartPermissionId, serviceChartPermissionIds) {
  921. dataRow.AddCell().SetString("是")
  922. } else {
  923. dataRow.AddCell().SetString("")
  924. }
  925. }
  926. // 财富管理/市场策略(处理方式其实跟上面的大套餐一样, 只是中间隔了小套餐按照顺序要这么处理=_=!)
  927. k += 1
  928. col5Name := row2Title[k]
  929. col5 := ""
  930. if svList != nil && len(svList) > 0 {
  931. for isv := range svList {
  932. if svList[isv].Title == col5Name {
  933. col5 = "是"
  934. break
  935. }
  936. }
  937. }
  938. dataRow.AddCell().SetString(col5)
  939. k += 1
  940. col6Name := row2Title[k]
  941. col6 := ""
  942. if svList != nil && len(svList) > 0 {
  943. for isv := range svList {
  944. if svList[isv].Title == col6Name {
  945. col6 = "是"
  946. break
  947. }
  948. }
  949. }
  950. dataRow.AddCell().SetString(col6)
  951. // 其他信息
  952. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.StartDate)) // 开始时间
  953. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.EndDate)) // 到期时间
  954. dataRow.AddCell().SetString(fmt.Sprint("¥", v.ContractAmount)) // 2022年合同金额
  955. dataRow.AddCell().SetString(v.AgreedPayTime) // 约定付款时间
  956. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.SignDate)) // 签订日
  957. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01", v.SignDate)) // 签订月
  958. dataRow.AddCell().SetString(fms.ContractStatusKeyNameMap[v.ContractStatus]) // 合同状态
  959. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  960. dataRow.AddCell().SetString(v.Remark) // 备注
  961. // 开票/到款信息
  962. ivList := invoiceMap[v.ContractRegisterId]
  963. ivListLen := len(ivList)
  964. if ivList != nil && len(ivList) > 0 {
  965. for ia := 0; ia < maxInvoice; ia++ {
  966. if ia < ivListLen {
  967. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", ivList[ia].InvoiceDate)) // 开票日
  968. dataRow.AddCell().SetString(fmt.Sprint(ivList[ia].Amount)) // 开票金额
  969. } else {
  970. // 这里要把不够的填充为空
  971. dataRow.AddCell().SetString("")
  972. dataRow.AddCell().SetString("")
  973. }
  974. }
  975. }
  976. pyList := paymentMap[v.ContractRegisterId]
  977. pyListLen := len(pyList)
  978. if pyList != nil && pyListLen > 0 {
  979. for ib := 0; ib < maxInvoice; ib++ {
  980. if ib < pyListLen {
  981. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", pyList[ib].InvoiceDate)) // 收款日
  982. dataRow.AddCell().SetString(fmt.Sprint(pyList[ib].Amount)) // 收款金额
  983. } else {
  984. // 已经是最后的几列了其实可以不用填充空, 万一后面要加列此处还是填充上吧
  985. dataRow.AddCell().SetString("")
  986. dataRow.AddCell().SetString("")
  987. }
  988. }
  989. }
  990. }
  991. // 输出文件
  992. var buffer bytes.Buffer
  993. _ = xlsxFile.Write(&buffer)
  994. content := bytes.NewReader(buffer.Bytes())
  995. //err = xlsxFile.Save(filePath)
  996. //if err != nil {
  997. // resp.FailData("保存文件失败", "Err:"+err.Error(), c)
  998. // return
  999. //}
  1000. //defer func() {
  1001. // _ = os.Remove(filePath)
  1002. //}()
  1003. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1004. fileName := "财务列表_" + randStr + ".xlsx"
  1005. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1006. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1007. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1008. }