register.go 71 KB

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