register.go 94 KB

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