register.go 100 KB

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