register.go 110 KB

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