register.go 95 KB

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