register.go 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590
  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. if req.AmountList[i].ServiceProductId == crm.CompanyProductFicc && sellerItem.DepartmentId != crm.SellerDepartmentId {
  791. resp.Fail("销售类型和所选套餐类型不一致", c)
  792. return
  793. }
  794. if req.AmountList[i].ServiceProductId == crm.CompanyProductRai && sellerItem.DepartmentId != crm.RaiSellerDepartmentId {
  795. resp.Fail("销售类型和所选套餐类型不一致", c)
  796. return
  797. }
  798. v.SellerId = sellerItem.SellerId
  799. v.SellerName = sellerItem.SellerName
  800. v.SellerGroupId = sellerItem.GroupId
  801. v.SellerGroupName = sellerItem.GroupName
  802. v.SellerTeamId = sellerItem.TeamId
  803. v.SellerTeamName = sellerItem.TeamName
  804. }
  805. // 到款登记-付款方式
  806. if req.InvoiceType == fms.ContractInvoiceTypePay {
  807. v.PayType = fmsService.CalculateContractPaymentType(req.AmountList[i].Amount, item.ContractAmount, dayDiff)
  808. }
  809. newInvoice = append(newInvoice, v)
  810. }
  811. }
  812. }
  813. // 获取原有的登记信息
  814. invoiceCond := `contract_register_id = ? AND invoice_type = ? `
  815. invoicePars := make([]interface{}, 0)
  816. invoicePars = append(invoicePars, req.ContractRegisterId, req.InvoiceType)
  817. originInvoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  818. if e != nil {
  819. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  820. return
  821. }
  822. // 比对原有和现有的登记信息
  823. logList := make([]*fms.ContractRegisterLog, 0)
  824. opData := ""
  825. opDataByte, e := json.Marshal(req)
  826. if e != nil {
  827. return
  828. }
  829. opData = string(opDataByte)
  830. opType := fms.ContractRegisterOpTypeInvoice
  831. if req.InvoiceType == fms.ContractInvoiceTypePay {
  832. opType = fms.ContractRegisterOpTypePayment
  833. }
  834. nowTime := time.Now().Local()
  835. // 需要删除的记录
  836. deleteInvoiceIds := make([]int, 0)
  837. for i := range originInvoiceList {
  838. if !utils.InArrayByInt(noChangeInvoiceIds, originInvoiceList[i].ContractInvoiceId) {
  839. deleteInvoiceIds = append(deleteInvoiceIds, originInvoiceList[i].ContractInvoiceId)
  840. logList = append(logList, &fms.ContractRegisterLog{
  841. ContractRegisterId: req.ContractRegisterId,
  842. AdminId: int(adminInfo.AdminId),
  843. AdminName: adminInfo.RealName,
  844. OpData: opData,
  845. OpType: opType,
  846. CreateTime: nowTime,
  847. AmountRemark: fmt.Sprint("删除", fms.ContractInvoiceKeyNameMap[opType], "金额", originInvoiceList[i].Amount, "元"),
  848. })
  849. }
  850. }
  851. // 新增的记录
  852. if len(newInvoice) > 0 {
  853. newAmount := decimal.NewFromFloat(0).Round(2)
  854. for i := range newInvoice {
  855. a := decimal.NewFromFloat(newInvoice[i].Amount).Round(2)
  856. newAmount = newAmount.Add(a)
  857. }
  858. ia, _ := newAmount.Round(2).Float64()
  859. logList = append(logList, &fms.ContractRegisterLog{
  860. ContractRegisterId: req.ContractRegisterId,
  861. AdminId: int(adminInfo.AdminId),
  862. AdminName: adminInfo.RealName,
  863. OpData: opData,
  864. OpType: opType,
  865. CreateTime: nowTime,
  866. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  867. })
  868. }
  869. // 删除并新增登记
  870. ob := new(fms.ContractInvoice)
  871. if e := ob.DeleteAndCreateNewInvoice(req.ContractRegisterId, req.InvoiceType, deleteInvoiceIds, newInvoice); e != nil {
  872. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  873. return
  874. }
  875. // 校验金额-是否修改状态
  876. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  877. // 开票到款汇总
  878. go fmsService.SummaryInvoicePaymentByContractRegisterId(req.ContractRegisterId)
  879. // 操作日志
  880. go func() {
  881. logOB := new(fms.ContractRegisterLog)
  882. if e := logOB.AddInBatches(logList); e != nil {
  883. return
  884. }
  885. }()
  886. resp.Ok("操作成功", c)
  887. }
  888. // Export
  889. // @Title 合同登记-导出
  890. // @Description 合同登记-导出
  891. // @Param Keyword query string false "关键词"
  892. // @Param StartDate query string false "合同开始日期"
  893. // @Param EndDate query string false "合同结束日期"
  894. // @Param ServiceType query int false "套餐类型"
  895. // @Param ContractType query int false "合同类型"
  896. // @Param RegisterStatus query int false "登记状态"
  897. // @Success 200 string "操作成功"
  898. // @router /contract/register/export [get]
  899. func (rg *RegisterController) Export(c *gin.Context) {
  900. var req fms.ContractRegisterListReq
  901. if e := c.BindQuery(&req); e != nil {
  902. err, ok := e.(validator.ValidationErrors)
  903. if !ok {
  904. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  905. return
  906. }
  907. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  908. return
  909. }
  910. cond := `1 = 1`
  911. pars := make([]interface{}, 0)
  912. // 合同编号/客户姓名/销售/实际使用方
  913. if req.Keyword != "" {
  914. kw := "%" + req.Keyword + "%"
  915. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
  916. pars = append(pars, kw, kw, kw, kw)
  917. }
  918. if req.StartDate != "" && req.EndDate != "" {
  919. st := fmt.Sprint(req.StartDate, " 00:00:00")
  920. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  921. cond += ` AND (create_time BETWEEN ? AND ?)`
  922. pars = append(pars, st, ed)
  923. }
  924. if req.ContractType != 0 {
  925. cond += ` AND contract_type = ?`
  926. pars = append(pars, req.ContractType)
  927. }
  928. if req.RegisterStatus != 0 {
  929. cond += ` AND register_status = ?`
  930. pars = append(pars, req.RegisterStatus)
  931. }
  932. if req.ServiceTypes != "" {
  933. serviceTypes := strings.Split(req.ServiceTypes, ",")
  934. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  935. if e != nil {
  936. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  937. return
  938. }
  939. if len(registerIds) > 0 {
  940. cond += ` AND contract_register_id IN ?`
  941. pars = append(pars, registerIds)
  942. } else {
  943. cond += ` AND 1 = 2`
  944. }
  945. }
  946. // 获取列表数据
  947. cr := new(fms.ContractRegister)
  948. list, e := cr.List(cond, pars)
  949. if e != nil {
  950. resp.FailData("获取合同列表失败", "Err:"+e.Error(), c)
  951. return
  952. }
  953. if len(list) == 0 {
  954. resp.Fail("无有效数据可导出", c)
  955. return
  956. }
  957. registerIds := make([]int, 0)
  958. for i := range list {
  959. registerIds = append(registerIds, list[i].ContractRegisterId)
  960. }
  961. // 获取小套餐品种
  962. cpCond := `product_id = ? AND permission_name <> ?`
  963. cpPars := make([]interface{}, 0)
  964. cpPars = append(cpPars, crm.CompanyProductFicc, crm.ChartPermissionStrategyName)
  965. cp := new(crm.ChartPermission)
  966. permissionList, e := cp.List(cpCond, cpPars)
  967. if e != nil {
  968. resp.FailData("获取小套餐品种失败", "Err:"+e.Error(), c)
  969. return
  970. }
  971. permissionLen := len(permissionList)
  972. permissionNameIdMap := make(map[string]int)
  973. for i := range permissionList {
  974. permissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  975. }
  976. // 获取所有FICC套餐服务
  977. serviceList, e := fms.GetContractServiceTemplateMapByProductId(crm.CompanyProductFicc)
  978. if e != nil {
  979. resp.FailData("获取套餐服务失败", "Err:"+e.Error(), c)
  980. return
  981. }
  982. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  983. otherService := make([]*fms.ContractServiceTemplateItem, 0)
  984. for i := range serviceList {
  985. if serviceList[i].Title != "FICC大套餐" && serviceList[i].Title != "FICC小套餐" {
  986. otherService = append(otherService, serviceList[i])
  987. }
  988. }
  989. otherServiceLen := len(otherService)
  990. // 获取所有权益套餐服务
  991. raiServiceList, e := fms.GetContractServiceTemplateMapByProductId(crm.CompanyProductRai)
  992. if e != nil {
  993. resp.FailData("获取权益套餐服务失败", "Err:"+e.Error(), c)
  994. return
  995. }
  996. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  997. raiOtherService := make([]*fms.ContractServiceTemplateItem, 0)
  998. for i := range raiServiceList {
  999. //获取二级套餐
  1000. secondServiceList, e := fms.GetContractServiceTemplateMapByParentId(raiServiceList[i].ServiceTemplateId)
  1001. if e != nil {
  1002. resp.FailData("获取二级权益套餐服务失败", "Err:"+e.Error(), c)
  1003. return
  1004. }
  1005. if len(secondServiceList) > 0 {
  1006. for _, sv := range secondServiceList {
  1007. //获取三级套餐
  1008. thirdServiceList, e := fms.GetContractServiceTemplateMapByParentId(sv.ServiceTemplateId)
  1009. if e != nil {
  1010. resp.FailData("获取三级权益套餐服务失败", "Err:"+e.Error(), c)
  1011. return
  1012. }
  1013. if len(thirdServiceList) > 0 {
  1014. for _, tv := range thirdServiceList {
  1015. raiOtherService = append(raiOtherService, tv)
  1016. }
  1017. }else{
  1018. raiOtherService = append(raiOtherService, sv)
  1019. }
  1020. }
  1021. }else{
  1022. raiOtherService = append(raiOtherService, raiServiceList[i])
  1023. }
  1024. }
  1025. otherServiceLen += len(raiOtherService)
  1026. //套餐金额map
  1027. serviceAmountMap := make(map[int]map[int]*fms.ContractServiceAmount)
  1028. // 套餐/开票/到款列表
  1029. serviceMap := make(map[int][]*fms.ContractService)
  1030. serviceChartPermissionsMap := make(map[int][]int)
  1031. invoiceMap := make(map[int][]*fms.ContractInvoice)
  1032. paymentMap := make(map[int][]*fms.ContractInvoice)
  1033. maxInvoice := 0
  1034. maxPayment := 0
  1035. if len(registerIds) > 0 {
  1036. // 获取套餐信息
  1037. csCond := `contract_register_id IN ?`
  1038. csPars := make([]interface{}, 0)
  1039. csPars = append(csPars, registerIds)
  1040. cs := new(fms.ContractService)
  1041. serviceList, e := cs.List(csCond, csPars)
  1042. if e != nil {
  1043. resp.FailData("获取合同套餐列表失败", "Err:"+e.Error(), c)
  1044. return
  1045. }
  1046. for i := range serviceList {
  1047. cid := serviceList[i].ContractRegisterId
  1048. if serviceMap[cid] == nil {
  1049. serviceMap[cid] = make([]*fms.ContractService, 0)
  1050. }
  1051. serviceMap[cid] = append(serviceMap[cid], serviceList[i])
  1052. // 小套餐权限
  1053. if serviceChartPermissionsMap[cid] == nil {
  1054. serviceChartPermissionsMap[cid] = make([]int, 0)
  1055. }
  1056. if serviceList[i].ChartPermissionIds != "" {
  1057. ids := utils.JoinStr2IntArr(serviceList[i].ChartPermissionIds, ",")
  1058. serviceChartPermissionsMap[cid] = append(serviceChartPermissionsMap[cid], ids...)
  1059. }
  1060. }
  1061. // 获取合同的套餐金额信息
  1062. serviceAmountList, e := fms.GetContractServiceAmountByContractRegisterIds(registerIds)
  1063. if e != nil {
  1064. resp.FailData("获取合同的套餐金额信息失败", "Err:"+e.Error(), c)
  1065. return
  1066. }
  1067. for _, v := range serviceAmountList {
  1068. if _, ok := serviceAmountMap[v.ContractRegisterId]; !ok {
  1069. serviceAmountMap[v.ContractRegisterId] = make(map[int]*fms.ContractServiceAmount)
  1070. }
  1071. serviceAmountMap[v.ContractRegisterId][v.ProductId] = v
  1072. }
  1073. // 获取开票/到款详情, 并取最大的开票/到款数(用于动态扩展第二列表头)
  1074. ci := new(fms.ContractInvoice)
  1075. invoiceList, e := ci.List(csCond, csPars, "")
  1076. if e != nil {
  1077. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  1078. return
  1079. }
  1080. for k := range invoiceList {
  1081. cid := invoiceList[k].ContractRegisterId
  1082. if invoiceMap[cid] == nil {
  1083. invoiceMap[cid] = make([]*fms.ContractInvoice, 0)
  1084. }
  1085. if paymentMap[cid] == nil {
  1086. paymentMap[cid] = make([]*fms.ContractInvoice, 0)
  1087. }
  1088. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypeMake {
  1089. invoiceMap[cid] = append(invoiceMap[cid], invoiceList[k])
  1090. continue
  1091. }
  1092. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypePay {
  1093. paymentMap[cid] = append(paymentMap[cid], invoiceList[k])
  1094. continue
  1095. }
  1096. }
  1097. // 取最大开票/到款数
  1098. for j := range invoiceMap {
  1099. if len(invoiceMap[j]) > maxInvoice {
  1100. maxInvoice = len(invoiceMap[j])
  1101. }
  1102. }
  1103. for p := range paymentMap {
  1104. if len(paymentMap[p]) > maxPayment {
  1105. maxPayment = len(paymentMap[p])
  1106. }
  1107. }
  1108. }
  1109. // 生成Excel文件
  1110. xlsxFile := xlsx.NewFile()
  1111. style := xlsx.NewStyle()
  1112. alignment := xlsx.Alignment{
  1113. Horizontal: "center",
  1114. Vertical: "center",
  1115. WrapText: true,
  1116. }
  1117. style.Alignment = alignment
  1118. style.ApplyAlignment = true
  1119. sheetName := "财务列表"
  1120. sheet, err := xlsxFile.AddSheet(sheetName)
  1121. if err != nil {
  1122. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1123. return
  1124. }
  1125. // 1行表头
  1126. hInt := 0
  1127. titleRow := sheet.AddRow()
  1128. titleRow.SetHeight(40)
  1129. // 1行1列-右合并两格, 下合并1行
  1130. cell1 := titleRow.AddCell()
  1131. cell1.HMerge = 4
  1132. cell1.VMerge = 1
  1133. cell1.SetString("FICC客户签约表")
  1134. cell1.SetStyle(style)
  1135. // 右增两列空白格用于第一列合并, 否则后续单元格合并会有问题
  1136. titleRow.AddCell().SetString("")
  1137. titleRow.AddCell().SetString("")
  1138. titleRow.AddCell().SetString("")
  1139. titleRow.AddCell().SetString("")
  1140. hInt += 5
  1141. // 1行2列
  1142. cell2 := titleRow.AddCell()
  1143. cell2.VMerge = 1
  1144. cell2.SetString("FICC大套餐")
  1145. cell2.SetStyle(style)
  1146. hInt ++
  1147. // 1行3列-右合并小套餐数
  1148. if permissionLen >= 1 {
  1149. cell3 := titleRow.AddCell()
  1150. hInt ++
  1151. cell3.HMerge = permissionLen - 1
  1152. cell3.VMerge = 1
  1153. cell3.SetString("FICC小套餐")
  1154. cell3.SetStyle(style)
  1155. // 同上右增单元格小套餐数-1的空白单元格用于合并
  1156. for i := 0; i < permissionLen-1; i++ {
  1157. titleRow.AddCell().SetString("")
  1158. hInt ++
  1159. }
  1160. }
  1161. for i := range otherService {
  1162. cellOther := titleRow.AddCell()
  1163. cellOther.VMerge = 1
  1164. hInt ++
  1165. cellOther.SetString(otherService[i].Title)
  1166. cellOther.SetStyle(style)
  1167. }
  1168. //权益大套餐
  1169. cell4 := titleRow.AddCell()
  1170. cell4.HMerge = 1
  1171. cell4.VMerge = 1
  1172. cell4.SetString("权益大套餐")
  1173. cell4.SetStyle(style)
  1174. titleRow.AddCell().SetString("")
  1175. hInt +=2
  1176. //权益分行业套餐
  1177. cell5 := titleRow.AddCell()
  1178. cell5.HMerge = 8
  1179. cell5.SetString("权益分行业套餐")
  1180. cell5.SetStyle(style)
  1181. titleRow.AddCell().SetString("")
  1182. titleRow.AddCell().SetString("")
  1183. titleRow.AddCell().SetString("")
  1184. titleRow.AddCell().SetString("")
  1185. titleRow.AddCell().SetString("")
  1186. titleRow.AddCell().SetString("")
  1187. titleRow.AddCell().SetString("")
  1188. titleRow.AddCell().SetString("")
  1189. //第二行,前面几个单元格用于第一行的合并
  1190. titleRow2 := sheet.AddRow()
  1191. titleRow2.SetHeight(30)
  1192. for i:= 0; i<hInt;i++ {
  1193. titleRow2.AddCell().SetString("")
  1194. }
  1195. //权益分行业套餐
  1196. row2Cell1 := titleRow2.AddCell()
  1197. row2Cell1.HMerge = 1
  1198. row2Cell1.SetString("医药")
  1199. row2Cell1.SetStyle(style)
  1200. titleRow2.AddCell().SetString("")
  1201. row2Cell2 := titleRow2.AddCell()
  1202. row2Cell2.HMerge = 1
  1203. row2Cell2.SetString("消费")
  1204. row2Cell2.SetStyle(style)
  1205. titleRow2.AddCell().SetString("")
  1206. row2Cell3 := titleRow2.AddCell()
  1207. row2Cell3.HMerge = 1
  1208. row2Cell3.SetString("科技")
  1209. row2Cell3.SetStyle(style)
  1210. titleRow2.AddCell().SetString("")
  1211. row2Cell4 := titleRow2.AddCell()
  1212. row2Cell4.HMerge = 1
  1213. row2Cell4.SetString("智造")
  1214. row2Cell4.SetStyle(style)
  1215. titleRow2.AddCell().SetString("")
  1216. row2Cell5 := titleRow2.AddCell()
  1217. row2Cell5.SetString("策略")
  1218. row2Cell5.SetStyle(style)
  1219. // 第三行表头
  1220. titleRow3 := sheet.AddRow()
  1221. titleRow3.SetHeight(60)
  1222. row3Title := make([]string, 0)
  1223. row3Title = append(row3Title, "客户名称", "新客户\n0-是\n1-否", "合同类型\n续约-0\n新增-1\n代付-2\n补充协议-3", "FICC销售", "权益销售", "FICC大套餐")
  1224. for i := range permissionList {
  1225. row3Title = append(row3Title, permissionList[i].PermissionName)
  1226. }
  1227. // 其他套餐
  1228. for i := range otherService {
  1229. row3Title = append(row3Title, otherService[i].Title)
  1230. }
  1231. // 权益三级套餐
  1232. for i := range raiOtherService {
  1233. row3Title = append(row3Title, raiOtherService[i].Title)
  1234. }
  1235. row3Title = append(row3Title, "套餐备注", "开始时间", "到期时间", "2022年合同金额", "金额单位", "FICC套餐总金额", "权益套餐总金额", "约定付款时间", "签订日", "合同状态",
  1236. "合同编号", "合规备注")
  1237. // 设置表头
  1238. for i := range row3Title {
  1239. v := titleRow3.AddCell()
  1240. v.SetString(row3Title[i])
  1241. v.SetStyle(style)
  1242. }
  1243. // 第二行表头-开票/收款(动态添加)
  1244. invoiceTitle := []string{"开票日", "开票金额", "套餐类型", "销售", "备注"}
  1245. for i := 0; i < maxInvoice; i++ {
  1246. n := i + 1
  1247. for ii := range invoiceTitle {
  1248. c := titleRow3.AddCell()
  1249. t := fmt.Sprintf("%s%d", invoiceTitle[ii], n)
  1250. c.SetString(t)
  1251. c.SetStyle(style)
  1252. row3Title = append(row3Title, t)
  1253. }
  1254. }
  1255. paymentTitle := []string{"到款日", "到款金额", "套餐类型", "备注"}
  1256. for i := 0; i < maxPayment; i++ {
  1257. n := i + 1
  1258. for ii := range paymentTitle {
  1259. c := titleRow2.AddCell()
  1260. t := fmt.Sprintf("%s%d", paymentTitle[ii], n)
  1261. c.SetString(t)
  1262. c.SetStyle(style)
  1263. row3Title = append(row3Title, t)
  1264. }
  1265. }
  1266. // 此处取第二行标题NameKeyMap, 后面的动态匹配
  1267. row2NameKeyMap := make(map[string]int)
  1268. for i := range row3Title {
  1269. row2NameKeyMap[row3Title[i]] = i
  1270. }
  1271. newCompanyMap := map[int]string{0: "1", 1: "0"}
  1272. contractTMap := map[int]int{
  1273. fms.ContractTypeNew: 1,
  1274. fms.ContractTypeRenew: 0,
  1275. fms.ContractTypeAgentPay: 2, // 代付合同
  1276. fms.ContractTypePlus: 3, // 补充协议
  1277. }
  1278. for _, v := range list {
  1279. k := -1 // 套餐匹配用
  1280. dataRow := sheet.AddRow()
  1281. dataRow.SetHeight(20)
  1282. k += 4
  1283. dataRow.AddCell().SetString(v.CompanyName)
  1284. dataRow.AddCell().SetString(newCompanyMap[v.NewCompany])
  1285. dataRow.AddCell().SetString(fmt.Sprint(contractTMap[v.ContractType]))
  1286. dataRow.AddCell().SetString(v.SellerName)
  1287. dataRow.AddCell().SetString(v.RaiSellerName)
  1288. // 大套餐
  1289. k += 1
  1290. col4Name := row3Title[k]
  1291. svList := serviceMap[v.ContractRegisterId]
  1292. col4 := ""
  1293. if svList != nil && len(svList) > 0 {
  1294. for isv := range svList {
  1295. if svList[isv].Title == col4Name {
  1296. // todo 判断权益套餐权限时会有问题,需要同时判断父级name
  1297. col4 = "是"
  1298. break
  1299. }
  1300. }
  1301. }
  1302. dataRow.AddCell().SetString(col4)
  1303. // 小套餐
  1304. serviceChartPermissionIds := serviceChartPermissionsMap[v.ContractRegisterId]
  1305. for i := 0; i < permissionLen; i++ {
  1306. k += 1
  1307. colName := row3Title[k]
  1308. chartPermissionId := permissionNameIdMap[colName]
  1309. if utils.InArray(chartPermissionId, serviceChartPermissionIds) {
  1310. dataRow.AddCell().SetString("是")
  1311. } else {
  1312. dataRow.AddCell().SetString("")
  1313. }
  1314. }
  1315. // 除大小套餐外的其他套餐(处理方式其实跟上面的大套餐一样, 只是中间隔了小套餐按照顺序要这么处理=_=!)
  1316. for i := 0; i < otherServiceLen; i++ {
  1317. k += 1
  1318. otherColName := row3Title[k]
  1319. otherCol := ""
  1320. if svList != nil && len(svList) > 0 {
  1321. for isv := range svList {
  1322. if svList[isv].Title == otherColName {
  1323. otherCol = "是"
  1324. break
  1325. }
  1326. }
  1327. }
  1328. dataRow.AddCell().SetString(otherCol)
  1329. }
  1330. // 其他信息
  1331. ficcAmount, _ := serviceAmountMap[v.ContractRegisterId][crm.CompanyProductFicc]
  1332. raiAmount, _ := serviceAmountMap[v.ContractRegisterId][crm.CompanyProductRai]
  1333. dataRow.AddCell().SetString(v.ServiceRemark) // 套餐备注
  1334. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.StartDate)) // 开始时间
  1335. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.EndDate)) // 到期时间
  1336. dataRow.AddCell().SetString(fmt.Sprint("¥", v.ContractAmount)) // 2022年合同金额
  1337. dataRow.AddCell().SetString(v.CurrencyUnit) // 货币单位
  1338. dataRow.AddCell().SetString(fmt.Sprint("¥", ficcAmount.ServiceAmount)) // FICC套餐总金额
  1339. dataRow.AddCell().SetString(fmt.Sprint("¥", raiAmount.ServiceAmount)) // 权益套餐总金额
  1340. dataRow.AddCell().SetString(v.AgreedPayTime) // 约定付款时间
  1341. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.SignDate)) // 签订日
  1342. dataRow.AddCell().SetString(fms.ContractStatusKeyNameMap[v.ContractStatus]) // 合同状态
  1343. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  1344. dataRow.AddCell().SetString(v.Remark) // 合规备注
  1345. // 开票/到款信息
  1346. ivList := invoiceMap[v.ContractRegisterId]
  1347. ivListLen := len(ivList)
  1348. for ia := 0; ia < maxInvoice; ia++ {
  1349. if ia < ivListLen {
  1350. if ivList != nil && ivList[ia] != nil {
  1351. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", ivList[ia].InvoiceDate)) // 开票日
  1352. dataRow.AddCell().SetString(fmt.Sprint(ivList[ia].OriginAmount)) // 开票金额
  1353. // todo 开票中的套餐类型
  1354. dataRow.AddCell().SetString("")
  1355. dataRow.AddCell().SetString(ivList[ia].SellerName) // 销售名称
  1356. dataRow.AddCell().SetString(ivList[ia].Remark) // 开票备注
  1357. continue
  1358. }
  1359. }
  1360. // 这里要把不够的填充为空
  1361. dataRow.AddCell().SetString("")
  1362. dataRow.AddCell().SetString("")
  1363. dataRow.AddCell().SetString("")
  1364. dataRow.AddCell().SetString("")
  1365. dataRow.AddCell().SetString("")
  1366. }
  1367. pyList := paymentMap[v.ContractRegisterId]
  1368. pyListLen := len(pyList)
  1369. for ib := 0; ib < maxPayment; ib++ {
  1370. if ib < pyListLen {
  1371. if pyList != nil && pyList[ib] != nil {
  1372. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", pyList[ib].InvoiceDate)) // 收款日
  1373. dataRow.AddCell().SetString(fmt.Sprint(pyList[ib].OriginAmount)) // 收款金额
  1374. //todo 到款的套餐类型
  1375. dataRow.AddCell().SetString("") // 套餐类型
  1376. dataRow.AddCell().SetString(pyList[ib].Remark) // 收款备注
  1377. continue
  1378. }
  1379. }
  1380. // 这里要把不够的填充为空
  1381. dataRow.AddCell().SetString("")
  1382. dataRow.AddCell().SetString("")
  1383. dataRow.AddCell().SetString("")
  1384. dataRow.AddCell().SetString("")
  1385. }
  1386. }
  1387. // 输出文件
  1388. var buffer bytes.Buffer
  1389. _ = xlsxFile.Write(&buffer)
  1390. content := bytes.NewReader(buffer.Bytes())
  1391. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1392. fileName := sheetName + randStr + ".xlsx"
  1393. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1394. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1395. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1396. }
  1397. // InvoiceList
  1398. // @Title 开票/到款列表
  1399. // @Description 开票/到款列表
  1400. // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
  1401. // @Param ContractCode query string false "合同编号"
  1402. // @Param StartDate query string false "开始日期"
  1403. // @Param EndDate query string false "结束日期"
  1404. // @Param MinAmount query float64 false "开票金额区间-最小值"
  1405. // @Param MaxAmount query float64 false "开票金额区间-最大值"
  1406. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  1407. // @Success 200 {object} fms.ContractInvoiceItem
  1408. // @router /contract/register/invoice_list [get]
  1409. func (rg *RegisterController) InvoiceList(c *gin.Context) {
  1410. var req fms.ContractInvoiceListReq
  1411. if e := c.BindQuery(&req); e != nil {
  1412. err, ok := e.(validator.ValidationErrors)
  1413. if !ok {
  1414. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1415. return
  1416. }
  1417. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1418. return
  1419. }
  1420. pageSize := req.PageSize
  1421. pageIndex := req.Current
  1422. if pageSize <= 0 {
  1423. pageSize = utils.PageSize20
  1424. }
  1425. if pageIndex <= 0 {
  1426. pageIndex = 1
  1427. }
  1428. cond := `invoice_type = ?`
  1429. pars := make([]interface{}, 0)
  1430. pars = append(pars, req.InvoiceType)
  1431. // 合同编号
  1432. if req.ContractCode != "" {
  1433. kw := fmt.Sprint("%", req.ContractCode, "%")
  1434. pars = append(pars, kw)
  1435. // 开票列表同时模糊查询销售名称
  1436. if req.InvoiceType == fms.ContractInvoiceTypeMake {
  1437. cond += ` AND (contract_code LIKE ? )`
  1438. pars = append(pars, kw)
  1439. } else {
  1440. cond += ` AND contract_code LIKE ?`
  1441. pars = append(pars, kw)
  1442. }
  1443. }
  1444. if req.StartDate != "" && req.EndDate != "" {
  1445. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1446. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1447. cond += ` AND (invoice_time BETWEEN ? AND ?)`
  1448. pars = append(pars, st, ed)
  1449. }
  1450. if req.MinAmount > 0 {
  1451. cond += ` AND amount >= ?`
  1452. pars = append(pars, req.MinAmount)
  1453. }
  1454. if req.MaxAmount > 0 {
  1455. cond += ` AND amount <= ?`
  1456. pars = append(pars, req.MaxAmount)
  1457. }
  1458. // 套餐类型
  1459. if req.ServiceProductId > 0 {
  1460. cond += ` AND service_product_id = ?`
  1461. pars = append(pars, req.ServiceProductId)
  1462. }
  1463. // 货币列表
  1464. currencyOB := new(fms.CurrencyUnit)
  1465. currencyCond := `enable = 1`
  1466. currencyPars := make([]interface{}, 0)
  1467. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1468. if e != nil {
  1469. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  1470. return
  1471. }
  1472. unitMap := make(map[string]string)
  1473. currencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1474. for i := range currencyList {
  1475. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1476. currencyTotals = append(currencyTotals, &fms.InvoiceListCurrencyTotal{
  1477. Name: currencyList[i].Name,
  1478. UnitName: currencyList[i].UnitName,
  1479. Code: currencyList[i].Code,
  1480. FlagImg: currencyList[i].FlagImg,
  1481. })
  1482. }
  1483. page := new(base.Page)
  1484. page.SetPageSize(pageSize)
  1485. page.SetCurrent(pageIndex)
  1486. page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: false})
  1487. if req.IsExport == 1 {
  1488. page.SetPageSize(10000)
  1489. page.SetCurrent(1)
  1490. }
  1491. total, list, e := fms.GetContractInvoiceItemPageList(page, cond, pars)
  1492. if e != nil {
  1493. resp.FailMsg("获取失败", "获取合同开票/到款列表失败, Err: "+e.Error(), c)
  1494. return
  1495. }
  1496. page.SetTotal(total)
  1497. for i := range list {
  1498. list[i].UnitName = unitMap[list[i].CurrencyUnit]
  1499. }
  1500. // 分币种合计金额
  1501. var amountTotal float64
  1502. sumList, e := fms.GetInvoiceListCurrencySum(cond, pars, "currency_unit")
  1503. if e != nil {
  1504. resp.FailMsg("获取失败", "获取开票/到款列表合计金额失败, Err: "+e.Error(), c)
  1505. return
  1506. }
  1507. sumMap := make(map[string]float64)
  1508. for i := range sumList {
  1509. amountTotal += sumList[i].AmountTotal
  1510. sumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  1511. }
  1512. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountTotal), 64)
  1513. for i := range currencyTotals {
  1514. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", sumMap[currencyTotals[i].Code]), 64)
  1515. currencyTotals[i].Amount = a
  1516. }
  1517. respData := &fms.InvoiceListRespData{
  1518. Page: page,
  1519. List: list,
  1520. AmountTotal: amountTotal,
  1521. CurrencyTotal: currencyTotals,
  1522. }
  1523. // 是否导出
  1524. if req.IsExport == 1 {
  1525. ExportInvoiceList(c, req, respData)
  1526. return
  1527. }
  1528. resp.OkData("获取成功", respData, c)
  1529. }
  1530. // ExportInvoiceList 导出开票/到款列表
  1531. func ExportInvoiceList(c *gin.Context, req fms.ContractInvoiceListReq, results *fms.InvoiceListRespData) {
  1532. list := make([]*fms.ContractInvoiceItem, 0)
  1533. if val, ok := results.List.([]*fms.ContractInvoiceItem); ok {
  1534. list = val
  1535. } else {
  1536. resp.Fail("列表数据有误", c)
  1537. return
  1538. }
  1539. if len(list) == 0 {
  1540. resp.Fail("列表数据为空", c)
  1541. return
  1542. }
  1543. listName := "开票"
  1544. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1545. listName = "到款"
  1546. }
  1547. // 生成Excel文件
  1548. xlsxFile := xlsx.NewFile()
  1549. style := xlsx.NewStyle()
  1550. alignment := xlsx.Alignment{
  1551. Horizontal: "center",
  1552. Vertical: "center",
  1553. WrapText: true,
  1554. }
  1555. style.Alignment = alignment
  1556. style.ApplyAlignment = true
  1557. sheet, err := xlsxFile.AddSheet(fmt.Sprintf("%s列表", listName))
  1558. if err != nil {
  1559. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1560. return
  1561. }
  1562. // 前两行显示合计金额, 第三行空出与列表数据隔一行
  1563. rowA := sheet.AddRow()
  1564. cellAA := rowA.AddCell()
  1565. cellAA.SetString(fmt.Sprintf("已开票合计金额(换算后):%.2f(元)", results.AmountTotal))
  1566. rowBData := "已开票金额:"
  1567. for _, v := range results.CurrencyTotal {
  1568. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  1569. }
  1570. rowB := sheet.AddRow()
  1571. rowB.AddCell().SetString(rowBData)
  1572. sheet.AddRow()
  1573. // 列表数据表头
  1574. titles := []string{"合同编号", fmt.Sprintf("%s金额", listName), "金额单位", "换算金额(元)",
  1575. fmt.Sprintf("%s日期", listName), "销售", "备注"}
  1576. titleRow := sheet.AddRow()
  1577. titleRow.SetHeight(40)
  1578. for i := range titles {
  1579. c := titleRow.AddCell()
  1580. c.SetString(titles[i])
  1581. c.SetStyle(style)
  1582. }
  1583. // 单元格赋值
  1584. for _, v := range list {
  1585. dataRow := sheet.AddRow()
  1586. dataRow.SetHeight(20)
  1587. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  1588. dataRow.AddCell().SetString(fmt.Sprint(v.OriginAmount)) // 开票金额
  1589. dataRow.AddCell().SetString(v.UnitName) // 金额单位
  1590. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 换算金额(元)
  1591. dataRow.AddCell().SetString(v.InvoiceDate) // 开票日
  1592. dataRow.AddCell().SetString(v.SellerName) // 销售
  1593. dataRow.AddCell().SetString(v.Remark) // 备注
  1594. }
  1595. // 输出文件
  1596. var buffer bytes.Buffer
  1597. _ = xlsxFile.Write(&buffer)
  1598. content := bytes.NewReader(buffer.Bytes())
  1599. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1600. fileName := fmt.Sprintf("%s列表_%s.xlsx", listName, randStr)
  1601. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1602. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1603. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1604. }
  1605. // Import
  1606. // @Title 合同登记-导入
  1607. // @Description 合同登记-导入
  1608. // @Success 200 string "操作成功"
  1609. // @router /contract/register/import [post]
  1610. func (rg *RegisterController) Import(c *gin.Context) {
  1611. h, err := c.FormFile("File")
  1612. if err != nil {
  1613. resp.FailData("获取文件失败", "Err:"+err.Error(), c)
  1614. return
  1615. }
  1616. ext := path.Ext(h.Filename)
  1617. if ext != ".xlsx" && ext != ".xls" {
  1618. resp.Fail("请上传Excel文件", c)
  1619. return
  1620. }
  1621. uploadDir := "static/xls"
  1622. err = os.MkdirAll(uploadDir, 766)
  1623. if err != nil {
  1624. resp.FailData("存储目录创建失败", "Err:"+err.Error(), c)
  1625. return
  1626. }
  1627. uploadPath := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
  1628. err = c.SaveUploadedFile(h, uploadPath)
  1629. if err != nil {
  1630. resp.FailData("保存本地文件失败", "Err:"+err.Error(), c)
  1631. return
  1632. }
  1633. defer func() {
  1634. _ = os.Remove(uploadPath)
  1635. }()
  1636. xlFile, err := xlsx.OpenFile(uploadPath)
  1637. if err != nil {
  1638. resp.FailData("打开文件失败", "Err:"+err.Error(), c)
  1639. return
  1640. }
  1641. // 获取所有已登记,根据合同编号去重
  1642. contractCodeArr := make([]string, 0)
  1643. registerOB := new(fms.ContractRegister)
  1644. registerCond := ``
  1645. registerPars := make([]interface{}, 0)
  1646. registerList, e := registerOB.List(registerCond, registerPars)
  1647. if e != nil {
  1648. resp.FailData("获取合同登记列表失败", "Err:"+e.Error(), c)
  1649. return
  1650. }
  1651. for i := range registerList {
  1652. contractCodeArr = append(contractCodeArr, registerList[i].ContractCode)
  1653. }
  1654. // 获取所有销售Map
  1655. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  1656. if e != nil {
  1657. resp.FailData("获取销售列表失败", "Err:"+e.Error(), c)
  1658. return
  1659. }
  1660. sellerMap := make(map[string]*crm.SellerAdminWithGroupTeam)
  1661. for i := range sellerList {
  1662. sellerMap[sellerList[i].SellerName] = sellerList[i]
  1663. }
  1664. // 获取品种权限Map
  1665. chartPermissionNameIdMap := make(map[string]int)
  1666. cpCond := `product_id = ?`
  1667. cpPars := make([]interface{}, 0)
  1668. cpPars = append(cpPars, crm.CompanyProductFicc)
  1669. cp := new(crm.ChartPermission)
  1670. permissionList, e := cp.List(cpCond, cpPars)
  1671. if e != nil {
  1672. resp.FailData("获取权限列表失败", "Err:"+e.Error(), c)
  1673. return
  1674. }
  1675. for i := range permissionList {
  1676. chartPermissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  1677. }
  1678. // 获取所有套餐模板
  1679. serviceTempCond := ``
  1680. serviceTempPars := make([]interface{}, 0)
  1681. serviceTempOB := new(fms.ContractServiceTemplate)
  1682. serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
  1683. if e != nil {
  1684. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  1685. return
  1686. }
  1687. serviceTempNameMap := make(map[string]*fms.ContractServiceTemplate)
  1688. serviceTempFullNameMap := make(map[string]*fms.ContractServiceTemplate)
  1689. serviceTempIdMap := make(map[int]*fms.ContractServiceTemplate)
  1690. for i := range serviceTempList {
  1691. serviceTempIdMap[serviceTempList[i].ServiceTemplateId] = serviceTempList[i]
  1692. serviceTempNameMap[serviceTempList[i].Title] = serviceTempList[i]
  1693. }
  1694. for i := range serviceTempList {
  1695. fullName := serviceTempList[i].Title
  1696. if serviceTempList[i].Pid > 0 {
  1697. parentItem := serviceTempIdMap[serviceTempList[i].Pid]
  1698. fullName += "_"+parentItem.Title
  1699. if parentItem.Pid > 0 {
  1700. fullName += "_"+serviceTempIdMap[parentItem.Pid].Title
  1701. }
  1702. }
  1703. serviceTempFullNameMap[fullName] = serviceTempList[i]
  1704. }
  1705. //权益行业套餐名称
  1706. raiIndustryMap := map[int]string{
  1707. 36:"医药",
  1708. 37:"医药",
  1709. 38:"消费",
  1710. 39:"消费",
  1711. 40:"科技",
  1712. 41:"科技",
  1713. 42:"智造",
  1714. 43:"智造",
  1715. 44:"策略",
  1716. }
  1717. // 获取货币列表及汇率(汇率为导入日的汇率)
  1718. rateList, e := fmsService.GetTodayCurrencyRateList()
  1719. if e != nil {
  1720. resp.FailData("获取货币列表及汇率失败", "Err:"+e.Error(), c)
  1721. return
  1722. }
  1723. rateMap := make(map[string]float64)
  1724. for i := range rateList {
  1725. rateMap[rateList[i].Code] = rateList[i].RMBRate
  1726. }
  1727. titleMap := make(map[int]string)
  1728. newIds := make([]int, 0)
  1729. newCompanyArr := []string{"0", "1"}
  1730. newCompanyMap := map[string]int{"0": 1, "1": 0}
  1731. contractTypeArr := []string{"0", "1", "2", "3"}
  1732. contractTypeMap := map[string]int{
  1733. "0": fms.ContractTypeRenew,
  1734. "1": fms.ContractTypeNew,
  1735. "2": fms.ContractTypeAgentPay,
  1736. "3": fms.ContractTypePlus,
  1737. }
  1738. // 更新登记状态
  1739. defer func() {
  1740. if len(newIds) > 0 {
  1741. go func() {
  1742. for i := range newIds {
  1743. fmsService.CheckContractRegisterAmount(newIds[i])
  1744. fmsService.SummaryInvoicePaymentByContractRegisterId(newIds[i])
  1745. }
  1746. }()
  1747. }
  1748. }()
  1749. invoiceMax := 3
  1750. checkDate := time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local)
  1751. for _, sheet := range xlFile.Sheets {
  1752. // 遍历行读取
  1753. maxRow := sheet.MaxRow
  1754. for i := 0; i < maxRow; i++ {
  1755. // 第三行开始读取表头
  1756. if i == 2 {
  1757. row := sheet.Row(i)
  1758. cells := row.Cells
  1759. for k, cell := range cells {
  1760. text := cell.String()
  1761. titleMap[k] = text
  1762. // 只检验前面部分表头, 后面很多动态列
  1763. if k == 0 {
  1764. if text != "客户名称" {
  1765. resp.Fail("【客户名称】列名称有误, 请参考模板导入", c)
  1766. return
  1767. }
  1768. continue
  1769. } else if k == 1 {
  1770. if !strings.Contains(text, "新客户") {
  1771. resp.Fail("【新客户】列名称有误, 请参考模板导入", c)
  1772. return
  1773. }
  1774. continue
  1775. } else if k == 2 {
  1776. if !strings.Contains(text, "合同类型") {
  1777. resp.Fail("【合同类型】列名称有误, 请参考模板导入", c)
  1778. return
  1779. }
  1780. continue
  1781. } else if k == 3 {
  1782. if text != "FICC销售" {
  1783. resp.Fail("【FICC销售】列名称有误, 请参考模板导入", c)
  1784. return
  1785. }
  1786. continue
  1787. } else if k == 4 {
  1788. if text != "权益销售" {
  1789. resp.Fail("【权益销售】列名称有误, 请参考模板导入", c)
  1790. return
  1791. }
  1792. continue
  1793. } else if k == 5 {
  1794. if text != "FICC大套餐" {
  1795. resp.Fail("【FICC大套餐】列名称有误, 请参考模板导入", c)
  1796. return
  1797. }
  1798. continue
  1799. }
  1800. }
  1801. }else if i >= 3 {
  1802. // 数据行
  1803. row := sheet.Row(i)
  1804. cells := row.Cells
  1805. // 登记信息
  1806. rowRegister := new(fms.ContractRegister)
  1807. // 套餐
  1808. rowServices := make([]*fms.ContractService, 0)
  1809. // 套餐金额
  1810. rowServiceAmount := make([]*fms.ContractServiceAmount, 0)
  1811. // 开票/到款
  1812. rowInvoices := make([]*fms.ContractInvoice, 0)
  1813. for ir := 0; ir < invoiceMax; ir++ {
  1814. rowInvoices = append(rowInvoices, new(fms.ContractInvoice))
  1815. }
  1816. rowPayments := make([]*fms.ContractInvoice, 0)
  1817. for ir := 0; ir < invoiceMax; ir++ {
  1818. rowPayments = append(rowPayments, new(fms.ContractInvoice))
  1819. }
  1820. // 小套餐权限
  1821. rowChartPermissionIdArr := make([]string, 0)
  1822. productIds := make(map[int]struct{})
  1823. isSkip := false
  1824. for k, cell := range cells {
  1825. v := utils.TrimStr(cell.String())
  1826. // 客户名称
  1827. if k == 0 {
  1828. if v == "" {
  1829. resp.Fail(fmt.Sprintf("第%d行客户名称不可为空, 请按模板导入", i+1), c)
  1830. return
  1831. }
  1832. rowRegister.CompanyName = v
  1833. continue
  1834. }
  1835. // 是否新客户
  1836. if k == 1 {
  1837. if !utils.InArrayByStr(newCompanyArr, v) {
  1838. resp.Fail(fmt.Sprintf("第%d行新客户有误, 请按模板导入", i+1), c)
  1839. return
  1840. }
  1841. rowRegister.NewCompany = newCompanyMap[v]
  1842. continue
  1843. }
  1844. // 合同类型
  1845. if k == 2 {
  1846. if !utils.InArrayByStr(contractTypeArr, v) {
  1847. resp.Fail(fmt.Sprintf("第%d行合同类型有误, 请按模板导入", i+1), c)
  1848. return
  1849. }
  1850. rowRegister.ContractType = contractTypeMap[v]
  1851. if rowRegister.ContractType == 0 {
  1852. resp.Fail(fmt.Sprintf("第%d行合同类型匹配有误, 请按模板导入", i+1), c)
  1853. return
  1854. }
  1855. continue
  1856. }
  1857. // FICC销售
  1858. if k == 3 {
  1859. if v != "" {
  1860. /*resp.Fail(fmt.Sprintf("第%d行销售名称不可为空, 请按模板导入", i+1), c)
  1861. return*/
  1862. sellerItem := sellerMap[v]
  1863. if sellerItem == nil {
  1864. resp.Fail(fmt.Sprintf("第%d行销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  1865. return
  1866. }
  1867. rowRegister.SellerId = sellerItem.SellerId
  1868. rowRegister.SellerName = sellerItem.SellerName
  1869. }
  1870. continue
  1871. }
  1872. // 权益销售
  1873. if k == 4 {
  1874. if v == "" && rowRegister.SellerName == "" {
  1875. resp.Fail(fmt.Sprintf("第FICC销售名称和权益销售名称不可都为空, 请按模板导入", i+1), c)
  1876. return
  1877. }
  1878. sellerItem := sellerMap[v]
  1879. if sellerItem == nil {
  1880. resp.Fail(fmt.Sprintf("第%d行权益销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  1881. return
  1882. }
  1883. rowRegister.RaiSellerId = sellerItem.SellerId
  1884. rowRegister.RaiSellerName = sellerItem.SellerName
  1885. continue
  1886. }
  1887. // FICC大套餐
  1888. if k == 5 {
  1889. if v == "是" {
  1890. tempItem := serviceTempNameMap[titleMap[k]]
  1891. if tempItem == nil {
  1892. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  1893. return
  1894. }
  1895. cs := &fms.ContractService{
  1896. ProductId: crm.CompanyProductFicc,
  1897. ServiceTemplateId: tempItem.ServiceTemplateId,
  1898. Title: tempItem.Title,
  1899. Value: tempItem.Value,
  1900. TableValue: tempItem.TableValue,
  1901. ChartPermissionId: tempItem.ChartPermissionId,
  1902. }
  1903. cs.Set()
  1904. rowServices = append(rowServices, cs)
  1905. productIds[crm.CompanyProductFicc] = struct{}{}
  1906. }
  1907. continue
  1908. }
  1909. // FICC小套餐
  1910. if k >= 6 && k <= 26 {
  1911. // 小套餐权限
  1912. if v == "是" {
  1913. rowChartPermissionIdArr = append(rowChartPermissionIdArr, strconv.Itoa(chartPermissionNameIdMap[titleMap[k]]))
  1914. productIds[crm.CompanyProductFicc] = struct{}{}
  1915. }
  1916. continue
  1917. }
  1918. // 其他类型套餐
  1919. if k >= 27 && k <= 33 {
  1920. if v == "是" {
  1921. tempItem := serviceTempNameMap[titleMap[k]]
  1922. if tempItem == nil {
  1923. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  1924. return
  1925. }
  1926. cs := &fms.ContractService{
  1927. ProductId: crm.CompanyProductFicc,
  1928. ServiceTemplateId: tempItem.ServiceTemplateId,
  1929. Title: tempItem.Title,
  1930. Value: tempItem.Value,
  1931. TableValue: tempItem.TableValue,
  1932. ChartPermissionId: tempItem.ChartPermissionId,
  1933. }
  1934. cs.Set()
  1935. rowServices = append(rowServices, cs)
  1936. productIds[crm.CompanyProductFicc] = struct{}{}
  1937. }
  1938. continue
  1939. }
  1940. // todo 权益行业套餐
  1941. if k >=34 && k<=44 {
  1942. if v == "是" {
  1943. // 权益大套餐
  1944. if k <= 35 {
  1945. //新增
  1946. parentName := "权益大套餐"
  1947. tempItem := serviceTempNameMap[titleMap[k]]
  1948. if tempItem == nil {
  1949. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  1950. return
  1951. }
  1952. cs := &fms.ContractService{
  1953. ProductId: crm.CompanyProductFicc,
  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. tempItem = serviceTempNameMap[parentName]
  1962. if tempItem == nil {
  1963. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  1964. return
  1965. }
  1966. cs = &fms.ContractService{
  1967. ProductId: crm.CompanyProductRai,
  1968. ServiceTemplateId: tempItem.ServiceTemplateId,
  1969. Title: tempItem.Title,
  1970. Value: tempItem.Value,
  1971. TableValue: tempItem.TableValue,
  1972. ChartPermissionId: tempItem.ChartPermissionId,
  1973. }
  1974. rowServices = append(rowServices, cs)
  1975. } else {
  1976. rootName := "行业套餐"
  1977. // 新增三条套餐信息
  1978. parentName, _ := raiIndustryMap[k]
  1979. childName := titleMap[k]
  1980. fullName := childName+"_"+parentName+"_"+rootName
  1981. if fullName != "" {
  1982. //增加三级权限
  1983. tempItem := serviceTempFullNameMap[fullName]
  1984. if tempItem == nil {
  1985. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  1986. return
  1987. }
  1988. cs := &fms.ContractService{
  1989. ProductId: crm.CompanyProductRai,
  1990. ServiceTemplateId: tempItem.ServiceTemplateId,
  1991. Title: tempItem.Title,
  1992. Value: tempItem.Value,
  1993. TableValue: tempItem.TableValue,
  1994. ChartPermissionId: tempItem.ChartPermissionId,
  1995. }
  1996. rowServices = append(rowServices, cs)
  1997. //增加二级权限
  1998. tempItem = serviceTempFullNameMap[parentName+"_"+rootName]
  1999. if tempItem == nil {
  2000. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2001. return
  2002. }
  2003. cs = &fms.ContractService{
  2004. ProductId: crm.CompanyProductRai,
  2005. ServiceTemplateId: tempItem.ServiceTemplateId,
  2006. Title: tempItem.Title,
  2007. Value: tempItem.Value,
  2008. TableValue: tempItem.TableValue,
  2009. ChartPermissionId: tempItem.ChartPermissionId,
  2010. }
  2011. rowServices = append(rowServices, cs)
  2012. //增加一级权限
  2013. tempItem = serviceTempFullNameMap[rootName]
  2014. if tempItem == nil {
  2015. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2016. return
  2017. }
  2018. cs = &fms.ContractService{
  2019. ProductId: crm.CompanyProductRai,
  2020. ServiceTemplateId: tempItem.ServiceTemplateId,
  2021. Title: tempItem.Title,
  2022. Value: tempItem.Value,
  2023. TableValue: tempItem.TableValue,
  2024. ChartPermissionId: tempItem.ChartPermissionId,
  2025. }
  2026. rowServices = append(rowServices, cs)
  2027. }
  2028. }
  2029. productIds[crm.CompanyProductRai] = struct{}{}
  2030. }
  2031. continue
  2032. }
  2033. // 权益研选等套餐
  2034. if k >= 45 && k<=49 {
  2035. if v == "是" {
  2036. tempItem := serviceTempNameMap[titleMap[k]]
  2037. if tempItem == nil {
  2038. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2039. return
  2040. }
  2041. cs := &fms.ContractService{
  2042. ProductId: crm.CompanyProductRai,
  2043. ServiceTemplateId: tempItem.ServiceTemplateId,
  2044. Title: tempItem.Title,
  2045. Value: tempItem.Value,
  2046. TableValue: tempItem.TableValue,
  2047. ChartPermissionId: tempItem.ChartPermissionId,
  2048. }
  2049. cs.Set()
  2050. rowServices = append(rowServices, cs)
  2051. productIds[crm.CompanyProductRai] = struct{}{}
  2052. }
  2053. continue
  2054. }
  2055. // 套餐备注
  2056. if k == 50 {
  2057. rowRegister.ServiceRemark = v
  2058. continue
  2059. }
  2060. // 开始时间/到期时间
  2061. if k == 51 {
  2062. // 转换失败可能是因为格式为Excel日期格式, 读取出来会是一串数字, 将其转换成日期字符串再处理
  2063. va := cell.Value
  2064. if va == "" {
  2065. resp.Fail(fmt.Sprintf("第%d行开始时间不可为空, 请按模板导入", i+1), c)
  2066. return
  2067. }
  2068. startDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2069. if e != nil {
  2070. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2071. startDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2072. if e != nil {
  2073. resp.Fail(fmt.Sprintf("第%d行开始时间格式转换有误, 请按模板导入", i+1), c)
  2074. return
  2075. }
  2076. }
  2077. // 转换后的日期小于1900-01-01表示当前生成的日期是有问题的
  2078. if startDate.Before(checkDate) {
  2079. resp.Fail(fmt.Sprintf("第%d行开始时间格式有误, 请按模板导入", i+1), c)
  2080. return
  2081. }
  2082. rowRegister.StartDate = startDate
  2083. continue
  2084. }
  2085. if k == 52 {
  2086. va := cell.Value
  2087. if va == "" {
  2088. resp.Fail(fmt.Sprintf("第%d行到期时间不可为空, 请按模板导入", i+1), c)
  2089. return
  2090. }
  2091. endDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2092. if e != nil {
  2093. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2094. endDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2095. if e != nil {
  2096. resp.Fail(fmt.Sprintf("第%d行到期时间格式转换有误, 请按模板导入", i+1), c)
  2097. return
  2098. }
  2099. }
  2100. if endDate.Before(checkDate) {
  2101. resp.Fail(fmt.Sprintf("第%d行到期时间格式有误, 请按模板导入", i+1), c)
  2102. return
  2103. }
  2104. rowRegister.EndDate = endDate
  2105. continue
  2106. }
  2107. // 合同金额
  2108. if k == 53 {
  2109. amountStr := v
  2110. amount, e := strconv.ParseFloat(amountStr, 64)
  2111. if e != nil {
  2112. resp.Fail(fmt.Sprintf("第%d行合同金额有误, 请按模板导入", i+1), c)
  2113. return
  2114. }
  2115. rowRegister.ContractAmount = amount
  2116. continue
  2117. }
  2118. // 金额单位
  2119. if k == 54 {
  2120. rate := rateMap[v]
  2121. if rate <= 0 {
  2122. resp.Fail(fmt.Sprintf("第%d行金额单位有误, 请按模板导入", i+1), c)
  2123. return
  2124. }
  2125. rowRegister.CurrencyUnit = v
  2126. rowRegister.RMBRate = rate
  2127. continue
  2128. }
  2129. // todo FICC套餐总金额
  2130. if k == 55 {
  2131. amountStr := v
  2132. amount, e := strconv.ParseFloat(amountStr, 64)
  2133. if e != nil {
  2134. resp.Fail(fmt.Sprintf("第%d行FICC套餐总金额有误, 请按模板导入", i+1), c)
  2135. return
  2136. }
  2137. if amount > 0 {
  2138. tmp := &fms.ContractServiceAmount{
  2139. ProductId: crm.CompanyProductFicc,
  2140. ServiceAmount: amount,
  2141. CurrencyUnit: rowRegister.CurrencyUnit,
  2142. TimeBase: base.TimeBase{},
  2143. }
  2144. rowServiceAmount = append(rowServiceAmount, tmp)
  2145. }
  2146. continue
  2147. }
  2148. // todo 权益套餐总金额
  2149. if k == 56 {
  2150. amountStr := v
  2151. amount, e := strconv.ParseFloat(amountStr, 64)
  2152. if e != nil {
  2153. resp.Fail(fmt.Sprintf("第%d行权益套餐总金额有误, 请按模板导入", i+1), c)
  2154. return
  2155. }
  2156. if amount > 0 {
  2157. tmp := &fms.ContractServiceAmount{
  2158. ProductId: crm.CompanyProductRai,
  2159. ServiceAmount: amount,
  2160. CurrencyUnit: rowRegister.CurrencyUnit,
  2161. TimeBase: base.TimeBase{},
  2162. }
  2163. rowServiceAmount = append(rowServiceAmount, tmp)
  2164. }
  2165. continue
  2166. }
  2167. // 约定付款日期
  2168. if k == 57 {
  2169. rowRegister.AgreedPayTime = v
  2170. continue
  2171. }
  2172. // 签订日
  2173. if k == 58 {
  2174. va := cell.Value
  2175. if va == "" {
  2176. continue
  2177. }
  2178. signDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2179. if e != nil {
  2180. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2181. signDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2182. if e != nil {
  2183. resp.Fail(fmt.Sprintf("第%d行签订日格式转换有误, 请按模板导入", i+1), c)
  2184. return
  2185. }
  2186. }
  2187. if signDate.Before(checkDate) {
  2188. resp.Fail(fmt.Sprintf("第%d行签订日格式有误, 请按模板导入", i+1), c)
  2189. return
  2190. }
  2191. rowRegister.SignDate = signDate
  2192. continue
  2193. }
  2194. // 合同状态
  2195. if k == 59 {
  2196. rowRegister.ContractStatus = fms.ContractStatusNameKeyMap[v]
  2197. if rowRegister.ContractStatus == 0 {
  2198. resp.Fail(fmt.Sprintf("第%d行合同状态不匹配, 请按模板导入", i+1), c)
  2199. return
  2200. }
  2201. continue
  2202. }
  2203. // 合同编号
  2204. if k == 60 {
  2205. rowContractCode := v
  2206. if rowContractCode == "" {
  2207. resp.Fail(fmt.Sprintf("第%d行合同编号不可为空, 请按模板导入", i+1), c)
  2208. return
  2209. }
  2210. if utils.InArrayByStr(contractCodeArr, rowContractCode) {
  2211. // 此合同已登记, 跳过本行的读取
  2212. isSkip = true
  2213. break
  2214. }
  2215. rowRegister.ContractCode = rowContractCode
  2216. continue
  2217. }
  2218. // 合规备注
  2219. if k == 61 {
  2220. rowRegister.Remark = v
  2221. continue
  2222. }
  2223. // 开票列表
  2224. k2 := 62
  2225. for ir := 0; ir < invoiceMax; ir++ {
  2226. n := ir + 1
  2227. // 开票日
  2228. k2 += 1
  2229. if k == k2 {
  2230. if v != "" {
  2231. va := cell.Value
  2232. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2233. if e != nil {
  2234. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2235. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2236. if e != nil {
  2237. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式转换有误, 请按模板导入", i+1, n), c)
  2238. return
  2239. }
  2240. }
  2241. if invoiceDate.Before(checkDate) {
  2242. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式有误, 请按模板导入", i+1, n), c)
  2243. return
  2244. }
  2245. rowInvoices[ir].InvoiceDate = invoiceDate
  2246. rowInvoices[ir].ContractCode = rowRegister.ContractCode
  2247. rowInvoices[ir].InvoiceType = fms.ContractInvoiceTypeMake
  2248. }
  2249. continue
  2250. }
  2251. // 开票金额
  2252. k2 += 1
  2253. if k == k2 {
  2254. if v != "" {
  2255. amountStr := v
  2256. amount, e := strconv.ParseFloat(amountStr, 64)
  2257. if e != nil {
  2258. resp.Fail(fmt.Sprintf("第%d行开票金额%d有误, 请按模板导入", i+1, n), c)
  2259. return
  2260. }
  2261. if rowRegister.RMBRate <= 0 {
  2262. resp.Fail(fmt.Sprintf("第%d行开票金额换算%d有误, 请按模板导入金额单位", i+1, n), c)
  2263. return
  2264. }
  2265. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amount/rowRegister.RMBRate), 64)
  2266. rowInvoices[ir].OriginAmount = amount
  2267. rowInvoices[ir].Amount = a
  2268. }
  2269. continue
  2270. }
  2271. // todo 开票套餐类型
  2272. k2 += 1
  2273. if k == k2 {
  2274. if v != "" {
  2275. }
  2276. continue
  2277. }
  2278. // 开票销售
  2279. k2 += 1
  2280. if k == k2 {
  2281. if v != "" {
  2282. sellerItem := sellerMap[v]
  2283. if sellerItem == nil {
  2284. resp.Fail(fmt.Sprintf("第%d行开票销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2285. return
  2286. }
  2287. rowInvoices[ir].SellerId = sellerItem.SellerId
  2288. rowInvoices[ir].SellerName = sellerItem.SellerName
  2289. rowInvoices[ir].SellerGroupId = sellerItem.GroupId
  2290. rowInvoices[ir].SellerGroupName = sellerItem.GroupName
  2291. rowInvoices[ir].SellerTeamId = sellerItem.TeamId
  2292. rowInvoices[ir].SellerTeamName = sellerItem.TeamName
  2293. }
  2294. continue
  2295. }
  2296. // 备注
  2297. k2 += 1
  2298. if k == k2 {
  2299. if v != "" {
  2300. rowInvoices[ir].Remark = v
  2301. }
  2302. continue
  2303. }
  2304. }
  2305. // 到款列表
  2306. for ir := 0; ir < invoiceMax; ir++ {
  2307. n := ir + 1
  2308. // 到款日
  2309. k2 += 1
  2310. if k == k2 {
  2311. if v != "" {
  2312. va := cell.Value
  2313. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2314. if e != nil {
  2315. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2316. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2317. if e != nil {
  2318. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式转换有误, 请按模板导入", i+1, n), c)
  2319. return
  2320. }
  2321. }
  2322. if invoiceDate.Before(checkDate) {
  2323. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式有误, 请按模板导入", i+1, n), c)
  2324. return
  2325. }
  2326. rowPayments[ir].InvoiceDate = invoiceDate
  2327. rowPayments[ir].ContractCode = rowRegister.ContractCode
  2328. rowPayments[ir].InvoiceType = fms.ContractInvoiceTypePay
  2329. }
  2330. continue
  2331. }
  2332. // 到款金额
  2333. k2 += 1
  2334. if k == k2 {
  2335. if v != "" {
  2336. amountStr := v
  2337. amount, e := strconv.ParseFloat(amountStr, 64)
  2338. if e != nil {
  2339. resp.Fail(fmt.Sprintf("第%d行到款金额%d有误, 请按模板导入", i+1, n), c)
  2340. return
  2341. }
  2342. if rowRegister.RMBRate <= 0 {
  2343. resp.Fail(fmt.Sprintf("第%d行到款金额换算%d有误, 请按模板导入金额单位", i+1, n), c)
  2344. return
  2345. }
  2346. // 付款方式
  2347. dayDiff := rowRegister.EndDate.Sub(rowRegister.StartDate).Hours() / 24
  2348. contractAmount := rowRegister.ContractAmount
  2349. payType := fmsService.CalculateContractPaymentType(amount, contractAmount, dayDiff)
  2350. rowPayments[ir].PayType = payType
  2351. rowPayments[ir].OriginAmount = amount
  2352. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amount/rowRegister.RMBRate), 64)
  2353. rowPayments[ir].Amount = a
  2354. }
  2355. continue
  2356. }
  2357. // todo 到款套餐类型
  2358. k2 += 1
  2359. if k == k2 {
  2360. if v != "" {
  2361. }
  2362. continue
  2363. }
  2364. // 备注
  2365. k2 += 1
  2366. if k == k2 {
  2367. if v != "" {
  2368. rowPayments[ir].Remark = v
  2369. }
  2370. continue
  2371. }
  2372. }
  2373. }
  2374. if isSkip {
  2375. continue
  2376. }
  2377. // 小套餐
  2378. if len(rowChartPermissionIdArr) > 0 {
  2379. // 说明有小套餐
  2380. tempItem := serviceTempNameMap["FICC小套餐"]
  2381. if tempItem == nil {
  2382. resp.Fail(fmt.Sprintf("第%d行小套餐名称不匹配, 请按模板导入", i+1), c)
  2383. return
  2384. }
  2385. rowChartPermissionIds := strings.Join(rowChartPermissionIdArr, ",")
  2386. cs := &fms.ContractService{
  2387. ProductId: crm.CompanyProductFicc,
  2388. ServiceTemplateId: tempItem.ServiceTemplateId,
  2389. Title: tempItem.Title,
  2390. Value: tempItem.Value,
  2391. TableValue: tempItem.TableValue,
  2392. ChartPermissionId: tempItem.ChartPermissionId,
  2393. ChartPermissionIds: rowChartPermissionIds,
  2394. }
  2395. cs.Set()
  2396. rowServices = append(rowServices, cs)
  2397. }
  2398. // 如果导入的最后一条合同编号为空并且合同编号之后的字段均为空
  2399. // excel这个包读行的时候不会再往后面没数据的地方读取, 所以此处需要重新判断一次
  2400. if rowRegister.ContractCode == "" {
  2401. resp.Fail(fmt.Sprintf("第%d行合同编号为空", i+1), c)
  2402. return
  2403. }
  2404. rowRegister.RegisterStatus = fms.ContractRegisterStatusIng
  2405. rowInvoiceList := make([]*fms.ContractInvoice, 0)
  2406. // 过滤信息不完整的开票到款
  2407. for l := range rowInvoices {
  2408. if rowInvoices[l].ContractCode != "" {
  2409. if rowInvoices[l].OriginAmount <= 0 || rowInvoices[l].SellerId == 0 {
  2410. resp.Fail(fmt.Sprintf("第%d行开票信息必填项不完整", i+1), c)
  2411. return
  2412. }
  2413. rowInvoiceList = append(rowInvoiceList, rowInvoices[l])
  2414. }
  2415. }
  2416. for l := range rowPayments {
  2417. if rowPayments[l].ContractCode != "" {
  2418. if rowPayments[l].OriginAmount <= 0 {
  2419. resp.Fail(fmt.Sprintf("第%d行到款信息必填项不完整", i+1), c)
  2420. return
  2421. }
  2422. rowInvoiceList = append(rowInvoiceList, rowPayments[l])
  2423. }
  2424. }
  2425. // 新增登记、套餐、开票到款信息
  2426. for proId, _ := range productIds {
  2427. rowRegister.ProductIds += strconv.Itoa(proId)+","
  2428. }
  2429. rowRegister.ProductIds = strings.Trim(rowRegister.ProductIds, ",")
  2430. newId, e := fms.CreateImportContractRegister(rowRegister, rowServices, rowInvoiceList, rowServiceAmount)
  2431. if e != nil {
  2432. resp.FailData(fmt.Sprintf("第%d行导入失败", i+1), "新增导入登记失败, Err: "+e.Error(), c)
  2433. return
  2434. }
  2435. newIds = append(newIds, newId)
  2436. }
  2437. }
  2438. }
  2439. resp.Ok("操作成功", c)
  2440. }
  2441. // CurrencyList
  2442. // @Title 货币单位列表
  2443. // @Description 货币单位列表
  2444. // @Success 200 {object} fms.CurrencyUnitItem
  2445. // @router /contract/register/currency_list [get]
  2446. func (rg *RegisterController) CurrencyList(c *gin.Context) {
  2447. list, e := fmsService.GetTodayCurrencyRateList()
  2448. if e != nil {
  2449. resp.FailData("获取失败", "获取今日货币汇率列表失败, Err: "+e.Error(), c)
  2450. return
  2451. }
  2452. resp.OkData("获取成功", list, c)
  2453. }