register.go 100 KB

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