register.go 94 KB

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