register.go 66 KB

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