register.go 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054
  1. package contract
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/gin-gonic/gin"
  8. "github.com/go-playground/validator/v10"
  9. jsoniter "github.com/json-iterator/go"
  10. "github.com/shopspring/decimal"
  11. "github.com/tealeg/xlsx"
  12. "hongze/fms_api/controller/resp"
  13. "hongze/fms_api/global"
  14. "hongze/fms_api/models/base"
  15. "hongze/fms_api/models/crm"
  16. "hongze/fms_api/models/fms"
  17. "hongze/fms_api/models/system"
  18. "hongze/fms_api/services/alarm_msg"
  19. crmService "hongze/fms_api/services/crm"
  20. fmsService "hongze/fms_api/services/fms"
  21. "hongze/fms_api/utils"
  22. "net/http"
  23. "os"
  24. "path"
  25. "strconv"
  26. "strings"
  27. "time"
  28. )
  29. // RegisterController 合同登记
  30. type RegisterController struct{}
  31. // List
  32. // @Title 合同登记列表
  33. // @Description 合同登记列表
  34. // @Param Keyword query string false "关键词"
  35. // @Param StartDate query string false "合同开始日期"
  36. // @Param EndDate query string false "合同结束日期"
  37. // @Param ServiceType query int false "套餐类型"
  38. // @Param ContractType query int false "合同类型"
  39. // @Param RegisterStatus query int false "登记状态"
  40. // @Success 200 {object} fms.ContractRegisterItem
  41. // @router /contract/register/list [get]
  42. func (rg *RegisterController) List(c *gin.Context) {
  43. var req fms.ContractRegisterListReq
  44. if e := c.BindQuery(&req); e != nil {
  45. err, ok := e.(validator.ValidationErrors)
  46. if !ok {
  47. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  48. return
  49. }
  50. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  51. return
  52. }
  53. cond := `1 = 1`
  54. pars := make([]interface{}, 0)
  55. // 合同编号/客户姓名/销售/实际使用方
  56. if req.Keyword != "" {
  57. kw := "%" + req.Keyword + "%"
  58. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
  59. pars = append(pars, kw, kw, kw, kw)
  60. }
  61. if req.StartDate != "" && req.EndDate != "" {
  62. st := fmt.Sprint(req.StartDate, " 00:00:00")
  63. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  64. cond += ` AND (create_time BETWEEN ? AND ?)`
  65. pars = append(pars, st, ed)
  66. }
  67. if req.ContractType != 0 {
  68. cond += ` AND contract_type = ?`
  69. pars = append(pars, req.ContractType)
  70. }
  71. if req.RegisterStatus != 0 {
  72. cond += ` AND register_status = ?`
  73. pars = append(pars, req.RegisterStatus)
  74. }
  75. // 套餐筛选
  76. if req.ServiceType != 0 {
  77. registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
  78. if e != nil {
  79. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  80. return
  81. }
  82. if len(registerIds) > 0 {
  83. cond += ` AND contract_register_id IN ?`
  84. pars = append(pars, registerIds)
  85. } else {
  86. cond += ` AND 1 = 2`
  87. }
  88. }
  89. page := new(base.Page)
  90. page.SetPageSize(req.PageSize)
  91. page.SetCurrent(req.Current)
  92. page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: false})
  93. total, list, e := fms.GetContractRegisterItemPageList(page, cond, pars)
  94. if e != nil {
  95. resp.FailMsg("获取失败", "获取合同登记列表失败, Err: "+e.Error(), c)
  96. return
  97. }
  98. registerIds := make([]int, 0)
  99. for i := range list {
  100. registerIds = append(registerIds, list[i].ContractRegisterId)
  101. }
  102. serviceMap := make(map[int]string, 0)
  103. invoiceMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  104. paymentMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  105. if len(registerIds) > 0 {
  106. // 获取服务套餐
  107. servicesNameList, e := fms.GetContractRegisterServicesNameByRegisterIds(registerIds)
  108. if e != nil {
  109. resp.FailMsg("获取失败", "获取套餐拼接字符串失败, Err: "+e.Error(), c)
  110. return
  111. }
  112. for i := range servicesNameList {
  113. serviceMap[servicesNameList[i].ContractRegisterId] = servicesNameList[i].ServicesName
  114. }
  115. // 获取开票/到款列表
  116. invoiceCond := `contract_register_id IN ?`
  117. invoicePars := make([]interface{}, 0)
  118. invoicePars = append(invoicePars, registerIds)
  119. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  120. if e != nil {
  121. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  122. return
  123. }
  124. for i := range invoiceList {
  125. if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  126. invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  127. }
  128. if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  129. paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  130. }
  131. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  132. invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  133. }
  134. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  135. paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  136. }
  137. }
  138. }
  139. respList := make([]*fms.ContractRegisterList, 0)
  140. for i := range list {
  141. v := new(fms.ContractRegisterList)
  142. v.ContractRegisterItem = list[i]
  143. v.ServicesName = serviceMap[list[i].ContractRegisterId]
  144. v.InvoiceList = invoiceMap[list[i].ContractRegisterId]
  145. v.PaymentList = paymentMap[list[i].ContractRegisterId]
  146. respList = append(respList, v)
  147. }
  148. page.SetTotal(total)
  149. baseData := new(base.BaseData)
  150. baseData.SetPage(page)
  151. baseData.SetList(respList)
  152. resp.OkData("获取成功", baseData, c)
  153. }
  154. // Add
  155. // @Title 新增合同登记
  156. // @Description 新增合同登记
  157. // @Param request body fms.ContractRegisterAddReq true "type json string"
  158. // @Success 200 string "操作成功"
  159. // @router /contract/register/add [post]
  160. func (rg *RegisterController) Add(c *gin.Context) {
  161. req := new(fms.ContractRegisterAddReq)
  162. err := c.ShouldBind(&req)
  163. if err != nil {
  164. errs, ok := err.(validator.ValidationErrors)
  165. if !ok {
  166. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  167. return
  168. }
  169. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  170. return
  171. }
  172. claims, _ := c.Get("adminInfo")
  173. adminInfo := claims.(*system.SysAdmin)
  174. // 日期校验
  175. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  176. if e != nil {
  177. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  178. return
  179. }
  180. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  181. if e != nil {
  182. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  183. return
  184. }
  185. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  186. if req.SignDate != "" {
  187. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  188. if e != nil {
  189. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  190. return
  191. }
  192. signDate = signDateTime
  193. }
  194. // 是否存在相同合同编号的登记
  195. ob := new(fms.ContractRegister)
  196. existCond := `contract_code = ?`
  197. existPars := make([]interface{}, 0)
  198. existPars = append(existPars, req.ContractCode)
  199. exist, e := ob.FetchByCondition(existCond, existPars)
  200. if e != nil && e != utils.ErrNoRow {
  201. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  202. return
  203. }
  204. if exist != nil && exist.ContractRegisterId > 0 {
  205. resp.Fail("合同编号已存在", c)
  206. return
  207. }
  208. nowTime := time.Now().Local()
  209. ob.ContractCode = req.ContractCode
  210. ob.RelateContractCode = req.RelateContractCode
  211. ob.CrmContractId = req.CrmContractId
  212. ob.ContractSource = req.ContractSource
  213. ob.CompanyName = req.CompanyName
  214. ob.ActualCompanyName = req.ActualCompanyName
  215. ob.ProductId = req.ProductId
  216. ob.SellerId = req.SellerId
  217. ob.SellerName = req.SellerName
  218. ob.ContractType = req.ContractType
  219. ob.ContractAmount = req.ContractAmount
  220. ob.StartDate = startDate
  221. ob.EndDate = endDate
  222. ob.SignDate = signDate
  223. ob.AgreedPayTime = req.AgreedPayTime
  224. ob.ContractStatus = req.ContractStatus
  225. ob.RegisterStatus = fms.ContractRegisterStatusIng
  226. ob.Remark = req.Remark
  227. ob.ServiceRemark = req.ServiceRemark
  228. ob.HasPayment = req.HasPayment
  229. ob.NewCompany = req.NewCompany
  230. ob.Set()
  231. // 存在代付的直接完成登记, 且不允许进行开票/到款登记
  232. if req.HasPayment == 1 {
  233. ob.RegisterStatus = fms.ContractRegisterStatusComplete
  234. }
  235. // 套餐信息
  236. serviceList, e := fmsService.HandleContractServiceAndDetail(req.ProductId, req.Services, true)
  237. if e != nil {
  238. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  239. return
  240. }
  241. // 新增合同及套餐
  242. if e = fms.CreateContractRegisterAndServices(ob, serviceList); e != nil {
  243. resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
  244. return
  245. }
  246. // 操作日志
  247. go func() {
  248. opData := ""
  249. opDataByte, e := json.Marshal(req)
  250. if e != nil {
  251. return
  252. }
  253. opData = string(opDataByte)
  254. logItem := new(fms.ContractRegisterLog)
  255. logItem.ContractRegisterId = ob.ContractRegisterId
  256. logItem.AdminId = int(adminInfo.AdminId)
  257. logItem.AdminName = adminInfo.RealName
  258. logItem.OpData = opData
  259. logItem.OpType = fms.ContractRegisterOpTypeSave
  260. logItem.CreateTime = nowTime
  261. logItem.Remark = req.Remark
  262. if e = logItem.Create(); e != nil {
  263. return
  264. }
  265. }()
  266. resp.Ok("操作成功", c)
  267. }
  268. // Edit
  269. // @Title 编辑合同登记
  270. // @Description 编辑合同登记
  271. // @Param request body fms.ContractRegisterEditReq true "type json string"
  272. // @Success 200 string "操作成功"
  273. // @router /contract/register/edit [post]
  274. func (rg *RegisterController) Edit(c *gin.Context) {
  275. req := new(fms.ContractRegisterEditReq)
  276. err := c.ShouldBind(&req)
  277. if err != nil {
  278. errs, ok := err.(validator.ValidationErrors)
  279. if !ok {
  280. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  281. return
  282. }
  283. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  284. return
  285. }
  286. claims, _ := c.Get("adminInfo")
  287. adminInfo := claims.(*system.SysAdmin)
  288. // 日期校验
  289. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  290. if e != nil {
  291. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  292. return
  293. }
  294. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  295. if e != nil {
  296. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  297. return
  298. }
  299. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  300. if req.SignDate != "" {
  301. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  302. if e != nil {
  303. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  304. return
  305. }
  306. signDate = signDateTime
  307. }
  308. ob := new(fms.ContractRegister)
  309. item, e := ob.Fetch(req.ContractRegisterId)
  310. if e != nil {
  311. if e == utils.ErrNoRow {
  312. resp.Fail("登记记录不存在或已被删除", c)
  313. return
  314. }
  315. resp.FailMsg("操作失败", "获取合同登记信息失败, Err:"+e.Error(), c)
  316. return
  317. }
  318. // 是否存在相同合同编号的登记
  319. existCond := `contract_code = ?`
  320. existPars := make([]interface{}, 0)
  321. existPars = append(existPars, req.ContractCode)
  322. exist, e := ob.FetchByCondition(existCond, existPars)
  323. if e != nil && e != utils.ErrNoRow {
  324. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  325. return
  326. }
  327. if exist != nil && exist.ContractRegisterId > 0 && exist.ContractRegisterId != item.ContractRegisterId {
  328. resp.Fail("合同编号已存在", c)
  329. return
  330. }
  331. originHasPayment := item.HasPayment
  332. updateCols := []string{
  333. "ContractCode", "RelateContractCode", "CrmContractId", "ContractSource", "CompanyName", "ActualCompanyName",
  334. "SellerId", "SellerName", "ContractType", "ContractAmount", "StartDate", "EndDate", "SignDate", "AgreedPayTime",
  335. "ContractStatus", "RegisterStatus", "Remark", "ServiceRemark", "HasPayment", "NewCompany", "ModifyTime",
  336. }
  337. nowTime := time.Now().Local()
  338. item.ContractCode = req.ContractCode
  339. item.RelateContractCode = req.RelateContractCode
  340. item.CrmContractId = req.CrmContractId
  341. item.ContractSource = req.ContractSource
  342. item.CompanyName = req.CompanyName
  343. item.ActualCompanyName = req.ActualCompanyName
  344. item.SellerId = req.SellerId
  345. item.SellerName = req.SellerName
  346. item.ContractType = req.ContractType
  347. item.ContractAmount = req.ContractAmount
  348. item.StartDate = startDate
  349. item.EndDate = endDate
  350. item.SignDate = signDate
  351. item.AgreedPayTime = req.AgreedPayTime
  352. item.ContractStatus = req.ContractStatus
  353. item.RegisterStatus = fms.ContractRegisterStatusIng
  354. item.Remark = req.Remark
  355. item.ServiceRemark = req.ServiceRemark
  356. item.HasPayment = req.HasPayment
  357. item.NewCompany = req.NewCompany
  358. item.ModifyTime = nowTime
  359. // 存在代付的直接完成登记, 且不允许进行开票/到款登记
  360. if req.HasPayment == 1 {
  361. item.RegisterStatus = fms.ContractRegisterStatusComplete
  362. updateCols = append(updateCols, "RegisterStatus")
  363. }
  364. // 套餐信息
  365. serviceList, e := fmsService.HandleContractServiceAndDetail(req.ProductId, req.Services, true)
  366. if e != nil {
  367. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  368. return
  369. }
  370. // 更新合同及套餐
  371. if e = fms.UpdateContractRegisterAndServices(item, updateCols, serviceList); e != nil {
  372. resp.FailMsg("操作失败", "更新合同及套餐失败, Err: "+e.Error(), c)
  373. return
  374. }
  375. // 若从无代付修改为有代付, 则删除无代付期间新增的所有开票/到款登记(此情况并不经常出现, 但是可能会存在这种操作)
  376. if originHasPayment == 0 && req.HasPayment == 1 {
  377. go func() {
  378. if e = fms.DeleteContractInvoicesByRegisterId(item.ContractRegisterId); e != nil {
  379. alarm_msg.SendAlarmMsg("无代付修改为有代付, 删除开票到款记录失败, ErrMsg: "+err.Error(), 3)
  380. }
  381. }()
  382. }
  383. // 校验金额-是否修改状态
  384. go fmsService.CheckContractRegisterAmount(item.ContractRegisterId)
  385. // 操作日志
  386. go func() {
  387. opData := ""
  388. opDataByte, e := json.Marshal(req)
  389. if e != nil {
  390. return
  391. }
  392. opData = string(opDataByte)
  393. logItem := new(fms.ContractRegisterLog)
  394. logItem.ContractRegisterId = item.ContractRegisterId
  395. logItem.AdminId = int(adminInfo.AdminId)
  396. logItem.AdminName = adminInfo.RealName
  397. logItem.OpData = opData
  398. logItem.OpType = fms.ContractRegisterOpTypeEdit
  399. logItem.CreateTime = nowTime
  400. logItem.Remark = req.Remark
  401. if e = logItem.Create(); e != nil {
  402. return
  403. }
  404. }()
  405. resp.Ok("操作成功", c)
  406. }
  407. // Del
  408. // @Title 删除合同登记
  409. // @Description 删除合同登记
  410. // @Param request body fms.ContractRegisterDelReq true "type json string"
  411. // @Success 200 string "操作成功"
  412. // @router /contract/register/del [post]
  413. func (rg *RegisterController) Del(c *gin.Context) {
  414. req := new(fms.ContractRegisterDelReq)
  415. err := c.ShouldBind(&req)
  416. if err != nil {
  417. errs, ok := err.(validator.ValidationErrors)
  418. if !ok {
  419. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  420. return
  421. }
  422. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  423. return
  424. }
  425. claims, _ := c.Get("adminInfo")
  426. adminInfo := claims.(*system.SysAdmin)
  427. ob := new(fms.ContractRegister)
  428. item, e := ob.Fetch(req.ContractRegisterId)
  429. if e != nil {
  430. if e == utils.ErrNoRow {
  431. resp.Fail("合同登记不存在或已被删除", c)
  432. return
  433. }
  434. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  435. return
  436. }
  437. nowTime := time.Now().Local()
  438. item.IsDeleted = 1
  439. item.ModifyTime = nowTime
  440. updateCols := []string{"IsDeleted", "ModifyTime"}
  441. if e = item.Update(updateCols); e != nil {
  442. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  443. return
  444. }
  445. // 删除对应的开票到款登记
  446. go func() {
  447. if e = fms.DeleteContractInvoicesByRegisterId(item.ContractRegisterId); e != nil {
  448. alarm_msg.SendAlarmMsg("删除合同登记后, 删除开票到款记录失败, ErrMsg: "+err.Error(), 3)
  449. }
  450. }()
  451. // 操作日志
  452. go func() {
  453. opData := ""
  454. opDataByte, e := json.Marshal(req)
  455. if e != nil {
  456. return
  457. }
  458. opData = string(opDataByte)
  459. logItem := new(fms.ContractRegisterLog)
  460. logItem.ContractRegisterId = req.ContractRegisterId
  461. logItem.AdminId = int(adminInfo.AdminId)
  462. logItem.AdminName = adminInfo.RealName
  463. logItem.OpData = opData
  464. logItem.OpType = fms.ContractRegisterOpTypeDel
  465. logItem.CreateTime = nowTime
  466. if e = logItem.Create(); e != nil {
  467. return
  468. }
  469. }()
  470. resp.Ok("操作成功", c)
  471. }
  472. // Detail
  473. // @Title 合同登记详情
  474. // @Description 合同登记详情
  475. // @Param ContractRegisterId query int false "合同登记ID"
  476. // @Success 200 {object} fms.ContractRegisterDetail
  477. // @router /contract/register/detail [get]
  478. func (rg *RegisterController) Detail(c *gin.Context) {
  479. var req fms.ContractRegisterDetailReq
  480. if e := c.BindQuery(&req); e != nil {
  481. err, ok := e.(validator.ValidationErrors)
  482. if !ok {
  483. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  484. return
  485. }
  486. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  487. return
  488. }
  489. result := new(fms.ContractRegisterDetail)
  490. // 合同登记信息
  491. item, e := fms.GetContractRegisterItemById(req.ContractRegisterId)
  492. if e != nil {
  493. resp.FailData("获取失败", "获取合同登记详情失败, Err:"+e.Error(), c)
  494. return
  495. }
  496. result.ContractRegisterItem = item
  497. // 套餐信息
  498. serviceList, e := fmsService.GetContractServiceAndDetail(req.ContractRegisterId)
  499. if e != nil {
  500. resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
  501. return
  502. }
  503. result.ServiceList = serviceList
  504. // 开票/到款信息
  505. invoiceCond := `contract_register_id = ?`
  506. invoicePars := make([]interface{}, 0)
  507. invoicePars = append(invoicePars, req.ContractRegisterId)
  508. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  509. if e != nil {
  510. resp.FailData("获取失败", "获取合同开票/到款信息失败, Err: "+e.Error(), c)
  511. return
  512. }
  513. result.InvoiceList = make([]*fms.ContractInvoiceItem, 0)
  514. result.PaymentList = make([]*fms.ContractInvoiceItem, 0)
  515. for i := range invoiceList {
  516. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  517. result.InvoiceList = append(result.InvoiceList, invoiceList[i])
  518. continue
  519. }
  520. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  521. result.PaymentList = append(result.PaymentList, invoiceList[i])
  522. }
  523. }
  524. // 合同登记进度
  525. logCond := `contract_register_id = ?`
  526. logPars := make([]interface{}, 0)
  527. logPars = append(logPars, req.ContractRegisterId)
  528. logList, e := fms.GetContractRegisterLogItemList(logCond, logPars)
  529. if e != nil {
  530. resp.FailData("获取失败", "获取合同登记进度失败, Err: "+e.Error(), c)
  531. return
  532. }
  533. result.Logs = logList
  534. resp.OkData("获取成功", result, c)
  535. }
  536. // UpdateStatus
  537. // @Title 修改合同状态
  538. // @Description 修改合同状态
  539. // @Param request body fms.ContractRegisterUpdateStatusReq true "type json string"
  540. // @Success 200 string "操作成功"
  541. // @router /contract/register/update_status [post]
  542. func (rg *RegisterController) UpdateStatus(c *gin.Context) {
  543. req := new(fms.ContractRegisterUpdateStatusReq)
  544. err := c.ShouldBind(&req)
  545. if err != nil {
  546. errs, ok := err.(validator.ValidationErrors)
  547. if !ok {
  548. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  549. return
  550. }
  551. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  552. return
  553. }
  554. claims, _ := c.Get("adminInfo")
  555. adminInfo := claims.(*system.SysAdmin)
  556. ob := new(fms.ContractRegister)
  557. item, e := ob.Fetch(req.ContractRegisterId)
  558. if e != nil {
  559. if e == utils.ErrNoRow {
  560. resp.Fail("合同登记不存在或已被删除", c)
  561. return
  562. }
  563. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  564. return
  565. }
  566. nowTime := time.Now().Local()
  567. item.ContractStatus = req.ContractStatus
  568. item.ModifyTime = nowTime
  569. updateCols := []string{"ContractStatus", "ModifyTime"}
  570. if e = item.Update(updateCols); e != nil {
  571. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  572. return
  573. }
  574. // 校验金额-是否修改状态
  575. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  576. // 操作日志
  577. go func() {
  578. opData := ""
  579. opDataByte, e := json.Marshal(req)
  580. if e != nil {
  581. return
  582. }
  583. opData = string(opDataByte)
  584. logItem := new(fms.ContractRegisterLog)
  585. logItem.ContractRegisterId = req.ContractRegisterId
  586. logItem.AdminId = int(adminInfo.AdminId)
  587. logItem.AdminName = adminInfo.RealName
  588. logItem.OpData = opData
  589. logItem.OpType = fms.ContractRegisterOpTypeStatus
  590. logItem.CreateTime = nowTime
  591. if e = logItem.Create(); e != nil {
  592. return
  593. }
  594. }()
  595. resp.Ok("操作成功", c)
  596. }
  597. // Invoice
  598. // @Title 开票/到款登记
  599. // @Description 开票/到款登记
  600. // @Param request body fms.ContractInvoiceSaveReq true "type json string"
  601. // @Success 200 string "操作成功"
  602. // @router /contract/register/invoice [post]
  603. func (rg *RegisterController) Invoice(c *gin.Context) {
  604. req := new(fms.ContractInvoiceSaveReq)
  605. err := c.ShouldBind(&req)
  606. if err != nil {
  607. errs, ok := err.(validator.ValidationErrors)
  608. if !ok {
  609. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  610. return
  611. }
  612. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  613. return
  614. }
  615. claims, _ := c.Get("adminInfo")
  616. adminInfo := claims.(*system.SysAdmin)
  617. registerOB := new(fms.ContractRegister)
  618. item, e := registerOB.Fetch(req.ContractRegisterId)
  619. if e != nil {
  620. if e == utils.ErrNoRow {
  621. resp.Fail("合同登记不存在或已被删除", c)
  622. return
  623. }
  624. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  625. return
  626. }
  627. // 合同存在代付不允许开票/到款登记
  628. if item.HasPayment == 1 {
  629. resp.Fail("合同存在代付不允许添加开票/到款登记", c)
  630. return
  631. }
  632. // 合同有效时长
  633. dayDiff := item.EndDate.Sub(item.StartDate).Hours() / 24
  634. noChangeInvoiceIds := make([]int, 0)
  635. newInvoice := make([]*fms.ContractInvoice, 0)
  636. if len(req.AmountList) > 0 {
  637. // 获取销售分组信息
  638. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  639. if e != nil {
  640. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  641. return
  642. }
  643. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  644. for i := range sellerList {
  645. sellerMap[sellerList[i].SellerId] = sellerList[i]
  646. }
  647. for i := range req.AmountList {
  648. if req.AmountList[i].Amount <= 0 {
  649. resp.Fail("登记金额有误", c)
  650. return
  651. }
  652. if req.AmountList[i].InvoiceDate == "" {
  653. resp.Fail("请选择日期", c)
  654. return
  655. }
  656. // 开票登记销售必填
  657. if req.InvoiceType == fms.ContractInvoiceTypeMake && req.AmountList[i].SellerId <= 0 {
  658. resp.Fail("请选择销售", c)
  659. return
  660. }
  661. t, e := time.ParseInLocation(utils.FormatDate, req.AmountList[i].InvoiceDate, time.Local)
  662. if e != nil {
  663. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  664. return
  665. }
  666. if req.AmountList[i].InvoiceId > 0 {
  667. noChangeInvoiceIds = append(noChangeInvoiceIds, req.AmountList[i].InvoiceId)
  668. }
  669. if req.AmountList[i].InvoiceId == 0 {
  670. v := &fms.ContractInvoice{
  671. ContractRegisterId: req.ContractRegisterId,
  672. ContractCode: item.ContractCode,
  673. Amount: req.AmountList[i].Amount,
  674. InvoiceType: req.InvoiceType,
  675. InvoiceDate: t,
  676. AdminId: int(adminInfo.AdminId),
  677. AdminName: adminInfo.RealName,
  678. Remark: req.AmountList[i].Remark,
  679. }
  680. v.Set()
  681. // 开票登记-销售信息
  682. if req.InvoiceType == fms.ContractInvoiceTypeMake {
  683. sellerItem := sellerMap[req.AmountList[i].SellerId]
  684. if sellerItem == nil {
  685. resp.Fail("销售信息异常", c)
  686. return
  687. }
  688. v.SellerId = sellerItem.SellerId
  689. v.SellerName = sellerItem.SellerName
  690. v.SellerGroupId = sellerItem.GroupId
  691. v.SellerGroupName = sellerItem.GroupName
  692. v.SellerTeamId = sellerItem.TeamId
  693. v.SellerTeamName = sellerItem.TeamName
  694. }
  695. // 到款登记-付款方式
  696. if req.InvoiceType == fms.ContractInvoiceTypePay {
  697. v.PayType = fmsService.CalculateContractPaymentType(req.AmountList[i].Amount, item.ContractAmount, dayDiff)
  698. }
  699. newInvoice = append(newInvoice, v)
  700. }
  701. }
  702. }
  703. // 获取原有的登记信息
  704. invoiceCond := `contract_register_id = ? AND invoice_type = ?`
  705. invoicePars := make([]interface{}, 0)
  706. invoicePars = append(invoicePars, req.ContractRegisterId, req.InvoiceType)
  707. originInvoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  708. if e != nil {
  709. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  710. return
  711. }
  712. // 比对原有和现有的登记信息
  713. logList := make([]*fms.ContractRegisterLog, 0)
  714. opData := ""
  715. opDataByte, e := json.Marshal(req)
  716. if e != nil {
  717. return
  718. }
  719. opData = string(opDataByte)
  720. opType := fms.ContractRegisterOpTypeInvoice
  721. if req.InvoiceType == fms.ContractInvoiceTypePay {
  722. opType = fms.ContractRegisterOpTypePayment
  723. }
  724. nowTime := time.Now().Local()
  725. // 需要删除的记录
  726. deleteInvoiceIds := make([]int, 0)
  727. for i := range originInvoiceList {
  728. if !utils.InArrayByInt(noChangeInvoiceIds, originInvoiceList[i].ContractInvoiceId) {
  729. deleteInvoiceIds = append(deleteInvoiceIds, originInvoiceList[i].ContractInvoiceId)
  730. logList = append(logList, &fms.ContractRegisterLog{
  731. ContractRegisterId: req.ContractRegisterId,
  732. AdminId: int(adminInfo.AdminId),
  733. AdminName: adminInfo.RealName,
  734. OpData: opData,
  735. OpType: opType,
  736. CreateTime: nowTime,
  737. AmountRemark: fmt.Sprint("删除", fms.ContractInvoiceKeyNameMap[opType], "金额", originInvoiceList[i].Amount, "元"),
  738. })
  739. }
  740. }
  741. // 新增的记录
  742. if len(newInvoice) > 0 {
  743. newAmount := decimal.NewFromFloat(0).Round(2)
  744. for i := range newInvoice {
  745. a := decimal.NewFromFloat(newInvoice[i].Amount).Round(2)
  746. newAmount = newAmount.Add(a)
  747. }
  748. ia, _ := newAmount.Round(2).Float64()
  749. logList = append(logList, &fms.ContractRegisterLog{
  750. ContractRegisterId: req.ContractRegisterId,
  751. AdminId: int(adminInfo.AdminId),
  752. AdminName: adminInfo.RealName,
  753. OpData: opData,
  754. OpType: opType,
  755. CreateTime: nowTime,
  756. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  757. })
  758. }
  759. // 删除并新增登记
  760. ob := new(fms.ContractInvoice)
  761. if e := ob.DeleteAndCreateNewInvoice(req.ContractRegisterId, req.InvoiceType, deleteInvoiceIds, newInvoice); e != nil {
  762. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  763. return
  764. }
  765. // 校验金额-是否修改状态
  766. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  767. // 操作日志
  768. go func() {
  769. logOB := new(fms.ContractRegisterLog)
  770. if e := logOB.AddInBatches(logList); e != nil {
  771. return
  772. }
  773. }()
  774. resp.Ok("操作成功", c)
  775. }
  776. // Export
  777. // @Title 合同登记-导出
  778. // @Description 合同登记-导出
  779. // @Param Keyword query string false "关键词"
  780. // @Param StartDate query string false "合同开始日期"
  781. // @Param EndDate query string false "合同结束日期"
  782. // @Param ServiceType query int false "套餐类型"
  783. // @Param ContractType query int false "合同类型"
  784. // @Param RegisterStatus query int false "登记状态"
  785. // @Success 200 string "操作成功"
  786. // @router /contract/register/export [get]
  787. func (rg *RegisterController) Export(c *gin.Context) {
  788. var req fms.ContractRegisterListReq
  789. if e := c.BindQuery(&req); e != nil {
  790. err, ok := e.(validator.ValidationErrors)
  791. if !ok {
  792. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  793. return
  794. }
  795. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  796. return
  797. }
  798. cond := `1 = 1`
  799. pars := make([]interface{}, 0)
  800. // 合同编号/客户姓名/销售/实际使用方
  801. if req.Keyword != "" {
  802. kw := "%" + req.Keyword + "%"
  803. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
  804. pars = append(pars, kw, kw, kw, kw)
  805. }
  806. if req.StartDate != "" && req.EndDate != "" {
  807. st := fmt.Sprint(req.StartDate, " 00:00:00")
  808. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  809. cond += ` AND (create_time BETWEEN ? AND ?)`
  810. pars = append(pars, st, ed)
  811. }
  812. if req.ContractType != 0 {
  813. cond += ` AND contract_type = ?`
  814. pars = append(pars, req.ContractType)
  815. }
  816. if req.RegisterStatus != 0 {
  817. cond += ` AND register_status = ?`
  818. pars = append(pars, req.RegisterStatus)
  819. }
  820. if req.ServiceType != 0 {
  821. registerIds, e := fms.GetContractRegisterIdsByTempId(req.ServiceType)
  822. if e != nil {
  823. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  824. return
  825. }
  826. if len(registerIds) > 0 {
  827. cond += ` AND contract_register_id IN ?`
  828. pars = append(pars, registerIds)
  829. } else {
  830. cond += ` AND 1 = 2`
  831. }
  832. }
  833. // 获取列表数据
  834. cr := new(fms.ContractRegister)
  835. list, e := cr.List(cond, pars)
  836. if e != nil {
  837. resp.FailData("获取合同列表失败", "Err:"+e.Error(), c)
  838. return
  839. }
  840. if len(list) == 0 {
  841. resp.Fail("无有效数据可导出", c)
  842. return
  843. }
  844. registerIds := make([]int, 0)
  845. for i := range list {
  846. registerIds = append(registerIds, list[i].ContractRegisterId)
  847. }
  848. // 获取小套餐品种
  849. cpCond := `product_id = ? AND permission_name <> ?`
  850. cpPars := make([]interface{}, 0)
  851. cpPars = append(cpPars, crm.CompanyProductFicc, crm.ChartPermissionStrategyName)
  852. cp := new(crm.ChartPermission)
  853. permissionList, e := cp.List(cpCond, cpPars)
  854. if e != nil {
  855. resp.FailData("获取小套餐品种失败", "Err:"+e.Error(), c)
  856. return
  857. }
  858. permissionLen := len(permissionList)
  859. permissionNameIdMap := make(map[string]int)
  860. for i := range permissionList {
  861. permissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  862. }
  863. // 获取套餐服务
  864. serviceList, e := fms.GetContractServiceTemplateMapByProductId(crm.CompanyProductFicc)
  865. if e != nil {
  866. resp.FailData("获取套餐服务失败", "Err:"+e.Error(), c)
  867. return
  868. }
  869. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  870. otherService := make([]*fms.ContractServiceTemplateItem, 0)
  871. for i := range serviceList {
  872. if serviceList[i].Title != "FICC大套餐" && serviceList[i].Title != "FICC小套餐" {
  873. otherService = append(otherService, serviceList[i])
  874. }
  875. }
  876. otherServiceLen := len(otherService)
  877. // 套餐/开票/到款列表
  878. serviceMap := make(map[int][]*fms.ContractService)
  879. serviceChartPermissionsMap := make(map[int][]int)
  880. invoiceMap := make(map[int][]*fms.ContractInvoice)
  881. paymentMap := make(map[int][]*fms.ContractInvoice)
  882. maxInvoice := 0
  883. maxPayment := 0
  884. if len(registerIds) > 0 {
  885. // 获取套餐信息
  886. csCond := `contract_register_id IN ?`
  887. csPars := make([]interface{}, 0)
  888. csPars = append(csPars, registerIds)
  889. cs := new(fms.ContractService)
  890. serviceList, e := cs.List(csCond, csPars)
  891. if e != nil {
  892. resp.FailData("获取合同套餐列表失败", "Err:"+e.Error(), c)
  893. return
  894. }
  895. for i := range serviceList {
  896. cid := serviceList[i].ContractRegisterId
  897. if serviceMap[cid] == nil {
  898. serviceMap[cid] = make([]*fms.ContractService, 0)
  899. }
  900. serviceMap[cid] = append(serviceMap[cid], serviceList[i])
  901. // 小套餐权限
  902. if serviceChartPermissionsMap[cid] == nil {
  903. serviceChartPermissionsMap[cid] = make([]int, 0)
  904. }
  905. if serviceList[i].ChartPermissionIds != "" {
  906. ids := utils.JoinStr2IntArr(serviceList[i].ChartPermissionIds, ",")
  907. serviceChartPermissionsMap[cid] = append(serviceChartPermissionsMap[cid], ids...)
  908. }
  909. }
  910. // 获取开票/到款详情, 并取最大的开票/到款数(用于动态扩展第二列表头)
  911. ci := new(fms.ContractInvoice)
  912. invoiceList, e := ci.List(csCond, csPars, "")
  913. if e != nil {
  914. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  915. return
  916. }
  917. for k := range invoiceList {
  918. cid := invoiceList[k].ContractRegisterId
  919. if invoiceMap[cid] == nil {
  920. invoiceMap[cid] = make([]*fms.ContractInvoice, 0)
  921. }
  922. if paymentMap[cid] == nil {
  923. paymentMap[cid] = make([]*fms.ContractInvoice, 0)
  924. }
  925. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypeMake {
  926. invoiceMap[cid] = append(invoiceMap[cid], invoiceList[k])
  927. continue
  928. }
  929. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypePay {
  930. paymentMap[cid] = append(paymentMap[cid], invoiceList[k])
  931. continue
  932. }
  933. }
  934. // 取最大开票/到款数
  935. for j := range invoiceMap {
  936. if len(invoiceMap[j]) > maxInvoice {
  937. maxInvoice = len(invoiceMap[j])
  938. }
  939. }
  940. for p := range paymentMap {
  941. if len(paymentMap[p]) > maxPayment {
  942. maxPayment = len(paymentMap[p])
  943. }
  944. }
  945. }
  946. // 生成Excel文件
  947. xlsxFile := xlsx.NewFile()
  948. style := xlsx.NewStyle()
  949. alignment := xlsx.Alignment{
  950. Horizontal: "center",
  951. Vertical: "center",
  952. WrapText: true,
  953. }
  954. style.Alignment = alignment
  955. style.ApplyAlignment = true
  956. sheetName := "财务列表"
  957. sheet, err := xlsxFile.AddSheet(sheetName)
  958. if err != nil {
  959. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  960. return
  961. }
  962. // 1行表头
  963. titleRow := sheet.AddRow()
  964. titleRow.SetHeight(40)
  965. // 1行1列-右合并两格
  966. cell1 := titleRow.AddCell()
  967. cell1.HMerge = 3
  968. cell1.SetString("FICC客户签约表 2022")
  969. cell1.SetStyle(style)
  970. // 右增两列空白格用于第一列合并, 否则后续单元格合并会有问题
  971. titleRow.AddCell().SetString("")
  972. titleRow.AddCell().SetString("")
  973. titleRow.AddCell().SetString("")
  974. // 1行2列
  975. cell2 := titleRow.AddCell()
  976. cell2.SetString("FICC大套餐")
  977. cell2.SetStyle(style)
  978. // 1行3列-右合并小套餐数
  979. if permissionLen >= 1 {
  980. cell3 := titleRow.AddCell()
  981. cell3.HMerge = permissionLen - 1
  982. cell3.SetString("FICC小套餐")
  983. cell3.SetStyle(style)
  984. // 同上右增单元格小套餐数-1的空白单元格用于合并
  985. for i := 0; i < permissionLen-1; i++ {
  986. titleRow.AddCell().SetString("")
  987. }
  988. }
  989. for i := range otherService {
  990. cellOther := titleRow.AddCell()
  991. cellOther.SetString(otherService[i].Title)
  992. cellOther.SetStyle(style)
  993. }
  994. // 第二行表头
  995. titleRow2 := sheet.AddRow()
  996. titleRow2.SetHeight(60)
  997. row2Title := make([]string, 0)
  998. row2Title = append(row2Title, "客户名称", "新客户\n0-是\n1-否", "合同类型\n续约-0\n新增-1\n代付-2\n补充协议-3", "销售", "FICC大套餐")
  999. for i := range permissionList {
  1000. row2Title = append(row2Title, permissionList[i].PermissionName)
  1001. }
  1002. // 其他套餐
  1003. for i := range otherService {
  1004. row2Title = append(row2Title, otherService[i].Title)
  1005. }
  1006. row2Title = append(row2Title, "套餐备注", "开始时间", "到期时间", "2022年合同金额", "约定付款时间", "签订日", "合同状态",
  1007. "合同编号", "合规备注")
  1008. // 设置表头
  1009. for i := range row2Title {
  1010. v := titleRow2.AddCell()
  1011. v.SetString(row2Title[i])
  1012. v.SetStyle(style)
  1013. }
  1014. // 第二行表头-开票/收款(动态添加)
  1015. invoiceTitle := []string{"开票日", "开票金额", "销售", "备注"}
  1016. for i := 0; i < maxInvoice; i++ {
  1017. n := i + 1
  1018. for ii := range invoiceTitle {
  1019. c := titleRow2.AddCell()
  1020. t := fmt.Sprintf("%s%d", invoiceTitle[ii], n)
  1021. c.SetString(t)
  1022. c.SetStyle(style)
  1023. row2Title = append(row2Title, t)
  1024. }
  1025. }
  1026. paymentTitle := []string{"到款日", "到款金额", "备注"}
  1027. for i := 0; i < maxPayment; i++ {
  1028. n := i + 1
  1029. for ii := range paymentTitle {
  1030. c := titleRow2.AddCell()
  1031. t := fmt.Sprintf("%s%d", paymentTitle[ii], n)
  1032. c.SetString(t)
  1033. c.SetStyle(style)
  1034. row2Title = append(row2Title, t)
  1035. }
  1036. }
  1037. // 此处取第二行标题NameKeyMap, 后面的动态匹配
  1038. row2NameKeyMap := make(map[string]int)
  1039. for i := range row2Title {
  1040. row2NameKeyMap[row2Title[i]] = i
  1041. }
  1042. newCompanyMap := map[int]string{0: "1", 1: "0"}
  1043. contractTMap := map[int]int{
  1044. fms.ContractTypeNew: 1,
  1045. fms.ContractTypeRenew: 0,
  1046. fms.ContractTypeAgentPay: 2, // 代付合同
  1047. fms.ContractTypePlus: 3, // 补充协议
  1048. }
  1049. for _, v := range list {
  1050. k := -1 // 套餐匹配用
  1051. dataRow := sheet.AddRow()
  1052. dataRow.SetHeight(20)
  1053. k += 4
  1054. dataRow.AddCell().SetString(v.CompanyName)
  1055. dataRow.AddCell().SetString(newCompanyMap[v.NewCompany])
  1056. dataRow.AddCell().SetString(fmt.Sprint(contractTMap[v.ContractType]))
  1057. dataRow.AddCell().SetString(v.SellerName)
  1058. // 大套餐
  1059. k += 1
  1060. col4Name := row2Title[k]
  1061. svList := serviceMap[v.ContractRegisterId]
  1062. col4 := ""
  1063. if svList != nil && len(svList) > 0 {
  1064. for isv := range svList {
  1065. if svList[isv].Title == col4Name {
  1066. col4 = "是"
  1067. break
  1068. }
  1069. }
  1070. }
  1071. dataRow.AddCell().SetString(col4)
  1072. // 小套餐
  1073. serviceChartPermissionIds := serviceChartPermissionsMap[v.ContractRegisterId]
  1074. for i := 0; i < permissionLen; i++ {
  1075. k += 1
  1076. colName := row2Title[k]
  1077. chartPermissionId := permissionNameIdMap[colName]
  1078. if utils.InArray(chartPermissionId, serviceChartPermissionIds) {
  1079. dataRow.AddCell().SetString("是")
  1080. } else {
  1081. dataRow.AddCell().SetString("")
  1082. }
  1083. }
  1084. // 除大小套餐外的其他套餐(处理方式其实跟上面的大套餐一样, 只是中间隔了小套餐按照顺序要这么处理=_=!)
  1085. for i := 0; i < otherServiceLen; i++ {
  1086. k += 1
  1087. otherColName := row2Title[k]
  1088. otherCol := ""
  1089. if svList != nil && len(svList) > 0 {
  1090. for isv := range svList {
  1091. if svList[isv].Title == otherColName {
  1092. otherCol = "是"
  1093. break
  1094. }
  1095. }
  1096. }
  1097. dataRow.AddCell().SetString(otherCol)
  1098. }
  1099. // 其他信息
  1100. dataRow.AddCell().SetString(v.ServiceRemark) // 套餐备注
  1101. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.StartDate)) // 开始时间
  1102. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.EndDate)) // 到期时间
  1103. dataRow.AddCell().SetString(fmt.Sprint("¥", v.ContractAmount)) // 2022年合同金额
  1104. dataRow.AddCell().SetString(v.AgreedPayTime) // 约定付款时间
  1105. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.SignDate)) // 签订日
  1106. dataRow.AddCell().SetString(fms.ContractStatusKeyNameMap[v.ContractStatus]) // 合同状态
  1107. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  1108. dataRow.AddCell().SetString(v.Remark) // 合规备注
  1109. // 开票/到款信息
  1110. ivList := invoiceMap[v.ContractRegisterId]
  1111. ivListLen := len(ivList)
  1112. if ivList != nil && len(ivList) > 0 {
  1113. for ia := 0; ia < maxInvoice; ia++ {
  1114. if ia < ivListLen {
  1115. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", ivList[ia].InvoiceDate)) // 开票日
  1116. dataRow.AddCell().SetString(fmt.Sprint(ivList[ia].Amount)) // 开票金额
  1117. dataRow.AddCell().SetString(ivList[ia].SellerName) // 销售名称
  1118. dataRow.AddCell().SetString(ivList[ia].Remark) // 开票备注
  1119. } else {
  1120. // 这里要把不够的填充为空
  1121. dataRow.AddCell().SetString("")
  1122. dataRow.AddCell().SetString("")
  1123. dataRow.AddCell().SetString("")
  1124. dataRow.AddCell().SetString("")
  1125. }
  1126. }
  1127. }
  1128. pyList := paymentMap[v.ContractRegisterId]
  1129. pyListLen := len(pyList)
  1130. if pyList != nil && pyListLen > 0 {
  1131. for ib := 0; ib < maxPayment; ib++ {
  1132. if ib < pyListLen {
  1133. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", pyList[ib].InvoiceDate)) // 收款日
  1134. dataRow.AddCell().SetString(fmt.Sprint(pyList[ib].Amount)) // 收款金额
  1135. dataRow.AddCell().SetString(pyList[ib].Remark) // 收款备注
  1136. } else {
  1137. // 已经是最后的几列了其实可以不用填充空, 万一后面要加列此处还是填充上吧
  1138. dataRow.AddCell().SetString("")
  1139. dataRow.AddCell().SetString("")
  1140. dataRow.AddCell().SetString("")
  1141. }
  1142. }
  1143. }
  1144. }
  1145. // 输出文件
  1146. var buffer bytes.Buffer
  1147. _ = xlsxFile.Write(&buffer)
  1148. content := bytes.NewReader(buffer.Bytes())
  1149. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1150. fileName := sheetName + randStr + ".xlsx"
  1151. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1152. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1153. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1154. }
  1155. // InvoiceList
  1156. // @Title 开票/到款列表
  1157. // @Description 开票/到款列表
  1158. // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
  1159. // @Param ContractCode query string false "合同编号"
  1160. // @Param StartDate query string false "开始日期"
  1161. // @Param EndDate query string false "结束日期"
  1162. // @Param MinAmount query float64 false "开票金额区间-最小值"
  1163. // @Param MaxAmount query float64 false "开票金额区间-最大值"
  1164. // @Success 200 {object} fms.ContractInvoiceItem
  1165. // @router /contract/register/invoice_list [get]
  1166. func (rg *RegisterController) InvoiceList(c *gin.Context) {
  1167. var req fms.ContractInvoiceListReq
  1168. if e := c.BindQuery(&req); e != nil {
  1169. err, ok := e.(validator.ValidationErrors)
  1170. if !ok {
  1171. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1172. return
  1173. }
  1174. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1175. return
  1176. }
  1177. cond := `invoice_type = ?`
  1178. pars := make([]interface{}, 0)
  1179. pars = append(pars, req.InvoiceType)
  1180. // 合同编号
  1181. if req.ContractCode != "" {
  1182. kw := fmt.Sprint("%", req.ContractCode, "%")
  1183. cond += ` AND contract_code LIKE ?`
  1184. pars = append(pars, kw)
  1185. }
  1186. if req.StartDate != "" && req.EndDate != "" {
  1187. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1188. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1189. cond += ` AND (invoice_time BETWEEN ? AND ?)`
  1190. pars = append(pars, st, ed)
  1191. }
  1192. if req.MinAmount > 0 {
  1193. cond += ` AND amount >= ?`
  1194. pars = append(pars, req.MinAmount)
  1195. }
  1196. if req.MaxAmount > 0 {
  1197. cond += ` AND amount <= ?`
  1198. pars = append(pars, req.MaxAmount)
  1199. }
  1200. page := new(base.Page)
  1201. page.SetPageSize(req.PageSize)
  1202. page.SetCurrent(req.Current)
  1203. page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: false})
  1204. total, list, e := fms.GetContractInvoiceItemPageList(page, cond, pars)
  1205. if e != nil {
  1206. resp.FailMsg("获取失败", "获取合同开票/到款列表失败, Err: "+e.Error(), c)
  1207. return
  1208. }
  1209. page.SetTotal(total)
  1210. baseData := new(base.BaseData)
  1211. baseData.SetPage(page)
  1212. baseData.SetList(list)
  1213. resp.OkData("获取成功", baseData, c)
  1214. }
  1215. // InvoiceExport
  1216. // @Title 开票/到款列表-导出
  1217. // @Description 合同登记-导出
  1218. // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
  1219. // @Param ContractCode query string false "合同编号"
  1220. // @Param StartDate query string false "开始日期"
  1221. // @Param EndDate query string false "结束日期"
  1222. // @Param MinAmount query float64 false "开票金额区间-最小值"
  1223. // @Param MaxAmount query float64 false "开票金额区间-最大值"
  1224. // @Success 200 string "操作成功"
  1225. // @router /contract/register/invoice_export [get]
  1226. func (rg *RegisterController) InvoiceExport(c *gin.Context) {
  1227. var req fms.ContractInvoiceListReq
  1228. if e := c.BindQuery(&req); e != nil {
  1229. err, ok := e.(validator.ValidationErrors)
  1230. if !ok {
  1231. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1232. return
  1233. }
  1234. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1235. return
  1236. }
  1237. cond := `invoice_type = ?`
  1238. pars := make([]interface{}, 0)
  1239. pars = append(pars, req.InvoiceType)
  1240. // 合同编号
  1241. if req.ContractCode != "" {
  1242. kw := fmt.Sprint("%", req.ContractCode, "%")
  1243. cond += ` AND contract_code LIKE ?`
  1244. pars = append(pars, kw)
  1245. }
  1246. if req.StartDate != "" && req.EndDate != "" {
  1247. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1248. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1249. cond += ` AND (invoice_time BETWEEN ? AND ?)`
  1250. pars = append(pars, st, ed)
  1251. }
  1252. if req.MinAmount > 0 {
  1253. cond += ` AND amount >= ?`
  1254. pars = append(pars, req.MinAmount)
  1255. }
  1256. if req.MaxAmount > 0 {
  1257. cond += ` AND amount <= ?`
  1258. pars = append(pars, req.MaxAmount)
  1259. }
  1260. // 获取列表数据
  1261. cr := new(fms.ContractInvoice)
  1262. orderRule := `invoice_time DESC`
  1263. list, e := cr.List(cond, pars, orderRule)
  1264. if e != nil {
  1265. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  1266. return
  1267. }
  1268. if len(list) == 0 {
  1269. resp.Fail("无有效数据可导出", c)
  1270. return
  1271. }
  1272. // 生成Excel文件
  1273. xlsxFile := xlsx.NewFile()
  1274. style := xlsx.NewStyle()
  1275. alignment := xlsx.Alignment{
  1276. Horizontal: "center",
  1277. Vertical: "center",
  1278. WrapText: true,
  1279. }
  1280. style.Alignment = alignment
  1281. style.ApplyAlignment = true
  1282. sheet, err := xlsxFile.AddSheet("开票列表")
  1283. if err != nil {
  1284. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1285. return
  1286. }
  1287. // 表头
  1288. titleRow := sheet.AddRow()
  1289. titleRow.SetHeight(40)
  1290. cell1 := titleRow.AddCell()
  1291. cell1.SetString("合同编号")
  1292. cell1.SetStyle(style)
  1293. cell2 := titleRow.AddCell()
  1294. cell2.SetString("开票金额")
  1295. cell2.SetStyle(style)
  1296. cell3 := titleRow.AddCell()
  1297. cell3.SetString("开票日期")
  1298. cell3.SetStyle(style)
  1299. for _, v := range list {
  1300. dataRow := sheet.AddRow()
  1301. dataRow.SetHeight(20)
  1302. dataRow.AddCell().SetString(v.ContractCode)
  1303. dataRow.AddCell().SetString(fmt.Sprint(v.Amount))
  1304. dataRow.AddCell().SetString(utils.TimeTransferString("2006-01-02", v.InvoiceDate))
  1305. }
  1306. // 输出文件
  1307. var buffer bytes.Buffer
  1308. _ = xlsxFile.Write(&buffer)
  1309. content := bytes.NewReader(buffer.Bytes())
  1310. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1311. fileName := "开票列表_" + randStr + ".xlsx"
  1312. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1313. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1314. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1315. }
  1316. // Import
  1317. // @Title 合同登记-导入
  1318. // @Description 合同登记-导入
  1319. // @Success 200 string "操作成功"
  1320. // @router /contract/register/import [post]
  1321. func (rg *RegisterController) Import(c *gin.Context) {
  1322. h, err := c.FormFile("File")
  1323. if err != nil {
  1324. resp.FailData("获取文件失败", "Err:"+err.Error(), c)
  1325. return
  1326. }
  1327. ext := path.Ext(h.Filename)
  1328. if ext != ".xlsx" && ext != ".xls" {
  1329. resp.Fail("请上传Excel文件", c)
  1330. return
  1331. }
  1332. uploadDir := "static/xls"
  1333. err = os.MkdirAll(uploadDir, 766)
  1334. if err != nil {
  1335. resp.FailData("存储目录创建失败", "Err:"+err.Error(), c)
  1336. return
  1337. }
  1338. uploadPath := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
  1339. err = c.SaveUploadedFile(h, uploadPath)
  1340. if err != nil {
  1341. resp.FailData("保存本地文件失败", "Err:"+err.Error(), c)
  1342. return
  1343. }
  1344. defer func() {
  1345. _ = os.Remove(uploadPath)
  1346. }()
  1347. xlFile, err := xlsx.OpenFile(uploadPath)
  1348. if err != nil {
  1349. resp.FailData("打开文件失败", "Err:"+err.Error(), c)
  1350. return
  1351. }
  1352. // 获取所有已登记,根据合同编号去重
  1353. contractCodeArr := make([]string, 0)
  1354. registerOB := new(fms.ContractRegister)
  1355. registerCond := ``
  1356. registerPars := make([]interface{}, 0)
  1357. registerList, e := registerOB.List(registerCond, registerPars)
  1358. if e != nil {
  1359. resp.FailData("获取合同登记列表失败", "Err:"+e.Error(), c)
  1360. return
  1361. }
  1362. for i := range registerList {
  1363. contractCodeArr = append(contractCodeArr, registerList[i].ContractCode)
  1364. }
  1365. // 获取所有销售Map
  1366. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  1367. if e != nil {
  1368. resp.FailData("获取销售列表失败", "Err:"+e.Error(), c)
  1369. return
  1370. }
  1371. sellerMap := make(map[string]*crm.SellerAdminWithGroupTeam)
  1372. for i := range sellerList {
  1373. sellerMap[sellerList[i].SellerName] = sellerList[i]
  1374. }
  1375. // 获取品种权限Map
  1376. chartPermissionNameIdMap := make(map[string]int)
  1377. cpCond := `product_id = ?`
  1378. cpPars := make([]interface{}, 0)
  1379. cpPars = append(cpPars, crm.CompanyProductFicc)
  1380. cp := new(crm.ChartPermission)
  1381. permissionList, e := cp.List(cpCond, cpPars)
  1382. if e != nil {
  1383. resp.FailData("获取权限列表失败", "Err:"+e.Error(), c)
  1384. return
  1385. }
  1386. for i := range permissionList {
  1387. chartPermissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  1388. }
  1389. // 获取所有套餐模板
  1390. serviceTempCond := ``
  1391. serviceTempPars := make([]interface{}, 0)
  1392. serviceTempOB := new(fms.ContractServiceTemplate)
  1393. serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
  1394. if e != nil {
  1395. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  1396. return
  1397. }
  1398. serviceTempNameMap := make(map[string]*fms.ContractServiceTemplate)
  1399. for i := range serviceTempList {
  1400. serviceTempNameMap[serviceTempList[i].Title] = serviceTempList[i]
  1401. }
  1402. titleMap := make(map[int]string)
  1403. newIds := make([]int, 0)
  1404. newCompanyArr := []string{"0", "1"}
  1405. newCompanyMap := map[string]int{"0": 1, "1": 0}
  1406. contractTypeArr := []string{"0", "1", "2", "3"}
  1407. contractTypeMap := map[string]int{
  1408. "0": fms.ContractTypeRenew,
  1409. "1": fms.ContractTypeNew,
  1410. "2": fms.ContractTypeAgentPay,
  1411. "3": fms.ContractTypePlus,
  1412. }
  1413. // 更新登记状态
  1414. defer func() {
  1415. if len(newIds) > 0 {
  1416. go func() {
  1417. for i := range newIds {
  1418. fmsService.CheckContractRegisterAmount(newIds[i])
  1419. }
  1420. }()
  1421. }
  1422. }()
  1423. invoiceMax := 3
  1424. checkDate := time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local)
  1425. for _, sheet := range xlFile.Sheets {
  1426. // 遍历行读取
  1427. maxRow := sheet.MaxRow
  1428. for i := 0; i < maxRow; i++ {
  1429. // 第二行开始读取表头
  1430. if i == 1 {
  1431. row := sheet.Row(i)
  1432. cells := row.Cells
  1433. for k, cell := range cells {
  1434. text := cell.String()
  1435. titleMap[k] = text
  1436. // 只检验前面部分表头, 后面很多动态列
  1437. if k == 0 {
  1438. if text != "客户名称" {
  1439. resp.Fail("【客户名称】列名称有误, 请参考模板导入", c)
  1440. return
  1441. }
  1442. }
  1443. if k == 1 {
  1444. if !strings.Contains(text, "新客户") {
  1445. resp.Fail("【新客户】列名称有误, 请参考模板导入", c)
  1446. return
  1447. }
  1448. }
  1449. if k == 2 {
  1450. if !strings.Contains(text, "合同类型") {
  1451. resp.Fail("【合同类型】列名称有误, 请参考模板导入", c)
  1452. return
  1453. }
  1454. }
  1455. if k == 3 {
  1456. if text != "销售" {
  1457. resp.Fail("【销售】列名称有误, 请参考模板导入", c)
  1458. return
  1459. }
  1460. }
  1461. if k == 4 {
  1462. if text != "FICC大套餐" {
  1463. resp.Fail("【FICC大套餐】列名称有误, 请参考模板导入", c)
  1464. return
  1465. }
  1466. }
  1467. }
  1468. }
  1469. // 数据行
  1470. if i >= 2 {
  1471. row := sheet.Row(i)
  1472. cells := row.Cells
  1473. // 登记信息
  1474. rowRegister := new(fms.ContractRegister)
  1475. // 套餐
  1476. rowServices := make([]*fms.ContractService, 0)
  1477. // 开票/到款
  1478. rowInvoices := make([]*fms.ContractInvoice, 0)
  1479. for ir := 0; ir < invoiceMax; ir++ {
  1480. rowInvoices = append(rowInvoices, new(fms.ContractInvoice))
  1481. }
  1482. rowPayments := make([]*fms.ContractInvoice, 0)
  1483. for ir := 0; ir < invoiceMax; ir++ {
  1484. rowPayments = append(rowPayments, new(fms.ContractInvoice))
  1485. }
  1486. // 小套餐权限
  1487. rowChartPermissionIdArr := make([]string, 0)
  1488. isSkip := false
  1489. for k, cell := range cells {
  1490. v := utils.TrimStr(cell.String())
  1491. // 客户名称
  1492. if k == 0 {
  1493. if v == "" {
  1494. resp.Fail(fmt.Sprintf("第%d行客户名称不可为空, 请按模板导入", i+1), c)
  1495. return
  1496. }
  1497. rowRegister.CompanyName = v
  1498. continue
  1499. }
  1500. // 是否新客户
  1501. if k == 1 {
  1502. if !utils.InArrayByStr(newCompanyArr, v) {
  1503. resp.Fail(fmt.Sprintf("第%d行新客户有误, 请按模板导入", i+1), c)
  1504. return
  1505. }
  1506. rowRegister.NewCompany = newCompanyMap[v]
  1507. continue
  1508. }
  1509. // 合同类型
  1510. if k == 2 {
  1511. if !utils.InArrayByStr(contractTypeArr, v) {
  1512. resp.Fail(fmt.Sprintf("第%d行合同类型有误, 请按模板导入", i+1), c)
  1513. return
  1514. }
  1515. rowRegister.ContractType = contractTypeMap[v]
  1516. if rowRegister.ContractType == 0 {
  1517. resp.Fail(fmt.Sprintf("第%d行合同类型匹配有误, 请按模板导入", i+1), c)
  1518. return
  1519. }
  1520. continue
  1521. }
  1522. // 销售
  1523. if k == 3 {
  1524. if v == "" {
  1525. resp.Fail(fmt.Sprintf("第%d行销售名称不可为空, 请按模板导入", i+1), c)
  1526. return
  1527. }
  1528. sellerItem := sellerMap[v]
  1529. if sellerItem == nil {
  1530. resp.Fail(fmt.Sprintf("第%d行销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  1531. return
  1532. }
  1533. rowRegister.SellerId = sellerItem.SellerId
  1534. rowRegister.SellerName = sellerItem.SellerName
  1535. continue
  1536. }
  1537. // FICC大套餐
  1538. if k == 4 {
  1539. if v == "是" {
  1540. tempItem := serviceTempNameMap[titleMap[k]]
  1541. if tempItem == nil {
  1542. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  1543. return
  1544. }
  1545. cs := &fms.ContractService{
  1546. ProductId: crm.CompanyProductFicc,
  1547. ServiceTemplateId: tempItem.ServiceTemplateId,
  1548. Title: tempItem.Title,
  1549. Value: tempItem.Value,
  1550. TableValue: tempItem.TableValue,
  1551. ChartPermissionId: tempItem.ChartPermissionId,
  1552. }
  1553. cs.Set()
  1554. rowServices = append(rowServices, cs)
  1555. }
  1556. continue
  1557. }
  1558. // FICC小套餐
  1559. if k >= 5 && k <= 25 {
  1560. // 小套餐权限
  1561. if v == "是" {
  1562. rowChartPermissionIdArr = append(rowChartPermissionIdArr, strconv.Itoa(chartPermissionNameIdMap[titleMap[k]]))
  1563. }
  1564. continue
  1565. }
  1566. // 其他类型套餐
  1567. if k >= 26 && k <= 32 {
  1568. if v == "是" {
  1569. tempItem := serviceTempNameMap[titleMap[k]]
  1570. if tempItem == nil {
  1571. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  1572. return
  1573. }
  1574. cs := &fms.ContractService{
  1575. ProductId: crm.CompanyProductFicc,
  1576. ServiceTemplateId: tempItem.ServiceTemplateId,
  1577. Title: tempItem.Title,
  1578. Value: tempItem.Value,
  1579. TableValue: tempItem.TableValue,
  1580. ChartPermissionId: tempItem.ChartPermissionId,
  1581. }
  1582. cs.Set()
  1583. rowServices = append(rowServices, cs)
  1584. }
  1585. continue
  1586. }
  1587. // 套餐备注
  1588. if k == 33 {
  1589. rowRegister.ServiceRemark = v
  1590. continue
  1591. }
  1592. // 开始时间/到期时间
  1593. if k == 34 {
  1594. // 转换失败可能是因为格式为Excel日期格式, 读取出来会是一串数字, 将其转换成日期字符串再处理
  1595. va := cell.Value
  1596. if va == "" {
  1597. resp.Fail(fmt.Sprintf("第%d行开始时间不可为空, 请按模板导入", i+1), c)
  1598. return
  1599. }
  1600. startDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1601. if e != nil {
  1602. d := utils.ConvertToFormatDay(va, "2006/01/02")
  1603. startDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1604. if e != nil {
  1605. resp.Fail(fmt.Sprintf("第%d行开始时间格式转换有误, 请按模板导入", i+1), c)
  1606. return
  1607. }
  1608. }
  1609. // 转换后的日期小于1900-01-01表示当前生成的日期是有问题的
  1610. if startDate.Before(checkDate) {
  1611. resp.Fail(fmt.Sprintf("第%d行开始时间格式有误, 请按模板导入", i+1), c)
  1612. return
  1613. }
  1614. rowRegister.StartDate = startDate
  1615. continue
  1616. }
  1617. if k == 35 {
  1618. va := cell.Value
  1619. if va == "" {
  1620. resp.Fail(fmt.Sprintf("第%d行到期时间不可为空, 请按模板导入", i+1), c)
  1621. return
  1622. }
  1623. endDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1624. if e != nil {
  1625. d := utils.ConvertToFormatDay(va, "2006/01/02")
  1626. endDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1627. if e != nil {
  1628. resp.Fail(fmt.Sprintf("第%d行到期时间格式转换有误, 请按模板导入", i+1), c)
  1629. return
  1630. }
  1631. }
  1632. if endDate.Before(checkDate) {
  1633. resp.Fail(fmt.Sprintf("第%d行到期时间格式有误, 请按模板导入", i+1), c)
  1634. return
  1635. }
  1636. rowRegister.EndDate = endDate
  1637. continue
  1638. }
  1639. // 合同金额
  1640. if k == 36 {
  1641. amountStr := v
  1642. amount, e := strconv.ParseFloat(amountStr, 64)
  1643. if e != nil {
  1644. resp.Fail(fmt.Sprintf("第%d行合同金额有误, 请按模板导入", i+1), c)
  1645. return
  1646. }
  1647. rowRegister.ContractAmount = amount
  1648. continue
  1649. }
  1650. // 约定付款日期
  1651. if k == 37 {
  1652. rowRegister.AgreedPayTime = v
  1653. continue
  1654. }
  1655. // 签订日
  1656. if k == 38 {
  1657. va := cell.Value
  1658. if va == "" {
  1659. continue
  1660. }
  1661. signDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1662. if e != nil {
  1663. d := utils.ConvertToFormatDay(va, "2006/01/02")
  1664. signDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1665. if e != nil {
  1666. resp.Fail(fmt.Sprintf("第%d行签订日格式转换有误, 请按模板导入", i+1), c)
  1667. return
  1668. }
  1669. }
  1670. if signDate.Before(checkDate) {
  1671. resp.Fail(fmt.Sprintf("第%d行签订日格式有误, 请按模板导入", i+1), c)
  1672. return
  1673. }
  1674. rowRegister.SignDate = signDate
  1675. continue
  1676. }
  1677. // 合同状态
  1678. if k == 39 {
  1679. rowRegister.ContractStatus = fms.ContractStatusNameKeyMap[v]
  1680. if rowRegister.ContractStatus == 0 {
  1681. resp.Fail(fmt.Sprintf("第%d行合同状态不匹配, 请按模板导入", i+1), c)
  1682. return
  1683. }
  1684. continue
  1685. }
  1686. // 合同编号
  1687. if k == 40 {
  1688. rowContractCode := v
  1689. if rowContractCode == "" {
  1690. resp.Fail(fmt.Sprintf("第%d行合同编号不可为空, 请按模板导入", i+1), c)
  1691. return
  1692. }
  1693. if utils.InArrayByStr(contractCodeArr, rowContractCode) {
  1694. // 此合同已登记, 跳过本行的读取
  1695. isSkip = true
  1696. break
  1697. }
  1698. rowRegister.ContractCode = rowContractCode
  1699. continue
  1700. }
  1701. // 合规备注
  1702. if k == 41 {
  1703. rowRegister.Remark = v
  1704. continue
  1705. }
  1706. // 开票列表
  1707. k2 := 41
  1708. for ir := 0; ir < invoiceMax; ir++ {
  1709. n := ir + 1
  1710. // 开票日
  1711. k2 += 1
  1712. if k == k2 {
  1713. if v != "" {
  1714. va := cell.Value
  1715. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1716. if e != nil {
  1717. d := utils.ConvertToFormatDay(va, "2006/01/02")
  1718. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1719. if e != nil {
  1720. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式转换有误, 请按模板导入", i+1, n), c)
  1721. return
  1722. }
  1723. }
  1724. if invoiceDate.Before(checkDate) {
  1725. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式有误, 请按模板导入", i+1, n), c)
  1726. return
  1727. }
  1728. rowInvoices[ir].InvoiceDate = invoiceDate
  1729. rowInvoices[ir].ContractCode = rowRegister.ContractCode
  1730. rowInvoices[ir].InvoiceType = fms.ContractInvoiceTypeMake
  1731. }
  1732. continue
  1733. }
  1734. // 开票金额
  1735. k2 += 1
  1736. if k == k2 {
  1737. if v != "" {
  1738. amountStr := v
  1739. amount, e := strconv.ParseFloat(amountStr, 64)
  1740. if e != nil {
  1741. resp.Fail(fmt.Sprintf("第%d行开票金额%d有误, 请按模板导入", i+1, n), c)
  1742. return
  1743. }
  1744. rowInvoices[ir].Amount = amount
  1745. }
  1746. continue
  1747. }
  1748. // 开票销售
  1749. k2 += 1
  1750. if k == k2 {
  1751. if v != "" {
  1752. sellerItem := sellerMap[v]
  1753. if sellerItem == nil {
  1754. resp.Fail(fmt.Sprintf("第%d行开票销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  1755. return
  1756. }
  1757. rowInvoices[ir].SellerId = sellerItem.SellerId
  1758. rowInvoices[ir].SellerName = sellerItem.SellerName
  1759. rowInvoices[ir].SellerGroupId = sellerItem.GroupId
  1760. rowInvoices[ir].SellerGroupName = sellerItem.GroupName
  1761. rowInvoices[ir].SellerTeamId = sellerItem.TeamId
  1762. rowInvoices[ir].SellerTeamName = sellerItem.TeamName
  1763. }
  1764. continue
  1765. }
  1766. // 备注
  1767. k2 += 1
  1768. if k == k2 {
  1769. if v != "" {
  1770. rowInvoices[ir].Remark = v
  1771. }
  1772. continue
  1773. }
  1774. }
  1775. // 到款列表
  1776. for ir := 0; ir < invoiceMax; ir++ {
  1777. n := ir + 1
  1778. // 到款日
  1779. k2 += 1
  1780. if k == k2 {
  1781. if v != "" {
  1782. va := cell.Value
  1783. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  1784. if e != nil {
  1785. d := utils.ConvertToFormatDay(va, "2006/01/02")
  1786. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  1787. if e != nil {
  1788. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式转换有误, 请按模板导入", i+1, n), c)
  1789. return
  1790. }
  1791. }
  1792. if invoiceDate.Before(checkDate) {
  1793. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式有误, 请按模板导入", i+1, n), c)
  1794. return
  1795. }
  1796. rowPayments[ir].InvoiceDate = invoiceDate
  1797. rowPayments[ir].ContractCode = rowRegister.ContractCode
  1798. rowPayments[ir].InvoiceType = fms.ContractInvoiceTypePay
  1799. }
  1800. continue
  1801. }
  1802. // 到款金额
  1803. k2 += 1
  1804. if k == k2 {
  1805. if v != "" {
  1806. amountStr := v
  1807. amount, e := strconv.ParseFloat(amountStr, 64)
  1808. if e != nil {
  1809. resp.Fail(fmt.Sprintf("第%d行到款金额%d有误, 请按模板导入", i+1, n), c)
  1810. return
  1811. }
  1812. // 付款方式
  1813. dayDiff := rowRegister.EndDate.Sub(rowRegister.StartDate).Hours() / 24
  1814. contractAmount := rowRegister.ContractAmount
  1815. payType := fmsService.CalculateContractPaymentType(amount, contractAmount, dayDiff)
  1816. rowPayments[ir].Amount = amount
  1817. rowPayments[ir].PayType = payType
  1818. }
  1819. continue
  1820. }
  1821. // 备注
  1822. k2 += 1
  1823. if k == k2 {
  1824. if v != "" {
  1825. rowPayments[ir].Remark = v
  1826. }
  1827. continue
  1828. }
  1829. }
  1830. }
  1831. if isSkip {
  1832. continue
  1833. }
  1834. // 小套餐
  1835. if len(rowChartPermissionIdArr) > 0 {
  1836. // 说明有小套餐
  1837. tempItem := serviceTempNameMap["FICC小套餐"]
  1838. if tempItem == nil {
  1839. resp.Fail(fmt.Sprintf("第%d行小套餐名称不匹配, 请按模板导入", i+1), c)
  1840. return
  1841. }
  1842. rowChartPermissionIds := strings.Join(rowChartPermissionIdArr, ",")
  1843. cs := &fms.ContractService{
  1844. ProductId: crm.CompanyProductFicc,
  1845. ServiceTemplateId: tempItem.ServiceTemplateId,
  1846. Title: tempItem.Title,
  1847. Value: tempItem.Value,
  1848. TableValue: tempItem.TableValue,
  1849. ChartPermissionId: tempItem.ChartPermissionId,
  1850. ChartPermissionIds: rowChartPermissionIds,
  1851. }
  1852. cs.Set()
  1853. rowServices = append(rowServices, cs)
  1854. }
  1855. // 如果导入的最后一条合同编号为空并且合同编号之后的字段均为空
  1856. // excel这个包读行的时候不会再往后面没数据的地方读取, 所以此处需要重新判断一次
  1857. if rowRegister.ContractCode == "" {
  1858. resp.Fail(fmt.Sprintf("第%d行合同编号为空", i+1), c)
  1859. return
  1860. }
  1861. rowRegister.RegisterStatus = fms.ContractRegisterStatusIng
  1862. lastInvoices := make([]*fms.ContractInvoice, 0)
  1863. // 过滤信息不完整的开票到款
  1864. for l := range rowInvoices {
  1865. if rowInvoices[l].ContractCode != "" && rowInvoices[l].SellerId > 0 {
  1866. lastInvoices = append(lastInvoices, rowInvoices[l])
  1867. }
  1868. }
  1869. for l := range rowPayments {
  1870. if rowPayments[l].ContractCode != "" {
  1871. lastInvoices = append(lastInvoices, rowPayments[l])
  1872. }
  1873. }
  1874. // 新增登记、套餐、开票到款信息
  1875. newId, e := fms.CreateImportContractRegister(rowRegister, rowServices, lastInvoices)
  1876. if e != nil {
  1877. resp.FailData(fmt.Sprintf("第%d行导入失败", i+1), "新增导入登记失败, Err: "+e.Error(), c)
  1878. return
  1879. }
  1880. newIds = append(newIds, newId)
  1881. }
  1882. }
  1883. }
  1884. resp.Ok("操作成功", c)
  1885. }
  1886. // CurrencyList
  1887. // @Title 货币单位列表
  1888. // @Description 货币单位列表
  1889. // @Success 200 {object} fms.CurrencyUnitItem
  1890. // @router /contract/register/currency_list [get]
  1891. func (rg *RegisterController) CurrencyList(c *gin.Context) {
  1892. // 货币列表
  1893. ob := new(fms.CurrencyUnit)
  1894. cond := `enable = 1`
  1895. pars := make([]interface{}, 0)
  1896. list, e := ob.List(cond, pars)
  1897. if e != nil {
  1898. resp.FailData("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  1899. return
  1900. }
  1901. rateMap := make(map[string]float64)
  1902. rateList := make([]*fmsService.CurrencyRateItem, 0)
  1903. // 读取缓存
  1904. cacheJson, _ := global.Redis.Get(context.TODO(), utils.CURRENCY_RMB_RATE).Result()
  1905. if cacheJson != "" {
  1906. if e = jsoniter.UnmarshalFromString(cacheJson, &rateList); e != nil {
  1907. resp.FailData("获取失败", "读取汇率缓存失败, Err: "+e.Error(), c)
  1908. return
  1909. }
  1910. }
  1911. // 请求汇率接口
  1912. if cacheJson == "" {
  1913. rateList, e = fmsService.CurlRateApi()
  1914. if e != nil {
  1915. resp.FailData("获取失败", "请求汇率接口失败, Err: "+e.Error(), c)
  1916. return
  1917. }
  1918. newCache, e := jsoniter.MarshalToString(rateList)
  1919. if e != nil {
  1920. resp.FailData("获取失败", "写入汇率缓存失败, Err: "+e.Error(), c)
  1921. return
  1922. }
  1923. now := time.Now()
  1924. todayLast := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, time.Local)
  1925. sub := todayLast.Sub(now)
  1926. _ = global.Redis.SetEX(context.TODO(), utils.CURRENCY_RMB_RATE, newCache, sub)
  1927. }
  1928. for i := range rateList {
  1929. rateMap[rateList[i].Code] = rateList[i].Rate
  1930. }
  1931. respList := make([]*fms.CurrencyUnitItem, 0)
  1932. for i := range list {
  1933. respList = append(respList, &fms.CurrencyUnitItem{
  1934. Name: list[i].Name,
  1935. Code: list[i].Code,
  1936. Enable: list[i].Enable,
  1937. RMBRate: rateMap[list[i].Code],
  1938. })
  1939. }
  1940. resp.OkData("获取成功", respList, c)
  1941. }