register.go 98 KB

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