register.go 99 KB

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