register.go 93 KB

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