register.go 94 KB

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