register.go 96 KB

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