register.go 68 KB

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