12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832 |
- package contract
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "github.com/gin-gonic/gin"
- "github.com/go-playground/validator/v10"
- "github.com/shopspring/decimal"
- "github.com/tealeg/xlsx"
- "hongze/fms_api/controller/resp"
- "hongze/fms_api/global"
- "hongze/fms_api/models/base"
- "hongze/fms_api/models/crm"
- "hongze/fms_api/models/fms"
- "hongze/fms_api/models/system"
- fmsService "hongze/fms_api/services/fms"
- "hongze/fms_api/utils"
- "net/http"
- "os"
- "path"
- "strconv"
- "strings"
- "time"
- )
- // RegisterController 合同登记
- type RegisterController struct{}
- // List
- // @Title 合同登记列表
- // @Description 合同登记列表
- // @Param Keyword query string false "关键词"
- // @Param StartDate query string false "合同开始日期"
- // @Param EndDate query string false "合同结束日期"
- // @Param ServiceType query int false "套餐类型"
- // @Param ContractType query int false "合同类型"
- // @Param RegisterStatus query int false "登记状态"
- // @Success 200 {object} fms.ContractRegisterItem
- // @router /contract/register/list [get]
- func (rg *RegisterController) List(c *gin.Context) {
- var req fms.ContractRegisterListReq
- if e := c.BindQuery(&req); e != nil {
- err, ok := e.(validator.ValidationErrors)
- if !ok {
- resp.FailData("参数解析失败", "Err:"+e.Error(), c)
- return
- }
- resp.FailData("参数解析失败", err.Translate(global.Trans), c)
- return
- }
- cond := `1 = 1`
- pars := make([]interface{}, 0)
- // 合同编号/客户姓名/销售/实际使用方
- if req.Keyword != "" {
- kw := "%" + req.Keyword + "%"
- cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
- pars = append(pars, kw, kw, kw, kw)
- }
- if req.StartDate != "" && req.EndDate != "" {
- st := fmt.Sprint(req.StartDate, " 00:00:00")
- ed := fmt.Sprint(req.EndDate, " 23:59:59")
- cond += ` AND (create_time BETWEEN ? AND ?)`
- pars = append(pars, st, ed)
- }
- if req.ContractType != 0 {
- cond += ` AND contract_type = ?`
- pars = append(pars, req.ContractType)
- }
- if req.RegisterStatus != 0 {
- cond += ` AND register_status = ?`
- pars = append(pars, req.RegisterStatus)
- }
- // 套餐筛选
- if req.ServiceType != 0 {
- registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
- if e != nil {
- resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
- return
- }
- if len(registerIds) > 0 {
- cond += ` AND contract_register_id IN ?`
- pars = append(pars, registerIds)
- } else {
- cond += ` AND 1 = 2`
- }
- }
- page := new(base.Page)
- page.SetPageSize(req.PageSize)
- page.SetCurrent(req.Current)
- page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: false})
- total, list, e := fms.GetContractRegisterItemPageList(page, cond, pars)
- if e != nil {
- resp.FailMsg("获取失败", "获取合同登记列表失败, Err: "+e.Error(), c)
- return
- }
- registerIds := make([]int, 0)
- for i := range list {
- registerIds = append(registerIds, list[i].ContractRegisterId)
- }
- serviceMap := make(map[int]string, 0)
- invoiceMap := make(map[int][]*fms.ContractInvoiceItem, 0)
- paymentMap := make(map[int][]*fms.ContractInvoiceItem, 0)
- if len(registerIds) > 0 {
- // 获取服务套餐
- servicesNameList, e := fms.GetContractRegisterServicesNameByRegisterIds(registerIds)
- if e != nil {
- resp.FailMsg("获取失败", "获取套餐拼接字符串失败, Err: "+e.Error(), c)
- return
- }
- for i := range servicesNameList {
- serviceMap[servicesNameList[i].ContractRegisterId] = servicesNameList[i].ServicesName
- }
- // 获取开票/到款列表
- invoiceCond := `contract_register_id IN ?`
- invoicePars := make([]interface{}, 0)
- invoicePars = append(invoicePars, registerIds)
- invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
- if e != nil {
- resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
- return
- }
- for i := range invoiceList {
- if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
- invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
- }
- if paymentMap[invoiceList[i].ContractRegisterId] == nil {
- paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
- }
- if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
- invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
- }
- if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
- paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
- }
- }
- }
- respList := make([]*fms.ContractRegisterList, 0)
- for i := range list {
- v := new(fms.ContractRegisterList)
- v.ContractRegisterItem = list[i]
- v.ServicesName = serviceMap[list[i].ContractRegisterId]
- v.InvoiceList = invoiceMap[list[i].ContractRegisterId]
- v.PaymentList = paymentMap[list[i].ContractRegisterId]
- respList = append(respList, v)
- }
- page.SetTotal(total)
- baseData := new(base.BaseData)
- baseData.SetPage(page)
- baseData.SetList(respList)
- resp.OkData("获取成功", baseData, c)
- }
- // Add
- // @Title 新增合同登记
- // @Description 新增合同登记
- // @Param request body fms.ContractRegisterAddReq true "type json string"
- // @Success 200 string "操作成功"
- // @router /contract/register/add [post]
- func (rg *RegisterController) Add(c *gin.Context) {
- req := new(fms.ContractRegisterAddReq)
- err := c.ShouldBind(&req)
- if err != nil {
- errs, ok := err.(validator.ValidationErrors)
- if !ok {
- resp.FailData("参数解析失败", "Err:"+err.Error(), c)
- return
- }
- resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
- return
- }
- claims, _ := c.Get("adminInfo")
- adminInfo := claims.(*system.SysAdmin)
- // 日期校验
- startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
- if e != nil {
- resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
- return
- }
- endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
- if e != nil {
- resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
- return
- }
- signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
- if req.SignDate != "" {
- signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
- if e != nil {
- resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
- return
- }
- signDate = signDateTime
- }
- // 是否存在相同合同编号的登记
- ob := new(fms.ContractRegister)
- existCond := `contract_code = ?`
- existPars := make([]interface{}, 0)
- existPars = append(existPars, req.ContractCode)
- exist, e := ob.FetchByCondition(existCond, existPars)
- if e != nil && e != utils.ErrNoRow {
- resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
- return
- }
- if exist != nil && exist.ContractRegisterId > 0 {
- resp.Fail("合同编号已存在", c)
- return
- }
- nowTime := time.Now().Local()
- ob.ContractCode = req.ContractCode
- ob.RelateContractCode = req.RelateContractCode
- ob.CrmContractId = req.CrmContractId
- ob.ContractSource = req.ContractSource
- ob.CompanyName = req.CompanyName
- ob.ActualCompanyName = req.ActualCompanyName
- ob.ProductId = req.ProductId
- ob.SellerId = req.SellerId
- ob.SellerName = req.SellerName
- ob.ContractType = req.ContractType
- ob.ContractAmount = req.ContractAmount
- ob.StartDate = startDate
- ob.EndDate = endDate
- ob.SignDate = signDate
- ob.AgreedPayTime = req.AgreedPayTime
- ob.ContractStatus = req.ContractStatus
- ob.RegisterStatus = fms.ContractRegisterStatusIng
- ob.Remark = req.Remark
- ob.ServiceRemark = req.ServiceRemark
- ob.HasPayment = req.HasPayment
- ob.Set()
- // 存在代付的直接完成登记, 且不允许进行开票/到款登记
- if req.HasPayment == 1 {
- ob.RegisterStatus = fms.ContractRegisterStatusComplete
- }
- // 套餐信息
- serviceList, e := fmsService.HandleContractServiceAndDetail(req.ProductId, req.Services, true)
- if e != nil {
- resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
- return
- }
- // 新增合同及套餐
- if e = fms.CreateContractRegisterAndServices(ob, serviceList); e != nil {
- resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
- return
- }
- // 操作日志
- go func() {
- opData := ""
- opDataByte, e := json.Marshal(req)
- if e != nil {
- return
- }
- opData = string(opDataByte)
- logItem := new(fms.ContractRegisterLog)
- logItem.ContractRegisterId = ob.ContractRegisterId
- logItem.AdminId = int(adminInfo.AdminId)
- logItem.AdminName = adminInfo.RealName
- logItem.OpData = opData
- logItem.OpType = fms.ContractRegisterOpTypeSave
- logItem.CreateTime = nowTime
- logItem.Remark = req.Remark
- if e = logItem.Create(); e != nil {
- return
- }
- }()
- resp.Ok("操作成功", c)
- }
- // Edit
- // @Title 编辑合同登记
- // @Description 编辑合同登记
- // @Param request body fms.ContractRegisterEditReq true "type json string"
- // @Success 200 string "操作成功"
- // @router /contract/register/edit [post]
- func (rg *RegisterController) Edit(c *gin.Context) {
- req := new(fms.ContractRegisterEditReq)
- err := c.ShouldBind(&req)
- if err != nil {
- errs, ok := err.(validator.ValidationErrors)
- if !ok {
- resp.FailData("参数解析失败", "Err:"+err.Error(), c)
- return
- }
- resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
- return
- }
- claims, _ := c.Get("adminInfo")
- adminInfo := claims.(*system.SysAdmin)
- // 日期校验
- startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
- if e != nil {
- resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
- return
- }
- endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
- if e != nil {
- resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
- return
- }
- signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
- if req.SignDate != "" {
- signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
- if e != nil {
- resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
- return
- }
- signDate = signDateTime
- }
- ob := new(fms.ContractRegister)
- item, e := ob.Fetch(req.ContractRegisterId)
- if e != nil {
- if e == utils.ErrNoRow {
- resp.Fail("登记记录不存在或已被删除", c)
- return
- }
- resp.FailMsg("操作失败", "获取合同登记信息失败, Err:"+e.Error(), c)
- return
- }
- // 是否存在相同合同编号的登记
- existCond := `contract_code = ?`
- existPars := make([]interface{}, 0)
- existPars = append(existPars, req.ContractCode)
- exist, e := ob.FetchByCondition(existCond, existPars)
- if e != nil && e != utils.ErrNoRow {
- resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
- return
- }
- if exist != nil && exist.ContractRegisterId > 0 && exist.ContractRegisterId != item.ContractRegisterId {
- resp.Fail("合同编号已存在", c)
- return
- }
- updateCols := []string{
- "ContractCode", "RelateContractCode", "CrmContractId", "ContractSource", "CompanyName", "ActualCompanyName",
- "SellerId", "SellerName", "ContractType", "ContractAmount", "StartDate", "EndDate", "SignDate", "AgreedPayTime",
- "ContractStatus", "RegisterStatus", "Remark", "ServiceRemark", "HasPayment", "ModifyTime",
- }
- nowTime := time.Now().Local()
- item.ContractCode = req.ContractCode
- item.RelateContractCode = req.RelateContractCode
- item.CrmContractId = req.CrmContractId
- item.ContractSource = req.ContractSource
- item.CompanyName = req.CompanyName
- item.ActualCompanyName = req.ActualCompanyName
- item.SellerId = req.SellerId
- item.SellerName = req.SellerName
- item.ContractType = req.ContractType
- item.ContractAmount = req.ContractAmount
- item.StartDate = startDate
- item.EndDate = endDate
- item.SignDate = signDate
- item.AgreedPayTime = req.AgreedPayTime
- item.ContractStatus = req.ContractStatus
- item.RegisterStatus = fms.ContractRegisterStatusIng
- item.Remark = req.Remark
- item.ServiceRemark = req.ServiceRemark
- item.HasPayment = req.HasPayment
- item.ModifyTime = nowTime
- // 存在代付的直接完成登记, 且不允许进行开票/到款登记
- if req.HasPayment == 1 {
- item.RegisterStatus = fms.ContractRegisterStatusComplete
- updateCols = append(updateCols, "RegisterStatus")
- }
- // 套餐信息
- serviceList, e := fmsService.HandleContractServiceAndDetail(req.ProductId, req.Services, true)
- if e != nil {
- resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
- return
- }
- // 更新合同及套餐
- if e = fms.UpdateContractRegisterAndServices(item, updateCols, serviceList); e != nil {
- resp.FailMsg("操作失败", "更新合同及套餐失败, Err: "+e.Error(), c)
- return
- }
- // 校验金额-是否修改状态
- go fmsService.CheckContractRegisterAmount(item.ContractRegisterId)
- // 操作日志
- go func() {
- opData := ""
- opDataByte, e := json.Marshal(req)
- if e != nil {
- return
- }
- opData = string(opDataByte)
- logItem := new(fms.ContractRegisterLog)
- logItem.ContractRegisterId = item.ContractRegisterId
- logItem.AdminId = int(adminInfo.AdminId)
- logItem.AdminName = adminInfo.RealName
- logItem.OpData = opData
- logItem.OpType = fms.ContractRegisterOpTypeEdit
- logItem.CreateTime = nowTime
- logItem.Remark = req.Remark
- if e = logItem.Create(); e != nil {
- return
- }
- }()
- resp.Ok("操作成功", c)
- }
- // Del
- // @Title 删除合同登记
- // @Description 删除合同登记
- // @Param request body fms.ContractRegisterDelReq true "type json string"
- // @Success 200 string "操作成功"
- // @router /contract/register/del [post]
- func (rg *RegisterController) Del(c *gin.Context) {
- req := new(fms.ContractRegisterDelReq)
- err := c.ShouldBind(&req)
- if err != nil {
- errs, ok := err.(validator.ValidationErrors)
- if !ok {
- resp.FailData("参数解析失败", "Err:"+err.Error(), c)
- return
- }
- resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
- return
- }
- claims, _ := c.Get("adminInfo")
- adminInfo := claims.(*system.SysAdmin)
- ob := new(fms.ContractRegister)
- item, e := ob.Fetch(req.ContractRegisterId)
- if e != nil {
- if e == utils.ErrNoRow {
- resp.Fail("合同登记不存在或已被删除", c)
- return
- }
- resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
- return
- }
- nowTime := time.Now().Local()
- item.IsDeleted = 1
- item.ModifyTime = nowTime
- updateCols := []string{"IsDeleted", "ModifyTime"}
- if e = item.Update(updateCols); e != nil {
- resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
- return
- }
- // 操作日志
- go func() {
- opData := ""
- opDataByte, e := json.Marshal(req)
- if e != nil {
- return
- }
- opData = string(opDataByte)
- logItem := new(fms.ContractRegisterLog)
- logItem.ContractRegisterId = req.ContractRegisterId
- logItem.AdminId = int(adminInfo.AdminId)
- logItem.AdminName = adminInfo.RealName
- logItem.OpData = opData
- logItem.OpType = fms.ContractRegisterOpTypeDel
- logItem.CreateTime = nowTime
- if e = logItem.Create(); e != nil {
- return
- }
- }()
- resp.Ok("操作成功", c)
- }
- // Detail
- // @Title 合同登记详情
- // @Description 合同登记详情
- // @Param ContractRegisterId query int false "合同登记ID"
- // @Success 200 {object} fms.ContractRegisterDetail
- // @router /contract/register/detail [get]
- func (rg *RegisterController) Detail(c *gin.Context) {
- var req fms.ContractRegisterDetailReq
- if e := c.BindQuery(&req); e != nil {
- err, ok := e.(validator.ValidationErrors)
- if !ok {
- resp.FailData("参数解析失败", "Err:"+e.Error(), c)
- return
- }
- resp.FailData("参数解析失败", err.Translate(global.Trans), c)
- return
- }
- result := new(fms.ContractRegisterDetail)
- // 合同登记信息
- item, e := fms.GetContractRegisterItemById(req.ContractRegisterId)
- if e != nil {
- resp.FailData("获取失败", "获取合同登记详情失败, Err:"+e.Error(), c)
- return
- }
- result.ContractRegisterItem = item
- // 套餐信息
- serviceList, e := fmsService.GetContractServiceAndDetail(req.ContractRegisterId)
- if e != nil {
- resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
- return
- }
- result.ServiceList = serviceList
- // 开票/到款信息
- invoiceCond := `contract_register_id = ?`
- invoicePars := make([]interface{}, 0)
- invoicePars = append(invoicePars, req.ContractRegisterId)
- invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
- if e != nil {
- resp.FailData("获取失败", "获取合同开票/到款信息失败, Err: "+e.Error(), c)
- return
- }
- result.InvoiceList = make([]*fms.ContractInvoiceItem, 0)
- result.PaymentList = make([]*fms.ContractInvoiceItem, 0)
- for i := range invoiceList {
- if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
- result.InvoiceList = append(result.InvoiceList, invoiceList[i])
- continue
- }
- if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
- result.PaymentList = append(result.PaymentList, invoiceList[i])
- }
- }
- // 合同登记进度
- logCond := `contract_register_id = ?`
- logPars := make([]interface{}, 0)
- logPars = append(logPars, req.ContractRegisterId)
- logList, e := fms.GetContractRegisterLogItemList(logCond, logPars)
- if e != nil {
- resp.FailData("获取失败", "获取合同登记进度失败, Err: "+e.Error(), c)
- return
- }
- result.Logs = logList
- resp.OkData("获取成功", result, c)
- }
- // UpdateStatus
- // @Title 修改合同状态
- // @Description 修改合同状态
- // @Param request body fms.ContractRegisterUpdateStatusReq true "type json string"
- // @Success 200 string "操作成功"
- // @router /contract/register/update_status [post]
- func (rg *RegisterController) UpdateStatus(c *gin.Context) {
- req := new(fms.ContractRegisterUpdateStatusReq)
- err := c.ShouldBind(&req)
- if err != nil {
- errs, ok := err.(validator.ValidationErrors)
- if !ok {
- resp.FailData("参数解析失败", "Err:"+err.Error(), c)
- return
- }
- resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
- return
- }
- claims, _ := c.Get("adminInfo")
- adminInfo := claims.(*system.SysAdmin)
- ob := new(fms.ContractRegister)
- item, e := ob.Fetch(req.ContractRegisterId)
- if e != nil {
- if e == utils.ErrNoRow {
- resp.Fail("合同登记不存在或已被删除", c)
- return
- }
- resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
- return
- }
- nowTime := time.Now().Local()
- item.ContractStatus = req.ContractStatus
- item.ModifyTime = nowTime
- updateCols := []string{"ContractStatus", "ModifyTime"}
- if e = item.Update(updateCols); e != nil {
- resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
- return
- }
- // 校验金额-是否修改状态
- go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
- // 操作日志
- go func() {
- opData := ""
- opDataByte, e := json.Marshal(req)
- if e != nil {
- return
- }
- opData = string(opDataByte)
- logItem := new(fms.ContractRegisterLog)
- logItem.ContractRegisterId = req.ContractRegisterId
- logItem.AdminId = int(adminInfo.AdminId)
- logItem.AdminName = adminInfo.RealName
- logItem.OpData = opData
- logItem.OpType = fms.ContractRegisterOpTypeStatus
- logItem.CreateTime = nowTime
- if e = logItem.Create(); e != nil {
- return
- }
- }()
- resp.Ok("操作成功", c)
- }
- // Invoice
- // @Title 开票/到款登记
- // @Description 开票/到款登记
- // @Param request body fms.ContractInvoiceSaveReq true "type json string"
- // @Success 200 string "操作成功"
- // @router /contract/register/invoice [post]
- func (rg *RegisterController) Invoice(c *gin.Context) {
- req := new(fms.ContractInvoiceSaveReq)
- err := c.ShouldBind(&req)
- if err != nil {
- errs, ok := err.(validator.ValidationErrors)
- if !ok {
- resp.FailData("参数解析失败", "Err:"+err.Error(), c)
- return
- }
- resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
- return
- }
- claims, _ := c.Get("adminInfo")
- adminInfo := claims.(*system.SysAdmin)
- registerOB := new(fms.ContractRegister)
- item, e := registerOB.Fetch(req.ContractRegisterId)
- if e != nil {
- if e == utils.ErrNoRow {
- resp.Fail("合同登记不存在或已被删除", c)
- return
- }
- resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
- return
- }
- // 合同存在代付不允许开票/到款登记
- if item.HasPayment == 1 {
- resp.Fail("合同存在代付不允许添加开票/到款登记", c)
- return
- }
- noChangeInvoiceIds := make([]int, 0)
- newInvoice := make([]*fms.ContractInvoice, 0)
- if len(req.AmountList) > 0 {
- for i := range req.AmountList {
- if req.AmountList[i].Amount <= 0 {
- resp.Fail("登记金额有误", c)
- return
- }
- if req.AmountList[i].InvoiceDate == "" {
- resp.Fail("请选择日期", c)
- return
- }
- t, e := time.ParseInLocation(utils.FormatDate, req.AmountList[i].InvoiceDate, time.Local)
- if e != nil {
- resp.FailData("日期格式有误", "Err:"+e.Error(), c)
- return
- }
- if req.AmountList[i].InvoiceId > 0 {
- noChangeInvoiceIds = append(noChangeInvoiceIds, req.AmountList[i].InvoiceId)
- } else {
- v := &fms.ContractInvoice{
- ContractRegisterId: req.ContractRegisterId,
- ContractCode: item.ContractCode,
- Amount: req.AmountList[i].Amount,
- InvoiceType: req.InvoiceType,
- InvoiceDate: t,
- AdminId: int(adminInfo.AdminId),
- AdminName: adminInfo.RealName,
- Remark: req.AmountList[i].Remark,
- }
- v.Set()
- newInvoice = append(newInvoice, v)
- }
- }
- }
- // 获取原有的登记信息
- invoiceCond := `contract_register_id = ? AND invoice_type = ?`
- invoicePars := make([]interface{}, 0)
- invoicePars = append(invoicePars, req.ContractRegisterId, req.InvoiceType)
- originInvoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
- if e != nil {
- resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
- return
- }
- // 比对原有和现有的登记信息
- logList := make([]*fms.ContractRegisterLog, 0)
- opData := ""
- opDataByte, e := json.Marshal(req)
- if e != nil {
- return
- }
- opData = string(opDataByte)
- opType := fms.ContractRegisterOpTypeInvoice
- if req.InvoiceType == fms.ContractInvoiceTypePay {
- opType = fms.ContractRegisterOpTypePayment
- }
- nowTime := time.Now().Local()
- // 需要删除的记录
- deleteInvoiceIds := make([]int, 0)
- for i := range originInvoiceList {
- if !utils.InArrayByInt(noChangeInvoiceIds, originInvoiceList[i].ContractInvoiceId) {
- deleteInvoiceIds = append(deleteInvoiceIds, originInvoiceList[i].ContractInvoiceId)
- logList = append(logList, &fms.ContractRegisterLog{
- ContractRegisterId: req.ContractRegisterId,
- AdminId: int(adminInfo.AdminId),
- AdminName: adminInfo.RealName,
- OpData: opData,
- OpType: opType,
- CreateTime: nowTime,
- AmountRemark: fmt.Sprint("删除", fms.ContractInvoiceKeyNameMap[opType], "金额", originInvoiceList[i].Amount, "元"),
- })
- }
- }
- // 新增的记录
- if len(newInvoice) > 0 {
- newAmount := decimal.NewFromFloat(0).Round(2)
- for i := range newInvoice {
- a := decimal.NewFromFloat(newInvoice[i].Amount).Round(2)
- newAmount = newAmount.Add(a)
- }
- ia, _ := newAmount.Round(2).Float64()
- logList = append(logList, &fms.ContractRegisterLog{
- ContractRegisterId: req.ContractRegisterId,
- AdminId: int(adminInfo.AdminId),
- AdminName: adminInfo.RealName,
- OpData: opData,
- OpType: opType,
- CreateTime: nowTime,
- AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
- })
- }
- // 删除并新增登记
- ob := new(fms.ContractInvoice)
- if e := ob.DeleteAndCreateNewInvoice(req.ContractRegisterId, req.InvoiceType, deleteInvoiceIds, newInvoice); e != nil {
- resp.FailData("日期格式有误", "Err:"+e.Error(), c)
- return
- }
- // 校验金额-是否修改状态
- go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
- // 操作日志
- go func() {
- logOB := new(fms.ContractRegisterLog)
- if e := logOB.AddInBatches(logList); e != nil {
- return
- }
- }()
- resp.Ok("操作成功", c)
- }
- // Export
- // @Title 合同登记-导出
- // @Description 合同登记-导出
- // @Param Keyword query string false "关键词"
- // @Param StartDate query string false "合同开始日期"
- // @Param EndDate query string false "合同结束日期"
- // @Param ServiceType query int false "套餐类型"
- // @Param ContractType query int false "合同类型"
- // @Param RegisterStatus query int false "登记状态"
- // @Success 200 string "操作成功"
- // @router /contract/register/export [get]
- func (rg *RegisterController) Export(c *gin.Context) {
- var req fms.ContractRegisterListReq
- if e := c.BindQuery(&req); e != nil {
- err, ok := e.(validator.ValidationErrors)
- if !ok {
- resp.FailData("参数解析失败", "Err:"+e.Error(), c)
- return
- }
- resp.FailData("参数解析失败", err.Translate(global.Trans), c)
- return
- }
- cond := `1 = 1`
- pars := make([]interface{}, 0)
- // 合同编号/客户姓名/销售/实际使用方
- if req.Keyword != "" {
- kw := "%" + req.Keyword + "%"
- cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
- pars = append(pars, kw, kw, kw, kw)
- }
- if req.StartDate != "" && req.EndDate != "" {
- st := fmt.Sprint(req.StartDate, " 00:00:00")
- ed := fmt.Sprint(req.EndDate, " 23:59:59")
- cond += ` AND (create_time BETWEEN ? AND ?)`
- pars = append(pars, st, ed)
- }
- if req.ContractType != 0 {
- cond += ` AND contract_type = ?`
- pars = append(pars, req.ContractType)
- }
- if req.RegisterStatus != 0 {
- cond += ` AND register_status = ?`
- pars = append(pars, req.RegisterStatus)
- }
- if req.ServiceType != 0 {
- registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
- if e != nil {
- resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
- return
- }
- if len(registerIds) > 0 {
- cond += ` AND contract_register_id IN ?`
- pars = append(pars, registerIds)
- } else {
- cond += ` AND 1 = 2`
- }
- }
- // 获取列表数据
- cr := new(fms.ContractRegister)
- list, e := cr.List(cond, pars)
- if e != nil {
- resp.FailData("获取合同列表失败", "Err:"+e.Error(), c)
- return
- }
- if len(list) == 0 {
- resp.Fail("无有效数据可导出", c)
- return
- }
- registerIds := make([]int, 0)
- for i := range list {
- registerIds = append(registerIds, list[i].ContractRegisterId)
- }
- // 获取小套餐品种
- cpCond := `product_id = ? AND permission_name <> ?`
- cpPars := make([]interface{}, 0)
- cpPars = append(cpPars, crm.CompanyProductFicc, crm.ChartPermissionStrategyName)
- cp := new(crm.ChartPermission)
- permissionList, e := cp.List(cpCond, cpPars)
- if e != nil {
- resp.FailData("获取小套餐品种失败", "Err:"+e.Error(), c)
- return
- }
- permissionLen := len(permissionList)
- permissionNameIdMap := make(map[string]int)
- for i := range permissionList {
- permissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
- }
- // 获取套餐服务
- //serviceList, e := fms.GetContractServiceTemplateMapByProductId(crm.CompanyProductFicc)
- //if e != nil {
- // resp.FailData("获取套餐服务失败", "Err:"+e.Error(), c)
- // return
- //}
- // 套餐/开票/到款列表
- serviceMap := make(map[int][]*fms.ContractService)
- serviceChartPermissionsMap := make(map[int][]int)
- invoiceMap := make(map[int][]*fms.ContractInvoice)
- paymentMap := make(map[int][]*fms.ContractInvoice)
- maxInvoice := 0
- maxPayment := 0
- if len(registerIds) > 0 {
- // 获取套餐信息
- csCond := `contract_register_id IN ?`
- csPars := make([]interface{}, 0)
- csPars = append(csPars, registerIds)
- cs := new(fms.ContractService)
- serviceList, e := cs.List(csCond, csPars)
- if e != nil {
- resp.FailData("获取合同套餐列表失败", "Err:"+e.Error(), c)
- return
- }
- for i := range serviceList {
- cid := serviceList[i].ContractRegisterId
- if serviceMap[cid] == nil {
- serviceMap[cid] = make([]*fms.ContractService, 0)
- }
- serviceMap[cid] = append(serviceMap[cid], serviceList[i])
- // 小套餐权限
- if serviceChartPermissionsMap[cid] == nil {
- serviceChartPermissionsMap[cid] = make([]int, 0)
- }
- if serviceList[i].ChartPermissionIds != "" {
- ids := utils.JoinStr2IntArr(serviceList[i].ChartPermissionIds, ",")
- serviceChartPermissionsMap[cid] = append(serviceChartPermissionsMap[cid], ids...)
- }
- }
- // 获取开票/到款详情, 并取最大的开票/到款数(用于动态扩展第二列表头)
- ci := new(fms.ContractInvoice)
- invoiceList, e := ci.List(csCond, csPars, "")
- if e != nil {
- resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
- return
- }
- for k := range invoiceList {
- cid := invoiceList[k].ContractRegisterId
- if invoiceMap[cid] == nil {
- invoiceMap[cid] = make([]*fms.ContractInvoice, 0)
- }
- if paymentMap[cid] == nil {
- paymentMap[cid] = make([]*fms.ContractInvoice, 0)
- }
- if invoiceList[k].InvoiceType == fms.ContractInvoiceTypeMake {
- invoiceMap[cid] = append(invoiceMap[cid], invoiceList[k])
- continue
- }
- if invoiceList[k].InvoiceType == fms.ContractInvoiceTypePay {
- paymentMap[cid] = append(paymentMap[cid], invoiceList[k])
- continue
- }
- }
- // 取最大开票/到款数
- for j := range invoiceMap {
- if len(invoiceMap[j]) > maxInvoice {
- maxInvoice = len(invoiceMap[j])
- }
- }
- for p := range paymentMap {
- if len(paymentMap[p]) > maxPayment {
- maxPayment = len(paymentMap[p])
- }
- }
- }
- // 生成Excel文件
- //dir, err := os.Executable()
- //exPath := filepath.Dir(dir)
- //filePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
- xlsxFile := xlsx.NewFile()
- //if err != nil {
- // resp.FailData("生成文件失败", "Err:"+err.Error(), c)
- // return
- //}
- style := xlsx.NewStyle()
- alignment := xlsx.Alignment{
- Horizontal: "center",
- Vertical: "center",
- WrapText: true,
- }
- style.Alignment = alignment
- style.ApplyAlignment = true
- sheet, err := xlsxFile.AddSheet("合同登记")
- if err != nil {
- resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
- return
- }
- //_ = sheet.SetColWidth(0, 0, 60)
- //_ = sheet.SetColWidth(4, 10, 60)
- // 1行表头
- titleRow := sheet.AddRow()
- titleRow.SetHeight(40)
- // 1行1列-右合并两格
- cell1 := titleRow.AddCell()
- cell1.HMerge = 2
- cell1.SetValue("FICC客户签约表 2022")
- cell1.SetStyle(style)
- // 右增两列空白格用于第一列合并, 否则后续单元格合并会有问题
- titleRow.AddCell().SetValue("")
- titleRow.AddCell().SetValue("")
- // 1行2列
- cell2 := titleRow.AddCell()
- cell2.SetValue("FICC大套餐")
- cell2.SetStyle(style)
- // 1行3列-右合并小套餐数
- if permissionLen >= 1 {
- cell3 := titleRow.AddCell()
- cell3.HMerge = permissionLen - 1
- cell3.SetValue("FICC小套餐")
- cell3.SetStyle(style)
- // 同上右增单元格小套餐数-1的空白单元格用于合并
- for i := 0; i < permissionLen-1; i++ {
- titleRow.AddCell().SetValue("")
- }
- }
- cell4 := titleRow.AddCell()
- cell4.SetValue("市场策略")
- cell4.SetStyle(style)
- cell5 := titleRow.AddCell()
- cell5.SetValue("财富管理")
- cell5.SetStyle(style)
- // 第二行表头
- titleRow2 := sheet.AddRow()
- titleRow2.SetHeight(60)
- row2Title := make([]string, 0)
- row2Title = append(row2Title, "客户名称", "续约-0\n新增-1", "销售", "FICC大套餐")
- for i := range permissionList {
- row2Title = append(row2Title, permissionList[i].PermissionName)
- }
- row2Title = append(row2Title, "市场策略", "财富管理", "套餐备注", "开始时间", "到期时间", "2022年合同金额", "约定付款时间", "签订日",
- "签订月", "合同状态", "合同编号", "备注")
- for i := range row2Title {
- v := titleRow2.AddCell()
- v.SetValue(row2Title[i])
- v.SetStyle(style)
- }
- // 第二行表头-开票/收款(动态添加)
- for i := 0; i < maxInvoice; i++ {
- n := i + 1
- c1 := titleRow2.AddCell()
- t1 := fmt.Sprintf("%s%d", "开票日", n)
- c1.SetValue(t1)
- c1.SetStyle(style)
- c2 := titleRow2.AddCell()
- t2 := fmt.Sprintf("%s%d", "开票金额", n)
- c2.SetValue(t2)
- c2.SetStyle(style)
- row2Title = append(row2Title, t1, t2)
- }
- for i := 0; i < maxPayment; i++ {
- n := i + 1
- c1 := titleRow2.AddCell()
- t1 := fmt.Sprintf("%s%d", "收款日", n)
- c1.SetValue(t1)
- c1.SetStyle(style)
- c2 := titleRow2.AddCell()
- t2 := fmt.Sprintf("%s%d", "收款金额", n)
- c2.SetValue(t2)
- c2.SetStyle(style)
- row2Title = append(row2Title, t1, t2)
- }
- // 此处取第二行标题NameKeyMap, 后面的动态匹配
- row2NameKeyMap := make(map[string]int)
- for i := range row2Title {
- row2NameKeyMap[row2Title[i]] = i
- }
- contractTMap := map[int]int{
- fms.ContractTypeNew: 1,
- fms.ContractTypeRenew: 0,
- fms.ContractTypeAgentPay: 2, // 代付合同
- fms.ContractTypePlus: 3, // 补充协议
- }
- for _, v := range list {
- k := -1
- dataRow := sheet.AddRow()
- dataRow.SetHeight(20)
- k += 3
- dataRow.AddCell().SetString(v.CompanyName)
- dataRow.AddCell().SetString(fmt.Sprint(contractTMap[v.ContractType]))
- dataRow.AddCell().SetString(v.SellerName)
- // 大套餐
- k += 1
- col4Name := row2Title[k]
- svList := serviceMap[v.ContractRegisterId]
- col4 := ""
- if svList != nil && len(svList) > 0 {
- for isv := range svList {
- if svList[isv].Title == col4Name {
- col4 = "是"
- break
- }
- }
- }
- dataRow.AddCell().SetString(col4)
- // 小套餐
- serviceChartPermissionIds := serviceChartPermissionsMap[v.ContractRegisterId]
- for i := 0; i < permissionLen; i++ {
- k += 1
- colName := row2Title[k]
- chartPermissionId := permissionNameIdMap[colName]
- if utils.InArray(chartPermissionId, serviceChartPermissionIds) {
- dataRow.AddCell().SetString("是")
- } else {
- dataRow.AddCell().SetString("")
- }
- }
- // 财富管理/市场策略(处理方式其实跟上面的大套餐一样, 只是中间隔了小套餐按照顺序要这么处理=_=!)
- k += 1
- col5Name := row2Title[k]
- col5 := ""
- if svList != nil && len(svList) > 0 {
- for isv := range svList {
- if svList[isv].Title == col5Name {
- col5 = "是"
- break
- }
- }
- }
- dataRow.AddCell().SetString(col5)
- k += 1
- col6Name := row2Title[k]
- col6 := ""
- if svList != nil && len(svList) > 0 {
- for isv := range svList {
- if svList[isv].Title == col6Name {
- col6 = "是"
- break
- }
- }
- }
- dataRow.AddCell().SetString(col6)
- // 其他信息
- dataRow.AddCell().SetString(v.ServiceRemark) // 套餐备注
- dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.StartDate)) // 开始时间
- dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.EndDate)) // 到期时间
- dataRow.AddCell().SetString(fmt.Sprint("¥", v.ContractAmount)) // 2022年合同金额
- dataRow.AddCell().SetString(v.AgreedPayTime) // 约定付款时间
- dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.SignDate)) // 签订日
- dataRow.AddCell().SetString(utils.TimeTransferString("2006/01", v.SignDate)) // 签订月
- dataRow.AddCell().SetString(fms.ContractStatusKeyNameMap[v.ContractStatus]) // 合同状态
- dataRow.AddCell().SetString(v.ContractCode) // 合同编号
- dataRow.AddCell().SetString(v.Remark) // 备注
- // 开票/到款信息
- ivList := invoiceMap[v.ContractRegisterId]
- ivListLen := len(ivList)
- if ivList != nil && len(ivList) > 0 {
- for ia := 0; ia < maxInvoice; ia++ {
- if ia < ivListLen {
- dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", ivList[ia].InvoiceDate)) // 开票日
- dataRow.AddCell().SetString(fmt.Sprint(ivList[ia].Amount)) // 开票金额
- } else {
- // 这里要把不够的填充为空
- dataRow.AddCell().SetString("")
- dataRow.AddCell().SetString("")
- }
- }
- }
- pyList := paymentMap[v.ContractRegisterId]
- pyListLen := len(pyList)
- if pyList != nil && pyListLen > 0 {
- for ib := 0; ib < maxInvoice; ib++ {
- if ib < pyListLen {
- dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", pyList[ib].InvoiceDate)) // 收款日
- dataRow.AddCell().SetString(fmt.Sprint(pyList[ib].Amount)) // 收款金额
- } else {
- // 已经是最后的几列了其实可以不用填充空, 万一后面要加列此处还是填充上吧
- dataRow.AddCell().SetString("")
- dataRow.AddCell().SetString("")
- }
- }
- }
- }
- // 输出文件
- var buffer bytes.Buffer
- _ = xlsxFile.Write(&buffer)
- content := bytes.NewReader(buffer.Bytes())
- //err = xlsxFile.Save(filePath)
- //if err != nil {
- // resp.FailData("保存文件失败", "Err:"+err.Error(), c)
- // return
- //}
- //defer func() {
- // _ = os.Remove(filePath)
- //}()
- randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
- fileName := "财务列表_" + randStr + ".xlsx"
- c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
- c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
- }
- // InvoiceList
- // @Title 开票/到款列表
- // @Description 开票/到款列表
- // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
- // @Param ContractCode query string false "合同编号"
- // @Param StartDate query string false "开始日期"
- // @Param EndDate query string false "结束日期"
- // @Param MinAmount query float64 false "开票金额区间-最小值"
- // @Param MaxAmount query float64 false "开票金额区间-最大值"
- // @Success 200 {object} fms.ContractInvoiceItem
- // @router /contract/register/invoice_list [get]
- func (rg *RegisterController) InvoiceList(c *gin.Context) {
- var req fms.ContractInvoiceListReq
- if e := c.BindQuery(&req); e != nil {
- err, ok := e.(validator.ValidationErrors)
- if !ok {
- resp.FailData("参数解析失败", "Err:"+e.Error(), c)
- return
- }
- resp.FailData("参数解析失败", err.Translate(global.Trans), c)
- return
- }
- cond := `invoice_type = ?`
- pars := make([]interface{}, 0)
- pars = append(pars, req.InvoiceType)
- // 合同编号
- if req.ContractCode != "" {
- kw := fmt.Sprint("%", req.ContractCode, "%")
- cond += ` AND contract_code LIKE ?`
- pars = append(pars, kw)
- }
- if req.StartDate != "" && req.EndDate != "" {
- st := fmt.Sprint(req.StartDate, " 00:00:00")
- ed := fmt.Sprint(req.EndDate, " 23:59:59")
- cond += ` AND (invoice_time BETWEEN ? AND ?)`
- pars = append(pars, st, ed)
- }
- if req.MinAmount > 0 {
- cond += ` AND amount >= ?`
- pars = append(pars, req.MinAmount)
- }
- if req.MaxAmount > 0 {
- cond += ` AND amount <= ?`
- pars = append(pars, req.MaxAmount)
- }
- page := new(base.Page)
- page.SetPageSize(req.PageSize)
- page.SetCurrent(req.Current)
- page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: false})
- total, list, e := fms.GetContractInvoiceItemPageList(page, cond, pars)
- if e != nil {
- resp.FailMsg("获取失败", "获取合同开票/到款列表失败, Err: "+e.Error(), c)
- return
- }
- page.SetTotal(total)
- baseData := new(base.BaseData)
- baseData.SetPage(page)
- baseData.SetList(list)
- resp.OkData("获取成功", baseData, c)
- }
- // InvoiceExport
- // @Title 开票/到款列表-导出
- // @Description 合同登记-导出
- // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
- // @Param ContractCode query string false "合同编号"
- // @Param StartDate query string false "开始日期"
- // @Param EndDate query string false "结束日期"
- // @Param MinAmount query float64 false "开票金额区间-最小值"
- // @Param MaxAmount query float64 false "开票金额区间-最大值"
- // @Success 200 string "操作成功"
- // @router /contract/register/invoice_export [get]
- func (rg *RegisterController) InvoiceExport(c *gin.Context) {
- var req fms.ContractInvoiceListReq
- if e := c.BindQuery(&req); e != nil {
- err, ok := e.(validator.ValidationErrors)
- if !ok {
- resp.FailData("参数解析失败", "Err:"+e.Error(), c)
- return
- }
- resp.FailData("参数解析失败", err.Translate(global.Trans), c)
- return
- }
- cond := `invoice_type = ?`
- pars := make([]interface{}, 0)
- pars = append(pars, req.InvoiceType)
- // 合同编号
- if req.ContractCode != "" {
- kw := fmt.Sprint("%", req.ContractCode, "%")
- cond += ` AND contract_code LIKE ?`
- pars = append(pars, kw)
- }
- if req.StartDate != "" && req.EndDate != "" {
- st := fmt.Sprint(req.StartDate, " 00:00:00")
- ed := fmt.Sprint(req.EndDate, " 23:59:59")
- cond += ` AND (invoice_time BETWEEN ? AND ?)`
- pars = append(pars, st, ed)
- }
- if req.MinAmount > 0 {
- cond += ` AND amount >= ?`
- pars = append(pars, req.MinAmount)
- }
- if req.MaxAmount > 0 {
- cond += ` AND amount <= ?`
- pars = append(pars, req.MaxAmount)
- }
- // 获取列表数据
- cr := new(fms.ContractInvoice)
- orderRule := `invoice_time DESC`
- list, e := cr.List(cond, pars, orderRule)
- if e != nil {
- resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
- return
- }
- if len(list) == 0 {
- resp.Fail("无有效数据可导出", c)
- return
- }
- // 生成Excel文件
- xlsxFile := xlsx.NewFile()
- style := xlsx.NewStyle()
- alignment := xlsx.Alignment{
- Horizontal: "center",
- Vertical: "center",
- WrapText: true,
- }
- style.Alignment = alignment
- style.ApplyAlignment = true
- sheet, err := xlsxFile.AddSheet("开票列表")
- if err != nil {
- resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
- return
- }
- // 表头
- titleRow := sheet.AddRow()
- titleRow.SetHeight(40)
- cell1 := titleRow.AddCell()
- cell1.SetValue("合同编号")
- cell1.SetStyle(style)
- cell2 := titleRow.AddCell()
- cell2.SetValue("开票金额")
- cell2.SetStyle(style)
- cell3 := titleRow.AddCell()
- cell3.SetValue("开票日期")
- cell3.SetStyle(style)
- for _, v := range list {
- dataRow := sheet.AddRow()
- dataRow.SetHeight(20)
- dataRow.AddCell().SetString(v.ContractCode)
- dataRow.AddCell().SetString(fmt.Sprint(v.Amount))
- dataRow.AddCell().SetString(utils.TimeTransferString("2006-01-02", v.InvoiceDate))
- }
- // 输出文件
- var buffer bytes.Buffer
- _ = xlsxFile.Write(&buffer)
- content := bytes.NewReader(buffer.Bytes())
- randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
- fileName := "开票列表_" + randStr + ".xlsx"
- c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
- c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
- }
- // Import
- // @Title 合同登记-导入
- // @Description 合同登记-导入
- // @Success 200 string "操作成功"
- // @router /contract/register/import [post]
- func (rg *RegisterController) Import(c *gin.Context) {
- h, err := c.FormFile("File")
- if err != nil {
- resp.FailData("获取文件失败", "Err:"+err.Error(), c)
- return
- }
- ext := path.Ext(h.Filename)
- if ext != ".xlsx" && ext != ".xls" {
- resp.Fail("请上传Excel文件", c)
- return
- }
- uploadDir := "static/xls"
- err = os.MkdirAll(uploadDir, 766)
- if err != nil {
- resp.FailData("存储目录创建失败", "Err:"+err.Error(), c)
- return
- }
- uploadPath := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
- err = c.SaveUploadedFile(h, uploadPath)
- if err != nil {
- resp.FailData("保存本地文件失败", "Err:"+err.Error(), c)
- return
- }
- defer func() {
- _ = os.Remove(uploadPath)
- }()
- xlFile, err := xlsx.OpenFile(uploadPath)
- if err != nil {
- resp.FailData("打开文件失败", "Err:"+err.Error(), c)
- return
- }
- // 获取所有已登记,根据合同编号去重
- contractCodeArr := make([]string, 0)
- registerOB := new(fms.ContractRegister)
- registerCond := ``
- registerPars := make([]interface{}, 0)
- registerList, e := registerOB.List(registerCond, registerPars)
- if e != nil {
- resp.FailData("获取合同登记列表失败", "Err:"+e.Error(), c)
- return
- }
- for i := range registerList {
- contractCodeArr = append(contractCodeArr, registerList[i].ContractCode)
- }
- // 获取所有销售名称Map
- sellerNameIdMap := make(map[string]int)
- sellerCond := ``
- sellerPars := make([]interface{}, 0)
- sellerList, e := crm.GetCompanySellerByRoleCodes(sellerCond, sellerPars)
- if e != nil {
- resp.FailData("获取销售列表失败", "Err:"+e.Error(), c)
- return
- }
- for i := range sellerList {
- sellerNameIdMap[sellerList[i].RealName] = sellerList[i].AdminId
- }
- // 获取品种权限Map
- chartPermissionNameIdMap := make(map[string]int)
- cpCond := `product_id = ?`
- cpPars := make([]interface{}, 0)
- cpPars = append(cpPars, crm.CompanyProductFicc)
- cp := new(crm.ChartPermission)
- permissionList, e := cp.List(cpCond, cpPars)
- if e != nil {
- resp.FailData("获取权限列表失败", "Err:"+e.Error(), c)
- return
- }
- for i := range permissionList {
- chartPermissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
- }
- // 获取所有套餐模板
- serviceTempCond := ``
- serviceTempPars := make([]interface{}, 0)
- serviceTempOB := new(fms.ContractServiceTemplate)
- serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
- if e != nil {
- resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
- return
- }
- serviceTempNameMap := make(map[string]*fms.ContractServiceTemplate)
- for i := range serviceTempList {
- serviceTempNameMap[serviceTempList[i].Title] = serviceTempList[i]
- }
- titleMap := make(map[int]string)
- newIds := make([]int, 0)
- contractTypeArr := []string{"0", "1", "2", "3"}
- for _, sheet := range xlFile.Sheets {
- // 遍历行读取
- maxRow := sheet.MaxRow
- for i := 0; i < maxRow; i++ {
- // 第二行开始读取表头
- if i == 1 {
- row := sheet.Row(i)
- cells := row.Cells
- for k, cell := range cells {
- text := cell.String()
- titleMap[k] = text
- // 只检验前面部分表头
- if k == 0 {
- if text != "客户名称" {
- resp.Fail("匹配失败, 请按模板导入", c)
- return
- }
- }
- if k == 1 {
- if !strings.Contains(text, "续约") {
- resp.Fail("匹配失败, 请按模板导入", c)
- return
- }
- }
- if k == 2 {
- if text != "销售" {
- resp.Fail("匹配失败, 请按模板导入", c)
- return
- }
- }
- if k == 3 {
- if text != "FICC大套餐" {
- resp.Fail("匹配失败, 请按模板导入", c)
- return
- }
- }
- }
- }
- // 数据行
- if i >= 2 {
- row := sheet.Row(i)
- cells := row.Cells
- // 登记信息
- rowRegister := new(fms.ContractRegister)
- // 套餐
- rowServices := make([]*fms.ContractService, 0)
- // 开票/到款
- rowInvoices := make([]*fms.ContractInvoice, 0)
- rowChartPermissionIdArr := make([]string, 0)
- rowInvoice1 := new(fms.ContractInvoice)
- rowInvoice2 := new(fms.ContractInvoice)
- rowInvoice3 := new(fms.ContractInvoice)
- rowInvoice4 := new(fms.ContractInvoice)
- rowInvoice5 := new(fms.ContractInvoice)
- rowInvoice6 := new(fms.ContractInvoice)
- for k, cell := range cells {
- v := utils.TrimStr(cell.String())
- // 客户名称
- if k == 0 {
- rowRegister.CompanyName = v
- }
- // 续约/新增
- if k == 1 {
- if !utils.InArrayByStr(contractTypeArr, v) {
- resp.Fail("合同类型有误, 请按模板导入", c)
- return
- }
- if v == "0" {
- rowRegister.ContractType = fms.ContractTypeRenew
- }
- if v == "1" {
- rowRegister.ContractType = fms.ContractTypeNew
- }
- if v == "2" {
- rowRegister.ContractType = fms.ContractTypeAgentPay
- }
- if v == "3" {
- rowRegister.ContractType = fms.ContractTypePlus
- }
- }
- // 销售
- if k == 2 {
- rowRegister.SellerName = v
- rowRegister.SellerId = sellerNameIdMap[rowRegister.SellerName]
- }
- // FICC大套餐
- if k == 3 {
- if v == "是" {
- tempItem := serviceTempNameMap[titleMap[k]]
- if tempItem == nil {
- resp.Fail("套餐名称不匹配, 请按模板导入", c)
- return
- }
- cs := &fms.ContractService{
- ProductId: crm.CompanyProductFicc,
- ServiceTemplateId: tempItem.ServiceTemplateId,
- Title: tempItem.Title,
- Value: tempItem.Value,
- TableValue: tempItem.TableValue,
- ChartPermissionId: tempItem.ChartPermissionId,
- }
- cs.Set()
- rowServices = append(rowServices, cs)
- }
- }
- // FICC小套餐
- if k >= 4 && k <= 23 {
- // 小套餐权限
- if v == "是" {
- rowChartPermissionIdArr = append(rowChartPermissionIdArr, strconv.Itoa(chartPermissionNameIdMap[titleMap[k]]))
- }
- }
- // 市场策略/财富管理
- if k == 24 || k == 25 {
- if v == "是" {
- tempItem := serviceTempNameMap[titleMap[k]]
- if tempItem == nil {
- resp.Fail("市场策略/财富管理套餐名称不匹配, 请按模板导入", c)
- return
- }
- cs := &fms.ContractService{
- ProductId: crm.CompanyProductFicc,
- ServiceTemplateId: tempItem.ServiceTemplateId,
- Title: tempItem.Title,
- Value: tempItem.Value,
- TableValue: tempItem.TableValue,
- ChartPermissionId: tempItem.ChartPermissionId,
- }
- cs.Set()
- rowServices = append(rowServices, cs)
- }
- }
- // 套餐备注
- if k == 26 {
- rowRegister.ServiceRemark = v
- }
- // 开始时间/到期时间
- if k == 27 {
- startDate, e := time.ParseInLocation("2006/01/02", v, time.Local)
- if e != nil {
- resp.Fail("开始时间格式有误, 请按模板导入", c)
- return
- }
- rowRegister.StartDate = startDate
- }
- if k == 28 {
- endDate, e := time.ParseInLocation("2006/01/02", v, time.Local)
- if e != nil {
- resp.Fail("到期时间格式有误, 请按模板导入", c)
- return
- }
- rowRegister.EndDate = endDate
- }
- // 合同金额
- if k == 29 {
- amountStr := v
- amount, e := strconv.ParseFloat(amountStr, 64)
- if e != nil {
- resp.Fail("合同金额有误, 请按模板导入", c)
- return
- }
- rowRegister.ContractAmount = amount
- }
- // 约定付款日期
- if k == 30 {
- rowRegister.AgreedPayTime = v
- }
- // 签订日
- // k == 32为签订月,可忽略
- if k == 31 {
- signDate, e := time.ParseInLocation("2006/01/02", v, time.Local)
- if e != nil {
- resp.Fail("开始时间格式有误, 请按模板导入", c)
- return
- }
- rowRegister.SignDate = signDate
- }
- // 合同状态
- if k == 33 {
- rowRegister.ContractStatus = fms.ContractStatusNameKeyMap[v]
- }
- // 合同编号
- if k == 34 {
- rowContractCode := v
- if rowContractCode == "" {
- resp.Fail("合同编号不可为空, 请按模板导入", c)
- return
- }
- if utils.InArrayByStr(contractCodeArr, rowContractCode) {
- // 此合同已登记, 跳过本行的读取
- break
- }
- rowRegister.ContractCode = rowContractCode
- }
- // 备注
- if k == 35 {
- rowRegister.Remark = v
- }
- // 开票日/开票金额
- if k == 36 {
- if v != "" {
- fmt.Println("36", v)
- invoiceDate, e := time.ParseInLocation("2006/01/02", v, time.Local)
- if e != nil {
- resp.Fail("开票时间1格式有误, 请按模板导入", c)
- return
- }
- rowInvoice1.InvoiceDate = invoiceDate
- rowInvoice1.ContractCode = rowRegister.ContractCode
- rowInvoice1.InvoiceType = fms.ContractInvoiceTypeMake
- }
- }
- if k == 37 && v != "" {
- amountStr := v
- amount, e := strconv.ParseFloat(amountStr, 64)
- if e != nil {
- resp.Fail("开票金额1有误, 请按模板导入", c)
- return
- }
- rowInvoice1.Amount = amount
- rowInvoices = append(rowInvoices, rowInvoice1)
- }
- if k == 38 {
- if v != "" {
- invoiceDate, e := time.ParseInLocation("2006/01/02", v, time.Local)
- if e != nil {
- resp.Fail("开票时间2格式有误, 请按模板导入", c)
- return
- }
- rowInvoice2.InvoiceDate = invoiceDate
- rowInvoice2.ContractCode = rowRegister.ContractCode
- rowInvoice2.InvoiceType = fms.ContractInvoiceTypeMake
- }
- }
- if k == 39 && v != "" {
- amountStr := v
- amount, e := strconv.ParseFloat(amountStr, 64)
- if e != nil {
- resp.Fail("开票金额2有误, 请按模板导入", c)
- return
- }
- rowInvoice2.Amount = amount
- rowInvoices = append(rowInvoices, rowInvoice2)
- }
- if k == 40 {
- if v != "" {
- invoiceDate, e := time.ParseInLocation("2006/01/02", v, time.Local)
- if e != nil {
- resp.Fail("开票时间3格式有误, 请按模板导入", c)
- return
- }
- rowInvoice3.InvoiceDate = invoiceDate
- rowInvoice3.ContractCode = rowRegister.ContractCode
- rowInvoice3.InvoiceType = fms.ContractInvoiceTypeMake
- }
- }
- if k == 41 && v != "" {
- amountStr := v
- amount, e := strconv.ParseFloat(amountStr, 64)
- if e != nil {
- resp.Fail("开票金额3有误, 请按模板导入", c)
- return
- }
- rowInvoice3.Amount = amount
- rowInvoices = append(rowInvoices, rowInvoice3)
- }
- // 收款日/收款金额
- if k == 42 {
- if v != "" {
- invoiceDate, e := time.ParseInLocation("2006/01/02", v, time.Local)
- if e != nil {
- resp.Fail("收款时间1格式有误, 请按模板导入", c)
- return
- }
- rowInvoice4.InvoiceDate = invoiceDate
- rowInvoice4.ContractCode = rowRegister.ContractCode
- rowInvoice4.InvoiceType = fms.ContractInvoiceTypePay
- }
- }
- if k == 43 && v != "" {
- amountStr := v
- amount, e := strconv.ParseFloat(amountStr, 64)
- if e != nil {
- resp.Fail("收款金额1有误, 请按模板导入", c)
- return
- }
- rowInvoice4.Amount = amount
- rowInvoices = append(rowInvoices, rowInvoice4)
- }
- if k == 44 {
- if v != "" {
- invoiceDate, e := time.ParseInLocation("2006/01/02", v, time.Local)
- if e != nil {
- resp.Fail("收款时间2格式有误, 请按模板导入", c)
- return
- }
- rowInvoice5.InvoiceDate = invoiceDate
- rowInvoice5.ContractCode = rowRegister.ContractCode
- rowInvoice5.InvoiceType = fms.ContractInvoiceTypePay
- }
- }
- if k == 45 && v != "" {
- amountStr := v
- amount, e := strconv.ParseFloat(amountStr, 64)
- if e != nil {
- resp.Fail("收款金额2有误, 请按模板导入", c)
- return
- }
- rowInvoice5.Amount = amount
- rowInvoices = append(rowInvoices, rowInvoice5)
- }
- if k == 46 {
- if v != "" {
- invoiceDate, e := time.ParseInLocation("2006/01/02", v, time.Local)
- if e != nil {
- resp.Fail("收款时间3格式有误, 请按模板导入", c)
- return
- }
- rowInvoice6.InvoiceDate = invoiceDate
- rowInvoice6.ContractCode = rowRegister.ContractCode
- rowInvoice6.InvoiceType = fms.ContractInvoiceTypePay
- }
- }
- if k == 47 && v != "" {
- amountStr := v
- amount, e := strconv.ParseFloat(amountStr, 64)
- if e != nil {
- resp.Fail("收款金额3有误, 请按模板导入", c)
- return
- }
- rowInvoice6.Amount = amount
- rowInvoices = append(rowInvoices, rowInvoice6)
- }
- }
- // 小套餐
- if len(rowChartPermissionIdArr) > 0 {
- // 说明有小套餐
- tempItem := serviceTempNameMap["FICC小套餐"]
- if tempItem == nil {
- resp.Fail("小套餐名称不匹配, 请按模板导入", c)
- return
- }
- rowChartPermissionIds := strings.Join(rowChartPermissionIdArr, ",")
- cs := &fms.ContractService{
- ProductId: crm.CompanyProductFicc,
- ServiceTemplateId: tempItem.ServiceTemplateId,
- Title: tempItem.Title,
- Value: tempItem.Value,
- TableValue: tempItem.TableValue,
- ChartPermissionId: tempItem.ChartPermissionId,
- ChartPermissionIds: rowChartPermissionIds,
- }
- cs.Set()
- rowServices = append(rowServices, cs)
- }
- // 新增登记、套餐、开票到款信息
- newId, e := fms.CreateImportContractRegister(rowRegister, rowServices, rowInvoices)
- if e != nil {
- resp.FailData("导入失败", "新增导入登记失败, Err: "+e.Error(), c)
- return
- }
- if rowRegister.ContractType != fms.ContractTypePlus {
- newIds = append(newIds, newId)
- }
- }
- }
- }
- // 更新登记状态
- go func() {
- for i := range newIds {
- fmsService.CheckContractRegisterAmount(newIds[i])
- }
- }()
- resp.Ok("操作成功", c)
- }
|