register.go 94 KB

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