register.go 94 KB

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