register.go 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823
  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 rai_seller_name LIKE ? OR actual_company_name LIKE ?)`
  57. pars = append(pars, kw, 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.ServiceTypes != "" {
  75. serviceTypes := strings.Split(req.ServiceTypes, ",")
  76. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  77. if e != nil {
  78. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  79. return
  80. }
  81. if len(registerIds) > 0 {
  82. cond += ` AND contract_register_id IN ?`
  83. pars = append(pars, registerIds)
  84. } else {
  85. cond += ` AND 1 = 2`
  86. }
  87. }
  88. page := new(base.Page)
  89. page.SetPageSize(req.PageSize)
  90. page.SetCurrent(req.Current)
  91. page.AddOrderItem(base.OrderItem{Column: "create_time", Asc: false})
  92. total, list, e := fms.GetContractRegisterItemPageList(page, cond, pars)
  93. if e != nil {
  94. resp.FailMsg("获取失败", "获取合同登记列表失败, Err: "+e.Error(), c)
  95. return
  96. }
  97. registerIds := make([]int, 0)
  98. for i := range list {
  99. registerIds = append(registerIds, list[i].ContractRegisterId)
  100. }
  101. serviceMap := make(map[int]string, 0)
  102. invoiceMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  103. paymentMap := make(map[int][]*fms.ContractInvoiceItem, 0)
  104. if len(registerIds) > 0 {
  105. // 获取所有的服务套餐
  106. serviceMap, _, e = fmsService.GetContractServiceNameFormat(registerIds)
  107. if e != nil {
  108. resp.FailMsg("获取失败", e.Error(), c)
  109. return
  110. }
  111. // 获取开票/到款列表
  112. invoiceCond := `contract_register_id IN ?`
  113. invoicePars := make([]interface{}, 0)
  114. invoicePars = append(invoicePars, registerIds)
  115. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  116. if e != nil {
  117. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  118. return
  119. }
  120. for i := range invoiceList {
  121. if invoiceMap[invoiceList[i].ContractRegisterId] == nil {
  122. invoiceMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  123. }
  124. if paymentMap[invoiceList[i].ContractRegisterId] == nil {
  125. paymentMap[invoiceList[i].ContractRegisterId] = make([]*fms.ContractInvoiceItem, 0)
  126. }
  127. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  128. invoiceMap[invoiceList[i].ContractRegisterId] = append(invoiceMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  129. }
  130. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  131. paymentMap[invoiceList[i].ContractRegisterId] = append(paymentMap[invoiceList[i].ContractRegisterId], invoiceList[i])
  132. }
  133. }
  134. }
  135. respList := make([]*fms.ContractRegisterList, 0)
  136. for i := range list {
  137. v := new(fms.ContractRegisterList)
  138. v.ContractRegisterItem = list[i]
  139. v.ServicesName = serviceMap[list[i].ContractRegisterId]
  140. v.InvoiceList = invoiceMap[list[i].ContractRegisterId]
  141. v.PaymentList = paymentMap[list[i].ContractRegisterId]
  142. respList = append(respList, v)
  143. }
  144. page.SetTotal(total)
  145. baseData := new(base.BaseData)
  146. baseData.SetPage(page)
  147. baseData.SetList(respList)
  148. resp.OkData("获取成功", baseData, c)
  149. }
  150. // Add
  151. // @Title 新增合同登记
  152. // @Description 新增合同登记
  153. // @Param request body fms.ContractRegisterAddReq true "type json string"
  154. // @Success 200 string "操作成功"
  155. // @router /contract/register/add [post]
  156. func (rg *RegisterController) Add(c *gin.Context) {
  157. req := new(fms.ContractRegisterAddReq)
  158. err := c.ShouldBind(&req)
  159. if err != nil {
  160. errs, ok := err.(validator.ValidationErrors)
  161. if !ok {
  162. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  163. return
  164. }
  165. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  166. return
  167. }
  168. claims, _ := c.Get("adminInfo")
  169. adminInfo := claims.(*system.SysAdmin)
  170. // 日期校验
  171. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  172. if e != nil {
  173. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  174. return
  175. }
  176. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  177. if e != nil {
  178. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  179. return
  180. }
  181. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  182. if req.SignDate != "" {
  183. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  184. if e != nil {
  185. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  186. return
  187. }
  188. signDate = signDateTime
  189. }
  190. // 是否存在相同合同编号的登记
  191. ob := new(fms.ContractRegister)
  192. existCond := `contract_code = ?`
  193. existPars := make([]interface{}, 0)
  194. existPars = append(existPars, req.ContractCode)
  195. exist, e := ob.FetchByCondition(existCond, existPars)
  196. if e != nil && e != utils.ErrNoRow {
  197. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  198. return
  199. }
  200. if exist != nil && exist.ContractRegisterId > 0 {
  201. resp.Fail("合同编号已存在", c)
  202. return
  203. }
  204. // 货币及汇率
  205. rateList, e := fmsService.GetTodayCurrencyRateList()
  206. if e != nil {
  207. resp.FailMsg("操作失败", "获取今日货币汇率失败, Err: "+e.Error(), c)
  208. return
  209. }
  210. var rate float64
  211. for i := range rateList {
  212. if req.CurrencyUnit == rateList[i].Code {
  213. rate = rateList[i].RMBRate
  214. break
  215. }
  216. }
  217. if rate <= 0 {
  218. resp.FailMsg("操作失败", "货币汇率信息有误", c)
  219. return
  220. }
  221. // 查询销售信息
  222. var (
  223. sellerId int
  224. raiSellerId int
  225. sellerName string
  226. raiSellerName string
  227. )
  228. if req.SellerIds != "" {
  229. admin := new(crm.Admin)
  230. sellerIds := strings.Split(req.SellerIds, ",")
  231. if len(sellerIds) > 2 {
  232. resp.Fail("最多只能选择两个销售", c)
  233. return
  234. }
  235. var pars []interface{}
  236. cond := ` admin_id in (?) `
  237. pars = append(pars, sellerIds)
  238. sellers, e := admin.List(cond, pars)
  239. if e != nil {
  240. resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
  241. return
  242. }
  243. for _, v := range sellers {
  244. if v.DepartmentId == crm.SellerDepartmentId {
  245. sellerId = v.AdminId
  246. sellerName = v.AdminName
  247. }else if v.DepartmentId == crm.RaiSellerDepartmentId {
  248. raiSellerId = v.AdminId
  249. raiSellerName = v.AdminName
  250. }
  251. }
  252. }
  253. nowTime := time.Now().Local()
  254. ob.ContractCode = req.ContractCode
  255. ob.RelateContractCode = req.RelateContractCode
  256. ob.CrmContractId = req.CrmContractId
  257. ob.ContractSource = req.ContractSource
  258. ob.CompanyName = req.CompanyName
  259. ob.ActualCompanyName = req.ActualCompanyName
  260. ob.ProductIds = req.ProductIds
  261. ob.SellerId = sellerId
  262. ob.SellerName = sellerName
  263. ob.RaiSellerId = raiSellerId
  264. ob.RaiSellerName = raiSellerName
  265. ob.ContractType = req.ContractType
  266. ob.ContractAmount = req.ContractAmount
  267. ob.CurrencyUnit = req.CurrencyUnit
  268. ob.RMBRate = rate
  269. ob.StartDate = startDate
  270. ob.EndDate = endDate
  271. ob.SignDate = signDate
  272. ob.AgreedPayTime = req.AgreedPayTime
  273. ob.ContractStatus = req.ContractStatus
  274. ob.RegisterStatus = fms.ContractRegisterStatusIng
  275. ob.Remark = req.Remark
  276. ob.ServiceRemark = req.ServiceRemark
  277. ob.HasPayment = req.HasPayment
  278. ob.NewCompany = req.NewCompany
  279. ob.Set()
  280. // 存在代付的直接完成登记, 且不允许进行开票/到款登记
  281. if req.HasPayment == 1 || req.ContractStatus == fms.ContractStatusEnd {
  282. ob.RegisterStatus = fms.ContractRegisterStatusComplete
  283. }
  284. // 新增套餐金额详情内容
  285. serviceAmountMap := make(map[int]float64)
  286. serviceAmountList, e := fmsService.HandleContractServiceAmount(req.ServiceAmount, serviceAmountMap, req.CurrencyUnit)
  287. if e != nil {
  288. resp.FailMsg("操作失败", "新增合同套餐金额信息失败, Err: "+e.Error(), c)
  289. return
  290. }
  291. // 套餐信息
  292. serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
  293. if e != nil {
  294. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  295. return
  296. }
  297. // 新增合同及套餐
  298. if req.Supplement == 1 {
  299. //新增到款信息
  300. if ob.HasPayment == 1 {
  301. resp.Fail("合同存在代付不允许添加开票/到款登记", c)
  302. return
  303. }
  304. //新增合同信息
  305. if e = fms.CreateContractRegisterAndServicesAndPayMent(ob, serviceList, req.PrePayId); e != nil {
  306. resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
  307. return
  308. }
  309. prePayOB := new(fms.ContractPrePayment)
  310. ppItem, e := prePayOB.Fetch(req.PrePayId)
  311. if e != nil {
  312. if e == utils.ErrNoRow {
  313. resp.Fail("预到款不存在或已被删除", c)
  314. return
  315. }
  316. resp.FailMsg("获取预到款记录失败", "Err:"+e.Error(), c)
  317. return
  318. }
  319. // 合同有效时长(计算付款方式)
  320. dayDiff := ob.EndDate.Sub(ob.StartDate).Hours() / 24
  321. // 获取销售分组信息
  322. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  323. if e != nil {
  324. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  325. return
  326. }
  327. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  328. for i := range sellerList {
  329. sellerMap[sellerList[i].SellerId] = sellerList[i]
  330. }
  331. v := &fms.ContractInvoice{
  332. ContractRegisterId: ob.ContractRegisterId,
  333. ContractCode: ob.ContractCode,
  334. Amount: ppItem.Amount,
  335. OriginAmount: ppItem.OriginAmount,
  336. CurrencyUnit: ppItem.CurrencyUnit,
  337. InvoiceType: fms.ContractInvoiceTypePay,
  338. InvoiceDate: ppItem.CreateTime,
  339. AdminId: int(adminInfo.AdminId),
  340. AdminName: adminInfo.RealName,
  341. Remark: ppItem.Remark,
  342. IsPrePay: 1,
  343. }
  344. v.Set()
  345. // 到款登记-付款方式
  346. v.PayType = fmsService.CalculateContractPaymentType(ppItem.Amount, ob.ContractAmount, dayDiff)
  347. // 新增的记录
  348. logList := make([]*fms.ContractRegisterLog, 0)
  349. opData := ""
  350. opDataByte, e := json.Marshal(req)
  351. if e != nil {
  352. return
  353. }
  354. opData = string(opDataByte)
  355. opType := fms.ContractInvoiceTypePrePay
  356. newAmount := decimal.NewFromFloat(0).Round(2)
  357. a := decimal.NewFromFloat(v.Amount).Round(2)
  358. newAmount = newAmount.Add(a)
  359. ia, _ := newAmount.Round(2).Float64()
  360. logList = append(logList, &fms.ContractRegisterLog{
  361. ContractRegisterId: ob.ContractRegisterId,
  362. AdminId: int(adminInfo.AdminId),
  363. AdminName: adminInfo.RealName,
  364. OpData: opData,
  365. OpType: opType,
  366. CreateTime: nowTime,
  367. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  368. })
  369. if e := v.Create(); e != nil {
  370. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  371. return
  372. }
  373. //最后删除预到款记录
  374. e = ppItem.Delete()
  375. if e != nil {
  376. resp.FailMsg("删除预到款记录失败", "Err:"+e.Error(), c)
  377. return
  378. }
  379. // 校验金额-是否修改状态
  380. go fmsService.CheckContractRegisterAmount(ob.ContractRegisterId)
  381. // 开票到款汇总
  382. go fmsService.SummaryInvoicePaymentByContractRegisterId(ob.ContractRegisterId)
  383. // 操作日志
  384. go func() {
  385. logOB := new(fms.ContractRegisterLog)
  386. if e := logOB.AddInBatches(logList); e != nil {
  387. return
  388. }
  389. }()
  390. } else {
  391. if e = fms.CreateContractRegisterAndServices(ob, serviceList, serviceAmountList); e != nil {
  392. resp.FailMsg("操作失败", "新增合同及套餐失败, Err: "+e.Error(), c)
  393. return
  394. }
  395. }
  396. // 操作日志
  397. go func() {
  398. opData := ""
  399. opDataByte, e := json.Marshal(req)
  400. if e != nil {
  401. return
  402. }
  403. opData = string(opDataByte)
  404. logItem := new(fms.ContractRegisterLog)
  405. logItem.ContractRegisterId = ob.ContractRegisterId
  406. logItem.AdminId = int(adminInfo.AdminId)
  407. logItem.AdminName = adminInfo.RealName
  408. logItem.OpData = opData
  409. logItem.OpType = fms.ContractRegisterOpTypeSave
  410. logItem.CreateTime = nowTime
  411. logItem.Remark = req.Remark
  412. if e = logItem.Create(); e != nil {
  413. return
  414. }
  415. }()
  416. resp.Ok("操作成功", c)
  417. }
  418. // Edit
  419. // @Title 编辑合同登记
  420. // @Description 编辑合同登记
  421. // @Param request body fms.ContractRegisterEditReq true "type json string"
  422. // @Success 200 string "操作成功"
  423. // @router /contract/register/edit [post]
  424. func (rg *RegisterController) Edit(c *gin.Context) {
  425. req := new(fms.ContractRegisterEditReq)
  426. err := c.ShouldBind(&req)
  427. if err != nil {
  428. errs, ok := err.(validator.ValidationErrors)
  429. if !ok {
  430. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  431. return
  432. }
  433. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  434. return
  435. }
  436. claims, _ := c.Get("adminInfo")
  437. adminInfo := claims.(*system.SysAdmin)
  438. // 日期校验
  439. startDate, e := time.ParseInLocation(utils.FormatDate, req.StartDate, time.Local)
  440. if e != nil {
  441. resp.FailMsg("合同开始日期格式有误", "合同开始日期格式有误, Err: "+e.Error(), c)
  442. return
  443. }
  444. endDate, e := time.ParseInLocation(utils.FormatDate, req.EndDate, time.Local)
  445. if e != nil {
  446. resp.FailMsg("合同结束日期格式有误", "合同结束日期格式有误, Err: "+e.Error(), c)
  447. return
  448. }
  449. signDate, _ := time.ParseInLocation(utils.FormatDate, "0000-00-00", time.Local)
  450. if req.SignDate != "" {
  451. signDateTime, e := time.ParseInLocation(utils.FormatDate, req.SignDate, time.Local)
  452. if e != nil {
  453. resp.FailMsg("合同签订日期格式有误", "合同签订日期格式有误, Err: "+e.Error(), c)
  454. return
  455. }
  456. signDate = signDateTime
  457. }
  458. ob := new(fms.ContractRegister)
  459. item, e := ob.Fetch(req.ContractRegisterId)
  460. if e != nil {
  461. if e == utils.ErrNoRow {
  462. resp.Fail("登记记录不存在或已被删除", c)
  463. return
  464. }
  465. resp.FailMsg("操作失败", "获取合同登记信息失败, Err:"+e.Error(), c)
  466. return
  467. }
  468. // 查询销售信息
  469. var (
  470. sellerId int
  471. raiSellerId int
  472. sellerName string
  473. raiSellerName string
  474. )
  475. if req.SellerIds != "" {
  476. admin := new(crm.Admin)
  477. sellerIds := strings.Split(req.SellerIds, ",")
  478. if len(sellerIds) > 2 {
  479. resp.Fail("最多只能选择两个销售", c)
  480. return
  481. }
  482. var pars []interface{}
  483. cond := ` admin_id in (?) `
  484. pars = append(pars, sellerIds)
  485. sellers, e := admin.List(cond, pars)
  486. if e != nil {
  487. resp.FailMsg("获取销售信息失败", "获取销售信息失败, Err: "+e.Error(), c)
  488. return
  489. }
  490. for _, v := range sellers {
  491. if v.DepartmentId == crm.SellerDepartmentId {
  492. sellerId = v.AdminId
  493. sellerName = v.AdminName
  494. }else if v.DepartmentId == crm.RaiSellerDepartmentId {
  495. raiSellerId = v.AdminId
  496. raiSellerName = v.AdminName
  497. }
  498. }
  499. }
  500. // 是否存在相同合同编号的登记
  501. existCond := `contract_code = ?`
  502. existPars := make([]interface{}, 0)
  503. existPars = append(existPars, req.ContractCode)
  504. exist, e := ob.FetchByCondition(existCond, existPars)
  505. if e != nil && e != utils.ErrNoRow {
  506. resp.FailMsg("操作失败", "获取相同登记号失败, Err: "+e.Error(), c)
  507. return
  508. }
  509. if exist != nil && exist.ContractRegisterId > 0 && exist.ContractRegisterId != item.ContractRegisterId {
  510. resp.Fail("合同编号已存在", c)
  511. return
  512. }
  513. originHasPayment := item.HasPayment
  514. updateCols := []string{
  515. "ProductIds","ContractCode", "RelateContractCode", "CrmContractId", "ContractSource", "CompanyName", "ActualCompanyName",
  516. "SellerId", "SellerName", "ContractType", "ContractAmount", "StartDate", "EndDate", "SignDate", "AgreedPayTime",
  517. "ContractStatus", "RegisterStatus", "Remark", "ServiceRemark", "HasPayment", "NewCompany", "ModifyTime",
  518. }
  519. nowTime := time.Now().Local()
  520. item.ProductIds = req.ProductIds
  521. item.ContractCode = req.ContractCode
  522. item.RelateContractCode = req.RelateContractCode
  523. item.CrmContractId = req.CrmContractId
  524. item.ContractSource = req.ContractSource
  525. item.CompanyName = req.CompanyName
  526. item.ActualCompanyName = req.ActualCompanyName
  527. item.SellerId = sellerId
  528. item.SellerName = sellerName
  529. item.RaiSellerId = raiSellerId
  530. item.RaiSellerName = raiSellerName
  531. item.ContractType = req.ContractType
  532. item.ContractAmount = req.ContractAmount
  533. item.StartDate = startDate
  534. item.EndDate = endDate
  535. item.SignDate = signDate
  536. item.AgreedPayTime = req.AgreedPayTime
  537. item.ContractStatus = req.ContractStatus
  538. item.RegisterStatus = fms.ContractRegisterStatusIng
  539. item.Remark = req.Remark
  540. item.ServiceRemark = req.ServiceRemark
  541. item.HasPayment = req.HasPayment
  542. item.NewCompany = req.NewCompany
  543. item.ModifyTime = nowTime
  544. // 存在代付的直接完成登记, 且不允许进行开票/到款登记
  545. if req.HasPayment == 1 {
  546. item.RegisterStatus = fms.ContractRegisterStatusComplete
  547. updateCols = append(updateCols, "RegisterStatus")
  548. }
  549. // 开票到款信息
  550. invoiceOB := new(fms.ContractInvoice)
  551. invoiceCond := `contract_register_id = ?`
  552. invoicePars := make([]interface{}, 0)
  553. invoicePars = append(invoicePars, req.ContractRegisterId)
  554. invoiceList, e := invoiceOB.List(invoiceCond, invoicePars, "")
  555. if e != nil {
  556. resp.FailMsg("操作失败", "获取合同开票到款列表失败, Err: "+e.Error(), c)
  557. return
  558. }
  559. invoiceUpdateCols := make([]string, 0)
  560. // 开票到款操作类型: 0-无; 1-更新; 2-删除;
  561. logRemark := req.Remark
  562. invoiceHandleType := 0
  563. if originHasPayment == 0 && req.HasPayment == 1 {
  564. // 若从无代付修改为有代付, 则删除无代付期间新增的所有开票到款登记
  565. invoiceHandleType = 2
  566. } else {
  567. // 修改了货币单位后,同步更新汇率及开票到款的换算金额
  568. if req.CurrencyUnit != item.CurrencyUnit {
  569. rateList, e := fmsService.GetTodayCurrencyRateList()
  570. if e != nil {
  571. resp.FailMsg("操作失败", "获取货币列表及汇率失败, Err: "+e.Error(), c)
  572. return
  573. }
  574. var rate float64
  575. for i := range rateList {
  576. if rateList[i].Code == req.CurrencyUnit {
  577. rate = rateList[i].RMBRate
  578. break
  579. }
  580. }
  581. if rate < 0 {
  582. resp.FailMsg("操作失败", "货币汇率有误", c)
  583. return
  584. }
  585. item.CurrencyUnit = req.CurrencyUnit
  586. item.RMBRate = rate
  587. updateCols = append(updateCols, "CurrencyUnit", "RMBRate")
  588. // 调整开票到款换算后的金额, 保留两位小数
  589. for i := range invoiceList {
  590. invoiceList[i].CurrencyUnit = req.CurrencyUnit
  591. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceList[i].OriginAmount/rate), 64)
  592. invoiceList[i].Amount = a
  593. }
  594. invoiceUpdateCols = append(invoiceUpdateCols, "CurrencyUnit", "Amount")
  595. invoiceHandleType = 1
  596. logRemark = fmt.Sprintf("金额单位由%s修改为%s\n%s", item.CurrencyUnit, req.CurrencyUnit, logRemark)
  597. }
  598. }
  599. // 新增套餐金额详情内容
  600. serviceAmountMap := make(map[int]float64)
  601. serviceAmountList, e := fmsService.HandleContractServiceAmount(req.ServiceAmount, serviceAmountMap, req.CurrencyUnit)
  602. if e != nil {
  603. resp.FailMsg("操作失败", "新增合同套餐金额信息失败, Err: "+e.Error(), c)
  604. return
  605. }
  606. // 套餐信息
  607. serviceList, e := fmsService.HandleContractServiceAndDetail(req.Services, true, serviceAmountMap)
  608. if e != nil {
  609. resp.FailMsg("操作失败", "获取合同套餐详情失败, Err: "+e.Error(), c)
  610. return
  611. }
  612. // 更新合同登记、套餐、开票到款
  613. if e = fms.UpdateContractRegister(item, updateCols, serviceList, invoiceList, invoiceUpdateCols, invoiceHandleType, serviceAmountList); e != nil {
  614. resp.FailMsg("操作失败", "更新合同及套餐失败, Err: "+e.Error(), c)
  615. return
  616. }
  617. // 校验金额-是否修改状态
  618. go fmsService.CheckContractRegisterAmount(item.ContractRegisterId)
  619. // 操作日志
  620. go func() {
  621. opData := ""
  622. opDataByte, e := json.Marshal(req)
  623. if e != nil {
  624. return
  625. }
  626. opData = string(opDataByte)
  627. logItem := new(fms.ContractRegisterLog)
  628. logItem.ContractRegisterId = item.ContractRegisterId
  629. logItem.AdminId = int(adminInfo.AdminId)
  630. logItem.AdminName = adminInfo.RealName
  631. logItem.OpData = opData
  632. logItem.OpType = fms.ContractRegisterOpTypeEdit
  633. logItem.CreateTime = nowTime
  634. logItem.Remark = logRemark
  635. if e = logItem.Create(); e != nil {
  636. return
  637. }
  638. }()
  639. resp.Ok("操作成功", c)
  640. }
  641. // Del
  642. // @Title 删除合同登记
  643. // @Description 删除合同登记
  644. // @Param request body fms.ContractRegisterDelReq true "type json string"
  645. // @Success 200 string "操作成功"
  646. // @router /contract/register/del [post]
  647. func (rg *RegisterController) Del(c *gin.Context) {
  648. req := new(fms.ContractRegisterDelReq)
  649. err := c.ShouldBind(&req)
  650. if err != nil {
  651. errs, ok := err.(validator.ValidationErrors)
  652. if !ok {
  653. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  654. return
  655. }
  656. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  657. return
  658. }
  659. claims, _ := c.Get("adminInfo")
  660. adminInfo := claims.(*system.SysAdmin)
  661. ob := new(fms.ContractRegister)
  662. item, e := ob.Fetch(req.ContractRegisterId)
  663. if e != nil {
  664. if e == utils.ErrNoRow {
  665. resp.Fail("合同登记不存在或已被删除", c)
  666. return
  667. }
  668. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  669. return
  670. }
  671. nowTime := time.Now().Local()
  672. item.IsDeleted = 1
  673. item.ModifyTime = nowTime
  674. updateCols := []string{"IsDeleted", "ModifyTime"}
  675. if e = item.Update(updateCols); e != nil {
  676. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  677. return
  678. }
  679. // 删除对应的开票到款登记
  680. go func() {
  681. if e = fms.DeleteContractInvoicesByRegisterId(item.ContractRegisterId); e != nil {
  682. alarm_msg.SendAlarmMsg(fmt.Sprintf("删除合同登记%d后, 删除开票到款记录失败, ErrMsg: %s", item.ContractRegisterId, e.Error()), 3)
  683. return
  684. }
  685. if e = fms.DeleteInvoicePaymentSummaryByRegisterId(item.ContractRegisterId); e != nil {
  686. alarm_msg.SendAlarmMsg(fmt.Sprintf("删除合同登记%d后, 删除开票到款汇总数据失败, ErrMsg: %s", item.ContractRegisterId, e.Error()), 3)
  687. return
  688. }
  689. }()
  690. // 操作日志
  691. go func() {
  692. opData := ""
  693. opDataByte, e := json.Marshal(req)
  694. if e != nil {
  695. return
  696. }
  697. opData = string(opDataByte)
  698. logItem := new(fms.ContractRegisterLog)
  699. logItem.ContractRegisterId = req.ContractRegisterId
  700. logItem.AdminId = int(adminInfo.AdminId)
  701. logItem.AdminName = adminInfo.RealName
  702. logItem.OpData = opData
  703. logItem.OpType = fms.ContractRegisterOpTypeDel
  704. logItem.CreateTime = nowTime
  705. if e = logItem.Create(); e != nil {
  706. return
  707. }
  708. }()
  709. resp.Ok("操作成功", c)
  710. }
  711. // Detail
  712. // @Title 合同登记详情
  713. // @Description 合同登记详情
  714. // @Param ContractRegisterId query int false "合同登记ID"
  715. // @Success 200 {object} fms.ContractRegisterDetail
  716. // @router /contract/register/detail [get]
  717. func (rg *RegisterController) Detail(c *gin.Context) {
  718. var req fms.ContractRegisterDetailReq
  719. if e := c.BindQuery(&req); e != nil {
  720. err, ok := e.(validator.ValidationErrors)
  721. if !ok {
  722. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  723. return
  724. }
  725. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  726. return
  727. }
  728. result := new(fms.ContractRegisterDetail)
  729. // 合同登记信息
  730. item, e := fms.GetContractRegisterItemById(req.ContractRegisterId)
  731. if e != nil {
  732. resp.FailData("获取失败", "获取合同登记详情失败, Err:"+e.Error(), c)
  733. return
  734. }
  735. result.ContractRegisterItem = item
  736. // 套餐信息
  737. serviceAmountTempList, e := fms.GetContractServiceAmountByRegisterId(req.ContractRegisterId)
  738. if e != nil {
  739. resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
  740. return
  741. }
  742. serviceAmountList := make([]*fms.ContractServiceAmountItem, 0)
  743. for _, v := range serviceAmountTempList {
  744. tmp := &fms.ContractServiceAmountItem{
  745. ContractRegisterId: v.ContractRegisterId,
  746. ProductId: v.ProductId,
  747. ServiceAmount: v.ServiceAmount,
  748. CurrencyUnit: v.CurrencyUnit,
  749. }
  750. serviceAmountList = append(serviceAmountList, tmp)
  751. }
  752. result.ServiceAmountList = serviceAmountList
  753. // 套餐金额信息
  754. serviceList, e := fmsService.GetContractServiceAndDetail(req.ContractRegisterId)
  755. if e != nil {
  756. resp.FailData("获取失败", "获取合同套餐信息失败, Err: "+e.Error(), c)
  757. return
  758. }
  759. result.ServiceList = serviceList
  760. // 开票/到款信息
  761. invoiceCond := `contract_register_id = ?`
  762. invoicePars := make([]interface{}, 0)
  763. invoicePars = append(invoicePars, req.ContractRegisterId)
  764. invoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  765. if e != nil {
  766. resp.FailData("获取失败", "获取合同开票/到款信息失败, Err: "+e.Error(), c)
  767. return
  768. }
  769. result.InvoiceList = make([]*fms.ContractInvoiceItem, 0)
  770. result.PaymentList = make([]*fms.ContractInvoiceItem, 0)
  771. for i := range invoiceList {
  772. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypeMake {
  773. result.InvoiceList = append(result.InvoiceList, invoiceList[i])
  774. continue
  775. }
  776. if invoiceList[i].InvoiceType == fms.ContractInvoiceTypePay {
  777. result.PaymentList = append(result.PaymentList, invoiceList[i])
  778. }
  779. }
  780. // 合同登记进度
  781. logCond := `contract_register_id = ?`
  782. logPars := make([]interface{}, 0)
  783. logPars = append(logPars, req.ContractRegisterId)
  784. logList, e := fms.GetContractRegisterLogItemList(logCond, logPars)
  785. if e != nil {
  786. resp.FailData("获取失败", "获取合同登记进度失败, Err: "+e.Error(), c)
  787. return
  788. }
  789. result.Logs = logList
  790. resp.OkData("获取成功", result, c)
  791. }
  792. // UpdateStatus
  793. // @Title 修改合同状态
  794. // @Description 修改合同状态
  795. // @Param request body fms.ContractRegisterUpdateStatusReq true "type json string"
  796. // @Success 200 string "操作成功"
  797. // @router /contract/register/update_status [post]
  798. func (rg *RegisterController) UpdateStatus(c *gin.Context) {
  799. req := new(fms.ContractRegisterUpdateStatusReq)
  800. err := c.ShouldBind(&req)
  801. if err != nil {
  802. errs, ok := err.(validator.ValidationErrors)
  803. if !ok {
  804. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  805. return
  806. }
  807. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  808. return
  809. }
  810. claims, _ := c.Get("adminInfo")
  811. adminInfo := claims.(*system.SysAdmin)
  812. ob := new(fms.ContractRegister)
  813. item, e := ob.Fetch(req.ContractRegisterId)
  814. if e != nil {
  815. if e == utils.ErrNoRow {
  816. resp.Fail("合同登记不存在或已被删除", c)
  817. return
  818. }
  819. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  820. return
  821. }
  822. nowTime := time.Now().Local()
  823. item.ContractStatus = req.ContractStatus
  824. item.ModifyTime = nowTime
  825. updateCols := []string{"ContractStatus", "ModifyTime"}
  826. if e = item.Update(updateCols); e != nil {
  827. resp.FailMsg("操作失败", "更新合同登记失败, Err:"+e.Error(), c)
  828. return
  829. }
  830. // 校验金额-是否修改状态
  831. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  832. // 操作日志
  833. go func() {
  834. opData := ""
  835. opDataByte, e := json.Marshal(req)
  836. if e != nil {
  837. return
  838. }
  839. opData = string(opDataByte)
  840. logItem := new(fms.ContractRegisterLog)
  841. logItem.ContractRegisterId = req.ContractRegisterId
  842. logItem.AdminId = int(adminInfo.AdminId)
  843. logItem.AdminName = adminInfo.RealName
  844. logItem.OpData = opData
  845. logItem.OpType = fms.ContractRegisterOpTypeStatus
  846. logItem.CreateTime = nowTime
  847. if e = logItem.Create(); e != nil {
  848. return
  849. }
  850. }()
  851. resp.Ok("操作成功", c)
  852. }
  853. // Invoice
  854. // @Title 开票/到款登记
  855. // @Description 开票/到款登记
  856. // @Param request body fms.ContractInvoiceSaveReq true "type json string"
  857. // @Success 200 string "操作成功"
  858. // @router /contract/register/invoice [post]
  859. func (rg *RegisterController) Invoice(c *gin.Context) {
  860. req := new(fms.ContractInvoiceSaveReq)
  861. err := c.ShouldBind(&req)
  862. if err != nil {
  863. errs, ok := err.(validator.ValidationErrors)
  864. if !ok {
  865. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  866. return
  867. }
  868. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  869. return
  870. }
  871. claims, _ := c.Get("adminInfo")
  872. adminInfo := claims.(*system.SysAdmin)
  873. registerOB := new(fms.ContractRegister)
  874. item, e := registerOB.Fetch(req.ContractRegisterId)
  875. if e != nil {
  876. if e == utils.ErrNoRow {
  877. resp.Fail("合同登记不存在或已被删除", c)
  878. return
  879. }
  880. resp.FailMsg("获取合同登记失败", "Err:"+e.Error(), c)
  881. return
  882. }
  883. // 合同存在代付不允许开票/到款登记
  884. if item.HasPayment == 1 {
  885. resp.Fail("合同存在代付不允许添加开票/到款登记", c)
  886. return
  887. }
  888. noChangeInvoiceIds := make([]int, 0)
  889. newInvoice := make([]*fms.ContractInvoice, 0)
  890. if len(req.AmountList) > 0 {
  891. // 合同有效时长(计算付款方式)
  892. dayDiff := item.EndDate.Sub(item.StartDate).Hours() / 24
  893. // 获取销售分组信息
  894. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  895. if e != nil {
  896. resp.FailData("获取销售失败", "Err:"+e.Error(), c)
  897. return
  898. }
  899. sellerMap := make(map[int]*crm.SellerAdminWithGroupTeam)
  900. for i := range sellerList {
  901. sellerMap[sellerList[i].SellerId] = sellerList[i]
  902. }
  903. for i := range req.AmountList {
  904. if req.AmountList[i].Amount <= 0 {
  905. resp.Fail("登记金额有误", c)
  906. return
  907. }
  908. if req.AmountList[i].InvoiceDate == "" {
  909. resp.Fail("请选择日期", c)
  910. return
  911. }
  912. // 开票登记销售必填
  913. if req.InvoiceType == fms.ContractInvoiceTypeMake && req.AmountList[i].SellerId <= 0 {
  914. resp.Fail("请选择销售", c)
  915. return
  916. }
  917. t, e := time.ParseInLocation(utils.FormatDate, req.AmountList[i].InvoiceDate, time.Local)
  918. if e != nil {
  919. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  920. return
  921. }
  922. if req.AmountList[i].InvoiceId > 0 {
  923. noChangeInvoiceIds = append(noChangeInvoiceIds, req.AmountList[i].InvoiceId)
  924. continue
  925. }
  926. if req.AmountList[i].InvoiceId == 0 {
  927. v := &fms.ContractInvoice{
  928. ContractRegisterId: req.ContractRegisterId,
  929. ContractCode: item.ContractCode,
  930. Amount: req.AmountList[i].Amount,
  931. OriginAmount: req.AmountList[i].OriginAmount,
  932. CurrencyUnit: item.CurrencyUnit,
  933. InvoiceType: req.InvoiceType,
  934. ServiceProductId: req.AmountList[i].ServiceProductId,
  935. InvoiceDate: t,
  936. AdminId: int(adminInfo.AdminId),
  937. AdminName: adminInfo.RealName,
  938. Remark: req.AmountList[i].Remark,
  939. }
  940. v.Set()
  941. // 开票登记-销售信息
  942. if req.InvoiceType == fms.ContractInvoiceTypeMake {
  943. sellerItem := sellerMap[req.AmountList[i].SellerId]
  944. if sellerItem == nil {
  945. resp.Fail("销售信息异常", c)
  946. return
  947. }
  948. if req.AmountList[i].ServiceProductId == crm.CompanyProductFicc && sellerItem.DepartmentId != crm.SellerDepartmentId {
  949. resp.Fail("销售类型和所选套餐类型不一致", c)
  950. return
  951. }
  952. if req.AmountList[i].ServiceProductId == crm.CompanyProductRai && sellerItem.DepartmentId != crm.RaiSellerDepartmentId {
  953. resp.Fail("销售类型和所选套餐类型不一致", c)
  954. return
  955. }
  956. v.SellerId = sellerItem.SellerId
  957. v.SellerName = sellerItem.SellerName
  958. v.SellerGroupId = sellerItem.GroupId
  959. v.SellerGroupName = sellerItem.GroupName
  960. v.SellerTeamId = sellerItem.TeamId
  961. v.SellerTeamName = sellerItem.TeamName
  962. }
  963. // 到款登记-付款方式
  964. if req.InvoiceType == fms.ContractInvoiceTypePay {
  965. v.PayType = fmsService.CalculateContractPaymentType(req.AmountList[i].Amount, item.ContractAmount, dayDiff)
  966. }
  967. newInvoice = append(newInvoice, v)
  968. }
  969. }
  970. }
  971. // 获取原有的登记信息
  972. invoiceCond := `contract_register_id = ? AND invoice_type = ? `
  973. invoicePars := make([]interface{}, 0)
  974. invoicePars = append(invoicePars, req.ContractRegisterId, req.InvoiceType)
  975. originInvoiceList, e := fms.GetContractInvoiceItemList(invoiceCond, invoicePars)
  976. if e != nil {
  977. resp.FailMsg("获取失败", "获取开票/到款列表失败, Err: "+e.Error(), c)
  978. return
  979. }
  980. // 比对原有和现有的登记信息
  981. logList := make([]*fms.ContractRegisterLog, 0)
  982. opData := ""
  983. opDataByte, e := json.Marshal(req)
  984. if e != nil {
  985. return
  986. }
  987. opData = string(opDataByte)
  988. opType := fms.ContractRegisterOpTypeInvoice
  989. if req.InvoiceType == fms.ContractInvoiceTypePay {
  990. opType = fms.ContractRegisterOpTypePayment
  991. }
  992. nowTime := time.Now().Local()
  993. // 需要删除的记录
  994. deleteInvoiceIds := make([]int, 0)
  995. for i := range originInvoiceList {
  996. if !utils.InArrayByInt(noChangeInvoiceIds, originInvoiceList[i].ContractInvoiceId) {
  997. deleteInvoiceIds = append(deleteInvoiceIds, originInvoiceList[i].ContractInvoiceId)
  998. logList = append(logList, &fms.ContractRegisterLog{
  999. ContractRegisterId: req.ContractRegisterId,
  1000. AdminId: int(adminInfo.AdminId),
  1001. AdminName: adminInfo.RealName,
  1002. OpData: opData,
  1003. OpType: opType,
  1004. CreateTime: nowTime,
  1005. AmountRemark: fmt.Sprint("删除", fms.ContractInvoiceKeyNameMap[opType], "金额", originInvoiceList[i].Amount, "元"),
  1006. })
  1007. }
  1008. }
  1009. // todo 判断是否符合均分金额的条件,如果符合,需要生成金额分配记录表
  1010. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1011. }
  1012. // 新增的记录
  1013. if len(newInvoice) > 0 {
  1014. newAmount := decimal.NewFromFloat(0).Round(2)
  1015. for i := range newInvoice {
  1016. a := decimal.NewFromFloat(newInvoice[i].Amount).Round(2)
  1017. newAmount = newAmount.Add(a)
  1018. }
  1019. ia, _ := newAmount.Round(2).Float64()
  1020. logList = append(logList, &fms.ContractRegisterLog{
  1021. ContractRegisterId: req.ContractRegisterId,
  1022. AdminId: int(adminInfo.AdminId),
  1023. AdminName: adminInfo.RealName,
  1024. OpData: opData,
  1025. OpType: opType,
  1026. CreateTime: nowTime,
  1027. AmountRemark: fmt.Sprint("新增", fms.ContractInvoiceKeyNameMap[opType], "金额", ia, "元"),
  1028. })
  1029. }
  1030. // 删除并新增登记
  1031. ob := new(fms.ContractInvoice)
  1032. if e := ob.DeleteAndCreateNewInvoice(req.ContractRegisterId, req.InvoiceType, deleteInvoiceIds, newInvoice); e != nil {
  1033. resp.FailData("日期格式有误", "Err:"+e.Error(), c)
  1034. return
  1035. }
  1036. // 校验金额-是否修改状态
  1037. go fmsService.CheckContractRegisterAmount(req.ContractRegisterId)
  1038. // 开票到款汇总
  1039. go fmsService.SummaryInvoicePaymentByContractRegisterId(req.ContractRegisterId)
  1040. // 操作日志
  1041. go func() {
  1042. logOB := new(fms.ContractRegisterLog)
  1043. if e := logOB.AddInBatches(logList); e != nil {
  1044. return
  1045. }
  1046. }()
  1047. resp.Ok("操作成功", c)
  1048. }
  1049. // Export
  1050. // @Title 合同登记-导出
  1051. // @Description 合同登记-导出
  1052. // @Param Keyword query string false "关键词"
  1053. // @Param StartDate query string false "合同开始日期"
  1054. // @Param EndDate query string false "合同结束日期"
  1055. // @Param ServiceType query int false "套餐类型"
  1056. // @Param ContractType query int false "合同类型"
  1057. // @Param RegisterStatus query int false "登记状态"
  1058. // @Success 200 string "操作成功"
  1059. // @router /contract/register/export [get]
  1060. func (rg *RegisterController) Export(c *gin.Context) {
  1061. var req fms.ContractRegisterListReq
  1062. if e := c.BindQuery(&req); e != nil {
  1063. err, ok := e.(validator.ValidationErrors)
  1064. if !ok {
  1065. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1066. return
  1067. }
  1068. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1069. return
  1070. }
  1071. cond := `1 = 1`
  1072. pars := make([]interface{}, 0)
  1073. // 合同编号/客户姓名/销售/实际使用方
  1074. if req.Keyword != "" {
  1075. kw := "%" + req.Keyword + "%"
  1076. cond += ` AND (company_name LIKE ? OR contract_code LIKE ? OR seller_name LIKE ? OR actual_company_name LIKE ?)`
  1077. pars = append(pars, kw, kw, kw, kw)
  1078. }
  1079. if req.StartDate != "" && req.EndDate != "" {
  1080. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1081. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1082. cond += ` AND (create_time BETWEEN ? AND ?)`
  1083. pars = append(pars, st, ed)
  1084. }
  1085. if req.ContractType != 0 {
  1086. cond += ` AND contract_type = ?`
  1087. pars = append(pars, req.ContractType)
  1088. }
  1089. if req.RegisterStatus != 0 {
  1090. cond += ` AND register_status = ?`
  1091. pars = append(pars, req.RegisterStatus)
  1092. }
  1093. if req.ServiceTypes != "" {
  1094. serviceTypes := strings.Split(req.ServiceTypes, ",")
  1095. registerIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  1096. if e != nil {
  1097. resp.FailMsg("获取失败", "获取合同登记IDs失败, Err: "+e.Error(), c)
  1098. return
  1099. }
  1100. if len(registerIds) > 0 {
  1101. cond += ` AND contract_register_id IN ?`
  1102. pars = append(pars, registerIds)
  1103. } else {
  1104. cond += ` AND 1 = 2`
  1105. }
  1106. }
  1107. // 获取列表数据
  1108. cr := new(fms.ContractRegister)
  1109. list, e := cr.List(cond, pars)
  1110. if e != nil {
  1111. resp.FailData("获取合同列表失败", "Err:"+e.Error(), c)
  1112. return
  1113. }
  1114. if len(list) == 0 {
  1115. resp.Fail("无有效数据可导出", c)
  1116. return
  1117. }
  1118. registerIds := make([]int, 0)
  1119. for i := range list {
  1120. registerIds = append(registerIds, list[i].ContractRegisterId)
  1121. }
  1122. // 获取小套餐品种
  1123. cpCond := `product_id = ? AND permission_name <> ?`
  1124. cpPars := make([]interface{}, 0)
  1125. cpPars = append(cpPars, crm.CompanyProductFicc, crm.ChartPermissionStrategyName)
  1126. cp := new(crm.ChartPermission)
  1127. permissionList, e := cp.List(cpCond, cpPars)
  1128. if e != nil {
  1129. resp.FailData("获取小套餐品种失败", "Err:"+e.Error(), c)
  1130. return
  1131. }
  1132. permissionLen := len(permissionList)
  1133. permissionNameIdMap := make(map[string]int)
  1134. for i := range permissionList {
  1135. permissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  1136. }
  1137. // 获取所有FICC套餐服务
  1138. serviceList, e := fms.GetContractServiceTemplateMapByProductId(crm.CompanyProductFicc)
  1139. if e != nil {
  1140. resp.FailData("获取套餐服务失败", "Err:"+e.Error(), c)
  1141. return
  1142. }
  1143. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  1144. otherService := make([]*fms.ContractServiceTemplateItem, 0)
  1145. for i := range serviceList {
  1146. if serviceList[i].Title != "FICC大套餐" && serviceList[i].Title != "FICC小套餐" {
  1147. otherService = append(otherService, serviceList[i])
  1148. }
  1149. }
  1150. otherServiceLen := len(otherService)
  1151. // 获取所有权益套餐服务
  1152. raiServiceList, e := fms.GetContractServiceTemplateAllByProductId(crm.CompanyProductRai)
  1153. if e != nil {
  1154. resp.FailData("获取权益套餐服务失败", "Err:"+e.Error(), c)
  1155. return
  1156. }
  1157. raiServiceIdMap := make(map[int]*fms.ContractServiceTemplateItem)
  1158. for i := range raiServiceList {
  1159. raiServiceIdMap[raiServiceList[i].ServiceTemplateId] = raiServiceList[i]
  1160. }
  1161. // 除大小套餐外的其他套餐(下面的导出需要以此动态处理)
  1162. raiOtherService := make([]*fms.ContractServiceTemplateItem, 0)
  1163. raiServiceNotShowMap := make(map[int]struct{})
  1164. for _, v := range raiServiceList {
  1165. if v.Pid > 0 && raiServiceIdMap[v.Pid].Pid > 0 {
  1166. raiServiceNotShowMap[v.Pid] = struct{}{}
  1167. raiServiceNotShowMap[raiServiceIdMap[v.Pid].Pid] = struct{}{}
  1168. }else if v.Pid > 0 {
  1169. raiServiceNotShowMap[v.Pid] = struct{}{}
  1170. }
  1171. }
  1172. for _, v := range raiServiceList {
  1173. if _, ok := raiServiceNotShowMap[v.ServiceTemplateId]; !ok {
  1174. if v.Pid > 0 {
  1175. v.ParentTitle = raiServiceIdMap[v.Pid].Title
  1176. }
  1177. raiOtherService = append(raiOtherService, v)
  1178. }
  1179. }
  1180. otherServiceLen += len(raiOtherService)
  1181. //套餐金额map
  1182. serviceAmountMap := make(map[int]map[int]*fms.ContractServiceAmount)
  1183. // 套餐/开票/到款列表
  1184. serviceMap := make(map[int][]*fms.ContractServiceWithParentTitle)
  1185. serviceChartPermissionsMap := make(map[int][]int)
  1186. invoiceMap := make(map[int][]*fms.ContractInvoice)
  1187. paymentMap := make(map[int][]*fms.ContractInvoice)
  1188. maxInvoice := 0
  1189. maxPayment := 0
  1190. if len(registerIds) > 0 {
  1191. // 获取套餐信息
  1192. csCond := `cv.contract_register_id IN ?`
  1193. csPars := make([]interface{}, 0)
  1194. csPars = append(csPars, registerIds)
  1195. cs := new(fms.ContractService)
  1196. serviceList, e := cs.ListWithWithParentTitle(csCond, csPars)
  1197. if e != nil {
  1198. resp.FailData("获取合同套餐列表失败", "Err:"+e.Error(), c)
  1199. return
  1200. }
  1201. for i := range serviceList {
  1202. cid := serviceList[i].ContractRegisterId
  1203. if serviceMap[cid] == nil {
  1204. serviceMap[cid] = make([]*fms.ContractServiceWithParentTitle, 0)
  1205. }
  1206. serviceMap[cid] = append(serviceMap[cid], serviceList[i])
  1207. // 小套餐权限
  1208. if serviceChartPermissionsMap[cid] == nil {
  1209. serviceChartPermissionsMap[cid] = make([]int, 0)
  1210. }
  1211. if serviceList[i].ChartPermissionIds != "" {
  1212. ids := utils.JoinStr2IntArr(serviceList[i].ChartPermissionIds, ",")
  1213. serviceChartPermissionsMap[cid] = append(serviceChartPermissionsMap[cid], ids...)
  1214. }
  1215. }
  1216. // 获取合同的套餐金额信息
  1217. serviceAmountList, e := fms.GetContractServiceAmountByContractRegisterIds(registerIds)
  1218. if e != nil {
  1219. resp.FailData("获取合同的套餐金额信息失败", "Err:"+e.Error(), c)
  1220. return
  1221. }
  1222. for _, v := range serviceAmountList {
  1223. if _, ok := serviceAmountMap[v.ContractRegisterId]; !ok {
  1224. serviceAmountMap[v.ContractRegisterId] = make(map[int]*fms.ContractServiceAmount)
  1225. }
  1226. serviceAmountMap[v.ContractRegisterId][v.ProductId] = v
  1227. }
  1228. // 获取开票/到款详情, 并取最大的开票/到款数(用于动态扩展第二列表头)
  1229. ci := new(fms.ContractInvoice)
  1230. csCond = `contract_register_id IN ?`
  1231. csPars = make([]interface{}, 0)
  1232. csPars = append(csPars, registerIds)
  1233. invoiceList, e := ci.List(csCond, csPars, "")
  1234. if e != nil {
  1235. resp.FailData("获取开票/到款列表失败", "Err:"+e.Error(), c)
  1236. return
  1237. }
  1238. for k := range invoiceList {
  1239. cid := invoiceList[k].ContractRegisterId
  1240. if invoiceMap[cid] == nil {
  1241. invoiceMap[cid] = make([]*fms.ContractInvoice, 0)
  1242. }
  1243. if paymentMap[cid] == nil {
  1244. paymentMap[cid] = make([]*fms.ContractInvoice, 0)
  1245. }
  1246. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypeMake {
  1247. invoiceMap[cid] = append(invoiceMap[cid], invoiceList[k])
  1248. continue
  1249. }
  1250. if invoiceList[k].InvoiceType == fms.ContractInvoiceTypePay {
  1251. paymentMap[cid] = append(paymentMap[cid], invoiceList[k])
  1252. continue
  1253. }
  1254. }
  1255. // 取最大开票/到款数
  1256. for j := range invoiceMap {
  1257. if len(invoiceMap[j]) > maxInvoice {
  1258. maxInvoice = len(invoiceMap[j])
  1259. }
  1260. }
  1261. for p := range paymentMap {
  1262. if len(paymentMap[p]) > maxPayment {
  1263. maxPayment = len(paymentMap[p])
  1264. }
  1265. }
  1266. }
  1267. serviceProductIdMap := map[int]string{
  1268. 1:"FICC套餐",
  1269. 2:"权益套餐",
  1270. }
  1271. // 生成Excel文件
  1272. xlsxFile := xlsx.NewFile()
  1273. style := xlsx.NewStyle()
  1274. alignment := xlsx.Alignment{
  1275. Horizontal: "center",
  1276. Vertical: "center",
  1277. WrapText: true,
  1278. }
  1279. style.Alignment = alignment
  1280. style.ApplyAlignment = true
  1281. sheetName := "财务列表"
  1282. sheet, err := xlsxFile.AddSheet(sheetName)
  1283. if err != nil {
  1284. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1285. return
  1286. }
  1287. // 1行表头
  1288. hInt := 0
  1289. titleRow := sheet.AddRow()
  1290. titleRow.SetHeight(40)
  1291. // 1行1列-右合并两格, 下合并1行
  1292. cell1 := titleRow.AddCell()
  1293. cell1.HMerge = 4
  1294. cell1.VMerge = 1
  1295. cell1.SetString("FICC客户签约表")
  1296. cell1.SetStyle(style)
  1297. // 右增两列空白格用于第一列合并, 否则后续单元格合并会有问题
  1298. titleRow.AddCell().SetString("")
  1299. titleRow.AddCell().SetString("")
  1300. titleRow.AddCell().SetString("")
  1301. titleRow.AddCell().SetString("")
  1302. hInt += 5
  1303. // 1行2列
  1304. cell2 := titleRow.AddCell()
  1305. cell2.VMerge = 1
  1306. cell2.SetString("FICC大套餐")
  1307. cell2.SetStyle(style)
  1308. hInt ++
  1309. // 1行3列-右合并小套餐数
  1310. if permissionLen >= 1 {
  1311. cell3 := titleRow.AddCell()
  1312. hInt ++
  1313. cell3.HMerge = permissionLen - 1
  1314. cell3.VMerge = 1
  1315. cell3.SetString("FICC小套餐")
  1316. cell3.SetStyle(style)
  1317. // 同上右增单元格小套餐数-1的空白单元格用于合并
  1318. for i := 0; i < permissionLen-1; i++ {
  1319. titleRow.AddCell().SetString("")
  1320. hInt ++
  1321. }
  1322. }
  1323. for i := range otherService {
  1324. cellOther := titleRow.AddCell()
  1325. cellOther.VMerge = 1
  1326. hInt ++
  1327. cellOther.SetString(otherService[i].Title)
  1328. cellOther.SetStyle(style)
  1329. }
  1330. //权益大套餐
  1331. cell4 := titleRow.AddCell()
  1332. cell4.HMerge = 1
  1333. cell4.VMerge = 1
  1334. cell4.SetString("权益大套餐")
  1335. cell4.SetStyle(style)
  1336. titleRow.AddCell().SetString("")
  1337. hInt +=2
  1338. //权益分行业套餐
  1339. cell5 := titleRow.AddCell()
  1340. cell5.HMerge = 8
  1341. cell5.SetString("权益分行业套餐")
  1342. cell5.SetStyle(style)
  1343. titleRow.AddCell().SetString("")
  1344. titleRow.AddCell().SetString("")
  1345. titleRow.AddCell().SetString("")
  1346. titleRow.AddCell().SetString("")
  1347. titleRow.AddCell().SetString("")
  1348. titleRow.AddCell().SetString("")
  1349. titleRow.AddCell().SetString("")
  1350. titleRow.AddCell().SetString("")
  1351. //第二行,前面几个单元格用于第一行的合并
  1352. titleRow2 := sheet.AddRow()
  1353. titleRow2.SetHeight(30)
  1354. for i:= 0; i<hInt;i++ {
  1355. titleRow2.AddCell().SetString("")
  1356. }
  1357. //权益分行业套餐
  1358. row2Cell1 := titleRow2.AddCell()
  1359. row2Cell1.HMerge = 1
  1360. row2Cell1.SetString("医药")
  1361. row2Cell1.SetStyle(style)
  1362. titleRow2.AddCell().SetString("")
  1363. row2Cell2 := titleRow2.AddCell()
  1364. row2Cell2.HMerge = 1
  1365. row2Cell2.SetString("消费")
  1366. row2Cell2.SetStyle(style)
  1367. titleRow2.AddCell().SetString("")
  1368. row2Cell3 := titleRow2.AddCell()
  1369. row2Cell3.HMerge = 1
  1370. row2Cell3.SetString("科技")
  1371. row2Cell3.SetStyle(style)
  1372. titleRow2.AddCell().SetString("")
  1373. row2Cell4 := titleRow2.AddCell()
  1374. row2Cell4.HMerge = 1
  1375. row2Cell4.SetString("智造")
  1376. row2Cell4.SetStyle(style)
  1377. titleRow2.AddCell().SetString("")
  1378. row2Cell5 := titleRow2.AddCell()
  1379. row2Cell5.SetString("策略")
  1380. row2Cell5.SetStyle(style)
  1381. // 第三行表头
  1382. titleRow3 := sheet.AddRow()
  1383. titleRow3.SetHeight(60)
  1384. row3Title := make([]string, 0)
  1385. row3TitleParent := make([]string, 0)
  1386. row3Title = append(row3Title, "客户名称", "新客户\n0-是\n1-否", "合同类型\n续约-0\n新增-1\n代付-2\n补充协议-3", "FICC销售", "权益销售", "FICC大套餐")
  1387. for i := range permissionList {
  1388. row3Title = append(row3Title, permissionList[i].PermissionName)
  1389. }
  1390. // 其他套餐
  1391. for i := range otherService {
  1392. row3Title = append(row3Title, otherService[i].Title)
  1393. }
  1394. // 定义二级套餐名称
  1395. for i:= range row3Title {
  1396. row3TitleParent = append(row3TitleParent, row3Title[i])
  1397. }
  1398. // 权益三级套餐
  1399. for i := range raiOtherService {
  1400. row3Title = append(row3Title, raiOtherService[i].Title)
  1401. if raiOtherService[i].ParentTitle != "" {
  1402. row3TitleParent = append(row3TitleParent, raiOtherService[i].ParentTitle)
  1403. }else{
  1404. row3TitleParent = append(row3TitleParent, raiOtherService[i].Title)
  1405. }
  1406. }
  1407. row3Title = append(row3Title, "套餐备注", "开始时间", "到期时间", "2022年合同金额", "金额单位", "FICC套餐总金额", "权益套餐总金额", "约定付款时间", "签订日", "合同状态",
  1408. "合同编号", "合规备注")
  1409. // 设置表头
  1410. for i := range row3Title {
  1411. v := titleRow3.AddCell()
  1412. v.SetString(row3Title[i])
  1413. v.SetStyle(style)
  1414. }
  1415. // 第二行表头-开票/收款(动态添加)
  1416. invoiceTitle := []string{"开票日", "开票金额", "套餐类型", "销售", "备注"}
  1417. for i := 0; i < maxInvoice; i++ {
  1418. n := i + 1
  1419. for ii := range invoiceTitle {
  1420. c := titleRow3.AddCell()
  1421. t := fmt.Sprintf("%s%d", invoiceTitle[ii], n)
  1422. c.SetString(t)
  1423. c.SetStyle(style)
  1424. row3Title = append(row3Title, t)
  1425. }
  1426. }
  1427. paymentTitle := []string{"到款日", "到款金额", "套餐类型", "备注"}
  1428. for i := 0; i < maxPayment; i++ {
  1429. n := i + 1
  1430. for ii := range paymentTitle {
  1431. c := titleRow3.AddCell()
  1432. t := fmt.Sprintf("%s%d", paymentTitle[ii], n)
  1433. c.SetString(t)
  1434. c.SetStyle(style)
  1435. row3Title = append(row3Title, t)
  1436. }
  1437. }
  1438. // 此处取第二行标题NameKeyMap, 后面的动态匹配
  1439. row2NameKeyMap := make(map[string]int)
  1440. for i := range row3Title {
  1441. row2NameKeyMap[row3Title[i]] = i
  1442. }
  1443. newCompanyMap := map[int]string{0: "1", 1: "0"}
  1444. contractTMap := map[int]int{
  1445. fms.ContractTypeNew: 1,
  1446. fms.ContractTypeRenew: 0,
  1447. fms.ContractTypeAgentPay: 2, // 代付合同
  1448. fms.ContractTypePlus: 3, // 补充协议
  1449. }
  1450. for _, v := range list {
  1451. k := -1 // 套餐匹配用
  1452. dataRow := sheet.AddRow()
  1453. dataRow.SetHeight(20)
  1454. k += 4
  1455. dataRow.AddCell().SetString(v.CompanyName)
  1456. dataRow.AddCell().SetString(newCompanyMap[v.NewCompany])
  1457. dataRow.AddCell().SetString(fmt.Sprint(contractTMap[v.ContractType]))
  1458. dataRow.AddCell().SetString(v.SellerName)
  1459. dataRow.AddCell().SetString(v.RaiSellerName)
  1460. // 大套餐
  1461. k += 1
  1462. col4Name := row3Title[k]
  1463. svList := serviceMap[v.ContractRegisterId]
  1464. col4 := ""
  1465. if svList != nil && len(svList) > 0 {
  1466. for isv := range svList {
  1467. if svList[isv].Title == col4Name {
  1468. col4 = "是"
  1469. break
  1470. }
  1471. }
  1472. }
  1473. dataRow.AddCell().SetString(col4)
  1474. // 小套餐
  1475. serviceChartPermissionIds := serviceChartPermissionsMap[v.ContractRegisterId]
  1476. for i := 0; i < permissionLen; i++ {
  1477. k += 1
  1478. colName := row3Title[k]
  1479. chartPermissionId := permissionNameIdMap[colName]
  1480. if utils.InArray(chartPermissionId, serviceChartPermissionIds) {
  1481. dataRow.AddCell().SetString("是")
  1482. } else {
  1483. dataRow.AddCell().SetString("")
  1484. }
  1485. }
  1486. // 除大小套餐外的其他套餐(处理方式其实跟上面的大套餐一样, 只是中间隔了小套餐按照顺序要这么处理=_=!)
  1487. for i := 0; i < otherServiceLen; i++ {
  1488. k += 1
  1489. otherColName := row3Title[k]
  1490. otherCol := ""
  1491. if svList != nil && len(svList) > 0 {
  1492. for isv := range svList {
  1493. if svList[isv].Title == otherColName {
  1494. // 判断权益套餐权限时,需要同时判断父级name
  1495. if otherColName == "主观" || otherColName == "客观" {
  1496. if row3TitleParent[k] == svList[isv].ParentTitle {
  1497. otherCol = "是"
  1498. break
  1499. }
  1500. }else{
  1501. otherCol = "是"
  1502. break
  1503. }
  1504. }
  1505. }
  1506. }
  1507. dataRow.AddCell().SetString(otherCol)
  1508. }
  1509. // 其他信息
  1510. ficcAmount, _ := serviceAmountMap[v.ContractRegisterId][crm.CompanyProductFicc]
  1511. raiAmount, _ := serviceAmountMap[v.ContractRegisterId][crm.CompanyProductRai]
  1512. dataRow.AddCell().SetString(v.ServiceRemark) // 套餐备注
  1513. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.StartDate)) // 开始时间
  1514. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.EndDate)) // 到期时间
  1515. dataRow.AddCell().SetString(fmt.Sprint("¥", v.ContractAmount)) // 2022年合同金额
  1516. dataRow.AddCell().SetString(v.CurrencyUnit) // 货币单位
  1517. dataRow.AddCell().SetString(fmt.Sprint("¥", ficcAmount.ServiceAmount)) // FICC套餐总金额
  1518. dataRow.AddCell().SetString(fmt.Sprint("¥", raiAmount.ServiceAmount)) // 权益套餐总金额
  1519. dataRow.AddCell().SetString(v.AgreedPayTime) // 约定付款时间
  1520. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", v.SignDate)) // 签订日
  1521. dataRow.AddCell().SetString(fms.ContractStatusKeyNameMap[v.ContractStatus]) // 合同状态
  1522. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  1523. dataRow.AddCell().SetString(v.Remark) // 合规备注
  1524. // 开票/到款信息
  1525. ivList := invoiceMap[v.ContractRegisterId]
  1526. ivListLen := len(ivList)
  1527. for ia := 0; ia < maxInvoice; ia++ {
  1528. if ia < ivListLen {
  1529. if ivList != nil && ivList[ia] != nil {
  1530. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", ivList[ia].InvoiceDate)) // 开票日
  1531. dataRow.AddCell().SetString(fmt.Sprint(ivList[ia].OriginAmount)) // 开票金额
  1532. dataRow.AddCell().SetString(serviceProductIdMap[ivList[ia].ServiceProductId]) // 套餐类型
  1533. dataRow.AddCell().SetString(ivList[ia].SellerName) // 销售名称
  1534. dataRow.AddCell().SetString(ivList[ia].Remark) // 开票备注
  1535. continue
  1536. }
  1537. }
  1538. // 这里要把不够的填充为空
  1539. dataRow.AddCell().SetString("")
  1540. dataRow.AddCell().SetString("")
  1541. dataRow.AddCell().SetString("")
  1542. dataRow.AddCell().SetString("")
  1543. dataRow.AddCell().SetString("")
  1544. }
  1545. pyList := paymentMap[v.ContractRegisterId]
  1546. pyListLen := len(pyList)
  1547. for ib := 0; ib < maxPayment; ib++ {
  1548. if ib < pyListLen {
  1549. if pyList != nil && pyList[ib] != nil {
  1550. dataRow.AddCell().SetString(utils.TimeTransferString("2006/01/02", pyList[ib].InvoiceDate)) // 收款日
  1551. dataRow.AddCell().SetString(fmt.Sprint(pyList[ib].OriginAmount)) // 收款金额
  1552. dataRow.AddCell().SetString(serviceProductIdMap[pyList[ib].ServiceProductId]) // 套餐类型
  1553. dataRow.AddCell().SetString(pyList[ib].Remark) // 收款备注
  1554. continue
  1555. }
  1556. }
  1557. // 这里要把不够的填充为空
  1558. dataRow.AddCell().SetString("")
  1559. dataRow.AddCell().SetString("")
  1560. dataRow.AddCell().SetString("")
  1561. dataRow.AddCell().SetString("")
  1562. }
  1563. }
  1564. // 输出文件
  1565. var buffer bytes.Buffer
  1566. _ = xlsxFile.Write(&buffer)
  1567. content := bytes.NewReader(buffer.Bytes())
  1568. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1569. fileName := sheetName + randStr + ".xlsx"
  1570. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1571. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1572. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1573. }
  1574. // InvoiceList
  1575. // @Title 开票/到款列表
  1576. // @Description 开票/到款列表
  1577. // @Param InvoiceType query int false "类型: 1-开票登记; 2-到款登记"
  1578. // @Param ContractCode query string false "合同编号"
  1579. // @Param StartDate query string false "开始日期"
  1580. // @Param EndDate query string false "结束日期"
  1581. // @Param MinAmount query float64 false "开票金额区间-最小值"
  1582. // @Param MaxAmount query float64 false "开票金额区间-最大值"
  1583. // @Param IsExport query int false "是否导出: 0-否; 1-是"
  1584. // @Success 200 {object} fms.ContractInvoiceItem
  1585. // @router /contract/register/invoice_list [get]
  1586. func (rg *RegisterController) InvoiceList(c *gin.Context) {
  1587. var req fms.ContractInvoiceListReq
  1588. if e := c.BindQuery(&req); e != nil {
  1589. err, ok := e.(validator.ValidationErrors)
  1590. if !ok {
  1591. resp.FailData("参数解析失败", "Err:"+e.Error(), c)
  1592. return
  1593. }
  1594. resp.FailData("参数解析失败", err.Translate(global.Trans), c)
  1595. return
  1596. }
  1597. pageSize := req.PageSize
  1598. pageIndex := req.Current
  1599. if pageSize <= 0 {
  1600. pageSize = utils.PageSize20
  1601. }
  1602. if pageIndex <= 0 {
  1603. pageIndex = 1
  1604. }
  1605. cond := `invoice_type = ?`
  1606. pars := make([]interface{}, 0)
  1607. pars = append(pars, req.InvoiceType)
  1608. // 合同编号
  1609. if req.ContractCode != "" {
  1610. kw := fmt.Sprint("%", req.ContractCode, "%")
  1611. pars = append(pars, kw)
  1612. // 开票列表同时模糊查询销售名称
  1613. if req.InvoiceType == fms.ContractInvoiceTypeMake {
  1614. cond += ` AND (contract_code LIKE ? )`
  1615. pars = append(pars, kw)
  1616. } else {
  1617. cond += ` AND contract_code LIKE ?`
  1618. pars = append(pars, kw)
  1619. }
  1620. }
  1621. if req.StartDate != "" && req.EndDate != "" {
  1622. st := fmt.Sprint(req.StartDate, " 00:00:00")
  1623. ed := fmt.Sprint(req.EndDate, " 23:59:59")
  1624. cond += ` AND (invoice_time BETWEEN ? AND ?)`
  1625. pars = append(pars, st, ed)
  1626. }
  1627. if req.MinAmount > 0 {
  1628. cond += ` AND amount >= ?`
  1629. pars = append(pars, req.MinAmount)
  1630. }
  1631. if req.MaxAmount > 0 {
  1632. cond += ` AND amount <= ?`
  1633. pars = append(pars, req.MaxAmount)
  1634. }
  1635. // 套餐类型
  1636. if req.ServiceProductId > 0 {
  1637. cond += ` AND service_product_id = ?`
  1638. pars = append(pars, req.ServiceProductId)
  1639. }
  1640. // 销售
  1641. if req.SellerIds != "" {
  1642. sellerIds := strings.Split(req.SellerIds, ",")
  1643. cond += ` AND (seller_id in (?))`
  1644. pars = append(pars, sellerIds)
  1645. }
  1646. // 货币列表
  1647. currencyOB := new(fms.CurrencyUnit)
  1648. currencyCond := `enable = 1`
  1649. currencyPars := make([]interface{}, 0)
  1650. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  1651. if e != nil {
  1652. resp.FailMsg("获取失败", "获取货币列表失败, Err: "+e.Error(), c)
  1653. return
  1654. }
  1655. unitMap := make(map[string]string)
  1656. currencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  1657. for i := range currencyList {
  1658. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  1659. currencyTotals = append(currencyTotals, &fms.InvoiceListCurrencyTotal{
  1660. Name: currencyList[i].Name,
  1661. UnitName: currencyList[i].UnitName,
  1662. Code: currencyList[i].Code,
  1663. FlagImg: currencyList[i].FlagImg,
  1664. })
  1665. }
  1666. page := new(base.Page)
  1667. page.SetPageSize(pageSize)
  1668. page.SetCurrent(pageIndex)
  1669. page.AddOrderItem(base.OrderItem{Column: "invoice_time", Asc: false})
  1670. if req.IsExport == 1 {
  1671. page.SetPageSize(10000)
  1672. page.SetCurrent(1)
  1673. }
  1674. total, list, e := fms.GetContractInvoiceItemPageList(page, cond, pars)
  1675. if e != nil {
  1676. resp.FailMsg("获取失败", "获取合同开票/到款列表失败, Err: "+e.Error(), c)
  1677. return
  1678. }
  1679. page.SetTotal(total)
  1680. contractRegisterIds := make([]int, 0)
  1681. contractStatusMap := make(map[int]int)
  1682. for i := range list {
  1683. list[i].UnitName = unitMap[list[i].CurrencyUnit]
  1684. contractRegisterIds = append(contractRegisterIds, list[i].ContractRegisterId)
  1685. }
  1686. if len(contractRegisterIds) > 0 {
  1687. contractRegisters, err := fms.GetContractInfoByRegisterIds(contractRegisterIds)
  1688. if err != nil {
  1689. resp.FailMsg("查询合同信息失败", "查询合同信息失败, Err: "+err.Error(), c)
  1690. return
  1691. }
  1692. for _, v := range contractRegisters {
  1693. contractStatusMap[v.ContractRegisterId] = v.ContractStatus
  1694. }
  1695. }
  1696. for i := range list {
  1697. list[i].ContractStatus = contractStatusMap[list[i].ContractRegisterId]
  1698. }
  1699. // 分币种合计金额
  1700. var amountTotal float64
  1701. sumList, e := fms.GetInvoiceListCurrencySum(cond, pars, "currency_unit")
  1702. if e != nil {
  1703. resp.FailMsg("获取失败", "获取开票/到款列表合计金额失败, Err: "+e.Error(), c)
  1704. return
  1705. }
  1706. sumMap := make(map[string]float64)
  1707. for i := range sumList {
  1708. amountTotal += sumList[i].AmountTotal
  1709. sumMap[sumList[i].CurrencyUnit] = sumList[i].OriginAmountTotal
  1710. }
  1711. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountTotal), 64)
  1712. for i := range currencyTotals {
  1713. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", sumMap[currencyTotals[i].Code]), 64)
  1714. currencyTotals[i].Amount = a
  1715. }
  1716. respData := &fms.InvoiceListRespData{
  1717. Page: page,
  1718. List: list,
  1719. AmountTotal: amountTotal,
  1720. CurrencyTotal: currencyTotals,
  1721. }
  1722. // 是否导出
  1723. if req.IsExport == 1 {
  1724. ExportInvoiceList(c, req, respData)
  1725. return
  1726. }
  1727. resp.OkData("获取成功", respData, c)
  1728. }
  1729. // ExportInvoiceList 导出开票/到款列表
  1730. func ExportInvoiceList(c *gin.Context, req fms.ContractInvoiceListReq, results *fms.InvoiceListRespData) {
  1731. list := make([]*fms.ContractInvoiceItem, 0)
  1732. if val, ok := results.List.([]*fms.ContractInvoiceItem); ok {
  1733. list = val
  1734. } else {
  1735. resp.Fail("列表数据有误", c)
  1736. return
  1737. }
  1738. if len(list) == 0 {
  1739. resp.Fail("列表数据为空", c)
  1740. return
  1741. }
  1742. listName := "开票"
  1743. if req.InvoiceType == fms.ContractInvoiceTypePay {
  1744. listName = "到款"
  1745. }
  1746. // 生成Excel文件
  1747. xlsxFile := xlsx.NewFile()
  1748. style := xlsx.NewStyle()
  1749. alignment := xlsx.Alignment{
  1750. Horizontal: "center",
  1751. Vertical: "center",
  1752. WrapText: true,
  1753. }
  1754. style.Alignment = alignment
  1755. style.ApplyAlignment = true
  1756. sheet, err := xlsxFile.AddSheet(fmt.Sprintf("%s列表", listName))
  1757. if err != nil {
  1758. resp.FailData("新增Sheet失败", "Err:"+err.Error(), c)
  1759. return
  1760. }
  1761. // 前两行显示合计金额, 第三行空出与列表数据隔一行
  1762. rowA := sheet.AddRow()
  1763. cellAA := rowA.AddCell()
  1764. cellAA.SetString(fmt.Sprintf("已开票合计金额(换算后):%.2f(元)", results.AmountTotal))
  1765. rowBData := "已开票金额:"
  1766. for _, v := range results.CurrencyTotal {
  1767. rowBData += fmt.Sprintf("%s%.2f(%s) ", v.Name, v.Amount, v.UnitName)
  1768. }
  1769. rowB := sheet.AddRow()
  1770. rowB.AddCell().SetString(rowBData)
  1771. sheet.AddRow()
  1772. // 列表数据表头
  1773. titles := []string{"合同编号", "套餐类型", fmt.Sprintf("%s金额", listName), "金额单位", "换算金额(元)",
  1774. fmt.Sprintf("%s日期", listName), "销售", "备注"}
  1775. titleRow := sheet.AddRow()
  1776. titleRow.SetHeight(40)
  1777. for i := range titles {
  1778. c := titleRow.AddCell()
  1779. c.SetString(titles[i])
  1780. c.SetStyle(style)
  1781. }
  1782. ServiceTemplateStrMap := map[int]string{
  1783. crm.CompanyProductFicc: "FICC套餐",
  1784. crm.CompanyProductRai: "权益套餐",
  1785. }
  1786. // 单元格赋值
  1787. for _, v := range list {
  1788. dataRow := sheet.AddRow()
  1789. dataRow.SetHeight(20)
  1790. dataRow.AddCell().SetString(v.ContractCode) // 合同编号
  1791. dataRow.AddCell().SetString(ServiceTemplateStrMap[v.ServiceProductId]) // 套餐类型
  1792. dataRow.AddCell().SetString(fmt.Sprint(v.OriginAmount)) // 开票金额
  1793. dataRow.AddCell().SetString(v.UnitName) // 金额单位
  1794. dataRow.AddCell().SetString(fmt.Sprint(v.Amount)) // 换算金额(元)
  1795. dataRow.AddCell().SetString(v.InvoiceDate) // 开票日
  1796. dataRow.AddCell().SetString(v.SellerName) // 销售
  1797. dataRow.AddCell().SetString(v.Remark) // 备注
  1798. }
  1799. // 输出文件
  1800. var buffer bytes.Buffer
  1801. _ = xlsxFile.Write(&buffer)
  1802. content := bytes.NewReader(buffer.Bytes())
  1803. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1804. fileName := fmt.Sprintf("%s列表_%s.xlsx", listName, randStr)
  1805. c.Writer.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
  1806. c.Writer.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  1807. http.ServeContent(c.Writer, c.Request, fileName, time.Now(), content)
  1808. }
  1809. // Import
  1810. // @Title 合同登记-导入
  1811. // @Description 合同登记-导入
  1812. // @Success 200 string "操作成功"
  1813. // @router /contract/register/import [post]
  1814. func (rg *RegisterController) Import(c *gin.Context) {
  1815. h, err := c.FormFile("File")
  1816. if err != nil {
  1817. resp.FailData("获取文件失败", "Err:"+err.Error(), c)
  1818. return
  1819. }
  1820. ext := path.Ext(h.Filename)
  1821. if ext != ".xlsx" && ext != ".xls" {
  1822. resp.Fail("请上传Excel文件", c)
  1823. return
  1824. }
  1825. uploadDir := "static/xls"
  1826. err = os.MkdirAll(uploadDir, 766)
  1827. if err != nil {
  1828. resp.FailData("存储目录创建失败", "Err:"+err.Error(), c)
  1829. return
  1830. }
  1831. uploadPath := uploadDir + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + h.Filename
  1832. err = c.SaveUploadedFile(h, uploadPath)
  1833. if err != nil {
  1834. resp.FailData("保存本地文件失败", "Err:"+err.Error(), c)
  1835. return
  1836. }
  1837. defer func() {
  1838. _ = os.Remove(uploadPath)
  1839. }()
  1840. xlFile, err := xlsx.OpenFile(uploadPath)
  1841. if err != nil {
  1842. resp.FailData("打开文件失败", "Err:"+err.Error(), c)
  1843. return
  1844. }
  1845. // 获取所有已登记,根据合同编号去重
  1846. contractCodeArr := make([]string, 0)
  1847. registerOB := new(fms.ContractRegister)
  1848. registerCond := ``
  1849. registerPars := make([]interface{}, 0)
  1850. registerList, e := registerOB.List(registerCond, registerPars)
  1851. if e != nil {
  1852. resp.FailData("获取合同登记列表失败", "Err:"+e.Error(), c)
  1853. return
  1854. }
  1855. for i := range registerList {
  1856. contractCodeArr = append(contractCodeArr, registerList[i].ContractCode)
  1857. }
  1858. // 获取所有销售Map
  1859. sellerList, e := crmService.GetSellerDepartmentListWithGroupAndTeam()
  1860. if e != nil {
  1861. resp.FailData("获取销售列表失败", "Err:"+e.Error(), c)
  1862. return
  1863. }
  1864. sellerMap := make(map[string]*crm.SellerAdminWithGroupTeam)
  1865. for i := range sellerList {
  1866. sellerMap[sellerList[i].SellerName] = sellerList[i]
  1867. }
  1868. // 获取品种权限Map
  1869. chartPermissionNameIdMap := make(map[string]int)
  1870. cpCond := `product_id = ?`
  1871. cpPars := make([]interface{}, 0)
  1872. cpPars = append(cpPars, crm.CompanyProductFicc)
  1873. cp := new(crm.ChartPermission)
  1874. permissionList, e := cp.List(cpCond, cpPars)
  1875. if e != nil {
  1876. resp.FailData("获取权限列表失败", "Err:"+e.Error(), c)
  1877. return
  1878. }
  1879. for i := range permissionList {
  1880. chartPermissionNameIdMap[permissionList[i].PermissionName] = permissionList[i].ChartPermissionId
  1881. }
  1882. // 获取所有套餐模板
  1883. serviceTempCond := ``
  1884. serviceTempPars := make([]interface{}, 0)
  1885. serviceTempOB := new(fms.ContractServiceTemplate)
  1886. serviceTempList, e := serviceTempOB.List(serviceTempCond, serviceTempPars)
  1887. if e != nil {
  1888. resp.FailData("获取套餐模板列表失败", "Err:"+e.Error(), c)
  1889. return
  1890. }
  1891. serviceTempNameMap := make(map[string]*fms.ContractServiceTemplate)
  1892. serviceTempFullNameMap := make(map[string]*fms.ContractServiceTemplate)
  1893. serviceTempIdMap := make(map[int]*fms.ContractServiceTemplate)
  1894. for i := range serviceTempList {
  1895. serviceTempIdMap[serviceTempList[i].ServiceTemplateId] = serviceTempList[i]
  1896. serviceTempNameMap[serviceTempList[i].Title] = serviceTempList[i]
  1897. }
  1898. for i := range serviceTempList {
  1899. fullName := serviceTempList[i].Title
  1900. if serviceTempList[i].Pid > 0 {
  1901. parentItem := serviceTempIdMap[serviceTempList[i].Pid]
  1902. fullName += "_"+parentItem.Title
  1903. if parentItem.Pid > 0 {
  1904. fullName += "_"+serviceTempIdMap[parentItem.Pid].Title
  1905. }
  1906. }
  1907. serviceTempFullNameMap[fullName] = serviceTempList[i]
  1908. }
  1909. //权益行业套餐名称
  1910. raiIndustryMap := map[int]string{
  1911. 36:"医药",
  1912. 37:"医药",
  1913. 38:"消费",
  1914. 39:"消费",
  1915. 40:"科技",
  1916. 41:"科技",
  1917. 42:"智造",
  1918. 43:"智造",
  1919. 44:"策略",
  1920. }
  1921. // 获取货币列表及汇率(汇率为导入日的汇率)
  1922. rateList, e := fmsService.GetTodayCurrencyRateList()
  1923. if e != nil {
  1924. resp.FailData("获取货币列表及汇率失败", "Err:"+e.Error(), c)
  1925. return
  1926. }
  1927. rateMap := make(map[string]float64)
  1928. for i := range rateList {
  1929. rateMap[rateList[i].Code] = rateList[i].RMBRate
  1930. }
  1931. titleMap := make(map[int]string)
  1932. newIds := make([]int, 0)
  1933. newCompanyArr := []string{"0", "1"}
  1934. newCompanyMap := map[string]int{"0": 1, "1": 0}
  1935. contractTypeArr := []string{"0", "1", "2", "3"}
  1936. contractTypeMap := map[string]int{
  1937. "0": fms.ContractTypeRenew,
  1938. "1": fms.ContractTypeNew,
  1939. "2": fms.ContractTypeAgentPay,
  1940. "3": fms.ContractTypePlus,
  1941. }
  1942. // 更新登记状态
  1943. defer func() {
  1944. if len(newIds) > 0 {
  1945. go func() {
  1946. for i := range newIds {
  1947. fmsService.CheckContractRegisterAmount(newIds[i])
  1948. fmsService.SummaryInvoicePaymentByContractRegisterId(newIds[i])
  1949. }
  1950. }()
  1951. }
  1952. }()
  1953. invoiceMax := 3
  1954. checkDate := time.Date(1900, 1, 1, 0, 0, 0, 0, time.Local)
  1955. for _, sheet := range xlFile.Sheets {
  1956. // 遍历行读取
  1957. maxRow := sheet.MaxRow
  1958. for i := 0; i < maxRow; i++ {
  1959. // 第三行开始读取表头
  1960. if i == 2 {
  1961. row := sheet.Row(i)
  1962. cells := row.Cells
  1963. for k, cell := range cells {
  1964. text := cell.String()
  1965. titleMap[k] = text
  1966. // 只检验前面部分表头, 后面很多动态列
  1967. if k == 0 {
  1968. if text != "客户名称" {
  1969. resp.Fail("【客户名称】列名称有误, 请参考模板导入", c)
  1970. return
  1971. }
  1972. continue
  1973. } else if k == 1 {
  1974. if !strings.Contains(text, "新客户") {
  1975. resp.Fail("【新客户】列名称有误, 请参考模板导入", c)
  1976. return
  1977. }
  1978. continue
  1979. } else if k == 2 {
  1980. if !strings.Contains(text, "合同类型") {
  1981. resp.Fail("【合同类型】列名称有误, 请参考模板导入", c)
  1982. return
  1983. }
  1984. continue
  1985. } else if k == 3 {
  1986. if text != "FICC销售" {
  1987. resp.Fail("【FICC销售】列名称有误, 请参考模板导入", c)
  1988. return
  1989. }
  1990. continue
  1991. } else if k == 4 {
  1992. if text != "权益销售" {
  1993. resp.Fail("【权益销售】列名称有误, 请参考模板导入", c)
  1994. return
  1995. }
  1996. continue
  1997. } else if k == 5 {
  1998. if text != "FICC大套餐" {
  1999. resp.Fail("【FICC大套餐】列名称有误, 请参考模板导入", c)
  2000. return
  2001. }
  2002. continue
  2003. }
  2004. }
  2005. }else if i >= 3 {
  2006. // 数据行
  2007. row := sheet.Row(i)
  2008. cells := row.Cells
  2009. // 登记信息
  2010. rowRegister := new(fms.ContractRegister)
  2011. // 套餐
  2012. rowServices := make([]*fms.ContractService, 0)
  2013. // 套餐金额
  2014. rowServiceAmount := make([]*fms.ContractServiceAmount, 0)
  2015. // 开票/到款
  2016. rowInvoices := make([]*fms.ContractInvoice, 0)
  2017. for ir := 0; ir < invoiceMax; ir++ {
  2018. rowInvoices = append(rowInvoices, new(fms.ContractInvoice))
  2019. }
  2020. rowPayments := make([]*fms.ContractInvoice, 0)
  2021. for ir := 0; ir < invoiceMax; ir++ {
  2022. rowPayments = append(rowPayments, new(fms.ContractInvoice))
  2023. }
  2024. // 小套餐权限
  2025. rowChartPermissionIdArr := make([]string, 0)
  2026. productIds := make(map[int]struct{})
  2027. isSkip := false
  2028. for k, cell := range cells {
  2029. v := utils.TrimStr(cell.String())
  2030. // 客户名称
  2031. if k == 0 {
  2032. if v == "" {
  2033. resp.Fail(fmt.Sprintf("第%d行客户名称不可为空, 请按模板导入", i+1), c)
  2034. return
  2035. }
  2036. rowRegister.CompanyName = v
  2037. continue
  2038. }
  2039. // 是否新客户
  2040. if k == 1 {
  2041. if !utils.InArrayByStr(newCompanyArr, v) {
  2042. resp.Fail(fmt.Sprintf("第%d行新客户有误, 请按模板导入", i+1), c)
  2043. return
  2044. }
  2045. rowRegister.NewCompany = newCompanyMap[v]
  2046. continue
  2047. }
  2048. // 合同类型
  2049. if k == 2 {
  2050. if !utils.InArrayByStr(contractTypeArr, v) {
  2051. resp.Fail(fmt.Sprintf("第%d行合同类型有误, 请按模板导入", i+1), c)
  2052. return
  2053. }
  2054. rowRegister.ContractType = contractTypeMap[v]
  2055. if rowRegister.ContractType == 0 {
  2056. resp.Fail(fmt.Sprintf("第%d行合同类型匹配有误, 请按模板导入", i+1), c)
  2057. return
  2058. }
  2059. continue
  2060. }
  2061. // FICC销售
  2062. if k == 3 {
  2063. if v != "" {
  2064. /*resp.Fail(fmt.Sprintf("第%d行销售名称不可为空, 请按模板导入", i+1), c)
  2065. return*/
  2066. sellerItem := sellerMap[v]
  2067. if sellerItem == nil {
  2068. resp.Fail(fmt.Sprintf("第%d行销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2069. return
  2070. }
  2071. rowRegister.SellerId = sellerItem.SellerId
  2072. rowRegister.SellerName = sellerItem.SellerName
  2073. }
  2074. continue
  2075. }
  2076. // 权益销售
  2077. if k == 4 {
  2078. if v == "" && rowRegister.SellerName == "" {
  2079. resp.Fail(fmt.Sprintf("第FICC销售名称和权益销售名称不可都为空, 请按模板导入", i+1), c)
  2080. return
  2081. }
  2082. sellerItem := sellerMap[v]
  2083. if sellerItem == nil {
  2084. resp.Fail(fmt.Sprintf("第%d行权益销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2085. return
  2086. }
  2087. rowRegister.RaiSellerId = sellerItem.SellerId
  2088. rowRegister.RaiSellerName = sellerItem.SellerName
  2089. continue
  2090. }
  2091. // FICC大套餐
  2092. if k == 5 {
  2093. if v == "是" {
  2094. tempItem := serviceTempNameMap[titleMap[k]]
  2095. if tempItem == nil {
  2096. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2097. return
  2098. }
  2099. cs := &fms.ContractService{
  2100. ProductId: crm.CompanyProductFicc,
  2101. ServiceTemplateId: tempItem.ServiceTemplateId,
  2102. Title: tempItem.Title,
  2103. Value: tempItem.Value,
  2104. TableValue: tempItem.TableValue,
  2105. ChartPermissionId: tempItem.ChartPermissionId,
  2106. }
  2107. cs.Set()
  2108. rowServices = append(rowServices, cs)
  2109. productIds[crm.CompanyProductFicc] = struct{}{}
  2110. }
  2111. continue
  2112. }
  2113. // FICC小套餐
  2114. if k >= 6 && k <= 26 {
  2115. // 小套餐权限
  2116. if v == "是" {
  2117. rowChartPermissionIdArr = append(rowChartPermissionIdArr, strconv.Itoa(chartPermissionNameIdMap[titleMap[k]]))
  2118. productIds[crm.CompanyProductFicc] = struct{}{}
  2119. }
  2120. continue
  2121. }
  2122. // 其他类型套餐
  2123. if k >= 27 && k <= 33 {
  2124. if v == "是" {
  2125. tempItem := serviceTempNameMap[titleMap[k]]
  2126. if tempItem == nil {
  2127. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2128. return
  2129. }
  2130. cs := &fms.ContractService{
  2131. ProductId: crm.CompanyProductFicc,
  2132. ServiceTemplateId: tempItem.ServiceTemplateId,
  2133. Title: tempItem.Title,
  2134. Value: tempItem.Value,
  2135. TableValue: tempItem.TableValue,
  2136. ChartPermissionId: tempItem.ChartPermissionId,
  2137. }
  2138. cs.Set()
  2139. rowServices = append(rowServices, cs)
  2140. productIds[crm.CompanyProductFicc] = struct{}{}
  2141. }
  2142. continue
  2143. }
  2144. if k >=34 && k<=44 {
  2145. if v == "是" {
  2146. // 权益大套餐
  2147. if k <= 35 {
  2148. //新增
  2149. parentName := "权益大套餐"
  2150. tempItem := serviceTempNameMap[titleMap[k]]
  2151. if tempItem == nil {
  2152. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2153. return
  2154. }
  2155. cs := &fms.ContractService{
  2156. ProductId: crm.CompanyProductFicc,
  2157. ServiceTemplateId: tempItem.ServiceTemplateId,
  2158. Title: tempItem.Title,
  2159. Value: tempItem.Value,
  2160. TableValue: tempItem.TableValue,
  2161. ChartPermissionId: tempItem.ChartPermissionId,
  2162. }
  2163. rowServices = append(rowServices, cs)
  2164. tempItem = serviceTempNameMap[parentName]
  2165. if tempItem == nil {
  2166. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2167. return
  2168. }
  2169. cs = &fms.ContractService{
  2170. ProductId: crm.CompanyProductRai,
  2171. ServiceTemplateId: tempItem.ServiceTemplateId,
  2172. Title: tempItem.Title,
  2173. Value: tempItem.Value,
  2174. TableValue: tempItem.TableValue,
  2175. ChartPermissionId: tempItem.ChartPermissionId,
  2176. }
  2177. rowServices = append(rowServices, cs)
  2178. } else {
  2179. rootName := "行业套餐"
  2180. // 新增三条套餐信息
  2181. parentName, _ := raiIndustryMap[k]
  2182. childName := titleMap[k]
  2183. fullName := childName+"_"+parentName+"_"+rootName
  2184. if fullName != "" {
  2185. //增加三级权限
  2186. tempItem := serviceTempFullNameMap[fullName]
  2187. if tempItem == nil {
  2188. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2189. return
  2190. }
  2191. cs := &fms.ContractService{
  2192. ProductId: crm.CompanyProductRai,
  2193. ServiceTemplateId: tempItem.ServiceTemplateId,
  2194. Title: tempItem.Title,
  2195. Value: tempItem.Value,
  2196. TableValue: tempItem.TableValue,
  2197. ChartPermissionId: tempItem.ChartPermissionId,
  2198. }
  2199. rowServices = append(rowServices, cs)
  2200. //增加二级权限
  2201. tempItem = serviceTempFullNameMap[parentName+"_"+rootName]
  2202. if tempItem == nil {
  2203. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2204. return
  2205. }
  2206. cs = &fms.ContractService{
  2207. ProductId: crm.CompanyProductRai,
  2208. ServiceTemplateId: tempItem.ServiceTemplateId,
  2209. Title: tempItem.Title,
  2210. Value: tempItem.Value,
  2211. TableValue: tempItem.TableValue,
  2212. ChartPermissionId: tempItem.ChartPermissionId,
  2213. }
  2214. rowServices = append(rowServices, cs)
  2215. //增加一级权限
  2216. tempItem = serviceTempFullNameMap[rootName]
  2217. if tempItem == nil {
  2218. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2219. return
  2220. }
  2221. cs = &fms.ContractService{
  2222. ProductId: crm.CompanyProductRai,
  2223. ServiceTemplateId: tempItem.ServiceTemplateId,
  2224. Title: tempItem.Title,
  2225. Value: tempItem.Value,
  2226. TableValue: tempItem.TableValue,
  2227. ChartPermissionId: tempItem.ChartPermissionId,
  2228. }
  2229. rowServices = append(rowServices, cs)
  2230. }
  2231. }
  2232. productIds[crm.CompanyProductRai] = struct{}{}
  2233. }
  2234. continue
  2235. }
  2236. // 权益研选等套餐
  2237. if k >= 45 && k<=49 {
  2238. if v == "是" {
  2239. tempItem := serviceTempNameMap[titleMap[k]]
  2240. if tempItem == nil {
  2241. resp.Fail(fmt.Sprintf("第%d行套餐名称不匹配, 请按模板导入", i+1), c)
  2242. return
  2243. }
  2244. cs := &fms.ContractService{
  2245. ProductId: crm.CompanyProductRai,
  2246. ServiceTemplateId: tempItem.ServiceTemplateId,
  2247. Title: tempItem.Title,
  2248. Value: tempItem.Value,
  2249. TableValue: tempItem.TableValue,
  2250. ChartPermissionId: tempItem.ChartPermissionId,
  2251. }
  2252. cs.Set()
  2253. rowServices = append(rowServices, cs)
  2254. productIds[crm.CompanyProductRai] = struct{}{}
  2255. }
  2256. continue
  2257. }
  2258. // 套餐备注
  2259. if k == 50 {
  2260. rowRegister.ServiceRemark = v
  2261. continue
  2262. }
  2263. // 开始时间/到期时间
  2264. if k == 51 {
  2265. // 转换失败可能是因为格式为Excel日期格式, 读取出来会是一串数字, 将其转换成日期字符串再处理
  2266. va := cell.Value
  2267. if va == "" {
  2268. resp.Fail(fmt.Sprintf("第%d行开始时间不可为空, 请按模板导入", i+1), c)
  2269. return
  2270. }
  2271. startDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2272. if e != nil {
  2273. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2274. startDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2275. if e != nil {
  2276. resp.Fail(fmt.Sprintf("第%d行开始时间格式转换有误, 请按模板导入", i+1), c)
  2277. return
  2278. }
  2279. }
  2280. // 转换后的日期小于1900-01-01表示当前生成的日期是有问题的
  2281. if startDate.Before(checkDate) {
  2282. resp.Fail(fmt.Sprintf("第%d行开始时间格式有误, 请按模板导入", i+1), c)
  2283. return
  2284. }
  2285. rowRegister.StartDate = startDate
  2286. continue
  2287. }
  2288. if k == 52 {
  2289. va := cell.Value
  2290. if va == "" {
  2291. resp.Fail(fmt.Sprintf("第%d行到期时间不可为空, 请按模板导入", i+1), c)
  2292. return
  2293. }
  2294. endDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2295. if e != nil {
  2296. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2297. endDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2298. if e != nil {
  2299. resp.Fail(fmt.Sprintf("第%d行到期时间格式转换有误, 请按模板导入", i+1), c)
  2300. return
  2301. }
  2302. }
  2303. if endDate.Before(checkDate) {
  2304. resp.Fail(fmt.Sprintf("第%d行到期时间格式有误, 请按模板导入", i+1), c)
  2305. return
  2306. }
  2307. rowRegister.EndDate = endDate
  2308. continue
  2309. }
  2310. // 合同金额
  2311. if k == 53 {
  2312. amountStr := v
  2313. amount, e := strconv.ParseFloat(amountStr, 64)
  2314. if e != nil {
  2315. resp.Fail(fmt.Sprintf("第%d行合同金额有误, 请按模板导入", i+1), c)
  2316. return
  2317. }
  2318. rowRegister.ContractAmount = amount
  2319. continue
  2320. }
  2321. // 金额单位
  2322. if k == 54 {
  2323. rate := rateMap[v]
  2324. if rate <= 0 {
  2325. resp.Fail(fmt.Sprintf("第%d行金额单位有误, 请按模板导入", i+1), c)
  2326. return
  2327. }
  2328. rowRegister.CurrencyUnit = v
  2329. rowRegister.RMBRate = rate
  2330. continue
  2331. }
  2332. // FICC 套餐总金额
  2333. if k == 55 {
  2334. amountStr := v
  2335. amount, e := strconv.ParseFloat(amountStr, 64)
  2336. if e != nil {
  2337. resp.Fail(fmt.Sprintf("第%d行FICC套餐总金额有误, 请按模板导入", i+1), c)
  2338. return
  2339. }
  2340. if amount > 0 {
  2341. tmp := &fms.ContractServiceAmount{
  2342. ProductId: crm.CompanyProductFicc,
  2343. ServiceAmount: amount,
  2344. CurrencyUnit: rowRegister.CurrencyUnit,
  2345. TimeBase: base.TimeBase{},
  2346. }
  2347. rowServiceAmount = append(rowServiceAmount, tmp)
  2348. }
  2349. continue
  2350. }
  2351. // 权益套餐总金额
  2352. if k == 56 {
  2353. amountStr := v
  2354. amount, e := strconv.ParseFloat(amountStr, 64)
  2355. if e != nil {
  2356. resp.Fail(fmt.Sprintf("第%d行权益套餐总金额有误, 请按模板导入", i+1), c)
  2357. return
  2358. }
  2359. if amount > 0 {
  2360. tmp := &fms.ContractServiceAmount{
  2361. ProductId: crm.CompanyProductRai,
  2362. ServiceAmount: amount,
  2363. CurrencyUnit: rowRegister.CurrencyUnit,
  2364. TimeBase: base.TimeBase{},
  2365. }
  2366. rowServiceAmount = append(rowServiceAmount, tmp)
  2367. }
  2368. continue
  2369. }
  2370. // 约定付款日期
  2371. if k == 57 {
  2372. rowRegister.AgreedPayTime = v
  2373. continue
  2374. }
  2375. // 签订日
  2376. if k == 58 {
  2377. va := cell.Value
  2378. if va == "" {
  2379. continue
  2380. }
  2381. signDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2382. if e != nil {
  2383. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2384. signDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2385. if e != nil {
  2386. resp.Fail(fmt.Sprintf("第%d行签订日格式转换有误, 请按模板导入", i+1), c)
  2387. return
  2388. }
  2389. }
  2390. if signDate.Before(checkDate) {
  2391. resp.Fail(fmt.Sprintf("第%d行签订日格式有误, 请按模板导入", i+1), c)
  2392. return
  2393. }
  2394. rowRegister.SignDate = signDate
  2395. continue
  2396. }
  2397. // 合同状态
  2398. if k == 59 {
  2399. rowRegister.ContractStatus = fms.ContractStatusNameKeyMap[v]
  2400. if rowRegister.ContractStatus == 0 {
  2401. resp.Fail(fmt.Sprintf("第%d行合同状态不匹配, 请按模板导入", i+1), c)
  2402. return
  2403. }
  2404. continue
  2405. }
  2406. // 合同编号
  2407. if k == 60 {
  2408. rowContractCode := v
  2409. if rowContractCode == "" {
  2410. resp.Fail(fmt.Sprintf("第%d行合同编号不可为空, 请按模板导入", i+1), c)
  2411. return
  2412. }
  2413. if utils.InArrayByStr(contractCodeArr, rowContractCode) {
  2414. // 此合同已登记, 跳过本行的读取
  2415. isSkip = true
  2416. break
  2417. }
  2418. rowRegister.ContractCode = rowContractCode
  2419. continue
  2420. }
  2421. // 合规备注
  2422. if k == 61 {
  2423. rowRegister.Remark = v
  2424. continue
  2425. }
  2426. // 开票列表
  2427. k2 := 61
  2428. for ir := 0; ir < invoiceMax; ir++ {
  2429. n := ir + 1
  2430. // 开票日
  2431. k2 += 1
  2432. if k == k2 {
  2433. if v != "" {
  2434. va := cell.Value
  2435. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2436. if e != nil {
  2437. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2438. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2439. if e != nil {
  2440. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式转换有误, 请按模板导入", i+1, n), c)
  2441. return
  2442. }
  2443. }
  2444. if invoiceDate.Before(checkDate) {
  2445. resp.Fail(fmt.Sprintf("第%d行开票时间%d格式有误, 请按模板导入", i+1, n), c)
  2446. return
  2447. }
  2448. rowInvoices[ir].InvoiceDate = invoiceDate
  2449. rowInvoices[ir].ContractCode = rowRegister.ContractCode
  2450. rowInvoices[ir].InvoiceType = fms.ContractInvoiceTypeMake
  2451. }
  2452. continue
  2453. }
  2454. // 开票金额
  2455. k2 += 1
  2456. if k == k2 {
  2457. if v != "" {
  2458. amountStr := v
  2459. amount, e := strconv.ParseFloat(amountStr, 64)
  2460. if e != nil {
  2461. resp.Fail(fmt.Sprintf("第%d行开票金额%d有误, 请按模板导入", i+1, n), c)
  2462. return
  2463. }
  2464. if rowRegister.RMBRate <= 0 {
  2465. resp.Fail(fmt.Sprintf("第%d行开票金额换算%d有误, 请按模板导入金额单位", i+1, n), c)
  2466. return
  2467. }
  2468. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amount/rowRegister.RMBRate), 64)
  2469. rowInvoices[ir].OriginAmount = amount
  2470. rowInvoices[ir].Amount = a
  2471. }
  2472. continue
  2473. }
  2474. // 开票套餐类型
  2475. k2 += 1
  2476. if k == k2 {
  2477. if v != "" {
  2478. if v == "FICC套餐" {
  2479. rowInvoices[ir].ServiceProductId = crm.CompanyProductFicc
  2480. }else if v == "权益套餐"{
  2481. rowInvoices[ir].ServiceProductId = crm.CompanyProductRai
  2482. }else{
  2483. resp.Fail(fmt.Sprintf("第%d行开票套餐类型%d:%s有误, 请按模板导入", i+1, n, v), c)
  2484. return
  2485. }
  2486. }
  2487. continue
  2488. }
  2489. // 开票销售
  2490. k2 += 1
  2491. if k == k2 {
  2492. if v != "" {
  2493. sellerItem := sellerMap[v]
  2494. if sellerItem == nil {
  2495. resp.Fail(fmt.Sprintf("第%d行开票销售名称与系统销售不匹配, 请核对名称后导入", i+1), c)
  2496. return
  2497. }
  2498. rowInvoices[ir].SellerId = sellerItem.SellerId
  2499. rowInvoices[ir].SellerName = sellerItem.SellerName
  2500. rowInvoices[ir].SellerGroupId = sellerItem.GroupId
  2501. rowInvoices[ir].SellerGroupName = sellerItem.GroupName
  2502. rowInvoices[ir].SellerTeamId = sellerItem.TeamId
  2503. rowInvoices[ir].SellerTeamName = sellerItem.TeamName
  2504. }
  2505. continue
  2506. }
  2507. // 备注
  2508. k2 += 1
  2509. if k == k2 {
  2510. if v != "" {
  2511. rowInvoices[ir].Remark = v
  2512. }
  2513. continue
  2514. }
  2515. }
  2516. // 到款列表
  2517. for ir := 0; ir < invoiceMax; ir++ {
  2518. n := ir + 1
  2519. // 到款日
  2520. k2 += 1
  2521. if k == k2 {
  2522. if v != "" {
  2523. va := cell.Value
  2524. invoiceDate, e := time.ParseInLocation("2006/01/02", va, time.Local)
  2525. if e != nil {
  2526. d := utils.ConvertToFormatDay(va, "2006/01/02")
  2527. invoiceDate, e = time.ParseInLocation("2006/01/02", d, time.Local)
  2528. if e != nil {
  2529. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式转换有误, 请按模板导入", i+1, n), c)
  2530. return
  2531. }
  2532. }
  2533. if invoiceDate.Before(checkDate) {
  2534. resp.Fail(fmt.Sprintf("第%d行到款时间%d格式有误, 请按模板导入", i+1, n), c)
  2535. return
  2536. }
  2537. rowPayments[ir].InvoiceDate = invoiceDate
  2538. rowPayments[ir].ContractCode = rowRegister.ContractCode
  2539. rowPayments[ir].InvoiceType = fms.ContractInvoiceTypePay
  2540. }
  2541. continue
  2542. }
  2543. // 到款金额
  2544. k2 += 1
  2545. if k == k2 {
  2546. if v != "" {
  2547. amountStr := v
  2548. amount, e := strconv.ParseFloat(amountStr, 64)
  2549. if e != nil {
  2550. resp.Fail(fmt.Sprintf("第%d行到款金额%d有误, 请按模板导入", i+1, n), c)
  2551. return
  2552. }
  2553. if rowRegister.RMBRate <= 0 {
  2554. resp.Fail(fmt.Sprintf("第%d行到款金额换算%d有误, 请按模板导入金额单位", i+1, n), c)
  2555. return
  2556. }
  2557. // 付款方式
  2558. dayDiff := rowRegister.EndDate.Sub(rowRegister.StartDate).Hours() / 24
  2559. contractAmount := rowRegister.ContractAmount
  2560. payType := fmsService.CalculateContractPaymentType(amount, contractAmount, dayDiff)
  2561. rowPayments[ir].PayType = payType
  2562. rowPayments[ir].OriginAmount = amount
  2563. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", amount/rowRegister.RMBRate), 64)
  2564. rowPayments[ir].Amount = a
  2565. }
  2566. continue
  2567. }
  2568. // 到款套餐类型
  2569. k2 += 1
  2570. if k == k2 {
  2571. if v != "" {
  2572. if v == "FICC套餐" {
  2573. rowPayments[ir].ServiceProductId = crm.CompanyProductFicc
  2574. }else if v == "权益套餐"{
  2575. rowPayments[ir].ServiceProductId = crm.CompanyProductRai
  2576. }else{
  2577. resp.Fail(fmt.Sprintf("第%d行到款套餐类型%d:%s有误, 请按模板导入", i+1, n, v), c)
  2578. return
  2579. }
  2580. }
  2581. continue
  2582. }
  2583. // 备注
  2584. k2 += 1
  2585. if k == k2 {
  2586. if v != "" {
  2587. rowPayments[ir].Remark = v
  2588. }
  2589. continue
  2590. }
  2591. }
  2592. }
  2593. if isSkip {
  2594. continue
  2595. }
  2596. // 小套餐
  2597. if len(rowChartPermissionIdArr) > 0 {
  2598. // 说明有小套餐
  2599. tempItem := serviceTempNameMap["FICC小套餐"]
  2600. if tempItem == nil {
  2601. resp.Fail(fmt.Sprintf("第%d行小套餐名称不匹配, 请按模板导入", i+1), c)
  2602. return
  2603. }
  2604. rowChartPermissionIds := strings.Join(rowChartPermissionIdArr, ",")
  2605. cs := &fms.ContractService{
  2606. ProductId: crm.CompanyProductFicc,
  2607. ServiceTemplateId: tempItem.ServiceTemplateId,
  2608. Title: tempItem.Title,
  2609. Value: tempItem.Value,
  2610. TableValue: tempItem.TableValue,
  2611. ChartPermissionId: tempItem.ChartPermissionId,
  2612. ChartPermissionIds: rowChartPermissionIds,
  2613. }
  2614. cs.Set()
  2615. rowServices = append(rowServices, cs)
  2616. }
  2617. // 如果导入的最后一条合同编号为空并且合同编号之后的字段均为空
  2618. // excel这个包读行的时候不会再往后面没数据的地方读取, 所以此处需要重新判断一次
  2619. if rowRegister.ContractCode == "" {
  2620. resp.Fail(fmt.Sprintf("第%d行合同编号为空", i+1), c)
  2621. return
  2622. }
  2623. rowRegister.RegisterStatus = fms.ContractRegisterStatusIng
  2624. rowInvoiceList := make([]*fms.ContractInvoice, 0)
  2625. // 过滤信息不完整的开票到款
  2626. for l := range rowInvoices {
  2627. if rowInvoices[l].ContractCode != "" {
  2628. if rowInvoices[l].OriginAmount <= 0 || rowInvoices[l].SellerId == 0 {
  2629. resp.Fail(fmt.Sprintf("第%d行开票信息必填项不完整", i+1), c)
  2630. return
  2631. }
  2632. rowInvoiceList = append(rowInvoiceList, rowInvoices[l])
  2633. }
  2634. }
  2635. for l := range rowPayments {
  2636. if rowPayments[l].ContractCode != "" {
  2637. if rowPayments[l].OriginAmount <= 0 {
  2638. resp.Fail(fmt.Sprintf("第%d行到款信息必填项不完整", i+1), c)
  2639. return
  2640. }
  2641. rowInvoiceList = append(rowInvoiceList, rowPayments[l])
  2642. }
  2643. }
  2644. // 新增登记、套餐、开票到款信息
  2645. for proId, _ := range productIds {
  2646. rowRegister.ProductIds += strconv.Itoa(proId)+","
  2647. }
  2648. rowRegister.ProductIds = strings.Trim(rowRegister.ProductIds, ",")
  2649. newId, e := fms.CreateImportContractRegister(rowRegister, rowServices, rowInvoiceList, rowServiceAmount)
  2650. if e != nil {
  2651. resp.FailData(fmt.Sprintf("第%d行导入失败", i+1), "新增导入登记失败, Err: "+e.Error(), c)
  2652. return
  2653. }
  2654. newIds = append(newIds, newId)
  2655. }
  2656. }
  2657. }
  2658. resp.Ok("操作成功", c)
  2659. }
  2660. // CurrencyList
  2661. // @Title 货币单位列表
  2662. // @Description 货币单位列表
  2663. // @Success 200 {object} fms.CurrencyUnitItem
  2664. // @router /contract/register/currency_list [get]
  2665. func (rg *RegisterController) CurrencyList(c *gin.Context) {
  2666. list, e := fmsService.GetTodayCurrencyRateList()
  2667. if e != nil {
  2668. resp.FailData("获取失败", "获取今日货币汇率列表失败, Err: "+e.Error(), c)
  2669. return
  2670. }
  2671. resp.OkData("获取成功", list, c)
  2672. }