register.go 82 KB

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