register.go 90 KB

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