register.go 71 KB

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