register.go 71 KB

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