register.go 66 KB

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