register.go 71 KB

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