register.go 103 KB

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