register.go 94 KB

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