register.go 81 KB

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