register.go 99 KB

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