register.go 71 KB

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