register.go 68 KB

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