register.go 71 KB

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