register.go 67 KB

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