register.go 94 KB

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