register.go 62 KB

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