register.go 72 KB

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