register.go 67 KB

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