register.go 72 KB

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