register.go 106 KB

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