register.go 94 KB

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