register.go 94 KB

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