register.go 71 KB

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