register.go 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000
  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. "hongze/fms_api/services/alarm_msg"
  17. fmsService "hongze/fms_api/services/fms"
  18. "hongze/fms_api/utils"
  19. "net/http"
  20. "os"
  21. "path"
  22. "strconv"
  23. "strings"
  24. "time"
  25. )
  26. // RegisterController 合同登记
  27. type RegisterController struct{}
  28. // List
  29. // @Title 合同登记列表
  30. // @Description 合同登记列表
  31. // @Param Keyword query string false "关键词"
  32. // @Param StartDate query string false "合同开始日期"
  33. // @Param EndDate query string false "合同结束日期"
  34. // @Param ServiceType query int false "套餐类型"
  35. // @Param ContractType query int false "合同类型"
  36. // @Param RegisterStatus query int false "登记状态"
  37. // @Success 200 {object} fms.ContractRegisterItem
  38. // @router /contract/register/list [get]
  39. func (rg *RegisterController) List(c *gin.Context) {
  40. var req fms.ContractRegisterListReq
  41. if e := c.BindQuery(&req); e != nil {
  42. err, ok := e.(validator.ValidationErrors)
  43. if !ok {
  44. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  45. return
  46. }
  47. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  48. return
  49. }
  50. cond := `1 = 1`
  51. pars := make([]interface{}, 0)
  52. // 合同编号/客户姓名/销售/实际使用方
  53. if req.Keyword != "" {
  54. kw := "%" + req.Keyword + "%"
  55. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
  56. pars = append(pars, kw, kw, kw, kw)
  57. }
  58. if req.StartDate != "" && req.EndDate != "" {
  59. st := fmt.Sprint(req.StartDate, " 00:00:00")
  60. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  61. cond += ` AND (create_time BETWEEN ? AND ?)`
  62. pars = append(pars, st, ed)
  63. }
  64. if req.ContractType != 0 {
  65. cond += ` AND contract_type = ?`
  66. pars = append(pars, req.ContractType)
  67. }
  68. if req.RegisterStatus != 0 {
  69. cond += ` AND register_status = ?`
  70. pars = append(pars, req.RegisterStatus)
  71. }
  72. // 套餐筛选
  73. if req.ServiceType != 0 {
  74. registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
  75. if e != nil {
  76. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  77. return
  78. }
  79. if len(registerIds) > 0 {
  80. cond += ` AND contract_register_id IN ?`
  81. pars = append(pars, registerIds)
  82. } else {
  83. cond += ` AND 1 = 2`
  84. }
  85. }
  86. page := new(base.Page)
  87. page.SetPageSize(req.PageSize)
  88. page.SetCurrent(req.Current)
  89. page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: false})
  90. total, list, e := fms.GetContractRegisterItemPageList(page, cond, pars)
  91. if e != nil {
  92. resp.FailMsg("获取失败", "获取合同登记列表失败, Err: "+e.Error(), c)
  93. return
  94. }
  95. registerIds := make([]int, 0)
  96. for i := range list {
  97. registerIds = append(registerIds, list[i].ContractRegisterId)
  98. }
  99. serviceMap := make(map[int]string, 0)
  100. invoiceMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  101. paymentMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  102. if len(registerIds) > 0 {
  103. // 获取服务套餐
  104. servicesNameList, e := fms.GetContractRegisterServicesNameByRegisterIds(registerIds)
  105. if e != nil {
  106. resp.FailMsg("获取失败", "获取套餐拼接字符串失败, Err: "+e.Error(), c)
  107. return
  108. }
  109. for i := range servicesNameList {
  110. serviceMap[servicesNameList[i].ContractRegisterId] = servicesNameList[i].ServicesName
  111. }
  112. // 获取开票/到款列表
  113. invoiceCond := `contract_register_id IN ?`
  114. invoicePars := make([]interface{}, 0)
  115. invoicePars = append(invoicePars, registerIds)
  116. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  117. if e != nil {
  118. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  119. return
  120. }
  121. for i := range invoiceList {
  122. if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  123. invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  124. }
  125. if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  126. paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  127. }
  128. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  129. invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  130. }
  131. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  132. paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  133. }
  134. }
  135. }
  136. respList := make([]*fms.ContractRegisterList, 0)
  137. for i := range list {
  138. v := new(fms.ContractRegisterList)
  139. v.ContractRegisterItem = list[i]
  140. v.ServicesName = serviceMap[list[i].ContractRegisterId]
  141. v.InvoiceList = invoiceMap[list[i].ContractRegisterId]
  142. v.PaymentList = paymentMap[list[i].ContractRegisterId]
  143. respList = append(respList, v)
  144. }
  145. page.SetTotal(total)
  146. baseData := new(base.BaseData)
  147. baseData.SetPage(page)
  148. baseData.SetList(respList)
  149. resp.OkData("获取成功", baseData, c)
  150. }
  151. // Add
  152. // @Title 新增合同登记
  153. // @Description 新增合同登记
  154. // @Param request body fms.ContractRegisterAddReq true "type json string"
  155. // @Success 200 string "操作成功"
  156. // @router /contract/register/add [post]
  157. func (rg *RegisterController) Add(c *gin.Context) {
  158. req := new(fms.ContractRegisterAddReq)
  159. err := c.ShouldBind(&req)
  160. if err != nil {
  161. errs, ok := err.(validator.ValidationErrors)
  162. if !ok {
  163. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  164. return
  165. }
  166. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  167. return
  168. }
  169. claims, _ := c.Get("adminInfo")
  170. adminInfo := claims.(*system.SysAdmin)
  171. // 日期校验
  172. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  173. if e != nil {
  174. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  175. return
  176. }
  177. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  178. if e != nil {
  179. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  180. return
  181. }
  182. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  183. if req.SignDate != "" {
  184. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  185. if e != nil {
  186. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  187. return
  188. }
  189. signDate = signDateTime
  190. }
  191. // 是否存在相同合同编号的登记
  192. ob := new(fms.ContractRegister)
  193. existCond := `contract_code = ?`
  194. existPars := make([]interface{}, 0)
  195. existPars = append(existPars, req.ContractCode)
  196. exist, e := ob.FetchByCondition(existCond, existPars)
  197. if e != nil && e != utils.ErrNoRow {
  198. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  199. return
  200. }
  201. if exist != nil && exist.ContractRegisterId > 0 {
  202. resp.Fail("合同编号已存在", c)
  203. return
  204. }
  205. nowTime := time.Now().Local()
  206. ob.ContractCode = req.ContractCode
  207. ob.RelateContractCode = req.RelateContractCode
  208. ob.CrmContractId = req.CrmContractId
  209. ob.ContractSource = req.ContractSource
  210. ob.CompanyName = req.CompanyName
  211. ob.ActualCompanyName = req.ActualCompanyName
  212. ob.ProductId = req.ProductId
  213. ob.SellerId = req.SellerId
  214. ob.SellerName = req.SellerName
  215. ob.ContractType = req.ContractType
  216. ob.ContractAmount = req.ContractAmount
  217. ob.StartDate = startDate
  218. ob.EndDate = endDate
  219. ob.SignDate = signDate
  220. ob.AgreedPayTime = req.AgreedPayTime
  221. ob.ContractStatus = req.ContractStatus
  222. ob.RegisterStatus = fms.ContractRegisterStatusIng
  223. ob.Remark = req.Remark
  224. ob.ServiceRemark = req.ServiceRemark
  225. ob.HasPayment = req.HasPayment
  226. ob.NewCompany = req.NewCompany
  227. ob.Set()
  228. // 存在代付的直接完成登记, 且不允许进行开票/到款登记
  229. if req.HasPayment == 1 {
  230. ob.RegisterStatus = fms.ContractRegisterStatusComplete
  231. }
  232. // 套餐信息
  233. serviceList, e := fmsService.HandleContractServiceAndDetail(req.ProductId, req.Services, true)
  234. if e != nil {
  235. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  236. return
  237. }
  238. // 新增合同及套餐
  239. if e = fms.CreateContractRegisterAndServices(ob, serviceList); e != nil {
  240. resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
  241. return
  242. }
  243. // 操作日志
  244. go func() {
  245. opData := ""
  246. opDataByte, e := json.Marshal(req)
  247. if e != nil {
  248. return
  249. }
  250. opData = string(opDataByte)
  251. logItem := new(fms.ContractRegisterLog)
  252. logItem.ContractRegisterId = ob.ContractRegisterId
  253. logItem.AdminId = int(adminInfo.AdminId)
  254. logItem.AdminName = adminInfo.RealName
  255. logItem.OpData = opData
  256. logItem.OpType = fms.ContractRegisterOpTypeSave
  257. logItem.CreateTime = nowTime
  258. logItem.Remark = req.Remark
  259. if e = logItem.Create(); e != nil {
  260. return
  261. }
  262. }()
  263. resp.Ok("操作成功", c)
  264. }
  265. // Edit
  266. // @Title 编辑合同登记
  267. // @Description 编辑合同登记
  268. // @Param request body fms.ContractRegisterEditReq true "type json string"
  269. // @Success 200 string "操作成功"
  270. // @router /contract/register/edit [post]
  271. func (rg *RegisterController) Edit(c *gin.Context) {
  272. req := new(fms.ContractRegisterEditReq)
  273. err := c.ShouldBind(&req)
  274. if err != nil {
  275. errs, ok := err.(validator.ValidationErrors)
  276. if !ok {
  277. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  278. return
  279. }
  280. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  281. return
  282. }
  283. claims, _ := c.Get("adminInfo")
  284. adminInfo := claims.(*system.SysAdmin)
  285. // 日期校验
  286. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  287. if e != nil {
  288. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  289. return
  290. }
  291. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  292. if e != nil {
  293. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  294. return
  295. }
  296. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  297. if req.SignDate != "" {
  298. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  299. if e != nil {
  300. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  301. return
  302. }
  303. signDate = signDateTime
  304. }
  305. ob := new(fms.ContractRegister)
  306. item, e := ob.Fetch(req.ContractRegisterId)
  307. if e != nil {
  308. if e == utils.ErrNoRow {
  309. resp.Fail("登记记录不存在或已被删除", c)
  310. return
  311. }
  312. resp.FailMsg("操作失败", "获取合同登记信息失败, Err:"+e.Error(), c)
  313. return
  314. }
  315. // 是否存在相同合同编号的登记
  316. existCond := `contract_code = ?`
  317. existPars := make([]interface{}, 0)
  318. existPars = append(existPars, req.ContractCode)
  319. exist, e := ob.FetchByCondition(existCond, existPars)
  320. if e != nil && e != utils.ErrNoRow {
  321. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  322. return
  323. }
  324. if exist != nil && exist.ContractRegisterId > 0 && exist.ContractRegisterId != item.ContractRegisterId {
  325. resp.Fail("合同编号已存在", c)
  326. return
  327. }
  328. originHasPayment := item.HasPayment
  329. updateCols := []string{
  330. "ContractCode", "RelateContractCode", "CrmContractId", "ContractSource", "CompanyName", "ActualCompanyName",
  331. "SellerId", "SellerName", "ContractType", "ContractAmount", "StartDate", "EndDate", "SignDate", "AgreedPayTime",
  332. "ContractStatus", "RegisterStatus", "Remark", "ServiceRemark", "HasPayment", "NewCompany", "ModifyTime",
  333. }
  334. nowTime := time.Now().Local()
  335. item.ContractCode = req.ContractCode
  336. item.RelateContractCode = req.RelateContractCode
  337. item.CrmContractId = req.CrmContractId
  338. item.ContractSource = req.ContractSource
  339. item.CompanyName = req.CompanyName
  340. item.ActualCompanyName = req.ActualCompanyName
  341. item.SellerId = req.SellerId
  342. item.SellerName = req.SellerName
  343. item.ContractType = req.ContractType
  344. item.ContractAmount = req.ContractAmount
  345. item.StartDate = startDate
  346. item.EndDate = endDate
  347. item.SignDate = signDate
  348. item.AgreedPayTime = req.AgreedPayTime
  349. item.ContractStatus = req.ContractStatus
  350. item.RegisterStatus = fms.ContractRegisterStatusIng
  351. item.Remark = req.Remark
  352. item.ServiceRemark = req.ServiceRemark
  353. item.HasPayment = req.HasPayment
  354. item.NewCompany = req.NewCompany
  355. item.ModifyTime = nowTime
  356. // 存在代付的直接完成登记, 且不允许进行开票/到款登记
  357. if req.HasPayment == 1 {
  358. item.RegisterStatus = fms.ContractRegisterStatusComplete
  359. updateCols = append(updateCols, "RegisterStatus")
  360. }
  361. // 套餐信息
  362. serviceList, e := fmsService.HandleContractServiceAndDetail(req.ProductId, req.Services, true)
  363. if e != nil {
  364. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  365. return
  366. }
  367. // 更新合同及套餐
  368. if e = fms.UpdateContractRegisterAndServices(item, updateCols, serviceList); e != nil {
  369. resp.FailMsg("操作失败", "更新合同及套餐失败, Err: "+e.Error(), c)
  370. return
  371. }
  372. // 若从无代付修改为有代付, 则删除无代付期间新增的所有开票/到款登记(此情况并不经常出现, 但是可能会存在这种操作)
  373. if originHasPayment == 0 && req.HasPayment == 1 {
  374. go func() {
  375. if e = fms.DeleteContractInvoicesByRegisterId(item.ContractRegisterId); e != nil {
  376. alarm_msg.SendAlarmMsg("无代付修改为有代付, 删除开票到款记录失败, ErrMsg: "+err.Error(), 3)
  377. }
  378. }()
  379. }
  380. // 校验金额-是否修改状态
  381. go fmsService.CheckContractRegisterAmount(item.ContractRegisterId)
  382. // 操作日志
  383. go func() {
  384. opData := ""
  385. opDataByte, e := json.Marshal(req)
  386. if e != nil {
  387. return
  388. }
  389. opData = string(opDataByte)
  390. logItem := new(fms.ContractRegisterLog)
  391. logItem.ContractRegisterId = item.ContractRegisterId
  392. logItem.AdminId = int(adminInfo.AdminId)
  393. logItem.AdminName = adminInfo.RealName
  394. logItem.OpData = opData
  395. logItem.OpType = fms.ContractRegisterOpTypeEdit
  396. logItem.CreateTime = nowTime
  397. logItem.Remark = req.Remark
  398. if e = logItem.Create(); e != nil {
  399. return
  400. }
  401. }()
  402. resp.Ok("操作成功", c)
  403. }
  404. // Del
  405. // @Title 删除合同登记
  406. // @Description 删除合同登记
  407. // @Param request body fms.ContractRegisterDelReq true "type json string"
  408. // @Success 200 string "操作成功"
  409. // @router /contract/register/del [post]
  410. func (rg *RegisterController) Del(c *gin.Context) {
  411. req := new(fms.ContractRegisterDelReq)
  412. err := c.ShouldBind(&req)
  413. if err != nil {
  414. errs, ok := err.(validator.ValidationErrors)
  415. if !ok {
  416. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  417. return
  418. }
  419. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  420. return
  421. }
  422. claims, _ := c.Get("adminInfo")
  423. adminInfo := claims.(*system.SysAdmin)
  424. ob := new(fms.ContractRegister)
  425. item, e := ob.Fetch(req.ContractRegisterId)
  426. if e != nil {
  427. if e == utils.ErrNoRow {
  428. resp.Fail("合同登记不存在或已被删除", c)
  429. return
  430. }
  431. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  432. return
  433. }
  434. nowTime := time.Now().Local()
  435. item.IsDeleted = 1
  436. item.ModifyTime = nowTime
  437. updateCols := []string{"IsDeleted", "ModifyTime"}
  438. if e = item.Update(updateCols); e != nil {
  439. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  440. return
  441. }
  442. // 删除对应的开票到款登记
  443. go func() {
  444. if e = fms.DeleteContractInvoicesByRegisterId(item.ContractRegisterId); e != nil {
  445. alarm_msg.SendAlarmMsg("删除合同登记后, 删除开票到款记录失败, ErrMsg: "+err.Error(), 3)
  446. }
  447. }()
  448. // 操作日志
  449. go func() {
  450. opData := ""
  451. opDataByte, e := json.Marshal(req)
  452. if e != nil {
  453. return
  454. }
  455. opData = string(opDataByte)
  456. logItem := new(fms.ContractRegisterLog)
  457. logItem.ContractRegisterId = req.ContractRegisterId
  458. logItem.AdminId = int(adminInfo.AdminId)
  459. logItem.AdminName = adminInfo.RealName
  460. logItem.OpData = opData
  461. logItem.OpType = fms.ContractRegisterOpTypeDel
  462. logItem.CreateTime = nowTime
  463. if e = logItem.Create(); e != nil {
  464. return
  465. }
  466. }()
  467. resp.Ok("操作成功", c)
  468. }
  469. // Detail
  470. // @Title 合同登记详情
  471. // @Description 合同登记详情
  472. // @Param ContractRegisterId query int false "合同登记ID"
  473. // @Success 200 {object} fms.ContractRegisterDetail
  474. // @router /contract/register/detail [get]
  475. func (rg *RegisterController) Detail(c *gin.Context) {
  476. var req fms.ContractRegisterDetailReq
  477. if e := c.BindQuery(&req); e != nil {
  478. err, ok := e.(validator.ValidationErrors)
  479. if !ok {
  480. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  481. return
  482. }
  483. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  484. return
  485. }
  486. result := new(fms.ContractRegisterDetail)
  487. // 合同登记信息
  488. item, e := fms.GetContractRegisterItemById(req.ContractRegisterId)
  489. if e != nil {
  490. resp.FailData("获取失败", "获取合同登记详情失败, Err:"+e.Error(), c)
  491. return
  492. }
  493. result.ContractRegisterItem = item
  494. // 套餐信息
  495. serviceList, e := fmsService.GetContractServiceAndDetail(req.ContractRegisterId)
  496. if e != nil {
  497. resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
  498. return
  499. }
  500. result.ServiceList = serviceList
  501. // 开票/到款信息
  502. invoiceCond := `contract_register_id = ?`
  503. invoicePars := make([]interface{}, 0)
  504. invoicePars = append(invoicePars, req.ContractRegisterId)
  505. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  506. if e != nil {
  507. resp.FailData("获取失败", "获取合同开票/到款信息失败, Err: "+e.Error(), c)
  508. return
  509. }
  510. result.InvoiceList = make([]*fms.ContractInvoiceItem, 0)
  511. result.PaymentList = make([]*fms.ContractInvoiceItem, 0)
  512. for i := range invoiceList {
  513. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  514. result.InvoiceList = append(result.InvoiceList, invoiceList[i])
  515. continue
  516. }
  517. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  518. result.PaymentList = append(result.PaymentList, invoiceList[i])
  519. }
  520. }
  521. // 合同登记进度
  522. logCond := `contract_register_id = ?`
  523. logPars := make([]interface{}, 0)
  524. logPars = append(logPars, req.ContractRegisterId)
  525. logList, e := fms.GetContractRegisterLogItemList(logCond, logPars)
  526. if e != nil {
  527. resp.FailData("获取失败", "获取合同登记进度失败, Err: "+e.Error(), c)
  528. return
  529. }
  530. result.Logs = logList
  531. resp.OkData("获取成功", result, c)
  532. }
  533. // UpdateStatus
  534. // @Title 修改合同状态
  535. // @Description 修改合同状态
  536. // @Param request body fms.ContractRegisterUpdateStatusReq true "type json string"
  537. // @Success 200 string "操作成功"
  538. // @router /contract/register/update_status [post]
  539. func (rg *RegisterController) UpdateStatus(c *gin.Context) {
  540. req := new(fms.ContractRegisterUpdateStatusReq)
  541. err := c.ShouldBind(&req)
  542. if err != nil {
  543. errs, ok := err.(validator.ValidationErrors)
  544. if !ok {
  545. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  546. return
  547. }
  548. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  549. return
  550. }
  551. claims, _ := c.Get("adminInfo")
  552. adminInfo := claims.(*system.SysAdmin)
  553. ob := new(fms.ContractRegister)
  554. item, e := ob.Fetch(req.ContractRegisterId)
  555. if e != nil {
  556. if e == utils.ErrNoRow {
  557. resp.Fail("合同登记不存在或已被删除", c)
  558. return
  559. }
  560. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  561. return
  562. }
  563. nowTime := time.Now().Local()
  564. item.ContractStatus = req.ContractStatus
  565. item.ModifyTime = nowTime
  566. updateCols := []string{"ContractStatus", "ModifyTime"}
  567. if e = item.Update(updateCols); e != nil {
  568. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  569. return
  570. }
  571. // 校验金额-是否修改状态
  572. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  573. // 操作日志
  574. go func() {
  575. opData := ""
  576. opDataByte, e := json.Marshal(req)
  577. if e != nil {
  578. return
  579. }
  580. opData = string(opDataByte)
  581. logItem := new(fms.ContractRegisterLog)
  582. logItem.ContractRegisterId = req.ContractRegisterId
  583. logItem.AdminId = int(adminInfo.AdminId)
  584. logItem.AdminName = adminInfo.RealName
  585. logItem.OpData = opData
  586. logItem.OpType = fms.ContractRegisterOpTypeStatus
  587. logItem.CreateTime = nowTime
  588. if e = logItem.Create(); e != nil {
  589. return
  590. }
  591. }()
  592. resp.Ok("操作成功", c)
  593. }
  594. // Invoice
  595. // @Title 开票/到款登记
  596. // @Description 开票/到款登记
  597. // @Param request body fms.ContractInvoiceSaveReq true "type json string"
  598. // @Success 200 string "操作成功"
  599. // @router /contract/register/invoice [post]
  600. func (rg *RegisterController) Invoice(c *gin.Context) {
  601. req := new(fms.ContractInvoiceSaveReq)
  602. err := c.ShouldBind(&req)
  603. if err != nil {
  604. errs, ok := err.(validator.ValidationErrors)
  605. if !ok {
  606. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  607. return
  608. }
  609. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  610. return
  611. }
  612. claims, _ := c.Get("adminInfo")
  613. adminInfo := claims.(*system.SysAdmin)
  614. registerOB := new(fms.ContractRegister)
  615. item, e := registerOB.Fetch(req.ContractRegisterId)
  616. if e != nil {
  617. if e == utils.ErrNoRow {
  618. resp.Fail("合同登记不存在或已被删除", c)
  619. return
  620. }
  621. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  622. return
  623. }
  624. // 合同存在代付不允许开票/到款登记
  625. if item.HasPayment == 1 {
  626. resp.Fail("合同存在代付不允许添加开票/到款登记", c)
  627. return
  628. }
  629. noChangeInvoiceIds := make([]int, 0)
  630. newInvoice := make([]*fms.ContractInvoice, 0)
  631. if len(req.AmountList) > 0 {
  632. for i := range req.AmountList {
  633. if req.AmountList[i].Amount <= 0 {
  634. resp.Fail("登记金额有误", c)
  635. return
  636. }
  637. if req.AmountList[i].InvoiceDate == "" {
  638. resp.Fail("请选择日期", c)
  639. return
  640. }
  641. t, e := time.ParseInLocation(utils.FormatDate, req.AmountList[i].InvoiceDate, time.Local)
  642. if e != nil {
  643. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  644. return
  645. }
  646. if req.AmountList[i].InvoiceId > 0 {
  647. noChangeInvoiceIds = append(noChangeInvoiceIds, req.AmountList[i].InvoiceId)
  648. } else {
  649. v := &fms.ContractInvoice{
  650. ContractRegisterId: req.ContractRegisterId,
  651. ContractCode: item.ContractCode,
  652. Amount: req.AmountList[i].Amount,
  653. InvoiceType: req.InvoiceType,
  654. InvoiceDate: t,
  655. AdminId: int(adminInfo.AdminId),
  656. AdminName: adminInfo.RealName,
  657. Remark: req.AmountList[i].Remark,
  658. }
  659. v.Set()
  660. newInvoice = append(newInvoice, v)
  661. }
  662. }
  663. }
  664. // 获取原有的登记信息
  665. invoiceCond := `contract_register_id = ? AND invoice_type = ?`
  666. invoicePars := make([]interface{}, 0)
  667. invoicePars = append(invoicePars, req.ContractRegisterId, req.InvoiceType)
  668. originInvoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  669. if e != nil {
  670. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  671. return
  672. }
  673. // 比对原有和现有的登记信息
  674. logList := make([]*fms.ContractRegisterLog, 0)
  675. opData := ""
  676. opDataByte, e := json.Marshal(req)
  677. if e != nil {
  678. return
  679. }
  680. opData = string(opDataByte)
  681. opType := fms.ContractRegisterOpTypeInvoice
  682. if req.InvoiceType == fms.ContractInvoiceTypePay {
  683. opType = fms.ContractRegisterOpTypePayment
  684. }
  685. nowTime := time.Now().Local()
  686. // 需要删除的记录
  687. deleteInvoiceIds := make([]int, 0)
  688. for i := range originInvoiceList {
  689. if !utils.InArrayByInt(noChangeInvoiceIds, originInvoiceList[i].ContractInvoiceId) {
  690. deleteInvoiceIds = append(deleteInvoiceIds, originInvoiceList[i].ContractInvoiceId)
  691. logList = append(logList, &fms.ContractRegisterLog{
  692. ContractRegisterId: req.ContractRegisterId,
  693. AdminId: int(adminInfo.AdminId),
  694. AdminName: adminInfo.RealName,
  695. OpData: opData,
  696. OpType: opType,
  697. CreateTime: nowTime,
  698. AmountRemark: fmt.Sprint("删除", fms.ContractInvoiceKeyNameMap[opType], "金额", originInvoiceList[i].Amount, "元"),
  699. })
  700. }
  701. }
  702. // 新增的记录
  703. if len(newInvoice) > 0 {
  704. newAmount := decimal.NewFromFloat(0).Round(2)
  705. for i := range newInvoice {
  706. a := decimal.NewFromFloat(newInvoice[i].Amount).Round(2)
  707. newAmount = newAmount.Add(a)
  708. }
  709. ia, _ := newAmount.Round(2).Float64()
  710. logList = append(logList, &fms.ContractRegisterLog{
  711. ContractRegisterId: req.ContractRegisterId,
  712. AdminId: int(adminInfo.AdminId),
  713. AdminName: adminInfo.RealName,
  714. OpData: opData,
  715. OpType: opType,
  716. CreateTime: nowTime,
  717. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  718. })
  719. }
  720. // 删除并新增登记
  721. ob := new(fms.ContractInvoice)
  722. if e := ob.DeleteAndCreateNewInvoice(req.ContractRegisterId, req.InvoiceType, deleteInvoiceIds, newInvoice); e != nil {
  723. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  724. return
  725. }
  726. // 校验金额-是否修改状态
  727. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  728. // 操作日志
  729. go func() {
  730. logOB := new(fms.ContractRegisterLog)
  731. if e := logOB.AddInBatches(logList); e != nil {
  732. return
  733. }
  734. }()
  735. resp.Ok("操作成功", c)
  736. }
  737. // Export
  738. // @Title 合同登记-导出
  739. // @Description 合同登记-导出
  740. // @Param Keyword query string false "关键词"
  741. // @Param StartDate query string false "合同开始日期"
  742. // @Param EndDate query string false "合同结束日期"
  743. // @Param ServiceType query int false "套餐类型"
  744. // @Param ContractType query int false "合同类型"
  745. // @Param RegisterStatus query int false "登记状态"
  746. // @Success 200 string "操作成功"
  747. // @router /contract/register/export [get]
  748. func (rg *RegisterController) Export(c *gin.Context) {
  749. var req fms.ContractRegisterListReq
  750. if e := c.BindQuery(&req); e != nil {
  751. err, ok := e.(validator.ValidationErrors)
  752. if !ok {
  753. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  754. return
  755. }
  756. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  757. return
  758. }
  759. cond := `1 = 1`
  760. pars := make([]interface{}, 0)
  761. // 合同编号/客户姓名/销售/实际使用方
  762. if req.Keyword != "" {
  763. kw := "%" + req.Keyword + "%"
  764. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
  765. pars = append(pars, kw, kw, kw, kw)
  766. }
  767. if req.StartDate != "" && req.EndDate != "" {
  768. st := fmt.Sprint(req.StartDate, " 00:00:00")
  769. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  770. cond += ` AND (create_time BETWEEN ? AND ?)`
  771. pars = append(pars, st, ed)
  772. }
  773. if req.ContractType != 0 {
  774. cond += ` AND contract_type = ?`
  775. pars = append(pars, req.ContractType)
  776. }
  777. if req.RegisterStatus != 0 {
  778. cond += ` AND register_status = ?`
  779. pars = append(pars, req.RegisterStatus)
  780. }
  781. if req.ServiceType != 0 {
  782. registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
  783. if e != nil {
  784. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  785. return
  786. }
  787. if len(registerIds) > 0 {
  788. cond += ` AND contract_register_id IN ?`
  789. pars = append(pars, registerIds)
  790. } else {
  791. cond += ` AND 1 = 2`
  792. }
  793. }
  794. // 获取列表数据
  795. cr := new(fms.ContractRegister)
  796. list, e := cr.List(cond, pars)
  797. if e != nil {
  798. resp.FailData("获取合同列表失败", "Err:"+e.Error(), c)
  799. return
  800. }
  801. if len(list) == 0 {
  802. resp.Fail("无有效数据可导出", c)
  803. return
  804. }
  805. registerIds := make([]int, 0)
  806. for i := range list {
  807. registerIds = append(registerIds, list[i].ContractRegisterId)
  808. }
  809. // 获取小套餐品种
  810. cpCond := `product_id = ? AND permission_name <> ?`
  811. cpPars := make([]interface{}, 0)
  812. cpPars = append(cpPars, crm.CompanyProductFicc, crm.ChartPermissionStrategyName)
  813. cp := new(crm.ChartPermission)
  814. permissionList, e := cp.List(cpCond, cpPars)
  815. if e != nil {
  816. resp.FailData("获取小套餐品种失败", "Err:"+e.Error(), c)
  817. return
  818. }
  819. permissionLen := len(permissionList)
  820. permissionNameIdMap := make(map[string]int)
  821. for i := range permissionList {
  822. permissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  823. }
  824. // 获取套餐服务
  825. //serviceList, e := fms.GetContractServiceTemplateMapByProductId(crm.CompanyProductFicc)
  826. //if e != nil {
  827. // resp.FailData("获取套餐服务失败", "Err:"+e.Error(), c)
  828. // return
  829. //}
  830. // 套餐/开票/到款列表
  831. serviceMap := make(map[int][]*fms.ContractService)
  832. serviceChartPermissionsMap := make(map[int][]int)
  833. invoiceMap := make(map[int][]*fms.ContractInvoice)
  834. paymentMap := make(map[int][]*fms.ContractInvoice)
  835. maxInvoice := 0
  836. maxPayment := 0
  837. if len(registerIds) > 0 {
  838. // 获取套餐信息
  839. csCond := `contract_register_id IN ?`
  840. csPars := make([]interface{}, 0)
  841. csPars = append(csPars, registerIds)
  842. cs := new(fms.ContractService)
  843. serviceList, e := cs.List(csCond, csPars)
  844. if e != nil {
  845. resp.FailData("获取合同套餐列表失败", "Err:"+e.Error(), c)
  846. return
  847. }
  848. for i := range serviceList {
  849. cid := serviceList[i].ContractRegisterId
  850. if serviceMap[cid] == nil {
  851. serviceMap[cid] = make([]*fms.ContractService, 0)
  852. }
  853. serviceMap[cid] = append(serviceMap[cid], serviceList[i])
  854. // 小套餐权限
  855. if serviceChartPermissionsMap[cid] == nil {
  856. serviceChartPermissionsMap[cid] = make([]int, 0)
  857. }
  858. if serviceList[i].ChartPermissionIds != "" {
  859. ids := utils.JoinStr2IntArr(serviceList[i].ChartPermissionIds, ",")
  860. serviceChartPermissionsMap[cid] = append(serviceChartPermissionsMap[cid], ids...)
  861. }
  862. }
  863. // 获取开票/到款详情, 并取最大的开票/到款数(用于动态扩展第二列表头)
  864. ci := new(fms.ContractInvoice)
  865. invoiceList, e := ci.List(csCond, csPars, "")
  866. if e != nil {
  867. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  868. return
  869. }
  870. for k := range invoiceList {
  871. cid := invoiceList[k].ContractRegisterId
  872. if invoiceMap[cid] == nil {
  873. invoiceMap[cid] = make([]*fms.ContractInvoice, 0)
  874. }
  875. if paymentMap[cid] == nil {
  876. paymentMap[cid] = make([]*fms.ContractInvoice, 0)
  877. }
  878. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypeMake {
  879. invoiceMap[cid] = append(invoiceMap[cid], invoiceList[k])
  880. continue
  881. }
  882. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypePay {
  883. paymentMap[cid] = append(paymentMap[cid], invoiceList[k])
  884. continue
  885. }
  886. }
  887. // 取最大开票/到款数
  888. for j := range invoiceMap {
  889. if len(invoiceMap[j]) > maxInvoice {
  890. maxInvoice = len(invoiceMap[j])
  891. }
  892. }
  893. for p := range paymentMap {
  894. if len(paymentMap[p]) > maxPayment {
  895. maxPayment = len(paymentMap[p])
  896. }
  897. }
  898. }
  899. // 生成Excel文件
  900. //dir, err := os.Executable()
  901. //exPath := filepath.Dir(dir)
  902. //filePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  903. xlsxFile := xlsx.NewFile()
  904. //if err != nil {
  905. // resp.FailData("生成文件失败", "Err:"+err.Error(), c)
  906. // return
  907. //}
  908. style := xlsx.NewStyle()
  909. alignment := xlsx.Alignment{
  910. Horizontal: "center",
  911. Vertical: "center",
  912. WrapText: true,
  913. }
  914. style.Alignment = alignment
  915. style.ApplyAlignment = true
  916. sheet, err := xlsxFile.AddSheet("合同登记")
  917. if err != nil {
  918. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  919. return
  920. }
  921. //_ = sheet.SetColWidth(0, 0, 60)
  922. //_ = sheet.SetColWidth(4, 10, 60)
  923. // 1行表头
  924. titleRow := sheet.AddRow()
  925. titleRow.SetHeight(40)
  926. // 1行1列-右合并两格
  927. cell1 := titleRow.AddCell()
  928. cell1.HMerge = 2
  929. cell1.SetValue("FICC客户签约表 2022")
  930. cell1.SetStyle(style)
  931. // 右增两列空白格用于第一列合并, 否则后续单元格合并会有问题
  932. titleRow.AddCell().SetValue("")
  933. titleRow.AddCell().SetValue("")
  934. // 1行2列
  935. cell2 := titleRow.AddCell()
  936. cell2.SetValue("FICC大套餐")
  937. cell2.SetStyle(style)
  938. // 1行3列-右合并小套餐数
  939. if permissionLen >= 1 {
  940. cell3 := titleRow.AddCell()
  941. cell3.HMerge = permissionLen - 1
  942. cell3.SetValue("FICC小套餐")
  943. cell3.SetStyle(style)
  944. // 同上右增单元格小套餐数-1的空白单元格用于合并
  945. for i := 0; i < permissionLen-1; i++ {
  946. titleRow.AddCell().SetValue("")
  947. }
  948. }
  949. cell4 := titleRow.AddCell()
  950. cell4.SetValue("市场策略")
  951. cell4.SetStyle(style)
  952. cell5 := titleRow.AddCell()
  953. cell5.SetValue("财富管理")
  954. cell5.SetStyle(style)
  955. // 第二行表头
  956. titleRow2 := sheet.AddRow()
  957. titleRow2.SetHeight(60)
  958. row2Title := make([]string, 0)
  959. row2Title = append(row2Title, "客户名称", "续约-0\n新增-1", "销售", "FICC大套餐")
  960. for i := range permissionList {
  961. row2Title = append(row2Title, permissionList[i].PermissionName)
  962. }
  963. row2Title = append(row2Title, "市场策略", "财富管理", "套餐备注", "开始时间", "到期时间", "2022年合同金额", "约定付款时间", "签订日",
  964. "签订月", "合同状态", "合同编号", "备注")
  965. for i := range row2Title {
  966. v := titleRow2.AddCell()
  967. v.SetValue(row2Title[i])
  968. v.SetStyle(style)
  969. }
  970. // 第二行表头-开票/收款(动态添加)
  971. for i := 0; i < maxInvoice; i++ {
  972. n := i + 1
  973. c1 := titleRow2.AddCell()
  974. t1 := fmt.Sprintf("%s%d", "开票日", n)
  975. c1.SetValue(t1)
  976. c1.SetStyle(style)
  977. c2 := titleRow2.AddCell()
  978. t2 := fmt.Sprintf("%s%d", "开票金额", n)
  979. c2.SetValue(t2)
  980. c2.SetStyle(style)
  981. row2Title = append(row2Title, t1, t2)
  982. }
  983. for i := 0; i < maxPayment; i++ {
  984. n := i + 1
  985. c1 := titleRow2.AddCell()
  986. t1 := fmt.Sprintf("%s%d", "收款日", n)
  987. c1.SetValue(t1)
  988. c1.SetStyle(style)
  989. c2 := titleRow2.AddCell()
  990. t2 := fmt.Sprintf("%s%d", "收款金额", n)
  991. c2.SetValue(t2)
  992. c2.SetStyle(style)
  993. row2Title = append(row2Title, t1, t2)
  994. }
  995. // 此处取第二行标题NameKeyMap, 后面的动态匹配
  996. row2NameKeyMap := make(map[string]int)
  997. for i := range row2Title {
  998. row2NameKeyMap[row2Title[i]] = i
  999. }
  1000. contractTMap := map[int]int{
  1001. fms.ContractTypeNew: 1,
  1002. fms.ContractTypeRenew: 0,
  1003. fms.ContractTypeAgentPay: 2, // 代付合同
  1004. fms.ContractTypePlus: 3, // 补充协议
  1005. }
  1006. for _, v := range list {
  1007. k := -1
  1008. dataRow := sheet.AddRow()
  1009. dataRow.SetHeight(20)
  1010. k += 3
  1011. dataRow.AddCell().SetString(v.CompanyName)
  1012. dataRow.AddCell().SetString(fmt.Sprint(contractTMap[v.ContractType]))
  1013. dataRow.AddCell().SetString(v.SellerName)
  1014. // 大套餐
  1015. k += 1
  1016. col4Name := row2Title[k]
  1017. svList := serviceMap[v.ContractRegisterId]
  1018. col4 := ""
  1019. if svList != nil && len(svList) > 0 {
  1020. for isv := range svList {
  1021. if svList[isv].Title == col4Name {
  1022. col4 = "是"
  1023. break
  1024. }
  1025. }
  1026. }
  1027. dataRow.AddCell().SetString(col4)
  1028. // 小套餐
  1029. serviceChartPermissionIds := serviceChartPermissionsMap[v.ContractRegisterId]
  1030. for i := 0; i < permissionLen; i++ {
  1031. k += 1
  1032. colName := row2Title[k]
  1033. chartPermissionId := permissionNameIdMap[colName]
  1034. if utils.InArray(chartPermissionId, serviceChartPermissionIds) {
  1035. dataRow.AddCell().SetString("是")
  1036. } else {
  1037. dataRow.AddCell().SetString("")
  1038. }
  1039. }
  1040. // 财富管理/市场策略(处理方式其实跟上面的大套餐一样, 只是中间隔了小套餐按照顺序要这么处理=_=!)
  1041. k += 1
  1042. col5Name := row2Title[k]
  1043. col5 := ""
  1044. if svList != nil && len(svList) > 0 {
  1045. for isv := range svList {
  1046. if svList[isv].Title == col5Name {
  1047. col5 = "是"
  1048. break
  1049. }
  1050. }
  1051. }
  1052. dataRow.AddCell().SetString(col5)
  1053. k += 1
  1054. col6Name := row2Title[k]
  1055. col6 := ""
  1056. if svList != nil && len(svList) > 0 {
  1057. for isv := range svList {
  1058. if svList[isv].Title == col6Name {
  1059. col6 = "是"
  1060. break
  1061. }
  1062. }
  1063. }
  1064. dataRow.AddCell().SetString(col6)
  1065. // 其他信息
  1066. dataRow.AddCell().SetString(v.ServiceRemark) // 套餐备注
  1067. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.StartDate)) // 开始时间
  1068. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.EndDate)) // 到期时间
  1069. dataRow.AddCell().SetString(fmt.Sprint("¥", v.ContractAmount)) // 2022年合同金额
  1070. dataRow.AddCell().SetString(v.AgreedPayTime) // 约定付款时间
  1071. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.SignDate)) // 签订日
  1072. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01", v.SignDate)) // 签订月
  1073. dataRow.AddCell().SetString(fms.ContractStatusKeyNameMap[v.ContractStatus]) // 合同状态
  1074. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  1075. dataRow.AddCell().SetString(v.Remark) // 备注
  1076. // 开票/到款信息
  1077. ivList := invoiceMap[v.ContractRegisterId]
  1078. ivListLen := len(ivList)
  1079. if ivList != nil && len(ivList) > 0 {
  1080. for ia := 0; ia < maxInvoice; ia++ {
  1081. if ia < ivListLen {
  1082. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", ivList[ia].InvoiceDate)) // 开票日
  1083. dataRow.AddCell().SetString(fmt.Sprint(ivList[ia].Amount)) // 开票金额
  1084. } else {
  1085. // 这里要把不够的填充为空
  1086. dataRow.AddCell().SetString("")
  1087. dataRow.AddCell().SetString("")
  1088. }
  1089. }
  1090. }
  1091. pyList := paymentMap[v.ContractRegisterId]
  1092. pyListLen := len(pyList)
  1093. if pyList != nil && pyListLen > 0 {
  1094. for ib := 0; ib < maxInvoice; ib++ {
  1095. if ib < pyListLen {
  1096. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", pyList[ib].InvoiceDate)) // 收款日
  1097. dataRow.AddCell().SetString(fmt.Sprint(pyList[ib].Amount)) // 收款金额
  1098. } else {
  1099. // 已经是最后的几列了其实可以不用填充空, 万一后面要加列此处还是填充上吧
  1100. dataRow.AddCell().SetString("")
  1101. dataRow.AddCell().SetString("")
  1102. }
  1103. }
  1104. }
  1105. }
  1106. // 输出文件
  1107. var buffer bytes.Buffer
  1108. _ = xlsxFile.Write(&buffer)
  1109. content := bytes.NewReader(buffer.Bytes())
  1110. //err = xlsxFile.Save(filePath)
  1111. //if err != nil {
  1112. // resp.FailData("保存文件失败", "Err:"+err.Error(), c)
  1113. // return
  1114. //}
  1115. //defer func() {
  1116. // _ = os.Remove(filePath)
  1117. //}()
  1118. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1119. fileName := "财务列表_" + randStr + ".xlsx"
  1120. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1121. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1122. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1123. }
  1124. // InvoiceList
  1125. // @Title 开票/到款列表
  1126. // @Description 开票/到款列表
  1127. // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
  1128. // @Param ContractCode query string false "合同编号"
  1129. // @Param StartDate query string false "开始日期"
  1130. // @Param EndDate query string false "结束日期"
  1131. // @Param MinAmount query float64 false "开票金额区间-最小值"
  1132. // @Param MaxAmount query float64 false "开票金额区间-最大值"
  1133. // @Success 200 {object} fms.ContractInvoiceItem
  1134. // @router /contract/register/invoice_list [get]
  1135. func (rg *RegisterController) InvoiceList(c *gin.Context) {
  1136. var req fms.ContractInvoiceListReq
  1137. if e := c.BindQuery(&req); e != nil {
  1138. err, ok := e.(validator.ValidationErrors)
  1139. if !ok {
  1140. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1141. return
  1142. }
  1143. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1144. return
  1145. }
  1146. cond := `invoice_type = ?`
  1147. pars := make([]interface{}, 0)
  1148. pars = append(pars, req.InvoiceType)
  1149. // 合同编号
  1150. if req.ContractCode != "" {
  1151. kw := fmt.Sprint("%", req.ContractCode, "%")
  1152. cond += ` AND contract_code LIKE ?`
  1153. pars = append(pars, kw)
  1154. }
  1155. if req.StartDate != "" && req.EndDate != "" {
  1156. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1157. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1158. cond += ` AND (invoice_time BETWEEN ? AND ?)`
  1159. pars = append(pars, st, ed)
  1160. }
  1161. if req.MinAmount > 0 {
  1162. cond += ` AND amount >= ?`
  1163. pars = append(pars, req.MinAmount)
  1164. }
  1165. if req.MaxAmount > 0 {
  1166. cond += ` AND amount <= ?`
  1167. pars = append(pars, req.MaxAmount)
  1168. }
  1169. page := new(base.Page)
  1170. page.SetPageSize(req.PageSize)
  1171. page.SetCurrent(req.Current)
  1172. page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: false})
  1173. total, list, e := fms.GetContractInvoiceItemPageList(page, cond, pars)
  1174. if e != nil {
  1175. resp.FailMsg("获取失败", "获取合同开票/到款列表失败, Err: "+e.Error(), c)
  1176. return
  1177. }
  1178. page.SetTotal(total)
  1179. baseData := new(base.BaseData)
  1180. baseData.SetPage(page)
  1181. baseData.SetList(list)
  1182. resp.OkData("获取成功", baseData, c)
  1183. }
  1184. // InvoiceExport
  1185. // @Title 开票/到款列表-导出
  1186. // @Description 合同登记-导出
  1187. // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
  1188. // @Param ContractCode query string false "合同编号"
  1189. // @Param StartDate query string false "开始日期"
  1190. // @Param EndDate query string false "结束日期"
  1191. // @Param MinAmount query float64 false "开票金额区间-最小值"
  1192. // @Param MaxAmount query float64 false "开票金额区间-最大值"
  1193. // @Success 200 string "操作成功"
  1194. // @router /contract/register/invoice_export [get]
  1195. func (rg *RegisterController) InvoiceExport(c *gin.Context) {
  1196. var req fms.ContractInvoiceListReq
  1197. if e := c.BindQuery(&req); e != nil {
  1198. err, ok := e.(validator.ValidationErrors)
  1199. if !ok {
  1200. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1201. return
  1202. }
  1203. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1204. return
  1205. }
  1206. cond := `invoice_type = ?`
  1207. pars := make([]interface{}, 0)
  1208. pars = append(pars, req.InvoiceType)
  1209. // 合同编号
  1210. if req.ContractCode != "" {
  1211. kw := fmt.Sprint("%", req.ContractCode, "%")
  1212. cond += ` AND contract_code LIKE ?`
  1213. pars = append(pars, kw)
  1214. }
  1215. if req.StartDate != "" && req.EndDate != "" {
  1216. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1217. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1218. cond += ` AND (invoice_time BETWEEN ? AND ?)`
  1219. pars = append(pars, st, ed)
  1220. }
  1221. if req.MinAmount > 0 {
  1222. cond += ` AND amount >= ?`
  1223. pars = append(pars, req.MinAmount)
  1224. }
  1225. if req.MaxAmount > 0 {
  1226. cond += ` AND amount <= ?`
  1227. pars = append(pars, req.MaxAmount)
  1228. }
  1229. // 获取列表数据
  1230. cr := new(fms.ContractInvoice)
  1231. orderRule := `invoice_time DESC`
  1232. list, e := cr.List(cond, pars, orderRule)
  1233. if e != nil {
  1234. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  1235. return
  1236. }
  1237. if len(list) == 0 {
  1238. resp.Fail("无有效数据可导出", c)
  1239. return
  1240. }
  1241. // 生成Excel文件
  1242. xlsxFile := xlsx.NewFile()
  1243. style := xlsx.NewStyle()
  1244. alignment := xlsx.Alignment{
  1245. Horizontal: "center",
  1246. Vertical: "center",
  1247. WrapText: true,
  1248. }
  1249. style.Alignment = alignment
  1250. style.ApplyAlignment = true
  1251. sheet, err := xlsxFile.AddSheet("开票列表")
  1252. if err != nil {
  1253. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1254. return
  1255. }
  1256. // 表头
  1257. titleRow := sheet.AddRow()
  1258. titleRow.SetHeight(40)
  1259. cell1 := titleRow.AddCell()
  1260. cell1.SetValue("合同编号")
  1261. cell1.SetStyle(style)
  1262. cell2 := titleRow.AddCell()
  1263. cell2.SetValue("开票金额")
  1264. cell2.SetStyle(style)
  1265. cell3 := titleRow.AddCell()
  1266. cell3.SetValue("开票日期")
  1267. cell3.SetStyle(style)
  1268. for _, v := range list {
  1269. dataRow := sheet.AddRow()
  1270. dataRow.SetHeight(20)
  1271. dataRow.AddCell().SetString(v.ContractCode)
  1272. dataRow.AddCell().SetString(fmt.Sprint(v.Amount))
  1273. dataRow.AddCell().SetString(utils.TimeTransferString("2006-01-02", v.InvoiceDate))
  1274. }
  1275. // 输出文件
  1276. var buffer bytes.Buffer
  1277. _ = xlsxFile.Write(&buffer)
  1278. content := bytes.NewReader(buffer.Bytes())
  1279. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1280. fileName := "开票列表_" + randStr + ".xlsx"
  1281. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1282. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1283. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1284. }
  1285. // Import
  1286. // @Title 合同登记-导入
  1287. // @Description 合同登记-导入
  1288. // @Success 200 string "操作成功"
  1289. // @router /contract/register/import [post]
  1290. func (rg *RegisterController) Import(c *gin.Context) {
  1291. h, err := c.FormFile("File")
  1292. if err != nil {
  1293. resp.FailData("获取文件失败", "Err:"+err.Error(), c)
  1294. return
  1295. }
  1296. ext := path.Ext(h.Filename)
  1297. if ext != ".xlsx" && ext != ".xls" {
  1298. resp.Fail("请上传Excel文件", c)
  1299. return
  1300. }
  1301. uploadDir := "static/xls"
  1302. err = os.MkdirAll(uploadDir, 766)
  1303. if err != nil {
  1304. resp.FailData("存储目录创建失败", "Err:"+err.Error(), c)
  1305. return
  1306. }
  1307. uploadPath := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
  1308. err = c.SaveUploadedFile(h, uploadPath)
  1309. if err != nil {
  1310. resp.FailData("保存本地文件失败", "Err:"+err.Error(), c)
  1311. return
  1312. }
  1313. defer func() {
  1314. _ = os.Remove(uploadPath)
  1315. }()
  1316. xlFile, err := xlsx.OpenFile(uploadPath)
  1317. if err != nil {
  1318. resp.FailData("打开文件失败", "Err:"+err.Error(), c)
  1319. return
  1320. }
  1321. // 获取所有已登记,根据合同编号去重
  1322. contractCodeArr := make([]string, 0)
  1323. registerOB := new(fms.ContractRegister)
  1324. registerCond := ``
  1325. registerPars := make([]interface{}, 0)
  1326. registerList, e := registerOB.List(registerCond, registerPars)
  1327. if e != nil {
  1328. resp.FailData("获取合同登记列表失败", "Err:"+e.Error(), c)
  1329. return
  1330. }
  1331. for i := range registerList {
  1332. contractCodeArr = append(contractCodeArr, registerList[i].ContractCode)
  1333. }
  1334. // 获取所有销售名称Map
  1335. sellerNameIdMap := make(map[string]int)
  1336. sellerCond := ``
  1337. sellerPars := make([]interface{}, 0)
  1338. sellerList, e := crm.GetCompanySellerByRoleCodes(sellerCond, sellerPars)
  1339. if e != nil {
  1340. resp.FailData("获取销售列表失败", "Err:"+e.Error(), c)
  1341. return
  1342. }
  1343. for i := range sellerList {
  1344. sellerNameIdMap[sellerList[i].RealName] = sellerList[i].AdminId
  1345. }
  1346. // 获取品种权限Map
  1347. chartPermissionNameIdMap := make(map[string]int)
  1348. cpCond := `product_id = ?`
  1349. cpPars := make([]interface{}, 0)
  1350. cpPars = append(cpPars, crm.CompanyProductFicc)
  1351. cp := new(crm.ChartPermission)
  1352. permissionList, e := cp.List(cpCond, cpPars)
  1353. if e != nil {
  1354. resp.FailData("获取权限列表失败", "Err:"+e.Error(), c)
  1355. return
  1356. }
  1357. for i := range permissionList {
  1358. chartPermissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  1359. }
  1360. // 获取所有套餐模板
  1361. serviceTempCond := ``
  1362. serviceTempPars := make([]interface{}, 0)
  1363. serviceTempOB := new(fms.ContractServiceTemplate)
  1364. serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
  1365. if e != nil {
  1366. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  1367. return
  1368. }
  1369. serviceTempNameMap := make(map[string]*fms.ContractServiceTemplate)
  1370. for i := range serviceTempList {
  1371. serviceTempNameMap[serviceTempList[i].Title] = serviceTempList[i]
  1372. }
  1373. titleMap := make(map[int]string)
  1374. newIds := make([]int, 0)
  1375. contractTypeArr := []string{"0", "1", "2", "3"}
  1376. contractTypeMap := map[string]int{
  1377. "0": fms.ContractTypeRenew,
  1378. "1": fms.ContractTypeNew,
  1379. "2": fms.ContractTypeAgentPay,
  1380. "3": fms.ContractTypePlus,
  1381. }
  1382. checkDate := time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local)
  1383. for _, sheet := range xlFile.Sheets {
  1384. // 遍历行读取
  1385. maxRow := sheet.MaxRow
  1386. for i := 0; i < maxRow; i++ {
  1387. // 第二行开始读取表头
  1388. if i == 1 {
  1389. row := sheet.Row(i)
  1390. cells := row.Cells
  1391. for k, cell := range cells {
  1392. text := cell.String()
  1393. titleMap[k] = text
  1394. // 只检验前面部分表头
  1395. if k == 0 {
  1396. if text != "客户名称" {
  1397. resp.Fail("匹配失败, 请按模板导入", c)
  1398. return
  1399. }
  1400. }
  1401. if k == 1 {
  1402. if !strings.Contains(text, "续约") {
  1403. resp.Fail("匹配失败, 请按模板导入", c)
  1404. return
  1405. }
  1406. }
  1407. if k == 2 {
  1408. if text != "销售" {
  1409. resp.Fail("匹配失败, 请按模板导入", c)
  1410. return
  1411. }
  1412. }
  1413. if k == 3 {
  1414. if text != "FICC大套餐" {
  1415. resp.Fail("匹配失败, 请按模板导入", c)
  1416. return
  1417. }
  1418. }
  1419. }
  1420. }
  1421. // 数据行
  1422. if i >= 2 {
  1423. row := sheet.Row(i)
  1424. cells := row.Cells
  1425. // 登记信息
  1426. rowRegister := new(fms.ContractRegister)
  1427. // 套餐
  1428. rowServices := make([]*fms.ContractService, 0)
  1429. // 开票/到款
  1430. rowInvoices := make([]*fms.ContractInvoice, 0)
  1431. rowChartPermissionIdArr := make([]string, 0)
  1432. rowInvoice1 := new(fms.ContractInvoice)
  1433. rowInvoice2 := new(fms.ContractInvoice)
  1434. rowInvoice3 := new(fms.ContractInvoice)
  1435. rowInvoice4 := new(fms.ContractInvoice)
  1436. rowInvoice5 := new(fms.ContractInvoice)
  1437. rowInvoice6 := new(fms.ContractInvoice)
  1438. isSkip := false
  1439. for k, cell := range cells {
  1440. v := utils.TrimStr(cell.String())
  1441. // 客户名称
  1442. if k == 0 {
  1443. if v == "" {
  1444. resp.Fail(fmt.Sprintf("第%d行客户名称不可为空, 请按模板导入", i+1), c)
  1445. return
  1446. }
  1447. rowRegister.CompanyName = v
  1448. continue
  1449. }
  1450. // 续约/新增
  1451. if k == 1 {
  1452. if !utils.InArrayByStr(contractTypeArr, v) {
  1453. resp.Fail(fmt.Sprintf("第%d行合同类型有误, 请按模板导入", i+1), c)
  1454. return
  1455. }
  1456. rowRegister.ContractType = contractTypeMap[v]
  1457. if rowRegister.ContractType == 0 {
  1458. resp.Fail(fmt.Sprintf("第%d行合同类型匹配有误, 请按模板导入", i+1), c)
  1459. return
  1460. }
  1461. continue
  1462. }
  1463. // 销售
  1464. if k == 2 {
  1465. if v == "" {
  1466. resp.Fail(fmt.Sprintf("第%d行销售名称不可为空, 请按模板导入", i+1), c)
  1467. return
  1468. }
  1469. rowRegister.SellerName = v
  1470. rowRegister.SellerId = sellerNameIdMap[rowRegister.SellerName]
  1471. if rowRegister.SellerId == 0 {
  1472. resp.Fail(fmt.Sprintf("第%d行销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  1473. return
  1474. }
  1475. continue
  1476. }
  1477. // FICC大套餐
  1478. if k == 3 {
  1479. if v == "是" {
  1480. tempItem := serviceTempNameMap[titleMap[k]]
  1481. if tempItem == nil {
  1482. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  1483. return
  1484. }
  1485. cs := &fms.ContractService{
  1486. ProductId: crm.CompanyProductFicc,
  1487. ServiceTemplateId: tempItem.ServiceTemplateId,
  1488. Title: tempItem.Title,
  1489. Value: tempItem.Value,
  1490. TableValue: tempItem.TableValue,
  1491. ChartPermissionId: tempItem.ChartPermissionId,
  1492. }
  1493. cs.Set()
  1494. rowServices = append(rowServices, cs)
  1495. }
  1496. continue
  1497. }
  1498. // FICC小套餐
  1499. if k >= 4 && k <= 23 {
  1500. // 小套餐权限
  1501. if v == "是" {
  1502. rowChartPermissionIdArr = append(rowChartPermissionIdArr, strconv.Itoa(chartPermissionNameIdMap[titleMap[k]]))
  1503. }
  1504. continue
  1505. }
  1506. // 市场策略/财富管理
  1507. if k == 24 || k == 25 {
  1508. if v == "是" {
  1509. tempItem := serviceTempNameMap[titleMap[k]]
  1510. if tempItem == nil {
  1511. resp.Fail(fmt.Sprintf("第%d行市场策略/财富管理套餐名称不匹配, 请按模板导入", i+1), c)
  1512. return
  1513. }
  1514. cs := &fms.ContractService{
  1515. ProductId: crm.CompanyProductFicc,
  1516. ServiceTemplateId: tempItem.ServiceTemplateId,
  1517. Title: tempItem.Title,
  1518. Value: tempItem.Value,
  1519. TableValue: tempItem.TableValue,
  1520. ChartPermissionId: tempItem.ChartPermissionId,
  1521. }
  1522. cs.Set()
  1523. rowServices = append(rowServices, cs)
  1524. }
  1525. continue
  1526. }
  1527. // 套餐备注
  1528. if k == 26 {
  1529. rowRegister.ServiceRemark = v
  1530. continue
  1531. }
  1532. // 开始时间/到期时间
  1533. if k == 27 {
  1534. // 转换失败可能是因为格式为Excel日期格式, 读取出来会是一串数字, 将其转换成日期字符串再处理
  1535. va := cell.Value
  1536. if va == "" {
  1537. resp.Fail(fmt.Sprintf("第%d行开始时间不可为空, 请按模板导入", i+1), c)
  1538. return
  1539. }
  1540. startDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1541. if e != nil {
  1542. d := utils.ConvertToFormatDay(va, "2006/01/02")
  1543. startDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1544. if e != nil {
  1545. resp.Fail(fmt.Sprintf("第%d行开始时间格式转换有误, 请按模板导入", i+1), c)
  1546. return
  1547. }
  1548. }
  1549. // 转换后的日期小于1900-01-01表示当前生成的日期是有问题的
  1550. if startDate.Before(checkDate) {
  1551. resp.Fail(fmt.Sprintf("第%d行开始时间格式有误, 请按模板导入", i+1), c)
  1552. return
  1553. }
  1554. rowRegister.StartDate = startDate
  1555. continue
  1556. }
  1557. if k == 28 {
  1558. va := cell.Value
  1559. if va == "" {
  1560. resp.Fail(fmt.Sprintf("第%d行到期时间不可为空, 请按模板导入", i+1), c)
  1561. return
  1562. }
  1563. endDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1564. if e != nil {
  1565. d := utils.ConvertToFormatDay(va, "2006/01/02")
  1566. endDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1567. if e != nil {
  1568. resp.Fail(fmt.Sprintf("第%d行到期时间格式转换有误, 请按模板导入", i+1), c)
  1569. return
  1570. }
  1571. }
  1572. if endDate.Before(checkDate) {
  1573. resp.Fail(fmt.Sprintf("第%d行到期时间格式有误, 请按模板导入", i+1), c)
  1574. return
  1575. }
  1576. rowRegister.EndDate = endDate
  1577. continue
  1578. }
  1579. // 合同金额
  1580. if k == 29 {
  1581. amountStr := v
  1582. amount, e := strconv.ParseFloat(amountStr, 64)
  1583. if e != nil {
  1584. resp.Fail(fmt.Sprintf("第%d行合同金额有误, 请按模板导入", i+1), c)
  1585. return
  1586. }
  1587. rowRegister.ContractAmount = amount
  1588. continue
  1589. }
  1590. // 约定付款日期
  1591. if k == 30 {
  1592. rowRegister.AgreedPayTime = v
  1593. continue
  1594. }
  1595. // 签订日
  1596. // k == 32为签订月,可忽略
  1597. if k == 31 {
  1598. va := cell.Value
  1599. if va == "" {
  1600. continue
  1601. }
  1602. signDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1603. if e != nil {
  1604. d := utils.ConvertToFormatDay(va, "2006/01/02")
  1605. signDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1606. if e != nil {
  1607. resp.Fail(fmt.Sprintf("第%d行签订日格式转换有误, 请按模板导入", i+1), c)
  1608. return
  1609. }
  1610. }
  1611. if signDate.Before(checkDate) {
  1612. resp.Fail(fmt.Sprintf("第%d行签订日格式有误, 请按模板导入", i+1), c)
  1613. return
  1614. }
  1615. rowRegister.SignDate = signDate
  1616. continue
  1617. }
  1618. // 合同状态
  1619. if k == 33 {
  1620. rowRegister.ContractStatus = fms.ContractStatusNameKeyMap[v]
  1621. if rowRegister.ContractStatus == 0 {
  1622. resp.Fail(fmt.Sprintf("第%d行合同状态不匹配, 请按模板导入", i+1), c)
  1623. return
  1624. }
  1625. continue
  1626. }
  1627. // 合同编号
  1628. if k == 34 {
  1629. rowContractCode := v
  1630. if rowContractCode == "" {
  1631. resp.Fail(fmt.Sprintf("第%d行合同编号不可为空, 请按模板导入", i+1), c)
  1632. return
  1633. }
  1634. if utils.InArrayByStr(contractCodeArr, rowContractCode) {
  1635. // 此合同已登记, 跳过本行的读取
  1636. isSkip = true
  1637. break
  1638. }
  1639. rowRegister.ContractCode = rowContractCode
  1640. continue
  1641. }
  1642. // 备注
  1643. if k == 35 {
  1644. rowRegister.Remark = v
  1645. continue
  1646. }
  1647. // 开票日/开票金额
  1648. if k == 36 {
  1649. if v != "" {
  1650. va := cell.Value
  1651. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1652. if e != nil {
  1653. d := utils.ConvertToFormatDay(va, "2006/01/02")
  1654. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1655. if e != nil {
  1656. resp.Fail(fmt.Sprintf("第%d行开票时间1格式转换有误, 请按模板导入", i+1), c)
  1657. return
  1658. }
  1659. }
  1660. if invoiceDate.Before(checkDate) {
  1661. resp.Fail(fmt.Sprintf("第%d行开票时间1格式有误, 请按模板导入", i+1), c)
  1662. return
  1663. }
  1664. rowInvoice1.InvoiceDate = invoiceDate
  1665. rowInvoice1.ContractCode = rowRegister.ContractCode
  1666. rowInvoice1.InvoiceType = fms.ContractInvoiceTypeMake
  1667. }
  1668. continue
  1669. }
  1670. if k == 37 && v != "" {
  1671. amountStr := v
  1672. amount, e := strconv.ParseFloat(amountStr, 64)
  1673. if e != nil {
  1674. resp.Fail(fmt.Sprintf("第%d行开票金额1有误, 请按模板导入", i+1), c)
  1675. return
  1676. }
  1677. rowInvoice1.Amount = amount
  1678. rowInvoices = append(rowInvoices, rowInvoice1)
  1679. continue
  1680. }
  1681. if k == 38 {
  1682. if v != "" {
  1683. va := cell.Value
  1684. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1685. if e != nil {
  1686. d := utils.ConvertToFormatDay(va, "2006/01/02") //录入日期
  1687. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1688. if e != nil {
  1689. resp.Fail(fmt.Sprintf("第%d行开票时间2格式转换有误, 请按模板导入", i+1), c)
  1690. return
  1691. }
  1692. }
  1693. if invoiceDate.Before(checkDate) {
  1694. resp.Fail(fmt.Sprintf("第%d行开票时间2格式有误, 请按模板导入", i+1), c)
  1695. return
  1696. }
  1697. rowInvoice2.InvoiceDate = invoiceDate
  1698. rowInvoice2.ContractCode = rowRegister.ContractCode
  1699. rowInvoice2.InvoiceType = fms.ContractInvoiceTypeMake
  1700. }
  1701. continue
  1702. }
  1703. if k == 39 && v != "" {
  1704. amountStr := v
  1705. amount, e := strconv.ParseFloat(amountStr, 64)
  1706. if e != nil {
  1707. resp.Fail(fmt.Sprintf("第%d行开票金额2有误, 请按模板导入", i+1), c)
  1708. return
  1709. }
  1710. rowInvoice2.Amount = amount
  1711. rowInvoices = append(rowInvoices, rowInvoice2)
  1712. continue
  1713. }
  1714. if k == 40 {
  1715. if v != "" {
  1716. va := cell.Value
  1717. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1718. if e != nil {
  1719. d := utils.ConvertToFormatDay(va, "2006/01/02") //录入日期
  1720. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1721. if e != nil {
  1722. resp.Fail(fmt.Sprintf("第%d行开票时间3格式转换有误, 请按模板导入", i+1), c)
  1723. return
  1724. }
  1725. }
  1726. if invoiceDate.Before(checkDate) {
  1727. resp.Fail(fmt.Sprintf("第%d行开票时间3格式有误, 请按模板导入", i+1), c)
  1728. return
  1729. }
  1730. rowInvoice3.InvoiceDate = invoiceDate
  1731. rowInvoice3.ContractCode = rowRegister.ContractCode
  1732. rowInvoice3.InvoiceType = fms.ContractInvoiceTypeMake
  1733. }
  1734. continue
  1735. }
  1736. if k == 41 && v != "" {
  1737. amountStr := v
  1738. amount, e := strconv.ParseFloat(amountStr, 64)
  1739. if e != nil {
  1740. resp.Fail(fmt.Sprintf("第%d行开票金额3有误, 请按模板导入", i+1), c)
  1741. return
  1742. }
  1743. rowInvoice3.Amount = amount
  1744. rowInvoices = append(rowInvoices, rowInvoice3)
  1745. continue
  1746. }
  1747. // 收款日/收款金额
  1748. if k == 42 {
  1749. if v != "" {
  1750. va := cell.Value
  1751. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1752. if e != nil {
  1753. d := utils.ConvertToFormatDay(va, "2006/01/02") //录入日期
  1754. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1755. if e != nil {
  1756. resp.Fail(fmt.Sprintf("第%d行收款时间1格式转换有误, 请按模板导入", i+1), c)
  1757. return
  1758. }
  1759. }
  1760. if invoiceDate.Before(checkDate) {
  1761. resp.Fail(fmt.Sprintf("第%d行收款时间1格式有误, 请按模板导入", i+1), c)
  1762. return
  1763. }
  1764. rowInvoice4.InvoiceDate = invoiceDate
  1765. rowInvoice4.ContractCode = rowRegister.ContractCode
  1766. rowInvoice4.InvoiceType = fms.ContractInvoiceTypePay
  1767. }
  1768. continue
  1769. }
  1770. if k == 43 && v != "" {
  1771. amountStr := v
  1772. amount, e := strconv.ParseFloat(amountStr, 64)
  1773. if e != nil {
  1774. resp.Fail(fmt.Sprintf("第%d行收款金额1有误, 请按模板导入", i+1), c)
  1775. return
  1776. }
  1777. rowInvoice4.Amount = amount
  1778. rowInvoices = append(rowInvoices, rowInvoice4)
  1779. continue
  1780. }
  1781. if k == 44 {
  1782. if v != "" {
  1783. va := cell.Value
  1784. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1785. if e != nil {
  1786. d := utils.ConvertToFormatDay(va, "2006/01/02") //录入日期
  1787. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1788. if e != nil {
  1789. resp.Fail(fmt.Sprintf("第%d行收款时间2格式转换有误, 请按模板导入", i+1), c)
  1790. return
  1791. }
  1792. }
  1793. if invoiceDate.Before(checkDate) {
  1794. resp.Fail(fmt.Sprintf("第%d行收款时间2格式有误, 请按模板导入", i+1), c)
  1795. return
  1796. }
  1797. rowInvoice5.InvoiceDate = invoiceDate
  1798. rowInvoice5.ContractCode = rowRegister.ContractCode
  1799. rowInvoice5.InvoiceType = fms.ContractInvoiceTypePay
  1800. }
  1801. continue
  1802. }
  1803. if k == 45 && v != "" {
  1804. amountStr := v
  1805. amount, e := strconv.ParseFloat(amountStr, 64)
  1806. if e != nil {
  1807. resp.Fail(fmt.Sprintf("第%d行收款金额2有误, 请按模板导入", i+1), c)
  1808. return
  1809. }
  1810. rowInvoice5.Amount = amount
  1811. rowInvoices = append(rowInvoices, rowInvoice5)
  1812. continue
  1813. }
  1814. if k == 46 {
  1815. if v != "" {
  1816. va := cell.Value
  1817. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1818. if e != nil {
  1819. d := utils.ConvertToFormatDay(va, "2006/01/02") //录入日期
  1820. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1821. if e != nil {
  1822. resp.Fail(fmt.Sprintf("第%d行收款时间3格式转换有误, 请按模板导入", i+1), c)
  1823. return
  1824. }
  1825. }
  1826. if invoiceDate.Before(checkDate) {
  1827. resp.Fail(fmt.Sprintf("第%d行收款时间3格式有误, 请按模板导入", i+1), c)
  1828. return
  1829. }
  1830. rowInvoice6.InvoiceDate = invoiceDate
  1831. rowInvoice6.ContractCode = rowRegister.ContractCode
  1832. rowInvoice6.InvoiceType = fms.ContractInvoiceTypePay
  1833. }
  1834. continue
  1835. }
  1836. if k == 47 && v != "" {
  1837. amountStr := v
  1838. amount, e := strconv.ParseFloat(amountStr, 64)
  1839. if e != nil {
  1840. resp.Fail(fmt.Sprintf("第%d行收款金额3有误, 请按模板导入", i+1), c)
  1841. return
  1842. }
  1843. rowInvoice6.Amount = amount
  1844. rowInvoices = append(rowInvoices, rowInvoice6)
  1845. continue
  1846. }
  1847. }
  1848. if isSkip {
  1849. continue
  1850. }
  1851. // 小套餐
  1852. if len(rowChartPermissionIdArr) > 0 {
  1853. // 说明有小套餐
  1854. tempItem := serviceTempNameMap["FICC小套餐"]
  1855. if tempItem == nil {
  1856. resp.Fail(fmt.Sprintf("第%d行小套餐名称不匹配, 请按模板导入", i+1), c)
  1857. return
  1858. }
  1859. rowChartPermissionIds := strings.Join(rowChartPermissionIdArr, ",")
  1860. cs := &fms.ContractService{
  1861. ProductId: crm.CompanyProductFicc,
  1862. ServiceTemplateId: tempItem.ServiceTemplateId,
  1863. Title: tempItem.Title,
  1864. Value: tempItem.Value,
  1865. TableValue: tempItem.TableValue,
  1866. ChartPermissionId: tempItem.ChartPermissionId,
  1867. ChartPermissionIds: rowChartPermissionIds,
  1868. }
  1869. cs.Set()
  1870. rowServices = append(rowServices, cs)
  1871. }
  1872. // 如果导入的最后一条合同编号为空并且合同编号之后的字段均为空
  1873. // excel这个包读行的时候不会再往后面没数据的地方读取, 所以此处需要重新判断一次
  1874. if rowRegister.ContractCode == "" {
  1875. resp.Fail(fmt.Sprintf("第%d行合同编号为空", i+1), c)
  1876. return
  1877. }
  1878. rowRegister.RegisterStatus = fms.ContractRegisterStatusIng
  1879. // 新增登记、套餐、开票到款信息
  1880. newId, e := fms.CreateImportContractRegister(rowRegister, rowServices, rowInvoices)
  1881. if e != nil {
  1882. resp.FailData(fmt.Sprintf("第%d行导入失败", i+1), "新增导入登记失败, Err: "+e.Error(), c)
  1883. return
  1884. }
  1885. newIds = append(newIds, newId)
  1886. }
  1887. }
  1888. }
  1889. // 更新登记状态
  1890. go func() {
  1891. for i := range newIds {
  1892. fmsService.CheckContractRegisterAmount(newIds[i])
  1893. }
  1894. }()
  1895. resp.Ok("操作成功", c)
  1896. }