register.go 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824
  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 rai_seller_name LIKE ? OR actual_company_name LIKE ?)`
  57. pars = append(pars, kw, 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.ServiceTypes != "" {
  75. serviceTypes := strings.Split(req.ServiceTypes, ",")
  76. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  77. if e != nil {
  78. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  79. return
  80. }
  81. if len(registerIds) > 0 {
  82. cond += ` AND contract_register_id IN ?`
  83. pars = append(pars, registerIds)
  84. } else {
  85. cond += ` AND 1 = 2`
  86. }
  87. }
  88. page := new(base.Page)
  89. page.SetPageSize(req.PageSize)
  90. page.SetCurrent(req.Current)
  91. page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: false})
  92. total, list, e := fms.GetContractRegisterItemPageList(page, cond, pars)
  93. if e != nil {
  94. resp.FailMsg("获取失败", "获取合同登记列表失败, Err: "+e.Error(), c)
  95. return
  96. }
  97. registerIds := make([]int, 0)
  98. for i := range list {
  99. registerIds = append(registerIds, list[i].ContractRegisterId)
  100. }
  101. serviceMap := make(map[int]string, 0)
  102. invoiceMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  103. paymentMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  104. if len(registerIds) > 0 {
  105. // 获取所有的服务套餐
  106. serviceMap, _, e = fmsService.GetContractServiceNameFormat(registerIds)
  107. if e != nil {
  108. resp.FailMsg("获取失败", e.Error(), c)
  109. return
  110. }
  111. // 获取开票/到款列表
  112. invoiceCond := `contract_register_id IN ?`
  113. invoicePars := make([]interface{}, 0)
  114. invoicePars = append(invoicePars, registerIds)
  115. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  116. if e != nil {
  117. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  118. return
  119. }
  120. for i := range invoiceList {
  121. if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  122. invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  123. }
  124. if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  125. paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  126. }
  127. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  128. invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  129. }
  130. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  131. paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  132. }
  133. }
  134. }
  135. respList := make([]*fms.ContractRegisterList, 0)
  136. for i := range list {
  137. v := new(fms.ContractRegisterList)
  138. v.ContractRegisterItem = list[i]
  139. v.ServicesName = serviceMap[list[i].ContractRegisterId]
  140. v.InvoiceList = invoiceMap[list[i].ContractRegisterId]
  141. v.PaymentList = paymentMap[list[i].ContractRegisterId]
  142. respList = append(respList, v)
  143. }
  144. page.SetTotal(total)
  145. baseData := new(base.BaseData)
  146. baseData.SetPage(page)
  147. baseData.SetList(respList)
  148. resp.OkData("获取成功", baseData, c)
  149. }
  150. // Add
  151. // @Title 新增合同登记
  152. // @Description 新增合同登记
  153. // @Param request body fms.ContractRegisterAddReq true "type json string"
  154. // @Success 200 string "操作成功"
  155. // @router /contract/register/add [post]
  156. func (rg *RegisterController) Add(c *gin.Context) {
  157. req := new(fms.ContractRegisterAddReq)
  158. err := c.ShouldBind(&req)
  159. if err != nil {
  160. errs, ok := err.(validator.ValidationErrors)
  161. if !ok {
  162. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  163. return
  164. }
  165. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  166. return
  167. }
  168. claims, _ := c.Get("adminInfo")
  169. adminInfo := claims.(*system.SysAdmin)
  170. // 日期校验
  171. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  172. if e != nil {
  173. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  174. return
  175. }
  176. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  177. if e != nil {
  178. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  179. return
  180. }
  181. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  182. if req.SignDate != "" {
  183. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  184. if e != nil {
  185. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  186. return
  187. }
  188. signDate = signDateTime
  189. }
  190. // 是否存在相同合同编号的登记
  191. ob := new(fms.ContractRegister)
  192. existCond := `contract_code = ?`
  193. existPars := make([]interface{}, 0)
  194. existPars = append(existPars, req.ContractCode)
  195. exist, e := ob.FetchByCondition(existCond, existPars)
  196. if e != nil && e != utils.ErrNoRow {
  197. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  198. return
  199. }
  200. if exist != nil && exist.ContractRegisterId > 0 {
  201. resp.Fail("合同编号已存在", c)
  202. return
  203. }
  204. // 货币及汇率
  205. rateList, e := fmsService.GetTodayCurrencyRateList()
  206. if e != nil {
  207. resp.FailMsg("操作失败", "获取今日货币汇率失败, Err: "+e.Error(), c)
  208. return
  209. }
  210. var rate float64
  211. for i := range rateList {
  212. if req.CurrencyUnit == rateList[i].Code {
  213. rate = rateList[i].RMBRate
  214. break
  215. }
  216. }
  217. if rate <= 0 {
  218. resp.FailMsg("操作失败", "货币汇率信息有误", c)
  219. return
  220. }
  221. // 查询销售信息
  222. var (
  223. sellerId int
  224. raiSellerId int
  225. sellerName string
  226. raiSellerName string
  227. )
  228. if req.SellerIds != "" {
  229. admin := new(crm.Admin)
  230. sellerIds := strings.Split(req.SellerIds, ",")
  231. if len(sellerIds) > 2 {
  232. resp.Fail("最多只能选择两个销售", c)
  233. return
  234. }
  235. var pars []interface{}
  236. cond := ` admin_id in (?) `
  237. pars = append(pars, sellerIds)
  238. sellers, e := admin.List(cond, pars)
  239. if e != nil {
  240. resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
  241. return
  242. }
  243. for _, v := range sellers {
  244. if v.DepartmentId == crm.SellerDepartmentId {
  245. sellerId = v.AdminId
  246. sellerName = v.AdminName
  247. }else if v.DepartmentId == crm.RaiSellerDepartmentId {
  248. raiSellerId = v.AdminId
  249. raiSellerName = v.AdminName
  250. }
  251. }
  252. }
  253. nowTime := time.Now().Local()
  254. ob.ContractCode = req.ContractCode
  255. ob.RelateContractCode = req.RelateContractCode
  256. ob.CrmContractId = req.CrmContractId
  257. ob.ContractSource = req.ContractSource
  258. ob.CompanyName = req.CompanyName
  259. ob.ActualCompanyName = req.ActualCompanyName
  260. ob.ProductIds = req.ProductIds
  261. ob.SellerId = sellerId
  262. ob.SellerName = sellerName
  263. ob.RaiSellerId = raiSellerId
  264. ob.RaiSellerName = raiSellerName
  265. ob.ContractType = req.ContractType
  266. ob.ContractAmount = req.ContractAmount
  267. ob.CurrencyUnit = req.CurrencyUnit
  268. ob.RMBRate = rate
  269. ob.StartDate = startDate
  270. ob.EndDate = endDate
  271. ob.SignDate = signDate
  272. ob.AgreedPayTime = req.AgreedPayTime
  273. ob.ContractStatus = req.ContractStatus
  274. ob.RegisterStatus = fms.ContractRegisterStatusIng
  275. ob.Remark = req.Remark
  276. ob.ServiceRemark = req.ServiceRemark
  277. ob.HasPayment = req.HasPayment
  278. ob.NewCompany = req.NewCompany
  279. ob.Set()
  280. // 存在代付的直接完成登记, 且不允许进行开票/到款登记
  281. if req.HasPayment == 1 || req.ContractStatus == fms.ContractStatusEnd {
  282. ob.RegisterStatus = fms.ContractRegisterStatusComplete
  283. }
  284. // 新增套餐金额详情内容
  285. serviceAmountMap := make(map[int]float64)
  286. serviceAmountList, e := fmsService.HandleContractServiceAmount(req.ServiceAmount, serviceAmountMap, req.CurrencyUnit)
  287. if e != nil {
  288. resp.FailMsg("操作失败", "新增合同套餐金额信息失败, Err: "+e.Error(), c)
  289. return
  290. }
  291. // 套餐信息
  292. serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
  293. if e != nil {
  294. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  295. return
  296. }
  297. // 新增合同及套餐
  298. if req.Supplement == 1 {
  299. //新增到款信息
  300. if ob.HasPayment == 1 {
  301. resp.Fail("合同存在代付不允许添加开票/到款登记", c)
  302. return
  303. }
  304. //新增合同信息
  305. if e = fms.CreateContractRegisterAndServicesAndPayMent(ob, serviceList, req.PrePayId); e != nil {
  306. resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
  307. return
  308. }
  309. prePayOB := new(fms.ContractPrePayment)
  310. ppItem, e := prePayOB.Fetch(req.PrePayId)
  311. if e != nil {
  312. if e == utils.ErrNoRow {
  313. resp.Fail("预到款不存在或已被删除", c)
  314. return
  315. }
  316. resp.FailMsg("获取预到款记录失败", "Err:"+e.Error(), c)
  317. return
  318. }
  319. // 合同有效时长(计算付款方式)
  320. dayDiff := ob.EndDate.Sub(ob.StartDate).Hours() / 24
  321. // 获取销售分组信息
  322. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  323. if e != nil {
  324. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  325. return
  326. }
  327. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  328. for i := range sellerList {
  329. sellerMap[sellerList[i].SellerId] = sellerList[i]
  330. }
  331. v := &fms.ContractInvoice{
  332. ContractRegisterId: ob.ContractRegisterId,
  333. ContractCode: ob.ContractCode,
  334. Amount: ppItem.Amount,
  335. OriginAmount: ppItem.OriginAmount,
  336. CurrencyUnit: ppItem.CurrencyUnit,
  337. InvoiceType: fms.ContractInvoiceTypePay,
  338. InvoiceDate: ppItem.PaymentDate,
  339. AdminId: int(adminInfo.AdminId),
  340. AdminName: adminInfo.RealName,
  341. Remark: ppItem.Remark,
  342. IsPrePay: 1,
  343. }
  344. v.Set()
  345. // 到款登记-付款方式
  346. v.PayType = fmsService.CalculateContractPaymentType(ppItem.Amount, ob.ContractAmount, dayDiff)
  347. // 新增的记录
  348. logList := make([]*fms.ContractRegisterLog, 0)
  349. opData := ""
  350. opDataByte, e := json.Marshal(req)
  351. if e != nil {
  352. return
  353. }
  354. opData = string(opDataByte)
  355. opType := fms.ContractInvoiceTypePrePay
  356. newAmount := decimal.NewFromFloat(0).Round(2)
  357. a := decimal.NewFromFloat(v.Amount).Round(2)
  358. newAmount = newAmount.Add(a)
  359. ia, _ := newAmount.Round(2).Float64()
  360. logList = append(logList, &fms.ContractRegisterLog{
  361. ContractRegisterId: ob.ContractRegisterId,
  362. AdminId: int(adminInfo.AdminId),
  363. AdminName: adminInfo.RealName,
  364. OpData: opData,
  365. OpType: opType,
  366. CreateTime: nowTime,
  367. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  368. })
  369. if e := v.Create(); e != nil {
  370. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  371. return
  372. }
  373. //最后删除预到款记录
  374. e = ppItem.Delete()
  375. if e != nil {
  376. resp.FailMsg("删除预到款记录失败", "Err:"+e.Error(), c)
  377. return
  378. }
  379. // 校验金额-是否修改状态
  380. go fmsService.CheckContractRegisterAmount(ob.ContractRegisterId)
  381. // 开票到款汇总
  382. go fmsService.SummaryInvoicePaymentByContractRegisterId(ob.ContractRegisterId)
  383. // 操作日志
  384. go func() {
  385. logOB := new(fms.ContractRegisterLog)
  386. if e := logOB.AddInBatches(logList); e != nil {
  387. return
  388. }
  389. }()
  390. } else {
  391. if e = fms.CreateContractRegisterAndServices(ob, serviceList, serviceAmountList); e != nil {
  392. resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
  393. return
  394. }
  395. }
  396. // 操作日志
  397. go func() {
  398. opData := ""
  399. opDataByte, e := json.Marshal(req)
  400. if e != nil {
  401. return
  402. }
  403. opData = string(opDataByte)
  404. logItem := new(fms.ContractRegisterLog)
  405. logItem.ContractRegisterId = ob.ContractRegisterId
  406. logItem.AdminId = int(adminInfo.AdminId)
  407. logItem.AdminName = adminInfo.RealName
  408. logItem.OpData = opData
  409. logItem.OpType = fms.ContractRegisterOpTypeSave
  410. logItem.CreateTime = nowTime
  411. logItem.Remark = req.Remark
  412. if e = logItem.Create(); e != nil {
  413. return
  414. }
  415. }()
  416. resp.Ok("操作成功", c)
  417. }
  418. // Edit
  419. // @Title 编辑合同登记
  420. // @Description 编辑合同登记
  421. // @Param request body fms.ContractRegisterEditReq true "type json string"
  422. // @Success 200 string "操作成功"
  423. // @router /contract/register/edit [post]
  424. func (rg *RegisterController) Edit(c *gin.Context) {
  425. req := new(fms.ContractRegisterEditReq)
  426. err := c.ShouldBind(&req)
  427. if err != nil {
  428. errs, ok := err.(validator.ValidationErrors)
  429. if !ok {
  430. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  431. return
  432. }
  433. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  434. return
  435. }
  436. claims, _ := c.Get("adminInfo")
  437. adminInfo := claims.(*system.SysAdmin)
  438. // 日期校验
  439. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  440. if e != nil {
  441. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  442. return
  443. }
  444. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  445. if e != nil {
  446. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  447. return
  448. }
  449. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  450. if req.SignDate != "" {
  451. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  452. if e != nil {
  453. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  454. return
  455. }
  456. signDate = signDateTime
  457. }
  458. ob := new(fms.ContractRegister)
  459. item, e := ob.Fetch(req.ContractRegisterId)
  460. if e != nil {
  461. if e == utils.ErrNoRow {
  462. resp.Fail("登记记录不存在或已被删除", c)
  463. return
  464. }
  465. resp.FailMsg("操作失败", "获取合同登记信息失败, Err:"+e.Error(), c)
  466. return
  467. }
  468. // 查询销售信息
  469. var (
  470. sellerId int
  471. raiSellerId int
  472. sellerName string
  473. raiSellerName string
  474. )
  475. if req.SellerIds != "" {
  476. admin := new(crm.Admin)
  477. sellerIds := strings.Split(req.SellerIds, ",")
  478. if len(sellerIds) > 2 {
  479. resp.Fail("最多只能选择两个销售", c)
  480. return
  481. }
  482. var pars []interface{}
  483. cond := ` admin_id in (?) `
  484. pars = append(pars, sellerIds)
  485. sellers, e := admin.List(cond, pars)
  486. if e != nil {
  487. resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
  488. return
  489. }
  490. for _, v := range sellers {
  491. if v.DepartmentId == crm.SellerDepartmentId {
  492. sellerId = v.AdminId
  493. sellerName = v.AdminName
  494. }else if v.DepartmentId == crm.RaiSellerDepartmentId {
  495. raiSellerId = v.AdminId
  496. raiSellerName = v.AdminName
  497. }
  498. }
  499. }
  500. // 是否存在相同合同编号的登记
  501. existCond := `contract_code = ?`
  502. existPars := make([]interface{}, 0)
  503. existPars = append(existPars, req.ContractCode)
  504. exist, e := ob.FetchByCondition(existCond, existPars)
  505. if e != nil && e != utils.ErrNoRow {
  506. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  507. return
  508. }
  509. if exist != nil && exist.ContractRegisterId > 0 && exist.ContractRegisterId != item.ContractRegisterId {
  510. resp.Fail("合同编号已存在", c)
  511. return
  512. }
  513. originHasPayment := item.HasPayment
  514. updateCols := []string{
  515. "ProductIds","ContractCode", "RelateContractCode", "CrmContractId", "ContractSource", "CompanyName", "ActualCompanyName",
  516. "SellerId", "SellerName", "ContractType", "ContractAmount", "StartDate", "EndDate", "SignDate", "AgreedPayTime",
  517. "ContractStatus", "RegisterStatus", "Remark", "ServiceRemark", "HasPayment", "NewCompany", "ActualPayCompanies", "ModifyTime",
  518. }
  519. nowTime := time.Now().Local()
  520. item.ProductIds = req.ProductIds
  521. item.ContractCode = req.ContractCode
  522. item.RelateContractCode = req.RelateContractCode
  523. item.CrmContractId = req.CrmContractId
  524. item.ContractSource = req.ContractSource
  525. item.CompanyName = req.CompanyName
  526. item.ActualCompanyName = req.ActualCompanyName
  527. item.SellerId = sellerId
  528. item.SellerName = sellerName
  529. item.RaiSellerId = raiSellerId
  530. item.RaiSellerName = raiSellerName
  531. item.ContractType = req.ContractType
  532. item.ContractAmount = req.ContractAmount
  533. item.StartDate = startDate
  534. item.EndDate = endDate
  535. item.SignDate = signDate
  536. item.AgreedPayTime = req.AgreedPayTime
  537. item.ContractStatus = req.ContractStatus
  538. item.RegisterStatus = fms.ContractRegisterStatusIng
  539. item.Remark = req.Remark
  540. item.ServiceRemark = req.ServiceRemark
  541. item.HasPayment = req.HasPayment
  542. item.NewCompany = req.NewCompany
  543. item.ActualPayCompanies = req.ActualPayCompanies
  544. item.ModifyTime = nowTime
  545. // 存在代付的直接完成登记, 且不允许进行开票/到款登记
  546. if req.HasPayment == 1 {
  547. item.RegisterStatus = fms.ContractRegisterStatusComplete
  548. updateCols = append(updateCols, "RegisterStatus")
  549. }
  550. // 开票到款信息
  551. invoiceOB := new(fms.ContractInvoice)
  552. invoiceCond := `contract_register_id = ?`
  553. invoicePars := make([]interface{}, 0)
  554. invoicePars = append(invoicePars, req.ContractRegisterId)
  555. invoiceList, e := invoiceOB.List(invoiceCond, invoicePars, "")
  556. if e != nil {
  557. resp.FailMsg("操作失败", "获取合同开票到款列表失败, Err: "+e.Error(), c)
  558. return
  559. }
  560. invoiceUpdateCols := make([]string, 0)
  561. // 开票到款操作类型: 0-无; 1-更新; 2-删除;
  562. logRemark := req.Remark
  563. invoiceHandleType := 0
  564. if originHasPayment == 0 && req.HasPayment == 1 {
  565. // 若从无代付修改为有代付, 则删除无代付期间新增的所有开票到款登记
  566. invoiceHandleType = 2
  567. } else {
  568. // 修改了货币单位后,同步更新汇率及开票到款的换算金额
  569. if req.CurrencyUnit != item.CurrencyUnit {
  570. rateList, e := fmsService.GetTodayCurrencyRateList()
  571. if e != nil {
  572. resp.FailMsg("操作失败", "获取货币列表及汇率失败, Err: "+e.Error(), c)
  573. return
  574. }
  575. var rate float64
  576. for i := range rateList {
  577. if rateList[i].Code == req.CurrencyUnit {
  578. rate = rateList[i].RMBRate
  579. break
  580. }
  581. }
  582. if rate < 0 {
  583. resp.FailMsg("操作失败", "货币汇率有误", c)
  584. return
  585. }
  586. item.CurrencyUnit = req.CurrencyUnit
  587. item.RMBRate = rate
  588. updateCols = append(updateCols, "CurrencyUnit", "RMBRate")
  589. // 调整开票到款换算后的金额, 保留两位小数
  590. for i := range invoiceList {
  591. invoiceList[i].CurrencyUnit = req.CurrencyUnit
  592. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceList[i].OriginAmount/rate), 64)
  593. invoiceList[i].Amount = a
  594. }
  595. invoiceUpdateCols = append(invoiceUpdateCols, "CurrencyUnit", "Amount")
  596. invoiceHandleType = 1
  597. logRemark = fmt.Sprintf("金额单位由%s修改为%s\n%s", item.CurrencyUnit, req.CurrencyUnit, logRemark)
  598. }
  599. }
  600. // 新增套餐金额详情内容
  601. serviceAmountMap := make(map[int]float64)
  602. serviceAmountList, e := fmsService.HandleContractServiceAmount(req.ServiceAmount, serviceAmountMap, req.CurrencyUnit)
  603. if e != nil {
  604. resp.FailMsg("操作失败", "新增合同套餐金额信息失败, Err: "+e.Error(), c)
  605. return
  606. }
  607. // 套餐信息
  608. serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
  609. if e != nil {
  610. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  611. return
  612. }
  613. // 更新合同登记、套餐、开票到款
  614. if e = fms.UpdateContractRegister(item, updateCols, serviceList, invoiceList, invoiceUpdateCols, invoiceHandleType, serviceAmountList); e != nil {
  615. resp.FailMsg("操作失败", "更新合同及套餐失败, Err: "+e.Error(), c)
  616. return
  617. }
  618. // 校验金额-是否修改状态
  619. go fmsService.CheckContractRegisterAmount(item.ContractRegisterId)
  620. // 操作日志
  621. go func() {
  622. opData := ""
  623. opDataByte, e := json.Marshal(req)
  624. if e != nil {
  625. return
  626. }
  627. opData = string(opDataByte)
  628. logItem := new(fms.ContractRegisterLog)
  629. logItem.ContractRegisterId = item.ContractRegisterId
  630. logItem.AdminId = int(adminInfo.AdminId)
  631. logItem.AdminName = adminInfo.RealName
  632. logItem.OpData = opData
  633. logItem.OpType = fms.ContractRegisterOpTypeEdit
  634. logItem.CreateTime = nowTime
  635. logItem.Remark = logRemark
  636. if e = logItem.Create(); e != nil {
  637. return
  638. }
  639. }()
  640. resp.Ok("操作成功", c)
  641. }
  642. // Del
  643. // @Title 删除合同登记
  644. // @Description 删除合同登记
  645. // @Param request body fms.ContractRegisterDelReq true "type json string"
  646. // @Success 200 string "操作成功"
  647. // @router /contract/register/del [post]
  648. func (rg *RegisterController) Del(c *gin.Context) {
  649. req := new(fms.ContractRegisterDelReq)
  650. err := c.ShouldBind(&req)
  651. if err != nil {
  652. errs, ok := err.(validator.ValidationErrors)
  653. if !ok {
  654. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  655. return
  656. }
  657. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  658. return
  659. }
  660. claims, _ := c.Get("adminInfo")
  661. adminInfo := claims.(*system.SysAdmin)
  662. ob := new(fms.ContractRegister)
  663. item, e := ob.Fetch(req.ContractRegisterId)
  664. if e != nil {
  665. if e == utils.ErrNoRow {
  666. resp.Fail("合同登记不存在或已被删除", c)
  667. return
  668. }
  669. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  670. return
  671. }
  672. nowTime := time.Now().Local()
  673. item.IsDeleted = 1
  674. item.ModifyTime = nowTime
  675. updateCols := []string{"IsDeleted", "ModifyTime"}
  676. if e = item.Update(updateCols); e != nil {
  677. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  678. return
  679. }
  680. // 删除对应的开票到款登记
  681. go func() {
  682. if e = fms.DeleteContractInvoicesByRegisterId(item.ContractRegisterId); e != nil {
  683. alarm_msg.SendAlarmMsg(fmt.Sprintf("删除合同登记%d后, 删除开票到款记录失败, ErrMsg: %s", item.ContractRegisterId, e.Error()), 3)
  684. return
  685. }
  686. if e = fms.DeleteInvoicePaymentSummaryByRegisterId(item.ContractRegisterId); e != nil {
  687. alarm_msg.SendAlarmMsg(fmt.Sprintf("删除合同登记%d后, 删除开票到款汇总数据失败, ErrMsg: %s", item.ContractRegisterId, e.Error()), 3)
  688. return
  689. }
  690. }()
  691. // 操作日志
  692. go func() {
  693. opData := ""
  694. opDataByte, e := json.Marshal(req)
  695. if e != nil {
  696. return
  697. }
  698. opData = string(opDataByte)
  699. logItem := new(fms.ContractRegisterLog)
  700. logItem.ContractRegisterId = req.ContractRegisterId
  701. logItem.AdminId = int(adminInfo.AdminId)
  702. logItem.AdminName = adminInfo.RealName
  703. logItem.OpData = opData
  704. logItem.OpType = fms.ContractRegisterOpTypeDel
  705. logItem.CreateTime = nowTime
  706. if e = logItem.Create(); e != nil {
  707. return
  708. }
  709. }()
  710. resp.Ok("操作成功", c)
  711. }
  712. // Detail
  713. // @Title 合同登记详情
  714. // @Description 合同登记详情
  715. // @Param ContractRegisterId query int false "合同登记ID"
  716. // @Success 200 {object} fms.ContractRegisterDetail
  717. // @router /contract/register/detail [get]
  718. func (rg *RegisterController) Detail(c *gin.Context) {
  719. var req fms.ContractRegisterDetailReq
  720. if e := c.BindQuery(&req); e != nil {
  721. err, ok := e.(validator.ValidationErrors)
  722. if !ok {
  723. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  724. return
  725. }
  726. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  727. return
  728. }
  729. result := new(fms.ContractRegisterDetail)
  730. // 合同登记信息
  731. item, e := fms.GetContractRegisterItemById(req.ContractRegisterId)
  732. if e != nil {
  733. resp.FailData("获取失败", "获取合同登记详情失败, Err:"+e.Error(), c)
  734. return
  735. }
  736. result.ContractRegisterItem = item
  737. // 套餐信息
  738. serviceAmountTempList, e := fms.GetContractServiceAmountByRegisterId(req.ContractRegisterId)
  739. if e != nil {
  740. resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
  741. return
  742. }
  743. serviceAmountList := make([]*fms.ContractServiceAmountItem, 0)
  744. for _, v := range serviceAmountTempList {
  745. tmp := &fms.ContractServiceAmountItem{
  746. ContractRegisterId: v.ContractRegisterId,
  747. ProductId: v.ProductId,
  748. ServiceAmount: v.ServiceAmount,
  749. CurrencyUnit: v.CurrencyUnit,
  750. }
  751. serviceAmountList = append(serviceAmountList, tmp)
  752. }
  753. result.ServiceAmountList = serviceAmountList
  754. // 套餐金额信息
  755. serviceList, e := fmsService.GetContractServiceAndDetail(req.ContractRegisterId)
  756. if e != nil {
  757. resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
  758. return
  759. }
  760. result.ServiceList = serviceList
  761. // 开票/到款信息
  762. invoiceCond := `contract_register_id = ?`
  763. invoicePars := make([]interface{}, 0)
  764. invoicePars = append(invoicePars, req.ContractRegisterId)
  765. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  766. if e != nil {
  767. resp.FailData("获取失败", "获取合同开票/到款信息失败, Err: "+e.Error(), c)
  768. return
  769. }
  770. result.InvoiceList = make([]*fms.ContractInvoiceItem, 0)
  771. result.PaymentList = make([]*fms.ContractInvoiceItem, 0)
  772. for i := range invoiceList {
  773. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  774. result.InvoiceList = append(result.InvoiceList, invoiceList[i])
  775. continue
  776. }
  777. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  778. result.PaymentList = append(result.PaymentList, invoiceList[i])
  779. }
  780. }
  781. // 合同登记进度
  782. logCond := `contract_register_id = ?`
  783. logPars := make([]interface{}, 0)
  784. logPars = append(logPars, req.ContractRegisterId)
  785. logList, e := fms.GetContractRegisterLogItemList(logCond, logPars)
  786. if e != nil {
  787. resp.FailData("获取失败", "获取合同登记进度失败, Err: "+e.Error(), c)
  788. return
  789. }
  790. result.Logs = logList
  791. resp.OkData("获取成功", result, c)
  792. }
  793. // UpdateStatus
  794. // @Title 修改合同状态
  795. // @Description 修改合同状态
  796. // @Param request body fms.ContractRegisterUpdateStatusReq true "type json string"
  797. // @Success 200 string "操作成功"
  798. // @router /contract/register/update_status [post]
  799. func (rg *RegisterController) UpdateStatus(c *gin.Context) {
  800. req := new(fms.ContractRegisterUpdateStatusReq)
  801. err := c.ShouldBind(&req)
  802. if err != nil {
  803. errs, ok := err.(validator.ValidationErrors)
  804. if !ok {
  805. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  806. return
  807. }
  808. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  809. return
  810. }
  811. claims, _ := c.Get("adminInfo")
  812. adminInfo := claims.(*system.SysAdmin)
  813. ob := new(fms.ContractRegister)
  814. item, e := ob.Fetch(req.ContractRegisterId)
  815. if e != nil {
  816. if e == utils.ErrNoRow {
  817. resp.Fail("合同登记不存在或已被删除", c)
  818. return
  819. }
  820. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  821. return
  822. }
  823. nowTime := time.Now().Local()
  824. item.ContractStatus = req.ContractStatus
  825. item.ModifyTime = nowTime
  826. updateCols := []string{"ContractStatus", "ModifyTime"}
  827. if e = item.Update(updateCols); e != nil {
  828. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  829. return
  830. }
  831. // 校验金额-是否修改状态
  832. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  833. // 操作日志
  834. go func() {
  835. opData := ""
  836. opDataByte, e := json.Marshal(req)
  837. if e != nil {
  838. return
  839. }
  840. opData = string(opDataByte)
  841. logItem := new(fms.ContractRegisterLog)
  842. logItem.ContractRegisterId = req.ContractRegisterId
  843. logItem.AdminId = int(adminInfo.AdminId)
  844. logItem.AdminName = adminInfo.RealName
  845. logItem.OpData = opData
  846. logItem.OpType = fms.ContractRegisterOpTypeStatus
  847. logItem.CreateTime = nowTime
  848. if e = logItem.Create(); e != nil {
  849. return
  850. }
  851. }()
  852. resp.Ok("操作成功", c)
  853. }
  854. // Invoice
  855. // @Title 开票/到款登记
  856. // @Description 开票/到款登记
  857. // @Param request body fms.ContractInvoiceSaveReq true "type json string"
  858. // @Success 200 string "操作成功"
  859. // @router /contract/register/invoice [post]
  860. func (rg *RegisterController) Invoice(c *gin.Context) {
  861. req := new(fms.ContractInvoiceSaveReq)
  862. err := c.ShouldBind(&req)
  863. if err != nil {
  864. errs, ok := err.(validator.ValidationErrors)
  865. if !ok {
  866. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  867. return
  868. }
  869. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  870. return
  871. }
  872. claims, _ := c.Get("adminInfo")
  873. adminInfo := claims.(*system.SysAdmin)
  874. registerOB := new(fms.ContractRegister)
  875. item, e := registerOB.Fetch(req.ContractRegisterId)
  876. if e != nil {
  877. if e == utils.ErrNoRow {
  878. resp.Fail("合同登记不存在或已被删除", c)
  879. return
  880. }
  881. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  882. return
  883. }
  884. // 合同存在代付不允许开票/到款登记
  885. if item.HasPayment == 1 {
  886. resp.Fail("合同存在代付不允许添加开票/到款登记", c)
  887. return
  888. }
  889. noChangeInvoiceIds := make([]int, 0)
  890. newInvoice := make([]*fms.ContractInvoice, 0)
  891. if len(req.AmountList) > 0 {
  892. // 合同有效时长(计算付款方式)
  893. dayDiff := item.EndDate.Sub(item.StartDate).Hours() / 24
  894. // 获取销售分组信息
  895. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  896. if e != nil {
  897. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  898. return
  899. }
  900. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  901. for i := range sellerList {
  902. sellerMap[sellerList[i].SellerId] = sellerList[i]
  903. }
  904. for i := range req.AmountList {
  905. if req.AmountList[i].Amount <= 0 {
  906. resp.Fail("登记金额有误", c)
  907. return
  908. }
  909. if req.AmountList[i].InvoiceDate == "" {
  910. resp.Fail("请选择日期", c)
  911. return
  912. }
  913. // 开票登记销售必填
  914. if req.InvoiceType == fms.ContractInvoiceTypeMake && req.AmountList[i].SellerId <= 0 {
  915. resp.Fail("请选择销售", c)
  916. return
  917. }
  918. t, e := time.ParseInLocation(utils.FormatDate, req.AmountList[i].InvoiceDate, time.Local)
  919. if e != nil {
  920. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  921. return
  922. }
  923. if req.AmountList[i].InvoiceId > 0 {
  924. noChangeInvoiceIds = append(noChangeInvoiceIds, req.AmountList[i].InvoiceId)
  925. continue
  926. }
  927. if req.AmountList[i].InvoiceId == 0 {
  928. v := &fms.ContractInvoice{
  929. ContractRegisterId: req.ContractRegisterId,
  930. ContractCode: item.ContractCode,
  931. Amount: req.AmountList[i].Amount,
  932. OriginAmount: req.AmountList[i].OriginAmount,
  933. CurrencyUnit: item.CurrencyUnit,
  934. InvoiceType: req.InvoiceType,
  935. ServiceProductId: req.AmountList[i].ServiceProductId,
  936. InvoiceDate: t,
  937. AdminId: int(adminInfo.AdminId),
  938. AdminName: adminInfo.RealName,
  939. Remark: req.AmountList[i].Remark,
  940. }
  941. v.Set()
  942. // 开票登记-销售信息
  943. if req.InvoiceType == fms.ContractInvoiceTypeMake {
  944. sellerItem := sellerMap[req.AmountList[i].SellerId]
  945. if sellerItem == nil {
  946. resp.Fail("销售信息异常", c)
  947. return
  948. }
  949. if req.AmountList[i].ServiceProductId == crm.CompanyProductFicc && sellerItem.DepartmentId != crm.SellerDepartmentId {
  950. resp.Fail("销售类型和所选套餐类型不一致", c)
  951. return
  952. }
  953. if req.AmountList[i].ServiceProductId == crm.CompanyProductRai && sellerItem.DepartmentId != crm.RaiSellerDepartmentId {
  954. resp.Fail("销售类型和所选套餐类型不一致", c)
  955. return
  956. }
  957. v.SellerId = sellerItem.SellerId
  958. v.SellerName = sellerItem.SellerName
  959. v.SellerGroupId = sellerItem.GroupId
  960. v.SellerGroupName = sellerItem.GroupName
  961. v.SellerTeamId = sellerItem.TeamId
  962. v.SellerTeamName = sellerItem.TeamName
  963. }
  964. // 到款登记-付款方式
  965. if req.InvoiceType == fms.ContractInvoiceTypePay {
  966. v.PayType = fmsService.CalculateContractPaymentType(req.AmountList[i].Amount, item.ContractAmount, dayDiff)
  967. }
  968. newInvoice = append(newInvoice, v)
  969. }
  970. }
  971. }
  972. // 获取原有的登记信息
  973. invoiceCond := `contract_register_id = ? AND invoice_type = ? `
  974. invoicePars := make([]interface{}, 0)
  975. invoicePars = append(invoicePars, req.ContractRegisterId, req.InvoiceType)
  976. originInvoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  977. if e != nil {
  978. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  979. return
  980. }
  981. // 比对原有和现有的登记信息
  982. logList := make([]*fms.ContractRegisterLog, 0)
  983. opData := ""
  984. opDataByte, e := json.Marshal(req)
  985. if e != nil {
  986. return
  987. }
  988. opData = string(opDataByte)
  989. opType := fms.ContractRegisterOpTypeInvoice
  990. if req.InvoiceType == fms.ContractInvoiceTypePay {
  991. opType = fms.ContractRegisterOpTypePayment
  992. }
  993. nowTime := time.Now().Local()
  994. // 需要删除的记录
  995. deleteInvoiceIds := make([]int, 0)
  996. for i := range originInvoiceList {
  997. if !utils.InArrayByInt(noChangeInvoiceIds, originInvoiceList[i].ContractInvoiceId) {
  998. deleteInvoiceIds = append(deleteInvoiceIds, originInvoiceList[i].ContractInvoiceId)
  999. logList = append(logList, &fms.ContractRegisterLog{
  1000. ContractRegisterId: req.ContractRegisterId,
  1001. AdminId: int(adminInfo.AdminId),
  1002. AdminName: adminInfo.RealName,
  1003. OpData: opData,
  1004. OpType: opType,
  1005. CreateTime: nowTime,
  1006. AmountRemark: fmt.Sprint("删除", fms.ContractInvoiceKeyNameMap[opType], "金额", originInvoiceList[i].Amount, "元"),
  1007. })
  1008. }
  1009. }
  1010. // todo 判断是否符合均分金额的条件,如果符合,需要生成金额分配记录表
  1011. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1012. }
  1013. // 新增的记录
  1014. if len(newInvoice) > 0 {
  1015. newAmount := decimal.NewFromFloat(0).Round(2)
  1016. for i := range newInvoice {
  1017. a := decimal.NewFromFloat(newInvoice[i].Amount).Round(2)
  1018. newAmount = newAmount.Add(a)
  1019. }
  1020. ia, _ := newAmount.Round(2).Float64()
  1021. logList = append(logList, &fms.ContractRegisterLog{
  1022. ContractRegisterId: req.ContractRegisterId,
  1023. AdminId: int(adminInfo.AdminId),
  1024. AdminName: adminInfo.RealName,
  1025. OpData: opData,
  1026. OpType: opType,
  1027. CreateTime: nowTime,
  1028. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  1029. })
  1030. }
  1031. // 删除并新增登记
  1032. ob := new(fms.ContractInvoice)
  1033. if e := ob.DeleteAndCreateNewInvoice(req.ContractRegisterId, req.InvoiceType, deleteInvoiceIds, newInvoice); e != nil {
  1034. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  1035. return
  1036. }
  1037. // 校验金额-是否修改状态
  1038. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  1039. // 开票到款汇总
  1040. go fmsService.SummaryInvoicePaymentByContractRegisterId(req.ContractRegisterId)
  1041. // 操作日志
  1042. go func() {
  1043. logOB := new(fms.ContractRegisterLog)
  1044. if e := logOB.AddInBatches(logList); e != nil {
  1045. return
  1046. }
  1047. }()
  1048. resp.Ok("操作成功", c)
  1049. }
  1050. // Export
  1051. // @Title 合同登记-导出
  1052. // @Description 合同登记-导出
  1053. // @Param Keyword query string false "关键词"
  1054. // @Param StartDate query string false "合同开始日期"
  1055. // @Param EndDate query string false "合同结束日期"
  1056. // @Param ServiceType query int false "套餐类型"
  1057. // @Param ContractType query int false "合同类型"
  1058. // @Param RegisterStatus query int false "登记状态"
  1059. // @Success 200 string "操作成功"
  1060. // @router /contract/register/export [get]
  1061. func (rg *RegisterController) Export(c *gin.Context) {
  1062. var req fms.ContractRegisterListReq
  1063. if e := c.BindQuery(&req); e != nil {
  1064. err, ok := e.(validator.ValidationErrors)
  1065. if !ok {
  1066. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1067. return
  1068. }
  1069. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1070. return
  1071. }
  1072. cond := `1 = 1`
  1073. pars := make([]interface{}, 0)
  1074. // 合同编号/客户姓名/销售/实际使用方
  1075. if req.Keyword != "" {
  1076. kw := "%" + req.Keyword + "%"
  1077. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
  1078. pars = append(pars, kw, kw, kw, kw)
  1079. }
  1080. if req.StartDate != "" && req.EndDate != "" {
  1081. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1082. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1083. cond += ` AND (create_time BETWEEN ? AND ?)`
  1084. pars = append(pars, st, ed)
  1085. }
  1086. if req.ContractType != 0 {
  1087. cond += ` AND contract_type = ?`
  1088. pars = append(pars, req.ContractType)
  1089. }
  1090. if req.RegisterStatus != 0 {
  1091. cond += ` AND register_status = ?`
  1092. pars = append(pars, req.RegisterStatus)
  1093. }
  1094. if req.ServiceTypes != "" {
  1095. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1096. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1097. if e != nil {
  1098. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  1099. return
  1100. }
  1101. if len(registerIds) > 0 {
  1102. cond += ` AND contract_register_id IN ?`
  1103. pars = append(pars, registerIds)
  1104. } else {
  1105. cond += ` AND 1 = 2`
  1106. }
  1107. }
  1108. // 获取列表数据
  1109. cr := new(fms.ContractRegister)
  1110. list, e := cr.List(cond, pars)
  1111. if e != nil {
  1112. resp.FailData("获取合同列表失败", "Err:"+e.Error(), c)
  1113. return
  1114. }
  1115. if len(list) == 0 {
  1116. resp.Fail("无有效数据可导出", c)
  1117. return
  1118. }
  1119. registerIds := make([]int, 0)
  1120. for i := range list {
  1121. registerIds = append(registerIds, list[i].ContractRegisterId)
  1122. }
  1123. // 获取小套餐品种
  1124. cpCond := `product_id = ? AND permission_name <> ?`
  1125. cpPars := make([]interface{}, 0)
  1126. cpPars = append(cpPars, crm.CompanyProductFicc, crm.ChartPermissionStrategyName)
  1127. cp := new(crm.ChartPermission)
  1128. permissionList, e := cp.List(cpCond, cpPars)
  1129. if e != nil {
  1130. resp.FailData("获取小套餐品种失败", "Err:"+e.Error(), c)
  1131. return
  1132. }
  1133. permissionLen := len(permissionList)
  1134. permissionNameIdMap := make(map[string]int)
  1135. for i := range permissionList {
  1136. permissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  1137. }
  1138. // 获取所有FICC套餐服务
  1139. serviceList, e := fms.GetContractServiceTemplateMapByProductId(crm.CompanyProductFicc)
  1140. if e != nil {
  1141. resp.FailData("获取套餐服务失败", "Err:"+e.Error(), c)
  1142. return
  1143. }
  1144. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  1145. otherService := make([]*fms.ContractServiceTemplateItem, 0)
  1146. for i := range serviceList {
  1147. if serviceList[i].Title != "FICC大套餐" && serviceList[i].Title != "FICC小套餐" {
  1148. otherService = append(otherService, serviceList[i])
  1149. }
  1150. }
  1151. otherServiceLen := len(otherService)
  1152. // 获取所有权益套餐服务
  1153. raiServiceList, e := fms.GetContractServiceTemplateAllByProductId(crm.CompanyProductRai)
  1154. if e != nil {
  1155. resp.FailData("获取权益套餐服务失败", "Err:"+e.Error(), c)
  1156. return
  1157. }
  1158. raiServiceIdMap := make(map[int]*fms.ContractServiceTemplateItem)
  1159. for i := range raiServiceList {
  1160. raiServiceIdMap[raiServiceList[i].ServiceTemplateId] = raiServiceList[i]
  1161. }
  1162. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  1163. raiOtherService := make([]*fms.ContractServiceTemplateItem, 0)
  1164. raiServiceNotShowMap := make(map[int]struct{})
  1165. for _, v := range raiServiceList {
  1166. if v.Pid > 0 && raiServiceIdMap[v.Pid].Pid > 0 {
  1167. raiServiceNotShowMap[v.Pid] = struct{}{}
  1168. raiServiceNotShowMap[raiServiceIdMap[v.Pid].Pid] = struct{}{}
  1169. }else if v.Pid > 0 {
  1170. raiServiceNotShowMap[v.Pid] = struct{}{}
  1171. }
  1172. }
  1173. for _, v := range raiServiceList {
  1174. if _, ok := raiServiceNotShowMap[v.ServiceTemplateId]; !ok {
  1175. if v.Pid > 0 {
  1176. v.ParentTitle = raiServiceIdMap[v.Pid].Title
  1177. }
  1178. raiOtherService = append(raiOtherService, v)
  1179. }
  1180. }
  1181. otherServiceLen += len(raiOtherService)
  1182. //套餐金额map
  1183. serviceAmountMap := make(map[int]map[int]*fms.ContractServiceAmount)
  1184. // 套餐/开票/到款列表
  1185. serviceMap := make(map[int][]*fms.ContractServiceWithParentTitle)
  1186. serviceChartPermissionsMap := make(map[int][]int)
  1187. invoiceMap := make(map[int][]*fms.ContractInvoice)
  1188. paymentMap := make(map[int][]*fms.ContractInvoice)
  1189. maxInvoice := 0
  1190. maxPayment := 0
  1191. if len(registerIds) > 0 {
  1192. // 获取套餐信息
  1193. csCond := `cv.contract_register_id IN ?`
  1194. csPars := make([]interface{}, 0)
  1195. csPars = append(csPars, registerIds)
  1196. cs := new(fms.ContractService)
  1197. serviceList, e := cs.ListWithWithParentTitle(csCond, csPars)
  1198. if e != nil {
  1199. resp.FailData("获取合同套餐列表失败", "Err:"+e.Error(), c)
  1200. return
  1201. }
  1202. for i := range serviceList {
  1203. cid := serviceList[i].ContractRegisterId
  1204. if serviceMap[cid] == nil {
  1205. serviceMap[cid] = make([]*fms.ContractServiceWithParentTitle, 0)
  1206. }
  1207. serviceMap[cid] = append(serviceMap[cid], serviceList[i])
  1208. // 小套餐权限
  1209. if serviceChartPermissionsMap[cid] == nil {
  1210. serviceChartPermissionsMap[cid] = make([]int, 0)
  1211. }
  1212. if serviceList[i].ChartPermissionIds != "" {
  1213. ids := utils.JoinStr2IntArr(serviceList[i].ChartPermissionIds, ",")
  1214. serviceChartPermissionsMap[cid] = append(serviceChartPermissionsMap[cid], ids...)
  1215. }
  1216. }
  1217. // 获取合同的套餐金额信息
  1218. serviceAmountList, e := fms.GetContractServiceAmountByContractRegisterIds(registerIds)
  1219. if e != nil {
  1220. resp.FailData("获取合同的套餐金额信息失败", "Err:"+e.Error(), c)
  1221. return
  1222. }
  1223. for _, v := range serviceAmountList {
  1224. if _, ok := serviceAmountMap[v.ContractRegisterId]; !ok {
  1225. serviceAmountMap[v.ContractRegisterId] = make(map[int]*fms.ContractServiceAmount)
  1226. }
  1227. serviceAmountMap[v.ContractRegisterId][v.ProductId] = v
  1228. }
  1229. // 获取开票/到款详情, 并取最大的开票/到款数(用于动态扩展第二列表头)
  1230. ci := new(fms.ContractInvoice)
  1231. csCond = `contract_register_id IN ?`
  1232. csPars = make([]interface{}, 0)
  1233. csPars = append(csPars, registerIds)
  1234. invoiceList, e := ci.List(csCond, csPars, "")
  1235. if e != nil {
  1236. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  1237. return
  1238. }
  1239. for k := range invoiceList {
  1240. cid := invoiceList[k].ContractRegisterId
  1241. if invoiceMap[cid] == nil {
  1242. invoiceMap[cid] = make([]*fms.ContractInvoice, 0)
  1243. }
  1244. if paymentMap[cid] == nil {
  1245. paymentMap[cid] = make([]*fms.ContractInvoice, 0)
  1246. }
  1247. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypeMake {
  1248. invoiceMap[cid] = append(invoiceMap[cid], invoiceList[k])
  1249. continue
  1250. }
  1251. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypePay {
  1252. paymentMap[cid] = append(paymentMap[cid], invoiceList[k])
  1253. continue
  1254. }
  1255. }
  1256. // 取最大开票/到款数
  1257. for j := range invoiceMap {
  1258. if len(invoiceMap[j]) > maxInvoice {
  1259. maxInvoice = len(invoiceMap[j])
  1260. }
  1261. }
  1262. for p := range paymentMap {
  1263. if len(paymentMap[p]) > maxPayment {
  1264. maxPayment = len(paymentMap[p])
  1265. }
  1266. }
  1267. }
  1268. serviceProductIdMap := map[int]string{
  1269. 1:"FICC套餐",
  1270. 2:"权益套餐",
  1271. }
  1272. // 生成Excel文件
  1273. xlsxFile := xlsx.NewFile()
  1274. style := xlsx.NewStyle()
  1275. alignment := xlsx.Alignment{
  1276. Horizontal: "center",
  1277. Vertical: "center",
  1278. WrapText: true,
  1279. }
  1280. style.Alignment = alignment
  1281. style.ApplyAlignment = true
  1282. sheetName := "财务列表"
  1283. sheet, err := xlsxFile.AddSheet(sheetName)
  1284. if err != nil {
  1285. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1286. return
  1287. }
  1288. // 1行表头
  1289. hInt := 0
  1290. titleRow := sheet.AddRow()
  1291. titleRow.SetHeight(40)
  1292. // 1行1列-右合并两格, 下合并1行
  1293. cell1 := titleRow.AddCell()
  1294. cell1.HMerge = 4
  1295. cell1.VMerge = 1
  1296. cell1.SetString("FICC客户签约表")
  1297. cell1.SetStyle(style)
  1298. // 右增两列空白格用于第一列合并, 否则后续单元格合并会有问题
  1299. titleRow.AddCell().SetString("")
  1300. titleRow.AddCell().SetString("")
  1301. titleRow.AddCell().SetString("")
  1302. titleRow.AddCell().SetString("")
  1303. hInt += 5
  1304. // 1行2列
  1305. cell2 := titleRow.AddCell()
  1306. cell2.VMerge = 1
  1307. cell2.SetString("FICC大套餐")
  1308. cell2.SetStyle(style)
  1309. hInt ++
  1310. // 1行3列-右合并小套餐数
  1311. if permissionLen >= 1 {
  1312. cell3 := titleRow.AddCell()
  1313. hInt ++
  1314. cell3.HMerge = permissionLen - 1
  1315. cell3.VMerge = 1
  1316. cell3.SetString("FICC小套餐")
  1317. cell3.SetStyle(style)
  1318. // 同上右增单元格小套餐数-1的空白单元格用于合并
  1319. for i := 0; i < permissionLen-1; i++ {
  1320. titleRow.AddCell().SetString("")
  1321. hInt ++
  1322. }
  1323. }
  1324. for i := range otherService {
  1325. cellOther := titleRow.AddCell()
  1326. cellOther.VMerge = 1
  1327. hInt ++
  1328. cellOther.SetString(otherService[i].Title)
  1329. cellOther.SetStyle(style)
  1330. }
  1331. //权益大套餐
  1332. cell4 := titleRow.AddCell()
  1333. cell4.HMerge = 1
  1334. cell4.VMerge = 1
  1335. cell4.SetString("权益大套餐")
  1336. cell4.SetStyle(style)
  1337. titleRow.AddCell().SetString("")
  1338. hInt +=2
  1339. //权益分行业套餐
  1340. cell5 := titleRow.AddCell()
  1341. cell5.HMerge = 8
  1342. cell5.SetString("权益分行业套餐")
  1343. cell5.SetStyle(style)
  1344. titleRow.AddCell().SetString("")
  1345. titleRow.AddCell().SetString("")
  1346. titleRow.AddCell().SetString("")
  1347. titleRow.AddCell().SetString("")
  1348. titleRow.AddCell().SetString("")
  1349. titleRow.AddCell().SetString("")
  1350. titleRow.AddCell().SetString("")
  1351. titleRow.AddCell().SetString("")
  1352. //第二行,前面几个单元格用于第一行的合并
  1353. titleRow2 := sheet.AddRow()
  1354. titleRow2.SetHeight(30)
  1355. for i:= 0; i<hInt;i++ {
  1356. titleRow2.AddCell().SetString("")
  1357. }
  1358. //权益分行业套餐
  1359. row2Cell1 := titleRow2.AddCell()
  1360. row2Cell1.HMerge = 1
  1361. row2Cell1.SetString("医药")
  1362. row2Cell1.SetStyle(style)
  1363. titleRow2.AddCell().SetString("")
  1364. row2Cell2 := titleRow2.AddCell()
  1365. row2Cell2.HMerge = 1
  1366. row2Cell2.SetString("消费")
  1367. row2Cell2.SetStyle(style)
  1368. titleRow2.AddCell().SetString("")
  1369. row2Cell3 := titleRow2.AddCell()
  1370. row2Cell3.HMerge = 1
  1371. row2Cell3.SetString("科技")
  1372. row2Cell3.SetStyle(style)
  1373. titleRow2.AddCell().SetString("")
  1374. row2Cell4 := titleRow2.AddCell()
  1375. row2Cell4.HMerge = 1
  1376. row2Cell4.SetString("智造")
  1377. row2Cell4.SetStyle(style)
  1378. titleRow2.AddCell().SetString("")
  1379. row2Cell5 := titleRow2.AddCell()
  1380. row2Cell5.SetString("策略")
  1381. row2Cell5.SetStyle(style)
  1382. // 第三行表头
  1383. titleRow3 := sheet.AddRow()
  1384. titleRow3.SetHeight(60)
  1385. row3Title := make([]string, 0)
  1386. row3TitleParent := make([]string, 0)
  1387. row3Title = append(row3Title, "客户名称", "新客户\n0-是\n1-否", "合同类型\n续约-0\n新增-1\n代付-2\n补充协议-3", "FICC销售", "权益销售", "FICC大套餐")
  1388. for i := range permissionList {
  1389. row3Title = append(row3Title, permissionList[i].PermissionName)
  1390. }
  1391. // 其他套餐
  1392. for i := range otherService {
  1393. row3Title = append(row3Title, otherService[i].Title)
  1394. }
  1395. // 定义二级套餐名称
  1396. for i:= range row3Title {
  1397. row3TitleParent = append(row3TitleParent, row3Title[i])
  1398. }
  1399. // 权益三级套餐
  1400. for i := range raiOtherService {
  1401. row3Title = append(row3Title, raiOtherService[i].Title)
  1402. if raiOtherService[i].ParentTitle != "" {
  1403. row3TitleParent = append(row3TitleParent, raiOtherService[i].ParentTitle)
  1404. }else{
  1405. row3TitleParent = append(row3TitleParent, raiOtherService[i].Title)
  1406. }
  1407. }
  1408. row3Title = append(row3Title, "套餐备注", "开始时间", "到期时间", "2022年合同金额", "金额单位", "FICC套餐总金额", "权益套餐总金额", "约定付款时间", "签订日", "合同状态",
  1409. "合同编号", "合规备注")
  1410. // 设置表头
  1411. for i := range row3Title {
  1412. v := titleRow3.AddCell()
  1413. v.SetString(row3Title[i])
  1414. v.SetStyle(style)
  1415. }
  1416. // 第二行表头-开票/收款(动态添加)
  1417. invoiceTitle := []string{"开票日", "开票金额", "套餐类型", "销售", "备注"}
  1418. for i := 0; i < maxInvoice; i++ {
  1419. n := i + 1
  1420. for ii := range invoiceTitle {
  1421. c := titleRow3.AddCell()
  1422. t := fmt.Sprintf("%s%d", invoiceTitle[ii], n)
  1423. c.SetString(t)
  1424. c.SetStyle(style)
  1425. row3Title = append(row3Title, t)
  1426. }
  1427. }
  1428. paymentTitle := []string{"到款日", "到款金额", "套餐类型", "备注"}
  1429. for i := 0; i < maxPayment; i++ {
  1430. n := i + 1
  1431. for ii := range paymentTitle {
  1432. c := titleRow3.AddCell()
  1433. t := fmt.Sprintf("%s%d", paymentTitle[ii], n)
  1434. c.SetString(t)
  1435. c.SetStyle(style)
  1436. row3Title = append(row3Title, t)
  1437. }
  1438. }
  1439. // 此处取第二行标题NameKeyMap, 后面的动态匹配
  1440. row2NameKeyMap := make(map[string]int)
  1441. for i := range row3Title {
  1442. row2NameKeyMap[row3Title[i]] = i
  1443. }
  1444. newCompanyMap := map[int]string{0: "1", 1: "0"}
  1445. contractTMap := map[int]int{
  1446. fms.ContractTypeNew: 1,
  1447. fms.ContractTypeRenew: 0,
  1448. fms.ContractTypeAgentPay: 2, // 代付合同
  1449. fms.ContractTypePlus: 3, // 补充协议
  1450. }
  1451. for _, v := range list {
  1452. k := -1 // 套餐匹配用
  1453. dataRow := sheet.AddRow()
  1454. dataRow.SetHeight(20)
  1455. k += 4
  1456. dataRow.AddCell().SetString(v.CompanyName)
  1457. dataRow.AddCell().SetString(newCompanyMap[v.NewCompany])
  1458. dataRow.AddCell().SetString(fmt.Sprint(contractTMap[v.ContractType]))
  1459. dataRow.AddCell().SetString(v.SellerName)
  1460. dataRow.AddCell().SetString(v.RaiSellerName)
  1461. // 大套餐
  1462. k += 1
  1463. col4Name := row3Title[k]
  1464. svList := serviceMap[v.ContractRegisterId]
  1465. col4 := ""
  1466. if svList != nil && len(svList) > 0 {
  1467. for isv := range svList {
  1468. if svList[isv].Title == col4Name {
  1469. col4 = "是"
  1470. break
  1471. }
  1472. }
  1473. }
  1474. dataRow.AddCell().SetString(col4)
  1475. // 小套餐
  1476. serviceChartPermissionIds := serviceChartPermissionsMap[v.ContractRegisterId]
  1477. for i := 0; i < permissionLen; i++ {
  1478. k += 1
  1479. colName := row3Title[k]
  1480. chartPermissionId := permissionNameIdMap[colName]
  1481. if utils.InArray(chartPermissionId, serviceChartPermissionIds) {
  1482. dataRow.AddCell().SetString("是")
  1483. } else {
  1484. dataRow.AddCell().SetString("")
  1485. }
  1486. }
  1487. // 除大小套餐外的其他套餐(处理方式其实跟上面的大套餐一样, 只是中间隔了小套餐按照顺序要这么处理=_=!)
  1488. for i := 0; i < otherServiceLen; i++ {
  1489. k += 1
  1490. otherColName := row3Title[k]
  1491. otherCol := ""
  1492. if svList != nil && len(svList) > 0 {
  1493. for isv := range svList {
  1494. if svList[isv].Title == otherColName {
  1495. // 判断权益套餐权限时,需要同时判断父级name
  1496. if otherColName == "主观" || otherColName == "客观" {
  1497. if row3TitleParent[k] == svList[isv].ParentTitle {
  1498. otherCol = "是"
  1499. break
  1500. }
  1501. }else{
  1502. otherCol = "是"
  1503. break
  1504. }
  1505. }
  1506. }
  1507. }
  1508. dataRow.AddCell().SetString(otherCol)
  1509. }
  1510. // 其他信息
  1511. ficcAmount, _ := serviceAmountMap[v.ContractRegisterId][crm.CompanyProductFicc]
  1512. raiAmount, _ := serviceAmountMap[v.ContractRegisterId][crm.CompanyProductRai]
  1513. dataRow.AddCell().SetString(v.ServiceRemark) // 套餐备注
  1514. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.StartDate)) // 开始时间
  1515. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.EndDate)) // 到期时间
  1516. dataRow.AddCell().SetString(fmt.Sprint("¥", v.ContractAmount)) // 2022年合同金额
  1517. dataRow.AddCell().SetString(v.CurrencyUnit) // 货币单位
  1518. dataRow.AddCell().SetString(fmt.Sprint("¥", ficcAmount.ServiceAmount)) // FICC套餐总金额
  1519. dataRow.AddCell().SetString(fmt.Sprint("¥", raiAmount.ServiceAmount)) // 权益套餐总金额
  1520. dataRow.AddCell().SetString(v.AgreedPayTime) // 约定付款时间
  1521. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.SignDate)) // 签订日
  1522. dataRow.AddCell().SetString(fms.ContractStatusKeyNameMap[v.ContractStatus]) // 合同状态
  1523. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  1524. dataRow.AddCell().SetString(v.Remark) // 合规备注
  1525. // 开票/到款信息
  1526. ivList := invoiceMap[v.ContractRegisterId]
  1527. ivListLen := len(ivList)
  1528. for ia := 0; ia < maxInvoice; ia++ {
  1529. if ia < ivListLen {
  1530. if ivList != nil && ivList[ia] != nil {
  1531. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", ivList[ia].InvoiceDate)) // 开票日
  1532. dataRow.AddCell().SetString(fmt.Sprint(ivList[ia].OriginAmount)) // 开票金额
  1533. dataRow.AddCell().SetString(serviceProductIdMap[ivList[ia].ServiceProductId]) // 套餐类型
  1534. dataRow.AddCell().SetString(ivList[ia].SellerName) // 销售名称
  1535. dataRow.AddCell().SetString(ivList[ia].Remark) // 开票备注
  1536. continue
  1537. }
  1538. }
  1539. // 这里要把不够的填充为空
  1540. dataRow.AddCell().SetString("")
  1541. dataRow.AddCell().SetString("")
  1542. dataRow.AddCell().SetString("")
  1543. dataRow.AddCell().SetString("")
  1544. dataRow.AddCell().SetString("")
  1545. }
  1546. pyList := paymentMap[v.ContractRegisterId]
  1547. pyListLen := len(pyList)
  1548. for ib := 0; ib < maxPayment; ib++ {
  1549. if ib < pyListLen {
  1550. if pyList != nil && pyList[ib] != nil {
  1551. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", pyList[ib].InvoiceDate)) // 收款日
  1552. dataRow.AddCell().SetString(fmt.Sprint(pyList[ib].OriginAmount)) // 收款金额
  1553. dataRow.AddCell().SetString(serviceProductIdMap[pyList[ib].ServiceProductId]) // 套餐类型
  1554. dataRow.AddCell().SetString(pyList[ib].Remark) // 收款备注
  1555. continue
  1556. }
  1557. }
  1558. // 这里要把不够的填充为空
  1559. dataRow.AddCell().SetString("")
  1560. dataRow.AddCell().SetString("")
  1561. dataRow.AddCell().SetString("")
  1562. dataRow.AddCell().SetString("")
  1563. }
  1564. }
  1565. // 输出文件
  1566. var buffer bytes.Buffer
  1567. _ = xlsxFile.Write(&buffer)
  1568. content := bytes.NewReader(buffer.Bytes())
  1569. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1570. fileName := sheetName + randStr + ".xlsx"
  1571. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1572. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1573. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1574. }
  1575. // InvoiceList
  1576. // @Title 开票/到款列表
  1577. // @Description 开票/到款列表
  1578. // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
  1579. // @Param ContractCode query string false "合同编号"
  1580. // @Param StartDate query string false "开始日期"
  1581. // @Param EndDate query string false "结束日期"
  1582. // @Param MinAmount query float64 false "开票金额区间-最小值"
  1583. // @Param MaxAmount query float64 false "开票金额区间-最大值"
  1584. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  1585. // @Success 200 {object} fms.ContractInvoiceItem
  1586. // @router /contract/register/invoice_list [get]
  1587. func (rg *RegisterController) InvoiceList(c *gin.Context) {
  1588. var req fms.ContractInvoiceListReq
  1589. if e := c.BindQuery(&req); e != nil {
  1590. err, ok := e.(validator.ValidationErrors)
  1591. if !ok {
  1592. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1593. return
  1594. }
  1595. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1596. return
  1597. }
  1598. pageSize := req.PageSize
  1599. pageIndex := req.Current
  1600. if pageSize <= 0 {
  1601. pageSize = utils.PageSize20
  1602. }
  1603. if pageIndex <= 0 {
  1604. pageIndex = 1
  1605. }
  1606. cond := `invoice_type = ?`
  1607. pars := make([]interface{}, 0)
  1608. pars = append(pars, req.InvoiceType)
  1609. // 合同编号
  1610. if req.ContractCode != "" {
  1611. kw := fmt.Sprint("%", req.ContractCode, "%")
  1612. pars = append(pars, kw)
  1613. // 开票列表同时模糊查询销售名称
  1614. if req.InvoiceType == fms.ContractInvoiceTypeMake {
  1615. cond += ` AND (contract_code LIKE ? )`
  1616. pars = append(pars, kw)
  1617. } else {
  1618. cond += ` AND contract_code LIKE ?`
  1619. pars = append(pars, kw)
  1620. }
  1621. }
  1622. if req.StartDate != "" && req.EndDate != "" {
  1623. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1624. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1625. cond += ` AND (invoice_time BETWEEN ? AND ?)`
  1626. pars = append(pars, st, ed)
  1627. }
  1628. if req.MinAmount > 0 {
  1629. cond += ` AND amount >= ?`
  1630. pars = append(pars, req.MinAmount)
  1631. }
  1632. if req.MaxAmount > 0 {
  1633. cond += ` AND amount <= ?`
  1634. pars = append(pars, req.MaxAmount)
  1635. }
  1636. // 套餐类型
  1637. if req.ServiceProductId > 0 {
  1638. cond += ` AND service_product_id = ?`
  1639. pars = append(pars, req.ServiceProductId)
  1640. }
  1641. // 销售
  1642. if req.SellerIds != "" {
  1643. sellerIds := strings.Split(req.SellerIds, ",")
  1644. cond += ` AND (seller_id in (?))`
  1645. pars = append(pars, sellerIds)
  1646. }
  1647. // 货币列表
  1648. currencyOB := new(fms.CurrencyUnit)
  1649. currencyCond := `enable = 1`
  1650. currencyPars := make([]interface{}, 0)
  1651. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1652. if e != nil {
  1653. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  1654. return
  1655. }
  1656. unitMap := make(map[string]string)
  1657. currencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1658. for i := range currencyList {
  1659. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1660. currencyTotals = append(currencyTotals, &fms.InvoiceListCurrencyTotal{
  1661. Name: currencyList[i].Name,
  1662. UnitName: currencyList[i].UnitName,
  1663. Code: currencyList[i].Code,
  1664. FlagImg: currencyList[i].FlagImg,
  1665. })
  1666. }
  1667. page := new(base.Page)
  1668. page.SetPageSize(pageSize)
  1669. page.SetCurrent(pageIndex)
  1670. page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: false})
  1671. if req.IsExport == 1 {
  1672. page.SetPageSize(10000)
  1673. page.SetCurrent(1)
  1674. }
  1675. total, list, e := fms.GetContractInvoiceItemPageList(page, cond, pars)
  1676. if e != nil {
  1677. resp.FailMsg("获取失败", "获取合同开票/到款列表失败, Err: "+e.Error(), c)
  1678. return
  1679. }
  1680. page.SetTotal(total)
  1681. contractRegisterIds := make([]int, 0)
  1682. contractStatusMap := make(map[int]int)
  1683. for i := range list {
  1684. list[i].UnitName = unitMap[list[i].CurrencyUnit]
  1685. contractRegisterIds = append(contractRegisterIds, list[i].ContractRegisterId)
  1686. }
  1687. if len(contractRegisterIds) > 0 {
  1688. contractRegisters, err := fms.GetContractInfoByRegisterIds(contractRegisterIds)
  1689. if err != nil {
  1690. resp.FailMsg("查询合同信息失败", "查询合同信息失败, Err: "+err.Error(), c)
  1691. return
  1692. }
  1693. for _, v := range contractRegisters {
  1694. contractStatusMap[v.ContractRegisterId] = v.ContractStatus
  1695. }
  1696. }
  1697. for i := range list {
  1698. list[i].ContractStatus = contractStatusMap[list[i].ContractRegisterId]
  1699. }
  1700. // 分币种合计金额
  1701. var amountTotal float64
  1702. sumList, e := fms.GetInvoiceListCurrencySum(cond, pars, "currency_unit")
  1703. if e != nil {
  1704. resp.FailMsg("获取失败", "获取开票/到款列表合计金额失败, Err: "+e.Error(), c)
  1705. return
  1706. }
  1707. sumMap := make(map[string]float64)
  1708. for i := range sumList {
  1709. amountTotal += sumList[i].AmountTotal
  1710. sumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  1711. }
  1712. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountTotal), 64)
  1713. for i := range currencyTotals {
  1714. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", sumMap[currencyTotals[i].Code]), 64)
  1715. currencyTotals[i].Amount = a
  1716. }
  1717. respData := &fms.InvoiceListRespData{
  1718. Page: page,
  1719. List: list,
  1720. AmountTotal: amountTotal,
  1721. CurrencyTotal: currencyTotals,
  1722. }
  1723. // 是否导出
  1724. if req.IsExport == 1 {
  1725. ExportInvoiceList(c, req, respData)
  1726. return
  1727. }
  1728. resp.OkData("获取成功", respData, c)
  1729. }
  1730. // ExportInvoiceList 导出开票/到款列表
  1731. func ExportInvoiceList(c *gin.Context, req fms.ContractInvoiceListReq, results *fms.InvoiceListRespData) {
  1732. list := make([]*fms.ContractInvoiceItem, 0)
  1733. if val, ok := results.List.([]*fms.ContractInvoiceItem); ok {
  1734. list = val
  1735. } else {
  1736. resp.Fail("列表数据有误", c)
  1737. return
  1738. }
  1739. if len(list) == 0 {
  1740. resp.Fail("列表数据为空", c)
  1741. return
  1742. }
  1743. listName := "开票"
  1744. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1745. listName = "到款"
  1746. }
  1747. // 生成Excel文件
  1748. xlsxFile := xlsx.NewFile()
  1749. style := xlsx.NewStyle()
  1750. alignment := xlsx.Alignment{
  1751. Horizontal: "center",
  1752. Vertical: "center",
  1753. WrapText: true,
  1754. }
  1755. style.Alignment = alignment
  1756. style.ApplyAlignment = true
  1757. sheet, err := xlsxFile.AddSheet(fmt.Sprintf("%s列表", listName))
  1758. if err != nil {
  1759. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1760. return
  1761. }
  1762. // 前两行显示合计金额, 第三行空出与列表数据隔一行
  1763. rowA := sheet.AddRow()
  1764. cellAA := rowA.AddCell()
  1765. cellAA.SetString(fmt.Sprintf("已开票合计金额(换算后):%.2f(元)", results.AmountTotal))
  1766. rowBData := "已开票金额:"
  1767. for _, v := range results.CurrencyTotal {
  1768. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  1769. }
  1770. rowB := sheet.AddRow()
  1771. rowB.AddCell().SetString(rowBData)
  1772. sheet.AddRow()
  1773. // 列表数据表头
  1774. titles := []string{"合同编号", "套餐类型", fmt.Sprintf("%s金额", listName), "金额单位", "换算金额(元)",
  1775. fmt.Sprintf("%s日期", listName), "销售", "备注"}
  1776. titleRow := sheet.AddRow()
  1777. titleRow.SetHeight(40)
  1778. for i := range titles {
  1779. c := titleRow.AddCell()
  1780. c.SetString(titles[i])
  1781. c.SetStyle(style)
  1782. }
  1783. ServiceTemplateStrMap := map[int]string{
  1784. crm.CompanyProductFicc: "FICC套餐",
  1785. crm.CompanyProductRai: "权益套餐",
  1786. }
  1787. // 单元格赋值
  1788. for _, v := range list {
  1789. dataRow := sheet.AddRow()
  1790. dataRow.SetHeight(20)
  1791. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  1792. dataRow.AddCell().SetString(ServiceTemplateStrMap[v.ServiceProductId]) // 套餐类型
  1793. dataRow.AddCell().SetString(fmt.Sprint(v.OriginAmount)) // 开票金额
  1794. dataRow.AddCell().SetString(v.UnitName) // 金额单位
  1795. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 换算金额(元)
  1796. dataRow.AddCell().SetString(v.InvoiceDate) // 开票日
  1797. dataRow.AddCell().SetString(v.SellerName) // 销售
  1798. dataRow.AddCell().SetString(v.Remark) // 备注
  1799. }
  1800. // 输出文件
  1801. var buffer bytes.Buffer
  1802. _ = xlsxFile.Write(&buffer)
  1803. content := bytes.NewReader(buffer.Bytes())
  1804. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1805. fileName := fmt.Sprintf("%s列表_%s.xlsx", listName, randStr)
  1806. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1807. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1808. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1809. }
  1810. // Import
  1811. // @Title 合同登记-导入
  1812. // @Description 合同登记-导入
  1813. // @Success 200 string "操作成功"
  1814. // @router /contract/register/import [post]
  1815. func (rg *RegisterController) Import(c *gin.Context) {
  1816. h, err := c.FormFile("File")
  1817. if err != nil {
  1818. resp.FailData("获取文件失败", "Err:"+err.Error(), c)
  1819. return
  1820. }
  1821. ext := path.Ext(h.Filename)
  1822. if ext != ".xlsx" && ext != ".xls" {
  1823. resp.Fail("请上传Excel文件", c)
  1824. return
  1825. }
  1826. uploadDir := "static/xls"
  1827. err = os.MkdirAll(uploadDir, 766)
  1828. if err != nil {
  1829. resp.FailData("存储目录创建失败", "Err:"+err.Error(), c)
  1830. return
  1831. }
  1832. uploadPath := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
  1833. err = c.SaveUploadedFile(h, uploadPath)
  1834. if err != nil {
  1835. resp.FailData("保存本地文件失败", "Err:"+err.Error(), c)
  1836. return
  1837. }
  1838. defer func() {
  1839. _ = os.Remove(uploadPath)
  1840. }()
  1841. xlFile, err := xlsx.OpenFile(uploadPath)
  1842. if err != nil {
  1843. resp.FailData("打开文件失败", "Err:"+err.Error(), c)
  1844. return
  1845. }
  1846. // 获取所有已登记,根据合同编号去重
  1847. contractCodeArr := make([]string, 0)
  1848. registerOB := new(fms.ContractRegister)
  1849. registerCond := ``
  1850. registerPars := make([]interface{}, 0)
  1851. registerList, e := registerOB.List(registerCond, registerPars)
  1852. if e != nil {
  1853. resp.FailData("获取合同登记列表失败", "Err:"+e.Error(), c)
  1854. return
  1855. }
  1856. for i := range registerList {
  1857. contractCodeArr = append(contractCodeArr, registerList[i].ContractCode)
  1858. }
  1859. // 获取所有销售Map
  1860. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  1861. if e != nil {
  1862. resp.FailData("获取销售列表失败", "Err:"+e.Error(), c)
  1863. return
  1864. }
  1865. sellerMap := make(map[string]*crm.SellerAdminWithGroupTeam)
  1866. for i := range sellerList {
  1867. sellerMap[sellerList[i].SellerName] = sellerList[i]
  1868. }
  1869. // 获取品种权限Map
  1870. chartPermissionNameIdMap := make(map[string]int)
  1871. cpCond := `product_id = ?`
  1872. cpPars := make([]interface{}, 0)
  1873. cpPars = append(cpPars, crm.CompanyProductFicc)
  1874. cp := new(crm.ChartPermission)
  1875. permissionList, e := cp.List(cpCond, cpPars)
  1876. if e != nil {
  1877. resp.FailData("获取权限列表失败", "Err:"+e.Error(), c)
  1878. return
  1879. }
  1880. for i := range permissionList {
  1881. chartPermissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  1882. }
  1883. // 获取所有套餐模板
  1884. serviceTempCond := ``
  1885. serviceTempPars := make([]interface{}, 0)
  1886. serviceTempOB := new(fms.ContractServiceTemplate)
  1887. serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
  1888. if e != nil {
  1889. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  1890. return
  1891. }
  1892. serviceTempNameMap := make(map[string]*fms.ContractServiceTemplate)
  1893. serviceTempFullNameMap := make(map[string]*fms.ContractServiceTemplate)
  1894. serviceTempIdMap := make(map[int]*fms.ContractServiceTemplate)
  1895. for i := range serviceTempList {
  1896. serviceTempIdMap[serviceTempList[i].ServiceTemplateId] = serviceTempList[i]
  1897. serviceTempNameMap[serviceTempList[i].Title] = serviceTempList[i]
  1898. }
  1899. for i := range serviceTempList {
  1900. fullName := serviceTempList[i].Title
  1901. if serviceTempList[i].Pid > 0 {
  1902. parentItem := serviceTempIdMap[serviceTempList[i].Pid]
  1903. fullName += "_"+parentItem.Title
  1904. if parentItem.Pid > 0 {
  1905. fullName += "_"+serviceTempIdMap[parentItem.Pid].Title
  1906. }
  1907. }
  1908. serviceTempFullNameMap[fullName] = serviceTempList[i]
  1909. }
  1910. //权益行业套餐名称
  1911. raiIndustryMap := map[int]string{
  1912. 36:"医药",
  1913. 37:"医药",
  1914. 38:"消费",
  1915. 39:"消费",
  1916. 40:"科技",
  1917. 41:"科技",
  1918. 42:"智造",
  1919. 43:"智造",
  1920. 44:"策略",
  1921. }
  1922. // 获取货币列表及汇率(汇率为导入日的汇率)
  1923. rateList, e := fmsService.GetTodayCurrencyRateList()
  1924. if e != nil {
  1925. resp.FailData("获取货币列表及汇率失败", "Err:"+e.Error(), c)
  1926. return
  1927. }
  1928. rateMap := make(map[string]float64)
  1929. for i := range rateList {
  1930. rateMap[rateList[i].Code] = rateList[i].RMBRate
  1931. }
  1932. titleMap := make(map[int]string)
  1933. newIds := make([]int, 0)
  1934. newCompanyArr := []string{"0", "1"}
  1935. newCompanyMap := map[string]int{"0": 1, "1": 0}
  1936. contractTypeArr := []string{"0", "1", "2", "3"}
  1937. contractTypeMap := map[string]int{
  1938. "0": fms.ContractTypeRenew,
  1939. "1": fms.ContractTypeNew,
  1940. "2": fms.ContractTypeAgentPay,
  1941. "3": fms.ContractTypePlus,
  1942. }
  1943. // 更新登记状态
  1944. defer func() {
  1945. if len(newIds) > 0 {
  1946. go func() {
  1947. for i := range newIds {
  1948. fmsService.CheckContractRegisterAmount(newIds[i])
  1949. fmsService.SummaryInvoicePaymentByContractRegisterId(newIds[i])
  1950. }
  1951. }()
  1952. }
  1953. }()
  1954. invoiceMax := 3
  1955. checkDate := time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local)
  1956. for _, sheet := range xlFile.Sheets {
  1957. // 遍历行读取
  1958. maxRow := sheet.MaxRow
  1959. for i := 0; i < maxRow; i++ {
  1960. // 第三行开始读取表头
  1961. if i == 2 {
  1962. row := sheet.Row(i)
  1963. cells := row.Cells
  1964. for k, cell := range cells {
  1965. text := cell.String()
  1966. titleMap[k] = text
  1967. // 只检验前面部分表头, 后面很多动态列
  1968. if k == 0 {
  1969. if text != "客户名称" {
  1970. resp.Fail("【客户名称】列名称有误, 请参考模板导入", c)
  1971. return
  1972. }
  1973. continue
  1974. } else if k == 1 {
  1975. if !strings.Contains(text, "新客户") {
  1976. resp.Fail("【新客户】列名称有误, 请参考模板导入", c)
  1977. return
  1978. }
  1979. continue
  1980. } else if k == 2 {
  1981. if !strings.Contains(text, "合同类型") {
  1982. resp.Fail("【合同类型】列名称有误, 请参考模板导入", c)
  1983. return
  1984. }
  1985. continue
  1986. } else if k == 3 {
  1987. if text != "FICC销售" {
  1988. resp.Fail("【FICC销售】列名称有误, 请参考模板导入", c)
  1989. return
  1990. }
  1991. continue
  1992. } else if k == 4 {
  1993. if text != "权益销售" {
  1994. resp.Fail("【权益销售】列名称有误, 请参考模板导入", c)
  1995. return
  1996. }
  1997. continue
  1998. } else if k == 5 {
  1999. if text != "FICC大套餐" {
  2000. resp.Fail("【FICC大套餐】列名称有误, 请参考模板导入", c)
  2001. return
  2002. }
  2003. continue
  2004. }
  2005. }
  2006. }else if i >= 3 {
  2007. // 数据行
  2008. row := sheet.Row(i)
  2009. cells := row.Cells
  2010. // 登记信息
  2011. rowRegister := new(fms.ContractRegister)
  2012. // 套餐
  2013. rowServices := make([]*fms.ContractService, 0)
  2014. // 套餐金额
  2015. rowServiceAmount := make([]*fms.ContractServiceAmount, 0)
  2016. // 开票/到款
  2017. rowInvoices := make([]*fms.ContractInvoice, 0)
  2018. for ir := 0; ir < invoiceMax; ir++ {
  2019. rowInvoices = append(rowInvoices, new(fms.ContractInvoice))
  2020. }
  2021. rowPayments := make([]*fms.ContractInvoice, 0)
  2022. for ir := 0; ir < invoiceMax; ir++ {
  2023. rowPayments = append(rowPayments, new(fms.ContractInvoice))
  2024. }
  2025. // 小套餐权限
  2026. rowChartPermissionIdArr := make([]string, 0)
  2027. productIds := make(map[int]struct{})
  2028. isSkip := false
  2029. for k, cell := range cells {
  2030. v := utils.TrimStr(cell.String())
  2031. // 客户名称
  2032. if k == 0 {
  2033. if v == "" {
  2034. resp.Fail(fmt.Sprintf("第%d行客户名称不可为空, 请按模板导入", i+1), c)
  2035. return
  2036. }
  2037. rowRegister.CompanyName = v
  2038. continue
  2039. }
  2040. // 是否新客户
  2041. if k == 1 {
  2042. if !utils.InArrayByStr(newCompanyArr, v) {
  2043. resp.Fail(fmt.Sprintf("第%d行新客户有误, 请按模板导入", i+1), c)
  2044. return
  2045. }
  2046. rowRegister.NewCompany = newCompanyMap[v]
  2047. continue
  2048. }
  2049. // 合同类型
  2050. if k == 2 {
  2051. if !utils.InArrayByStr(contractTypeArr, v) {
  2052. resp.Fail(fmt.Sprintf("第%d行合同类型有误, 请按模板导入", i+1), c)
  2053. return
  2054. }
  2055. rowRegister.ContractType = contractTypeMap[v]
  2056. if rowRegister.ContractType == 0 {
  2057. resp.Fail(fmt.Sprintf("第%d行合同类型匹配有误, 请按模板导入", i+1), c)
  2058. return
  2059. }
  2060. continue
  2061. }
  2062. // FICC销售
  2063. if k == 3 {
  2064. if v != "" {
  2065. /*resp.Fail(fmt.Sprintf("第%d行销售名称不可为空, 请按模板导入", i+1), c)
  2066. return*/
  2067. sellerItem := sellerMap[v]
  2068. if sellerItem == nil {
  2069. resp.Fail(fmt.Sprintf("第%d行销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2070. return
  2071. }
  2072. rowRegister.SellerId = sellerItem.SellerId
  2073. rowRegister.SellerName = sellerItem.SellerName
  2074. }
  2075. continue
  2076. }
  2077. // 权益销售
  2078. if k == 4 {
  2079. if v == "" && rowRegister.SellerName == "" {
  2080. resp.Fail(fmt.Sprintf("第FICC销售名称和权益销售名称不可都为空, 请按模板导入", i+1), c)
  2081. return
  2082. }
  2083. sellerItem := sellerMap[v]
  2084. if sellerItem == nil {
  2085. resp.Fail(fmt.Sprintf("第%d行权益销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2086. return
  2087. }
  2088. rowRegister.RaiSellerId = sellerItem.SellerId
  2089. rowRegister.RaiSellerName = sellerItem.SellerName
  2090. continue
  2091. }
  2092. // FICC大套餐
  2093. if k == 5 {
  2094. if v == "是" {
  2095. tempItem := serviceTempNameMap[titleMap[k]]
  2096. if tempItem == nil {
  2097. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2098. return
  2099. }
  2100. cs := &fms.ContractService{
  2101. ProductId: crm.CompanyProductFicc,
  2102. ServiceTemplateId: tempItem.ServiceTemplateId,
  2103. Title: tempItem.Title,
  2104. Value: tempItem.Value,
  2105. TableValue: tempItem.TableValue,
  2106. ChartPermissionId: tempItem.ChartPermissionId,
  2107. }
  2108. cs.Set()
  2109. rowServices = append(rowServices, cs)
  2110. productIds[crm.CompanyProductFicc] = struct{}{}
  2111. }
  2112. continue
  2113. }
  2114. // FICC小套餐
  2115. if k >= 6 && k <= 26 {
  2116. // 小套餐权限
  2117. if v == "是" {
  2118. rowChartPermissionIdArr = append(rowChartPermissionIdArr, strconv.Itoa(chartPermissionNameIdMap[titleMap[k]]))
  2119. productIds[crm.CompanyProductFicc] = struct{}{}
  2120. }
  2121. continue
  2122. }
  2123. // 其他类型套餐
  2124. if k >= 27 && k <= 33 {
  2125. if v == "是" {
  2126. tempItem := serviceTempNameMap[titleMap[k]]
  2127. if tempItem == nil {
  2128. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2129. return
  2130. }
  2131. cs := &fms.ContractService{
  2132. ProductId: crm.CompanyProductFicc,
  2133. ServiceTemplateId: tempItem.ServiceTemplateId,
  2134. Title: tempItem.Title,
  2135. Value: tempItem.Value,
  2136. TableValue: tempItem.TableValue,
  2137. ChartPermissionId: tempItem.ChartPermissionId,
  2138. }
  2139. cs.Set()
  2140. rowServices = append(rowServices, cs)
  2141. productIds[crm.CompanyProductFicc] = struct{}{}
  2142. }
  2143. continue
  2144. }
  2145. if k >=34 && k<=44 {
  2146. if v == "是" {
  2147. // 权益大套餐
  2148. if k <= 35 {
  2149. //新增
  2150. parentName := "权益大套餐"
  2151. tempItem := serviceTempNameMap[titleMap[k]]
  2152. if tempItem == nil {
  2153. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2154. return
  2155. }
  2156. cs := &fms.ContractService{
  2157. ProductId: crm.CompanyProductFicc,
  2158. ServiceTemplateId: tempItem.ServiceTemplateId,
  2159. Title: tempItem.Title,
  2160. Value: tempItem.Value,
  2161. TableValue: tempItem.TableValue,
  2162. ChartPermissionId: tempItem.ChartPermissionId,
  2163. }
  2164. rowServices = append(rowServices, cs)
  2165. tempItem = serviceTempNameMap[parentName]
  2166. if tempItem == nil {
  2167. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2168. return
  2169. }
  2170. cs = &fms.ContractService{
  2171. ProductId: crm.CompanyProductRai,
  2172. ServiceTemplateId: tempItem.ServiceTemplateId,
  2173. Title: tempItem.Title,
  2174. Value: tempItem.Value,
  2175. TableValue: tempItem.TableValue,
  2176. ChartPermissionId: tempItem.ChartPermissionId,
  2177. }
  2178. rowServices = append(rowServices, cs)
  2179. } else {
  2180. rootName := "行业套餐"
  2181. // 新增三条套餐信息
  2182. parentName, _ := raiIndustryMap[k]
  2183. childName := titleMap[k]
  2184. fullName := childName+"_"+parentName+"_"+rootName
  2185. if fullName != "" {
  2186. //增加三级权限
  2187. tempItem := serviceTempFullNameMap[fullName]
  2188. if tempItem == nil {
  2189. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2190. return
  2191. }
  2192. cs := &fms.ContractService{
  2193. ProductId: crm.CompanyProductRai,
  2194. ServiceTemplateId: tempItem.ServiceTemplateId,
  2195. Title: tempItem.Title,
  2196. Value: tempItem.Value,
  2197. TableValue: tempItem.TableValue,
  2198. ChartPermissionId: tempItem.ChartPermissionId,
  2199. }
  2200. rowServices = append(rowServices, cs)
  2201. //增加二级权限
  2202. tempItem = serviceTempFullNameMap[parentName+"_"+rootName]
  2203. if tempItem == nil {
  2204. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2205. return
  2206. }
  2207. cs = &fms.ContractService{
  2208. ProductId: crm.CompanyProductRai,
  2209. ServiceTemplateId: tempItem.ServiceTemplateId,
  2210. Title: tempItem.Title,
  2211. Value: tempItem.Value,
  2212. TableValue: tempItem.TableValue,
  2213. ChartPermissionId: tempItem.ChartPermissionId,
  2214. }
  2215. rowServices = append(rowServices, cs)
  2216. //增加一级权限
  2217. tempItem = serviceTempFullNameMap[rootName]
  2218. if tempItem == nil {
  2219. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2220. return
  2221. }
  2222. cs = &fms.ContractService{
  2223. ProductId: crm.CompanyProductRai,
  2224. ServiceTemplateId: tempItem.ServiceTemplateId,
  2225. Title: tempItem.Title,
  2226. Value: tempItem.Value,
  2227. TableValue: tempItem.TableValue,
  2228. ChartPermissionId: tempItem.ChartPermissionId,
  2229. }
  2230. rowServices = append(rowServices, cs)
  2231. }
  2232. }
  2233. productIds[crm.CompanyProductRai] = struct{}{}
  2234. }
  2235. continue
  2236. }
  2237. // 权益研选等套餐
  2238. if k >= 45 && k<=49 {
  2239. if v == "是" {
  2240. tempItem := serviceTempNameMap[titleMap[k]]
  2241. if tempItem == nil {
  2242. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2243. return
  2244. }
  2245. cs := &fms.ContractService{
  2246. ProductId: crm.CompanyProductRai,
  2247. ServiceTemplateId: tempItem.ServiceTemplateId,
  2248. Title: tempItem.Title,
  2249. Value: tempItem.Value,
  2250. TableValue: tempItem.TableValue,
  2251. ChartPermissionId: tempItem.ChartPermissionId,
  2252. }
  2253. cs.Set()
  2254. rowServices = append(rowServices, cs)
  2255. productIds[crm.CompanyProductRai] = struct{}{}
  2256. }
  2257. continue
  2258. }
  2259. // 套餐备注
  2260. if k == 50 {
  2261. rowRegister.ServiceRemark = v
  2262. continue
  2263. }
  2264. // 开始时间/到期时间
  2265. if k == 51 {
  2266. // 转换失败可能是因为格式为Excel日期格式, 读取出来会是一串数字, 将其转换成日期字符串再处理
  2267. va := cell.Value
  2268. if va == "" {
  2269. resp.Fail(fmt.Sprintf("第%d行开始时间不可为空, 请按模板导入", i+1), c)
  2270. return
  2271. }
  2272. startDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2273. if e != nil {
  2274. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2275. startDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2276. if e != nil {
  2277. resp.Fail(fmt.Sprintf("第%d行开始时间格式转换有误, 请按模板导入", i+1), c)
  2278. return
  2279. }
  2280. }
  2281. // 转换后的日期小于1900-01-01表示当前生成的日期是有问题的
  2282. if startDate.Before(checkDate) {
  2283. resp.Fail(fmt.Sprintf("第%d行开始时间格式有误, 请按模板导入", i+1), c)
  2284. return
  2285. }
  2286. rowRegister.StartDate = startDate
  2287. continue
  2288. }
  2289. if k == 52 {
  2290. va := cell.Value
  2291. if va == "" {
  2292. resp.Fail(fmt.Sprintf("第%d行到期时间不可为空, 请按模板导入", i+1), c)
  2293. return
  2294. }
  2295. endDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2296. if e != nil {
  2297. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2298. endDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2299. if e != nil {
  2300. resp.Fail(fmt.Sprintf("第%d行到期时间格式转换有误, 请按模板导入", i+1), c)
  2301. return
  2302. }
  2303. }
  2304. if endDate.Before(checkDate) {
  2305. resp.Fail(fmt.Sprintf("第%d行到期时间格式有误, 请按模板导入", i+1), c)
  2306. return
  2307. }
  2308. rowRegister.EndDate = endDate
  2309. continue
  2310. }
  2311. // 合同金额
  2312. if k == 53 {
  2313. amountStr := v
  2314. amount, e := strconv.ParseFloat(amountStr, 64)
  2315. if e != nil {
  2316. resp.Fail(fmt.Sprintf("第%d行合同金额有误, 请按模板导入", i+1), c)
  2317. return
  2318. }
  2319. rowRegister.ContractAmount = amount
  2320. continue
  2321. }
  2322. // 金额单位
  2323. if k == 54 {
  2324. rate := rateMap[v]
  2325. if rate <= 0 {
  2326. resp.Fail(fmt.Sprintf("第%d行金额单位有误, 请按模板导入", i+1), c)
  2327. return
  2328. }
  2329. rowRegister.CurrencyUnit = v
  2330. rowRegister.RMBRate = rate
  2331. continue
  2332. }
  2333. // FICC 套餐总金额
  2334. if k == 55 {
  2335. amountStr := v
  2336. amount, e := strconv.ParseFloat(amountStr, 64)
  2337. if e != nil {
  2338. resp.Fail(fmt.Sprintf("第%d行FICC套餐总金额有误, 请按模板导入", i+1), c)
  2339. return
  2340. }
  2341. if amount > 0 {
  2342. tmp := &fms.ContractServiceAmount{
  2343. ProductId: crm.CompanyProductFicc,
  2344. ServiceAmount: amount,
  2345. CurrencyUnit: rowRegister.CurrencyUnit,
  2346. TimeBase: base.TimeBase{},
  2347. }
  2348. rowServiceAmount = append(rowServiceAmount, tmp)
  2349. }
  2350. continue
  2351. }
  2352. // 权益套餐总金额
  2353. if k == 56 {
  2354. amountStr := v
  2355. amount, e := strconv.ParseFloat(amountStr, 64)
  2356. if e != nil {
  2357. resp.Fail(fmt.Sprintf("第%d行权益套餐总金额有误, 请按模板导入", i+1), c)
  2358. return
  2359. }
  2360. if amount > 0 {
  2361. tmp := &fms.ContractServiceAmount{
  2362. ProductId: crm.CompanyProductRai,
  2363. ServiceAmount: amount,
  2364. CurrencyUnit: rowRegister.CurrencyUnit,
  2365. TimeBase: base.TimeBase{},
  2366. }
  2367. rowServiceAmount = append(rowServiceAmount, tmp)
  2368. }
  2369. continue
  2370. }
  2371. // 约定付款日期
  2372. if k == 57 {
  2373. rowRegister.AgreedPayTime = v
  2374. continue
  2375. }
  2376. // 签订日
  2377. if k == 58 {
  2378. va := cell.Value
  2379. if va == "" {
  2380. continue
  2381. }
  2382. signDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2383. if e != nil {
  2384. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2385. signDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2386. if e != nil {
  2387. resp.Fail(fmt.Sprintf("第%d行签订日格式转换有误, 请按模板导入", i+1), c)
  2388. return
  2389. }
  2390. }
  2391. if signDate.Before(checkDate) {
  2392. resp.Fail(fmt.Sprintf("第%d行签订日格式有误, 请按模板导入", i+1), c)
  2393. return
  2394. }
  2395. rowRegister.SignDate = signDate
  2396. continue
  2397. }
  2398. // 合同状态
  2399. if k == 59 {
  2400. rowRegister.ContractStatus = fms.ContractStatusNameKeyMap[v]
  2401. if rowRegister.ContractStatus == 0 {
  2402. resp.Fail(fmt.Sprintf("第%d行合同状态不匹配, 请按模板导入", i+1), c)
  2403. return
  2404. }
  2405. continue
  2406. }
  2407. // 合同编号
  2408. if k == 60 {
  2409. rowContractCode := v
  2410. if rowContractCode == "" {
  2411. resp.Fail(fmt.Sprintf("第%d行合同编号不可为空, 请按模板导入", i+1), c)
  2412. return
  2413. }
  2414. if utils.InArrayByStr(contractCodeArr, rowContractCode) {
  2415. // 此合同已登记, 跳过本行的读取
  2416. isSkip = true
  2417. break
  2418. }
  2419. rowRegister.ContractCode = rowContractCode
  2420. continue
  2421. }
  2422. // 合规备注
  2423. if k == 61 {
  2424. rowRegister.Remark = v
  2425. continue
  2426. }
  2427. // 开票列表
  2428. k2 := 61
  2429. for ir := 0; ir < invoiceMax; ir++ {
  2430. n := ir + 1
  2431. // 开票日
  2432. k2 += 1
  2433. if k == k2 {
  2434. if v != "" {
  2435. va := cell.Value
  2436. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2437. if e != nil {
  2438. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2439. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2440. if e != nil {
  2441. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式转换有误, 请按模板导入", i+1, n), c)
  2442. return
  2443. }
  2444. }
  2445. if invoiceDate.Before(checkDate) {
  2446. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式有误, 请按模板导入", i+1, n), c)
  2447. return
  2448. }
  2449. rowInvoices[ir].InvoiceDate = invoiceDate
  2450. rowInvoices[ir].ContractCode = rowRegister.ContractCode
  2451. rowInvoices[ir].InvoiceType = fms.ContractInvoiceTypeMake
  2452. }
  2453. continue
  2454. }
  2455. // 开票金额
  2456. k2 += 1
  2457. if k == k2 {
  2458. if v != "" {
  2459. amountStr := v
  2460. amount, e := strconv.ParseFloat(amountStr, 64)
  2461. if e != nil {
  2462. resp.Fail(fmt.Sprintf("第%d行开票金额%d有误, 请按模板导入", i+1, n), c)
  2463. return
  2464. }
  2465. if rowRegister.RMBRate <= 0 {
  2466. resp.Fail(fmt.Sprintf("第%d行开票金额换算%d有误, 请按模板导入金额单位", i+1, n), c)
  2467. return
  2468. }
  2469. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amount/rowRegister.RMBRate), 64)
  2470. rowInvoices[ir].OriginAmount = amount
  2471. rowInvoices[ir].Amount = a
  2472. }
  2473. continue
  2474. }
  2475. // 开票套餐类型
  2476. k2 += 1
  2477. if k == k2 {
  2478. if v != "" {
  2479. if v == "FICC套餐" {
  2480. rowInvoices[ir].ServiceProductId = crm.CompanyProductFicc
  2481. }else if v == "权益套餐"{
  2482. rowInvoices[ir].ServiceProductId = crm.CompanyProductRai
  2483. }else{
  2484. resp.Fail(fmt.Sprintf("第%d行开票套餐类型%d:%s有误, 请按模板导入", i+1, n, v), c)
  2485. return
  2486. }
  2487. }
  2488. continue
  2489. }
  2490. // 开票销售
  2491. k2 += 1
  2492. if k == k2 {
  2493. if v != "" {
  2494. sellerItem := sellerMap[v]
  2495. if sellerItem == nil {
  2496. resp.Fail(fmt.Sprintf("第%d行开票销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2497. return
  2498. }
  2499. rowInvoices[ir].SellerId = sellerItem.SellerId
  2500. rowInvoices[ir].SellerName = sellerItem.SellerName
  2501. rowInvoices[ir].SellerGroupId = sellerItem.GroupId
  2502. rowInvoices[ir].SellerGroupName = sellerItem.GroupName
  2503. rowInvoices[ir].SellerTeamId = sellerItem.TeamId
  2504. rowInvoices[ir].SellerTeamName = sellerItem.TeamName
  2505. }
  2506. continue
  2507. }
  2508. // 备注
  2509. k2 += 1
  2510. if k == k2 {
  2511. if v != "" {
  2512. rowInvoices[ir].Remark = v
  2513. }
  2514. continue
  2515. }
  2516. }
  2517. // 到款列表
  2518. for ir := 0; ir < invoiceMax; ir++ {
  2519. n := ir + 1
  2520. // 到款日
  2521. k2 += 1
  2522. if k == k2 {
  2523. if v != "" {
  2524. va := cell.Value
  2525. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2526. if e != nil {
  2527. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2528. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2529. if e != nil {
  2530. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式转换有误, 请按模板导入", i+1, n), c)
  2531. return
  2532. }
  2533. }
  2534. if invoiceDate.Before(checkDate) {
  2535. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式有误, 请按模板导入", i+1, n), c)
  2536. return
  2537. }
  2538. rowPayments[ir].InvoiceDate = invoiceDate
  2539. rowPayments[ir].ContractCode = rowRegister.ContractCode
  2540. rowPayments[ir].InvoiceType = fms.ContractInvoiceTypePay
  2541. }
  2542. continue
  2543. }
  2544. // 到款金额
  2545. k2 += 1
  2546. if k == k2 {
  2547. if v != "" {
  2548. amountStr := v
  2549. amount, e := strconv.ParseFloat(amountStr, 64)
  2550. if e != nil {
  2551. resp.Fail(fmt.Sprintf("第%d行到款金额%d有误, 请按模板导入", i+1, n), c)
  2552. return
  2553. }
  2554. if rowRegister.RMBRate <= 0 {
  2555. resp.Fail(fmt.Sprintf("第%d行到款金额换算%d有误, 请按模板导入金额单位", i+1, n), c)
  2556. return
  2557. }
  2558. // 付款方式
  2559. dayDiff := rowRegister.EndDate.Sub(rowRegister.StartDate).Hours() / 24
  2560. contractAmount := rowRegister.ContractAmount
  2561. payType := fmsService.CalculateContractPaymentType(amount, contractAmount, dayDiff)
  2562. rowPayments[ir].PayType = payType
  2563. rowPayments[ir].OriginAmount = amount
  2564. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amount/rowRegister.RMBRate), 64)
  2565. rowPayments[ir].Amount = a
  2566. }
  2567. continue
  2568. }
  2569. // 到款套餐类型
  2570. k2 += 1
  2571. if k == k2 {
  2572. if v != "" {
  2573. if v == "FICC套餐" {
  2574. rowPayments[ir].ServiceProductId = crm.CompanyProductFicc
  2575. }else if v == "权益套餐"{
  2576. rowPayments[ir].ServiceProductId = crm.CompanyProductRai
  2577. }else{
  2578. resp.Fail(fmt.Sprintf("第%d行到款套餐类型%d:%s有误, 请按模板导入", i+1, n, v), c)
  2579. return
  2580. }
  2581. }
  2582. continue
  2583. }
  2584. // 备注
  2585. k2 += 1
  2586. if k == k2 {
  2587. if v != "" {
  2588. rowPayments[ir].Remark = v
  2589. }
  2590. continue
  2591. }
  2592. }
  2593. }
  2594. if isSkip {
  2595. continue
  2596. }
  2597. // 小套餐
  2598. if len(rowChartPermissionIdArr) > 0 {
  2599. // 说明有小套餐
  2600. tempItem := serviceTempNameMap["FICC小套餐"]
  2601. if tempItem == nil {
  2602. resp.Fail(fmt.Sprintf("第%d行小套餐名称不匹配, 请按模板导入", i+1), c)
  2603. return
  2604. }
  2605. rowChartPermissionIds := strings.Join(rowChartPermissionIdArr, ",")
  2606. cs := &fms.ContractService{
  2607. ProductId: crm.CompanyProductFicc,
  2608. ServiceTemplateId: tempItem.ServiceTemplateId,
  2609. Title: tempItem.Title,
  2610. Value: tempItem.Value,
  2611. TableValue: tempItem.TableValue,
  2612. ChartPermissionId: tempItem.ChartPermissionId,
  2613. ChartPermissionIds: rowChartPermissionIds,
  2614. }
  2615. cs.Set()
  2616. rowServices = append(rowServices, cs)
  2617. }
  2618. // 如果导入的最后一条合同编号为空并且合同编号之后的字段均为空
  2619. // excel这个包读行的时候不会再往后面没数据的地方读取, 所以此处需要重新判断一次
  2620. if rowRegister.ContractCode == "" {
  2621. resp.Fail(fmt.Sprintf("第%d行合同编号为空", i+1), c)
  2622. return
  2623. }
  2624. rowRegister.RegisterStatus = fms.ContractRegisterStatusIng
  2625. rowInvoiceList := make([]*fms.ContractInvoice, 0)
  2626. // 过滤信息不完整的开票到款
  2627. for l := range rowInvoices {
  2628. if rowInvoices[l].ContractCode != "" {
  2629. if rowInvoices[l].OriginAmount <= 0 || rowInvoices[l].SellerId == 0 {
  2630. resp.Fail(fmt.Sprintf("第%d行开票信息必填项不完整", i+1), c)
  2631. return
  2632. }
  2633. rowInvoiceList = append(rowInvoiceList, rowInvoices[l])
  2634. }
  2635. }
  2636. for l := range rowPayments {
  2637. if rowPayments[l].ContractCode != "" {
  2638. if rowPayments[l].OriginAmount <= 0 {
  2639. resp.Fail(fmt.Sprintf("第%d行到款信息必填项不完整", i+1), c)
  2640. return
  2641. }
  2642. rowInvoiceList = append(rowInvoiceList, rowPayments[l])
  2643. }
  2644. }
  2645. // 新增登记、套餐、开票到款信息
  2646. for proId, _ := range productIds {
  2647. rowRegister.ProductIds += strconv.Itoa(proId)+","
  2648. }
  2649. rowRegister.ProductIds = strings.Trim(rowRegister.ProductIds, ",")
  2650. newId, e := fms.CreateImportContractRegister(rowRegister, rowServices, rowInvoiceList, rowServiceAmount)
  2651. if e != nil {
  2652. resp.FailData(fmt.Sprintf("第%d行导入失败", i+1), "新增导入登记失败, Err: "+e.Error(), c)
  2653. return
  2654. }
  2655. newIds = append(newIds, newId)
  2656. }
  2657. }
  2658. }
  2659. resp.Ok("操作成功", c)
  2660. }
  2661. // CurrencyList
  2662. // @Title 货币单位列表
  2663. // @Description 货币单位列表
  2664. // @Success 200 {object} fms.CurrencyUnitItem
  2665. // @router /contract/register/currency_list [get]
  2666. func (rg *RegisterController) CurrencyList(c *gin.Context) {
  2667. list, e := fmsService.GetTodayCurrencyRateList()
  2668. if e != nil {
  2669. resp.FailData("获取失败", "获取今日货币汇率列表失败, Err: "+e.Error(), c)
  2670. return
  2671. }
  2672. resp.OkData("获取成功", list, c)
  2673. }