register.go 69 KB

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