register.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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/shopspring/decimal"
  9. "github.com/tealeg/xlsx"
  10. "hongze/fms_api/controller/resp"
  11. "hongze/fms_api/global"
  12. "hongze/fms_api/models/base"
  13. "hongze/fms_api/models/crm"
  14. "hongze/fms_api/models/fms"
  15. "hongze/fms_api/models/system"
  16. fmsService "hongze/fms_api/services/fms"
  17. "hongze/fms_api/utils"
  18. "net/http"
  19. "time"
  20. )
  21. // RegisterController 合同登记
  22. type RegisterController struct{}
  23. // List
  24. // @Title 合同登记列表
  25. // @Description 合同登记列表
  26. // @Param Keyword query string false "关键词"
  27. // @Param StartDate query string false "合同开始日期"
  28. // @Param EndDate query string false "合同结束日期"
  29. // @Param ServiceType query int false "套餐类型"
  30. // @Param ContractType query int false "合同类型"
  31. // @Param RegisterStatus query int false "登记状态"
  32. // @Success 200 {object} fms.ContractRegisterItem
  33. // @router /contract/register/list [get]
  34. func (rg *RegisterController) List(c *gin.Context) {
  35. var req fms.ContractRegisterListReq
  36. if e := c.BindQuery(&req); e != nil {
  37. err, ok := e.(validator.ValidationErrors)
  38. if !ok {
  39. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  40. return
  41. }
  42. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  43. return
  44. }
  45. cond := `1 = 1`
  46. pars := make([]interface{}, 0)
  47. // 合同编号/客户姓名/销售/代付方
  48. if req.Keyword != "" {
  49. kw := "%" + req.Keyword + "%"
  50. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR pay_company_name LIKE ?)`
  51. pars = append(pars, kw, kw, kw)
  52. }
  53. if req.StartDate != "" && req.EndDate != "" {
  54. st := fmt.Sprint(req.StartDate, " 00:00:00")
  55. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  56. cond += ` AND (create_time BETWEEN ? AND ?)`
  57. pars = append(pars, st, ed)
  58. }
  59. if req.ContractType != 0 {
  60. cond += ` AND contract_type = ?`
  61. pars = append(pars, req.ContractType)
  62. }
  63. if req.RegisterStatus != 0 {
  64. cond += ` AND register_status = ?`
  65. pars = append(pars, req.RegisterStatus)
  66. }
  67. // 套餐筛选
  68. if req.ServiceType != 0 {
  69. registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
  70. if e != nil {
  71. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  72. return
  73. }
  74. if len(registerIds) > 0 {
  75. cond += ` AND contract_register_id IN ?`
  76. pars = append(pars, registerIds)
  77. } else {
  78. cond += ` AND 1 = 2`
  79. }
  80. }
  81. page := new(base.Page)
  82. page.SetPageSize(req.PageSize)
  83. page.SetCurrent(req.Current)
  84. page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: false})
  85. total, list, e := fms.GetContractRegisterItemPageList(page, cond, pars)
  86. if e != nil {
  87. resp.FailMsg("获取失败", "获取合同登记列表失败, Err: "+e.Error(), c)
  88. return
  89. }
  90. registerIds := make([]int, 0)
  91. for i := range list {
  92. registerIds = append(registerIds, list[i].ContractRegisterId)
  93. }
  94. serviceMap := make(map[int]string, 0)
  95. invoiceMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  96. paymentMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  97. if len(registerIds) > 0 {
  98. // 获取服务套餐
  99. servicesNameList, e := fms.GetContractRegisterServicesNameByRegisterIds(registerIds)
  100. if e != nil {
  101. resp.FailMsg("获取失败", "获取套餐拼接字符串失败, Err: "+e.Error(), c)
  102. return
  103. }
  104. for i := range servicesNameList {
  105. serviceMap[servicesNameList[i].ContractRegisterId] = servicesNameList[i].ServicesName
  106. }
  107. // 获取开票/到款列表
  108. invoiceCond := `contract_register_id IN ?`
  109. invoicePars := make([]interface{}, 0)
  110. invoicePars = append(invoicePars, registerIds)
  111. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  112. if e != nil {
  113. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  114. return
  115. }
  116. for i := range invoiceList {
  117. if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  118. invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  119. }
  120. if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  121. paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  122. }
  123. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  124. invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  125. }
  126. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  127. paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  128. }
  129. }
  130. }
  131. respList := make([]*fms.ContractRegisterList, 0)
  132. for i := range list {
  133. v := new(fms.ContractRegisterList)
  134. v.ContractRegisterItem = list[i]
  135. v.ServicesName = serviceMap[list[i].ContractRegisterId]
  136. v.InvoiceList = invoiceMap[list[i].ContractRegisterId]
  137. v.PaymentList = paymentMap[list[i].ContractRegisterId]
  138. respList = append(respList, v)
  139. }
  140. page.SetTotal(total)
  141. baseData := new(base.BaseData)
  142. baseData.SetPage(page)
  143. baseData.SetList(respList)
  144. resp.OkData("获取成功", baseData, c)
  145. }
  146. // Add
  147. // @Title 新增合同登记
  148. // @Description 新增合同登记
  149. // @Param request body fms.ContractRegisterAddReq true "type json string"
  150. // @Success 200 string "操作成功"
  151. // @router /contract/register/add [post]
  152. func (rg *RegisterController) Add(c *gin.Context) {
  153. req := new(fms.ContractRegisterAddReq)
  154. err := c.ShouldBind(&req)
  155. if err != nil {
  156. errs, ok := err.(validator.ValidationErrors)
  157. if !ok {
  158. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  159. return
  160. }
  161. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  162. return
  163. }
  164. claims, _ := c.Get("adminInfo")
  165. adminInfo := claims.(*system.SysAdmin)
  166. // 日期校验
  167. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  168. if e != nil {
  169. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  170. return
  171. }
  172. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  173. if e != nil {
  174. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  175. return
  176. }
  177. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  178. if req.SignDate != "" {
  179. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  180. if e != nil {
  181. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  182. return
  183. }
  184. signDate = signDateTime
  185. }
  186. // 是否存在相同合同编号的登记
  187. ob := new(fms.ContractRegister)
  188. existCond := `contract_code = ?`
  189. existPars := make([]interface{}, 0)
  190. existPars = append(existPars, req.ContractCode)
  191. exist, e := ob.FetchByCondition(existCond, existPars)
  192. if e != nil && e != utils.ErrNoRow {
  193. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  194. return
  195. }
  196. if exist != nil && exist.ContractRegisterId > 0 {
  197. resp.Fail("合同编号已存在", c)
  198. return
  199. }
  200. nowTime := time.Now().Local()
  201. ob.ContractCode = req.ContractCode
  202. ob.PayContractCode = req.PayContractCode
  203. ob.CrmContractId = req.CrmContractId
  204. ob.ContractSource = req.ContractSource
  205. ob.CompanyName = req.CompanyName
  206. ob.PayCompanyName = req.PayCompanyName
  207. ob.ProductId = req.ProductId
  208. ob.SellerId = req.SellerId
  209. ob.SellerName = req.SellerName
  210. ob.ContractType = req.ContractType
  211. ob.ContractAmount = req.ContractAmount
  212. ob.StartDate = startDate
  213. ob.EndDate = endDate
  214. ob.SignDate = signDate
  215. ob.AgreedPayTime = req.AgreedPayTime
  216. ob.ContractStatus = req.ContractStatus
  217. ob.RegisterStatus = fms.ContractRegisterStatusIng
  218. ob.Remark = req.Remark
  219. ob.Set()
  220. // 补充协议直接完成
  221. if req.ContractType == fms.ContractTypePlus {
  222. ob.RegisterStatus = fms.ContractRegisterStatusComplete
  223. }
  224. // 套餐信息
  225. serviceList, e := fmsService.HandleContractServiceAndDetail(req.ProductId, req.Services, true)
  226. if e != nil {
  227. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  228. return
  229. }
  230. // 新增合同及套餐
  231. if e = fms.CreateContractRegisterAndServices(ob, serviceList); e != nil {
  232. resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
  233. return
  234. }
  235. // 操作日志
  236. go func() {
  237. opData := ""
  238. opDataByte, e := json.Marshal(req)
  239. if e != nil {
  240. return
  241. }
  242. opData = string(opDataByte)
  243. logItem := new(fms.ContractRegisterLog)
  244. logItem.ContractRegisterId = ob.ContractRegisterId
  245. logItem.AdminId = int(adminInfo.AdminId)
  246. logItem.AdminName = adminInfo.RealName
  247. logItem.OpData = opData
  248. logItem.OpType = fms.ContractRegisterOpTypeSave
  249. logItem.CreateTime = nowTime
  250. if e = logItem.Create(); e != nil {
  251. return
  252. }
  253. }()
  254. resp.Ok("操作成功", c)
  255. }
  256. // Edit
  257. // @Title 编辑合同登记
  258. // @Description 编辑合同登记
  259. // @Param request body fms.ContractRegisterEditReq true "type json string"
  260. // @Success 200 string "操作成功"
  261. // @router /contract/register/edit [post]
  262. func (rg *RegisterController) Edit(c *gin.Context) {
  263. req := new(fms.ContractRegisterEditReq)
  264. err := c.ShouldBind(&req)
  265. if err != nil {
  266. errs, ok := err.(validator.ValidationErrors)
  267. if !ok {
  268. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  269. return
  270. }
  271. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  272. return
  273. }
  274. claims, _ := c.Get("adminInfo")
  275. adminInfo := claims.(*system.SysAdmin)
  276. // 日期校验
  277. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  278. if e != nil {
  279. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  280. return
  281. }
  282. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  283. if e != nil {
  284. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  285. return
  286. }
  287. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  288. if req.SignDate != "" {
  289. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  290. if e != nil {
  291. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  292. return
  293. }
  294. signDate = signDateTime
  295. }
  296. ob := new(fms.ContractRegister)
  297. item, e := ob.Fetch(req.ContractRegisterId)
  298. if e != nil {
  299. if e == utils.ErrNoRow {
  300. resp.Fail("登记记录不存在或已被删除", c)
  301. return
  302. }
  303. resp.FailMsg("操作失败", "获取合同登记信息失败, Err:"+e.Error(), c)
  304. return
  305. }
  306. // 是否存在相同合同编号的登记
  307. existCond := `contract_code = ?`
  308. existPars := make([]interface{}, 0)
  309. existPars = append(existPars, req.ContractCode)
  310. exist, e := ob.FetchByCondition(existCond, existPars)
  311. if e != nil && e != utils.ErrNoRow {
  312. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  313. return
  314. }
  315. if exist != nil && exist.ContractRegisterId > 0 && exist.ContractRegisterId != item.ContractRegisterId {
  316. resp.Fail("合同编号已存在", c)
  317. return
  318. }
  319. nowTime := time.Now().Local()
  320. item.ContractCode = req.ContractCode
  321. item.PayContractCode = req.PayContractCode
  322. item.CrmContractId = req.CrmContractId
  323. item.ContractSource = req.ContractSource
  324. item.CompanyName = req.CompanyName
  325. item.PayCompanyName = req.PayCompanyName
  326. item.SellerId = req.SellerId
  327. item.SellerName = req.SellerName
  328. item.ContractType = req.ContractType
  329. item.ContractAmount = req.ContractAmount
  330. item.StartDate = startDate
  331. item.EndDate = endDate
  332. item.SignDate = signDate
  333. item.AgreedPayTime = req.AgreedPayTime
  334. item.ContractStatus = req.ContractStatus
  335. item.RegisterStatus = fms.ContractRegisterStatusIng
  336. // 补充协议直接完成
  337. if req.ContractType == fms.ContractTypePlus {
  338. item.RegisterStatus = fms.ContractRegisterStatusComplete
  339. }
  340. item.Remark = req.Remark
  341. item.ModifyTime = nowTime
  342. updateCols := []string{
  343. "ContractCode", "CrmContractId", "ContractSource", "CompanyName", "SellerId", "SellerName",
  344. "ContractType", "ContractAmount", "StartDate", "EndDate", "SignDate", "AgreedPayTime", "ContractStatus",
  345. "RegisterStatus", "Remark", "ModifyTime",
  346. }
  347. // 套餐信息
  348. serviceList, e := fmsService.HandleContractServiceAndDetail(req.ProductId, req.Services, true)
  349. if e != nil {
  350. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  351. return
  352. }
  353. // 更新合同及套餐
  354. if e = fms.UpdateContractRegisterAndServices(item, updateCols, serviceList); e != nil {
  355. resp.FailMsg("操作失败", "更新合同及套餐失败, Err: "+e.Error(), c)
  356. return
  357. }
  358. // 非补充协议校验金额-是否修改状态
  359. if item.ContractType != fms.ContractTypePlus {
  360. go fmsService.CheckContractRegisterAmount(item.ContractRegisterId)
  361. }
  362. // 操作日志
  363. go func() {
  364. opData := ""
  365. opDataByte, e := json.Marshal(req)
  366. if e != nil {
  367. return
  368. }
  369. opData = string(opDataByte)
  370. logItem := new(fms.ContractRegisterLog)
  371. logItem.ContractRegisterId = item.ContractRegisterId
  372. logItem.AdminId = int(adminInfo.AdminId)
  373. logItem.AdminName = adminInfo.RealName
  374. logItem.OpData = opData
  375. logItem.OpType = fms.ContractRegisterOpTypeEdit
  376. logItem.CreateTime = nowTime
  377. if e = logItem.Create(); e != nil {
  378. return
  379. }
  380. }()
  381. resp.Ok("操作成功", c)
  382. }
  383. // Del
  384. // @Title 删除合同登记
  385. // @Description 删除合同登记
  386. // @Param request body fms.ContractRegisterDelReq true "type json string"
  387. // @Success 200 string "操作成功"
  388. // @router /contract/register/del [post]
  389. func (rg *RegisterController) Del(c *gin.Context) {
  390. req := new(fms.ContractRegisterDelReq)
  391. err := c.ShouldBind(&req)
  392. if err != nil {
  393. errs, ok := err.(validator.ValidationErrors)
  394. if !ok {
  395. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  396. return
  397. }
  398. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  399. return
  400. }
  401. claims, _ := c.Get("adminInfo")
  402. adminInfo := claims.(*system.SysAdmin)
  403. ob := new(fms.ContractRegister)
  404. item, e := ob.Fetch(req.ContractRegisterId)
  405. if e != nil {
  406. if e == utils.ErrNoRow {
  407. resp.Fail("合同登记不存在或已被删除", c)
  408. return
  409. }
  410. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  411. return
  412. }
  413. nowTime := time.Now().Local()
  414. item.IsDeleted = 1
  415. item.ModifyTime = nowTime
  416. updateCols := []string{"IsDeleted", "ModifyTime"}
  417. if e = item.Update(updateCols); e != nil {
  418. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  419. return
  420. }
  421. // 操作日志
  422. go func() {
  423. opData := ""
  424. opDataByte, e := json.Marshal(req)
  425. if e != nil {
  426. return
  427. }
  428. opData = string(opDataByte)
  429. logItem := new(fms.ContractRegisterLog)
  430. logItem.ContractRegisterId = req.ContractRegisterId
  431. logItem.AdminId = int(adminInfo.AdminId)
  432. logItem.AdminName = adminInfo.RealName
  433. logItem.OpData = opData
  434. logItem.OpType = fms.ContractRegisterOpTypeDel
  435. logItem.CreateTime = nowTime
  436. if e = logItem.Create(); e != nil {
  437. return
  438. }
  439. }()
  440. resp.Ok("操作成功", c)
  441. }
  442. // Detail
  443. // @Title 合同登记详情
  444. // @Description 合同登记详情
  445. // @Param ContractRegisterId query int false "合同登记ID"
  446. // @Success 200 {object} fms.ContractRegisterDetail
  447. // @router /contract/register/detail [get]
  448. func (rg *RegisterController) Detail(c *gin.Context) {
  449. var req fms.ContractRegisterDetailReq
  450. if e := c.BindQuery(&req); e != nil {
  451. err, ok := e.(validator.ValidationErrors)
  452. if !ok {
  453. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  454. return
  455. }
  456. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  457. return
  458. }
  459. result := new(fms.ContractRegisterDetail)
  460. // 合同登记信息
  461. item, e := fms.GetContractRegisterItemById(req.ContractRegisterId)
  462. if e != nil {
  463. resp.FailData("获取失败", "获取合同登记详情失败, Err:"+e.Error(), c)
  464. return
  465. }
  466. result.ContractRegisterItem = item
  467. // 套餐信息
  468. serviceList, e := fmsService.GetContractServiceAndDetail(req.ContractRegisterId)
  469. if e != nil {
  470. resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
  471. return
  472. }
  473. result.ServiceList = serviceList
  474. // 开票/到款信息
  475. invoiceCond := `contract_register_id = ?`
  476. invoicePars := make([]interface{}, 0)
  477. invoicePars = append(invoicePars, req.ContractRegisterId)
  478. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  479. if e != nil {
  480. resp.FailData("获取失败", "获取合同开票/到款信息失败, Err: "+e.Error(), c)
  481. return
  482. }
  483. result.InvoiceList = make([]*fms.ContractInvoiceItem, 0)
  484. result.PaymentList = make([]*fms.ContractInvoiceItem, 0)
  485. for i := range invoiceList {
  486. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  487. result.InvoiceList = append(result.InvoiceList, invoiceList[i])
  488. continue
  489. }
  490. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  491. result.PaymentList = append(result.PaymentList, invoiceList[i])
  492. }
  493. }
  494. // 合同登记进度
  495. logCond := `contract_register_id = ?`
  496. logPars := make([]interface{}, 0)
  497. logPars = append(logPars, req.ContractRegisterId)
  498. logList, e := fms.GetContractRegisterLogItemList(logCond, logPars)
  499. if e != nil {
  500. resp.FailData("获取失败", "获取合同登记进度失败, Err: "+e.Error(), c)
  501. return
  502. }
  503. result.Logs = logList
  504. resp.OkData("获取成功", result, c)
  505. }
  506. // UpdateStatus
  507. // @Title 修改合同状态
  508. // @Description 修改合同状态
  509. // @Param request body fms.ContractRegisterUpdateStatusReq true "type json string"
  510. // @Success 200 string "操作成功"
  511. // @router /contract/register/update_status [post]
  512. func (rg *RegisterController) UpdateStatus(c *gin.Context) {
  513. req := new(fms.ContractRegisterUpdateStatusReq)
  514. err := c.ShouldBind(&req)
  515. if err != nil {
  516. errs, ok := err.(validator.ValidationErrors)
  517. if !ok {
  518. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  519. return
  520. }
  521. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  522. return
  523. }
  524. claims, _ := c.Get("adminInfo")
  525. adminInfo := claims.(*system.SysAdmin)
  526. ob := new(fms.ContractRegister)
  527. item, e := ob.Fetch(req.ContractRegisterId)
  528. if e != nil {
  529. if e == utils.ErrNoRow {
  530. resp.Fail("合同登记不存在或已被删除", c)
  531. return
  532. }
  533. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  534. return
  535. }
  536. nowTime := time.Now().Local()
  537. item.ContractStatus = req.ContractStatus
  538. item.ModifyTime = nowTime
  539. updateCols := []string{"ContractStatus", "ModifyTime"}
  540. if e = item.Update(updateCols); e != nil {
  541. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  542. return
  543. }
  544. // 非补充协议校验金额-是否修改状态
  545. if item.ContractType != fms.ContractTypePlus {
  546. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  547. }
  548. // 操作日志
  549. go func() {
  550. opData := ""
  551. opDataByte, e := json.Marshal(req)
  552. if e != nil {
  553. return
  554. }
  555. opData = string(opDataByte)
  556. logItem := new(fms.ContractRegisterLog)
  557. logItem.ContractRegisterId = req.ContractRegisterId
  558. logItem.AdminId = int(adminInfo.AdminId)
  559. logItem.AdminName = adminInfo.RealName
  560. logItem.OpData = opData
  561. logItem.OpType = fms.ContractRegisterOpTypeStatus
  562. logItem.CreateTime = nowTime
  563. if e = logItem.Create(); e != nil {
  564. return
  565. }
  566. }()
  567. resp.Ok("操作成功", c)
  568. }
  569. // Invoice
  570. // @Title 开票/到款登记
  571. // @Description 开票/到款登记
  572. // @Param request body fms.ContractInvoiceSaveReq true "type json string"
  573. // @Success 200 string "操作成功"
  574. // @router /contract/register/invoice [post]
  575. func (rg *RegisterController) Invoice(c *gin.Context) {
  576. req := new(fms.ContractInvoiceSaveReq)
  577. err := c.ShouldBind(&req)
  578. if err != nil {
  579. errs, ok := err.(validator.ValidationErrors)
  580. if !ok {
  581. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  582. return
  583. }
  584. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  585. return
  586. }
  587. claims, _ := c.Get("adminInfo")
  588. adminInfo := claims.(*system.SysAdmin)
  589. registerOB := new(fms.ContractRegister)
  590. item, e := registerOB.Fetch(req.ContractRegisterId)
  591. if e != nil {
  592. if e == utils.ErrNoRow {
  593. resp.Fail("合同登记不存在或已被删除", c)
  594. return
  595. }
  596. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  597. return
  598. }
  599. if item.ContractType == fms.ContractTypePlus {
  600. resp.Fail("补充协议不允许添加开票/到款登记", c)
  601. return
  602. }
  603. noChangeInvoiceIds := make([]int, 0)
  604. newInvoice := make([]*fms.ContractInvoice, 0)
  605. if len(req.AmountList) > 0 {
  606. for i := range req.AmountList {
  607. if req.AmountList[i].Amount <= 0 {
  608. resp.Fail("登记金额有误", c)
  609. return
  610. }
  611. if req.AmountList[i].InvoiceDate == "" {
  612. resp.Fail("请选择日期", c)
  613. return
  614. }
  615. t, e := time.ParseInLocation(utils.FormatDate, req.AmountList[i].InvoiceDate, time.Local)
  616. if e != nil {
  617. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  618. return
  619. }
  620. if req.AmountList[i].InvoiceId > 0 {
  621. noChangeInvoiceIds = append(noChangeInvoiceIds, req.AmountList[i].InvoiceId)
  622. } else {
  623. v := &fms.ContractInvoice{
  624. ContractRegisterId: req.ContractRegisterId,
  625. ContractCode: item.ContractCode,
  626. Amount: req.AmountList[i].Amount,
  627. InvoiceType: req.InvoiceType,
  628. InvoiceDate: t,
  629. AdminId: int(adminInfo.AdminId),
  630. AdminName: adminInfo.RealName,
  631. }
  632. v.Set()
  633. newInvoice = append(newInvoice, v)
  634. }
  635. }
  636. }
  637. // 获取原有的登记信息
  638. invoiceCond := `contract_register_id = ? AND invoice_type = ?`
  639. invoicePars := make([]interface{}, 0)
  640. invoicePars = append(invoicePars, req.ContractRegisterId, req.InvoiceType)
  641. originInvoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  642. if e != nil {
  643. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  644. return
  645. }
  646. // 比对原有和现有的登记信息
  647. logList := make([]*fms.ContractRegisterLog, 0)
  648. opData := ""
  649. opDataByte, e := json.Marshal(req)
  650. if e != nil {
  651. return
  652. }
  653. opData = string(opDataByte)
  654. opType := fms.ContractRegisterOpTypeInvoice
  655. if req.InvoiceType == fms.ContractInvoiceTypePay {
  656. opType = fms.ContractRegisterOpTypePayment
  657. }
  658. nowTime := time.Now().Local()
  659. // 需要删除的记录
  660. deleteInvoiceIds := make([]int, 0)
  661. for i := range originInvoiceList {
  662. if !utils.InArrayByInt(noChangeInvoiceIds, originInvoiceList[i].ContractInvoiceId) {
  663. deleteInvoiceIds = append(deleteInvoiceIds, originInvoiceList[i].ContractInvoiceId)
  664. logList = append(logList, &fms.ContractRegisterLog{
  665. ContractRegisterId: req.ContractRegisterId,
  666. AdminId: int(adminInfo.AdminId),
  667. AdminName: adminInfo.RealName,
  668. OpData: opData,
  669. OpType: opType,
  670. CreateTime: nowTime,
  671. Remark: fmt.Sprint(adminInfo.RealName, " 删除", fms.ContractInvoiceKeyNameMap[opType], "金额", originInvoiceList[i].Amount, "元"),
  672. })
  673. }
  674. }
  675. // 新增的记录
  676. if len(newInvoice) > 0 {
  677. newAmount := decimal.NewFromFloat(0).Round(2)
  678. for i := range newInvoice {
  679. a := decimal.NewFromFloat(newInvoice[i].Amount).Round(2)
  680. newAmount = newAmount.Add(a)
  681. }
  682. ia, _ := newAmount.Round(2).Float64()
  683. logList = append(logList, &fms.ContractRegisterLog{
  684. ContractRegisterId: req.ContractRegisterId,
  685. AdminId: int(adminInfo.AdminId),
  686. AdminName: adminInfo.RealName,
  687. OpData: opData,
  688. OpType: opType,
  689. CreateTime: nowTime,
  690. Remark: fmt.Sprint(adminInfo.RealName, " 新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  691. })
  692. }
  693. // 删除并新增登记
  694. ob := new(fms.ContractInvoice)
  695. if e := ob.DeleteAndCreateNewInvoice(req.ContractRegisterId, req.InvoiceType, deleteInvoiceIds, newInvoice); e != nil {
  696. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  697. return
  698. }
  699. // 校验金额-是否修改状态
  700. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  701. // 操作日志
  702. go func() {
  703. logOB := new(fms.ContractRegisterLog)
  704. if e := logOB.AddInBatches(logList); e != nil {
  705. return
  706. }
  707. }()
  708. resp.Ok("操作成功", c)
  709. }
  710. // Export
  711. // @Title 合同登记-导出
  712. // @Description 合同登记-导出
  713. // @Param Keyword query string false "关键词"
  714. // @Param StartDate query string false "合同开始日期"
  715. // @Param EndDate query string false "合同结束日期"
  716. // @Param ServiceType query int false "套餐类型"
  717. // @Param ContractType query int false "合同类型"
  718. // @Param RegisterStatus query int false "登记状态"
  719. // @Success 200 string "操作成功"
  720. // @router /contract/register/export [get]
  721. func (rg *RegisterController) Export(c *gin.Context) {
  722. var req fms.ContractRegisterListReq
  723. if e := c.BindQuery(&req); e != nil {
  724. err, ok := e.(validator.ValidationErrors)
  725. if !ok {
  726. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  727. return
  728. }
  729. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  730. return
  731. }
  732. cond := `1 = 1`
  733. pars := make([]interface{}, 0)
  734. if req.Keyword != "" {
  735. kw := "%" + req.Keyword + "%"
  736. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ?)`
  737. pars = append(pars, kw, kw, kw)
  738. }
  739. if req.StartDate != "" && req.EndDate != "" {
  740. st := fmt.Sprint(req.StartDate, " 00:00:00")
  741. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  742. cond += ` AND (create_time BETWEEN ? AND ?)`
  743. pars = append(pars, st, ed)
  744. }
  745. if req.ContractType != 0 {
  746. cond += ` AND contract_type = ?`
  747. pars = append(pars, req.ContractType)
  748. }
  749. if req.RegisterStatus != 0 {
  750. cond += ` AND register_status = ?`
  751. pars = append(pars, req.RegisterStatus)
  752. }
  753. if req.ServiceType != 0 {
  754. registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
  755. if e != nil {
  756. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  757. return
  758. }
  759. if len(registerIds) > 0 {
  760. cond += ` AND contract_register_id IN ?`
  761. pars = append(pars, registerIds)
  762. } else {
  763. cond += ` AND 1 = 2`
  764. }
  765. }
  766. // 获取列表数据
  767. cr := new(fms.ContractRegister)
  768. list, e := cr.List(cond, pars)
  769. if e != nil {
  770. resp.FailData("获取合同列表失败", "Err:"+e.Error(), c)
  771. return
  772. }
  773. if len(list) == 0 {
  774. resp.Fail("无有效数据可导出", c)
  775. return
  776. }
  777. registerIds := make([]int, 0)
  778. for i := range list {
  779. registerIds = append(registerIds, list[i].ContractRegisterId)
  780. }
  781. // 获取小套餐品种
  782. cpCond := `product_id = ? AND permission_name <> ?`
  783. cpPars := make([]interface{}, 0)
  784. cpPars = append(cpPars, crm.CompanyProductFicc, crm.ChartPermissionStrategyName)
  785. cp := new(crm.ChartPermission)
  786. permissionList, e := cp.List(cpCond, cpPars)
  787. if e != nil {
  788. resp.FailData("获取小套餐品种失败", "Err:"+e.Error(), c)
  789. return
  790. }
  791. permissionLen := len(permissionList)
  792. permissionNameIdMap := make(map[string]int)
  793. for i := range permissionList {
  794. permissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  795. }
  796. // 获取套餐服务
  797. //serviceList, e := fms.GetContractServiceTemplateMapByProductId(crm.CompanyProductFicc)
  798. //if e != nil {
  799. // resp.FailData("获取套餐服务失败", "Err:"+e.Error(), c)
  800. // return
  801. //}
  802. // 套餐/开票/到款列表
  803. serviceMap := make(map[int][]*fms.ContractService)
  804. serviceChartPermissionsMap := make(map[int][]int)
  805. invoiceMap := make(map[int][]*fms.ContractInvoice)
  806. paymentMap := make(map[int][]*fms.ContractInvoice)
  807. maxInvoice := 0
  808. maxPayment := 0
  809. if len(registerIds) > 0 {
  810. // 获取套餐信息
  811. csCond := `contract_register_id IN ?`
  812. csPars := make([]interface{}, 0)
  813. csPars = append(csPars, registerIds)
  814. cs := new(fms.ContractService)
  815. serviceList, e := cs.List(csCond, csPars)
  816. if e != nil {
  817. resp.FailData("获取合同套餐列表失败", "Err:"+e.Error(), c)
  818. return
  819. }
  820. for i := range serviceList {
  821. cid := serviceList[i].ContractRegisterId
  822. if serviceMap[cid] == nil {
  823. serviceMap[cid] = make([]*fms.ContractService, 0)
  824. }
  825. serviceMap[cid] = append(serviceMap[cid], serviceList[i])
  826. // 小套餐权限
  827. if serviceChartPermissionsMap[cid] == nil {
  828. serviceChartPermissionsMap[cid] = make([]int, 0)
  829. }
  830. if serviceList[i].ChartPermissionIds != "" {
  831. ids := utils.JoinStr2IntArr(serviceList[i].ChartPermissionIds, ",")
  832. serviceChartPermissionsMap[cid] = append(serviceChartPermissionsMap[cid], ids...)
  833. }
  834. }
  835. // 获取开票/到款详情, 并取最大的开票/到款数(用于动态扩展第二列表头)
  836. ci := new(fms.ContractInvoice)
  837. invoiceList, e := ci.List(csCond, csPars, "")
  838. if e != nil {
  839. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  840. return
  841. }
  842. for k := range invoiceList {
  843. cid := invoiceList[k].ContractRegisterId
  844. if invoiceMap[cid] == nil {
  845. invoiceMap[cid] = make([]*fms.ContractInvoice, 0)
  846. }
  847. if paymentMap[cid] == nil {
  848. paymentMap[cid] = make([]*fms.ContractInvoice, 0)
  849. }
  850. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypeMake {
  851. invoiceMap[cid] = append(invoiceMap[cid], invoiceList[k])
  852. continue
  853. }
  854. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypePay {
  855. paymentMap[cid] = append(paymentMap[cid], invoiceList[k])
  856. continue
  857. }
  858. }
  859. // 取最大开票/到款数
  860. for j := range invoiceMap {
  861. if len(invoiceMap[j]) > maxInvoice {
  862. maxInvoice = len(invoiceMap[j])
  863. }
  864. }
  865. for p := range paymentMap {
  866. if len(paymentMap[p]) > maxPayment {
  867. maxPayment = len(paymentMap[p])
  868. }
  869. }
  870. }
  871. // 生成Excel文件
  872. //dir, err := os.Executable()
  873. //exPath := filepath.Dir(dir)
  874. //filePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  875. xlsxFile := xlsx.NewFile()
  876. //if err != nil {
  877. // resp.FailData("生成文件失败", "Err:"+err.Error(), c)
  878. // return
  879. //}
  880. style := xlsx.NewStyle()
  881. alignment := xlsx.Alignment{
  882. Horizontal: "center",
  883. Vertical: "center",
  884. WrapText: true,
  885. }
  886. style.Alignment = alignment
  887. style.ApplyAlignment = true
  888. sheet, err := xlsxFile.AddSheet("合同登记")
  889. if err != nil {
  890. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  891. return
  892. }
  893. //_ = sheet.SetColWidth(0, 0, 60)
  894. //_ = sheet.SetColWidth(4, 10, 60)
  895. // 1行表头
  896. titleRow := sheet.AddRow()
  897. titleRow.SetHeight(40)
  898. // 1行1列-右合并两格
  899. cell1 := titleRow.AddCell()
  900. cell1.HMerge = 2
  901. cell1.SetValue("FICC客户签约表 2022")
  902. cell1.SetStyle(style)
  903. // 右增两列空白格用于第一列合并, 否则后续单元格合并会有问题
  904. titleRow.AddCell().SetValue("")
  905. titleRow.AddCell().SetValue("")
  906. // 1行2列
  907. cell2 := titleRow.AddCell()
  908. cell2.SetValue("FICC大套餐")
  909. cell2.SetStyle(style)
  910. // 1行3列-右合并小套餐数
  911. if permissionLen >= 1 {
  912. cell3 := titleRow.AddCell()
  913. cell3.HMerge = permissionLen - 1
  914. cell3.SetValue("FICC小套餐")
  915. cell3.SetStyle(style)
  916. // 同上右增单元格小套餐数-1的空白单元格用于合并
  917. for i := 0; i < permissionLen-1; i++ {
  918. titleRow.AddCell().SetValue("")
  919. }
  920. }
  921. cell4 := titleRow.AddCell()
  922. cell4.SetValue("市场策略")
  923. cell4.SetStyle(style)
  924. cell5 := titleRow.AddCell()
  925. cell5.SetValue("财富管理")
  926. cell5.SetStyle(style)
  927. // 第二行表头
  928. titleRow2 := sheet.AddRow()
  929. titleRow2.SetHeight(60)
  930. row2Title := make([]string, 0)
  931. row2Title = append(row2Title, "客户名称", "续约-0\n新增-1", "销售", "FICC大套餐")
  932. for i := range permissionList {
  933. row2Title = append(row2Title, permissionList[i].PermissionName)
  934. }
  935. row2Title = append(row2Title, "市场策略", "财富管理", "开始时间", "到期时间", "2022年合同金额", "约定付款时间", "签订日",
  936. "签订月", "合同状态", "合同编号", "备注")
  937. for i := range row2Title {
  938. v := titleRow2.AddCell()
  939. v.SetValue(row2Title[i])
  940. v.SetStyle(style)
  941. }
  942. // 第二行表头-开票/收款(动态添加)
  943. for i := 0; i < maxInvoice; i++ {
  944. n := i + 1
  945. c1 := titleRow2.AddCell()
  946. t1 := fmt.Sprintf("%s%d", "开票日", n)
  947. c1.SetValue(t1)
  948. c1.SetStyle(style)
  949. c2 := titleRow2.AddCell()
  950. t2 := fmt.Sprintf("%s%d", "开票金额", n)
  951. c2.SetValue(t2)
  952. c2.SetStyle(style)
  953. row2Title = append(row2Title, t1, t2)
  954. }
  955. for i := 0; i < maxPayment; i++ {
  956. n := i + 1
  957. c1 := titleRow2.AddCell()
  958. t1 := fmt.Sprintf("%s%d", "收款日", n)
  959. c1.SetValue(t1)
  960. c1.SetStyle(style)
  961. c2 := titleRow2.AddCell()
  962. t2 := fmt.Sprintf("%s%d", "收款金额", n)
  963. c2.SetValue(t2)
  964. c2.SetStyle(style)
  965. row2Title = append(row2Title, t1, t2)
  966. }
  967. // 此处取第二行标题NameKeyMap, 后面的动态匹配
  968. row2NameKeyMap := make(map[string]int)
  969. for i := range row2Title {
  970. row2NameKeyMap[row2Title[i]] = i
  971. }
  972. // TODO:代付和补充协议
  973. contractTMap := map[int]int{
  974. fms.ContractTypeNew: 1,
  975. fms.ContractTypeRenew: 0,
  976. }
  977. for _, v := range list {
  978. k := -1
  979. dataRow := sheet.AddRow()
  980. dataRow.SetHeight(20)
  981. k += 3
  982. dataRow.AddCell().SetString(v.CompanyName)
  983. dataRow.AddCell().SetString(fmt.Sprint(contractTMap[v.ContractType]))
  984. dataRow.AddCell().SetString(v.SellerName)
  985. // 大套餐
  986. k += 1
  987. col4Name := row2Title[k]
  988. svList := serviceMap[v.ContractRegisterId]
  989. col4 := ""
  990. if svList != nil && len(svList) > 0 {
  991. for isv := range svList {
  992. if svList[isv].Title == col4Name {
  993. col4 = "是"
  994. break
  995. }
  996. }
  997. }
  998. dataRow.AddCell().SetString(col4)
  999. // 小套餐
  1000. serviceChartPermissionIds := serviceChartPermissionsMap[v.ContractRegisterId]
  1001. for i := 0; i < permissionLen; i++ {
  1002. k += 1
  1003. colName := row2Title[k]
  1004. chartPermissionId := permissionNameIdMap[colName]
  1005. if utils.InArray(chartPermissionId, serviceChartPermissionIds) {
  1006. dataRow.AddCell().SetString("是")
  1007. } else {
  1008. dataRow.AddCell().SetString("")
  1009. }
  1010. }
  1011. // 财富管理/市场策略(处理方式其实跟上面的大套餐一样, 只是中间隔了小套餐按照顺序要这么处理=_=!)
  1012. k += 1
  1013. col5Name := row2Title[k]
  1014. col5 := ""
  1015. if svList != nil && len(svList) > 0 {
  1016. for isv := range svList {
  1017. if svList[isv].Title == col5Name {
  1018. col5 = "是"
  1019. break
  1020. }
  1021. }
  1022. }
  1023. dataRow.AddCell().SetString(col5)
  1024. k += 1
  1025. col6Name := row2Title[k]
  1026. col6 := ""
  1027. if svList != nil && len(svList) > 0 {
  1028. for isv := range svList {
  1029. if svList[isv].Title == col6Name {
  1030. col6 = "是"
  1031. break
  1032. }
  1033. }
  1034. }
  1035. dataRow.AddCell().SetString(col6)
  1036. // 其他信息
  1037. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.StartDate)) // 开始时间
  1038. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.EndDate)) // 到期时间
  1039. dataRow.AddCell().SetString(fmt.Sprint("¥", v.ContractAmount)) // 2022年合同金额
  1040. dataRow.AddCell().SetString(v.AgreedPayTime) // 约定付款时间
  1041. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.SignDate)) // 签订日
  1042. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01", v.SignDate)) // 签订月
  1043. dataRow.AddCell().SetString(fms.ContractStatusKeyNameMap[v.ContractStatus]) // 合同状态
  1044. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  1045. dataRow.AddCell().SetString(v.Remark) // 备注
  1046. // 开票/到款信息
  1047. ivList := invoiceMap[v.ContractRegisterId]
  1048. ivListLen := len(ivList)
  1049. if ivList != nil && len(ivList) > 0 {
  1050. for ia := 0; ia < maxInvoice; ia++ {
  1051. if ia < ivListLen {
  1052. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", ivList[ia].InvoiceDate)) // 开票日
  1053. dataRow.AddCell().SetString(fmt.Sprint(ivList[ia].Amount)) // 开票金额
  1054. } else {
  1055. // 这里要把不够的填充为空
  1056. dataRow.AddCell().SetString("")
  1057. dataRow.AddCell().SetString("")
  1058. }
  1059. }
  1060. }
  1061. pyList := paymentMap[v.ContractRegisterId]
  1062. pyListLen := len(pyList)
  1063. if pyList != nil && pyListLen > 0 {
  1064. for ib := 0; ib < maxInvoice; ib++ {
  1065. if ib < pyListLen {
  1066. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", pyList[ib].InvoiceDate)) // 收款日
  1067. dataRow.AddCell().SetString(fmt.Sprint(pyList[ib].Amount)) // 收款金额
  1068. } else {
  1069. // 已经是最后的几列了其实可以不用填充空, 万一后面要加列此处还是填充上吧
  1070. dataRow.AddCell().SetString("")
  1071. dataRow.AddCell().SetString("")
  1072. }
  1073. }
  1074. }
  1075. }
  1076. // 输出文件
  1077. var buffer bytes.Buffer
  1078. _ = xlsxFile.Write(&buffer)
  1079. content := bytes.NewReader(buffer.Bytes())
  1080. //err = xlsxFile.Save(filePath)
  1081. //if err != nil {
  1082. // resp.FailData("保存文件失败", "Err:"+err.Error(), c)
  1083. // return
  1084. //}
  1085. //defer func() {
  1086. // _ = os.Remove(filePath)
  1087. //}()
  1088. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1089. fileName := "财务列表_" + randStr + ".xlsx"
  1090. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1091. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1092. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1093. }
  1094. // InvoiceList
  1095. // @Title 开票/到款列表
  1096. // @Description 开票/到款列表
  1097. // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
  1098. // @Param ContractCode query string false "合同编号"
  1099. // @Param StartDate query string false "开始日期"
  1100. // @Param EndDate query string false "结束日期"
  1101. // @Param MinAmount query float64 false "开票金额区间-最小值"
  1102. // @Param MaxAmount query float64 false "开票金额区间-最大值"
  1103. // @Success 200 {object} fms.ContractInvoiceItem
  1104. // @router /contract/register/invoice_list [get]
  1105. func (rg *RegisterController) InvoiceList(c *gin.Context) {
  1106. var req fms.ContractInvoiceListReq
  1107. if e := c.BindQuery(&req); e != nil {
  1108. err, ok := e.(validator.ValidationErrors)
  1109. if !ok {
  1110. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1111. return
  1112. }
  1113. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1114. return
  1115. }
  1116. cond := `invoice_type = ?`
  1117. pars := make([]interface{}, 0)
  1118. pars = append(pars, req.InvoiceType)
  1119. // 合同编号
  1120. if req.ContractCode != "" {
  1121. cond += ` AND contract_code = ?`
  1122. pars = append(pars, req.ContractCode)
  1123. }
  1124. if req.StartDate != "" && req.EndDate != "" {
  1125. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1126. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1127. cond += ` AND (create_time BETWEEN ? AND ?)`
  1128. pars = append(pars, st, ed)
  1129. }
  1130. if req.MinAmount > 0 && req.MaxAmount > 0 {
  1131. cond += ` AND (amount BETWEEN ? AND ?)`
  1132. pars = append(pars, req.MinAmount, req.MaxAmount)
  1133. }
  1134. page := new(base.Page)
  1135. page.SetPageSize(req.PageSize)
  1136. page.SetCurrent(req.Current)
  1137. page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: false})
  1138. total, list, e := fms.GetContractInvoiceItemPageList(page, cond, pars)
  1139. if e != nil {
  1140. resp.FailMsg("获取失败", "获取合同开票/到款列表失败, Err: "+e.Error(), c)
  1141. return
  1142. }
  1143. page.SetTotal(total)
  1144. baseData := new(base.BaseData)
  1145. baseData.SetPage(page)
  1146. baseData.SetList(list)
  1147. resp.OkData("获取成功", baseData, c)
  1148. }
  1149. // InvoiceExport
  1150. // @Title 开票/到款列表-导出
  1151. // @Description 合同登记-导出
  1152. // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
  1153. // @Param ContractCode query string false "合同编号"
  1154. // @Param StartDate query string false "开始日期"
  1155. // @Param EndDate query string false "结束日期"
  1156. // @Param MinAmount query float64 false "开票金额区间-最小值"
  1157. // @Param MaxAmount query float64 false "开票金额区间-最大值"
  1158. // @Success 200 string "操作成功"
  1159. // @router /contract/register/invoice_export [get]
  1160. func (rg *RegisterController) InvoiceExport(c *gin.Context) {
  1161. var req fms.ContractInvoiceListReq
  1162. if e := c.BindQuery(&req); e != nil {
  1163. err, ok := e.(validator.ValidationErrors)
  1164. if !ok {
  1165. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1166. return
  1167. }
  1168. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1169. return
  1170. }
  1171. cond := `invoice_type = ?`
  1172. pars := make([]interface{}, 0)
  1173. pars = append(pars, req.InvoiceType)
  1174. // 合同编号
  1175. if req.ContractCode != "" {
  1176. cond += ` AND contract_code = ?`
  1177. pars = append(pars, req.ContractCode)
  1178. }
  1179. if req.StartDate != "" && req.EndDate != "" {
  1180. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1181. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1182. cond += ` AND (create_time BETWEEN ? AND ?)`
  1183. pars = append(pars, st, ed)
  1184. }
  1185. if req.MinAmount > 0 && req.MaxAmount > 0 {
  1186. cond += ` AND (amount BETWEEN ? AND ?)`
  1187. pars = append(pars, req.MinAmount, req.MaxAmount)
  1188. }
  1189. // 获取列表数据
  1190. cr := new(fms.ContractInvoice)
  1191. orderRule := `invoice_time DESC`
  1192. list, e := cr.List(cond, pars, orderRule)
  1193. if e != nil {
  1194. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  1195. return
  1196. }
  1197. if len(list) == 0 {
  1198. resp.Fail("无有效数据可导出", c)
  1199. return
  1200. }
  1201. // 生成Excel文件
  1202. xlsxFile := xlsx.NewFile()
  1203. style := xlsx.NewStyle()
  1204. alignment := xlsx.Alignment{
  1205. Horizontal: "center",
  1206. Vertical: "center",
  1207. WrapText: true,
  1208. }
  1209. style.Alignment = alignment
  1210. style.ApplyAlignment = true
  1211. sheet, err := xlsxFile.AddSheet("开票列表")
  1212. if err != nil {
  1213. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1214. return
  1215. }
  1216. // 表头
  1217. titleRow := sheet.AddRow()
  1218. titleRow.SetHeight(40)
  1219. cell1 := titleRow.AddCell()
  1220. cell1.SetValue("合同编号")
  1221. cell1.SetStyle(style)
  1222. cell2 := titleRow.AddCell()
  1223. cell2.SetValue("开票金额")
  1224. cell2.SetStyle(style)
  1225. cell3 := titleRow.AddCell()
  1226. cell3.SetValue("开票日期")
  1227. cell3.SetStyle(style)
  1228. for _, v := range list {
  1229. dataRow := sheet.AddRow()
  1230. dataRow.SetHeight(20)
  1231. dataRow.AddCell().SetString(v.ContractCode)
  1232. dataRow.AddCell().SetString(fmt.Sprint(v.Amount))
  1233. dataRow.AddCell().SetString(utils.TimeTransferString("2006-01-02", v.InvoiceDate))
  1234. }
  1235. // 输出文件
  1236. var buffer bytes.Buffer
  1237. _ = xlsxFile.Write(&buffer)
  1238. content := bytes.NewReader(buffer.Bytes())
  1239. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1240. fileName := "开票列表_" + randStr + ".xlsx"
  1241. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1242. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1243. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1244. }
  1245. // Import
  1246. // @Title 合同登记-导入
  1247. // @Description 合同登记-导入
  1248. // @Success 200 string "操作成功"
  1249. // @router /contract/register/import [post]
  1250. func (rg *RegisterController) Import(c *gin.Context) {
  1251. //h, err := c.FormFile("File")
  1252. //if err != nil {
  1253. // resp.FailData("获取文件失败", "Err:"+err.Error(), c)
  1254. // return
  1255. //}
  1256. //ext := path.Ext(h.Filename)
  1257. //if ext != ".xlsx" && ext != ".xls" {
  1258. // resp.Fail("请上传Excel文件", c)
  1259. // return
  1260. //}
  1261. //
  1262. //uploadDir := "static/xls"
  1263. //err = os.MkdirAll(uploadDir, 766)
  1264. //if err != nil {
  1265. // resp.FailData("存储目录创建失败", "Err:"+err.Error(), c)
  1266. // return
  1267. //}
  1268. //uploadPath := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
  1269. //err = c.SaveUploadedFile(h, uploadPath)
  1270. //if err != nil {
  1271. // resp.FailData("保存本地文件失败", "Err:"+err.Error(), c)
  1272. // return
  1273. //}
  1274. //defer func() {
  1275. // _ = os.Remove(uploadPath)
  1276. //}()
  1277. //xlFile, err := xlsx.OpenFile(uploadPath)
  1278. //if err != nil {
  1279. // resp.FailData("打开文件失败", "Err:"+err.Error(), c)
  1280. // return
  1281. //}
  1282. //
  1283. //// 获取所有已登记,根据合同编号去重
  1284. //contractCodeArr := make([]string, 0)
  1285. //registerOB := new(fms.ContractRegister)
  1286. //registerCond := ``
  1287. //registerPars := make([]interface{}, 0)
  1288. //registerList, e := registerOB.List(registerCond, registerPars)
  1289. //if e != nil {
  1290. // resp.FailData("获取合同登记列表失败", "Err:"+e.Error(), c)
  1291. // return
  1292. //}
  1293. //for i := range registerList {
  1294. // contractCodeArr = append(contractCodeArr, registerList[i].ContractCode)
  1295. //}
  1296. //
  1297. //// 获取所有销售名称Map
  1298. //sellerNameIdMap := make(map[string]int)
  1299. //sellerCond := ``
  1300. //sellerPars := make([]interface{}, 0)
  1301. //sellerList, e := crm.GetCompanySellerByRoleCodes(sellerCond, sellerPars)
  1302. //if e != nil {
  1303. // resp.FailData("获取销售列表失败", "Err:"+e.Error(), c)
  1304. // return
  1305. //}
  1306. //for i := range sellerList {
  1307. // sellerNameIdMap[sellerList[i].RealName] = sellerList[i].AdminId
  1308. //}
  1309. //
  1310. //// 获取品种权限Map
  1311. //chartPermissionNameIdMap := make(map[string]int)
  1312. //cpCond := `product_id = ?`
  1313. //cpPars := make([]interface{}, 0)
  1314. //cpPars = append(cpPars, crm.CompanyProductFicc)
  1315. //cp := new(crm.ChartPermission)
  1316. //permissionList, e := cp.List(cpCond, cpPars)
  1317. //if e != nil {
  1318. // resp.FailData("获取权限列表失败", "Err:"+e.Error(), c)
  1319. // return
  1320. //}
  1321. //for i := range permissionList {
  1322. // chartPermissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  1323. //}
  1324. //
  1325. //// TODO:获取所有套餐
  1326. //
  1327. //titleMap := make(map[int]string)
  1328. //for _, sheet := range xlFile.Sheets {
  1329. // // 遍历行读取
  1330. // maxRow := sheet.MaxRow
  1331. // for i := 0; i < maxRow; i++ {
  1332. // // 第二行开始读取表头
  1333. // if i == 1 {
  1334. // row := sheet.Row(i)
  1335. // cells := row.Cells
  1336. // for k, cell := range cells {
  1337. // text := cell.String()
  1338. // titleMap[k] = text
  1339. // // 只检验前面部分表头
  1340. // if k == 0 {
  1341. // if text != "客户名称" {
  1342. // resp.Fail("匹配失败, 请按模板导入", c)
  1343. // return
  1344. // }
  1345. // }
  1346. // if k == 1 {
  1347. // if !strings.Contains(text, "续约") {
  1348. // resp.Fail("匹配失败, 请按模板导入", c)
  1349. // return
  1350. // }
  1351. // }
  1352. // if k == 2 {
  1353. // if text != "销售" {
  1354. // resp.Fail("匹配失败, 请按模板导入", c)
  1355. // return
  1356. // }
  1357. // }
  1358. // if k == 3 {
  1359. // if text != "FICC大套餐" {
  1360. // resp.Fail("匹配失败, 请按模板导入", c)
  1361. // return
  1362. // }
  1363. // }
  1364. // }
  1365. // }
  1366. // // 数据行
  1367. // if i >= 2 {
  1368. // row := sheet.Row(i)
  1369. // cells := row.Cells
  1370. // var userName, countryCode, mobile, companyName string
  1371. // for k, cell := range cells {
  1372. // if k == 0 {
  1373. // userName = utils.TrimStr(cell.String())
  1374. // }
  1375. // if k == 1 {
  1376. // countryCode = utils.TrimStr(cell.String())
  1377. // }
  1378. // if k == 2 {
  1379. // mobile = utils.TrimStr(cell.String())
  1380. // }
  1381. // if k == 3 {
  1382. // companyName = utils.TrimStr(cell.String())
  1383. // }
  1384. // }
  1385. //
  1386. // // TODO:新增登记
  1387. //
  1388. // // TODO:新增套餐
  1389. //
  1390. // // TODO:新增开票/到款信息
  1391. // }
  1392. // }
  1393. //}
  1394. resp.Ok("操作成功", c)
  1395. }