StatisticsController.cs 214 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456
  1. using Aspose.Cells;
  2. using OASystem.API.OAMethodLib;
  3. using OASystem.Domain.Dtos.Statistics;
  4. using OASystem.Domain.Entities.Customer;
  5. using OASystem.Domain.Entities.Groups;
  6. using OASystem.Domain.ViewModels.Financial;
  7. using OASystem.Domain.ViewModels.Statistics;
  8. using OASystem.Infrastructure.Repositories.Groups;
  9. using System.Data;
  10. using static OASystem.API.OAMethodLib.GeneralMethod;
  11. using TypeInfo = OASystem.Domain.ViewModels.Statistics.TypeInfo;
  12. namespace OASystem.API.Controllers
  13. {
  14. /// <summary>
  15. /// 统计模块
  16. /// </summary>
  17. [Route("api/[controller]")]
  18. [ApiController]
  19. public class StatisticsController : ControllerBase
  20. {
  21. private readonly int _decimalPlaces;
  22. private readonly IConfiguration _config;
  23. private readonly IMapper _mapper;
  24. private readonly SqlSugarClient _sqlSugar;
  25. private readonly DelegationInfoRepository _groupRep;
  26. private readonly SetDataRepository _setDataRep;
  27. private readonly TeamRateRepository _teamRateRep;
  28. private readonly VisitingClientsRepository _visitingClientsRep;
  29. /// <summary>
  30. /// Init
  31. /// </summary>
  32. /// <param name="mapper"></param>
  33. /// <param name="sqlSugar"></param>
  34. /// <param name="groupRep"></param>
  35. /// <param name="setDataRep"></param>
  36. public StatisticsController(IMapper mapper, IConfiguration config, SqlSugarClient sqlSugar, DelegationInfoRepository groupRep, SetDataRepository setDataRep, TeamRateRepository teamRate, VisitingClientsRepository visitingClientsRep)
  37. {
  38. _mapper = mapper;
  39. _config = config;
  40. _groupRep = groupRep;
  41. _setDataRep = setDataRep;
  42. _sqlSugar = sqlSugar;
  43. _teamRateRep = teamRate;
  44. _visitingClientsRep = visitingClientsRep;
  45. }
  46. #region 团组报表
  47. /// <summary>
  48. /// 团组报表
  49. /// Items
  50. /// </summary>
  51. /// <param name="_dto">团组列表请求dto</param>
  52. /// <returns></returns>
  53. [HttpPost("PostGroupStatementItems")]
  54. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  55. public async Task<IActionResult> PostGroupStatementItems(GroupStatementItemsDto _dto)
  56. {
  57. #region 参数验证
  58. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  59. if (_dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
  60. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  61. #region 页面操作权限验证
  62. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  63. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  64. #endregion
  65. #endregion
  66. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  67. {
  68. string sqlWhere = string.Empty;
  69. if (_dto.IsSure == 0) //未完成
  70. {
  71. sqlWhere += string.Format(@" And IsSure = 0");
  72. }
  73. else if (_dto.IsSure == 1) //已完成
  74. {
  75. sqlWhere += string.Format(@" And IsSure = 1");
  76. }
  77. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  78. {
  79. string tj = _dto.SearchCriteria;
  80. sqlWhere += string.Format(@"And (ssd.Name Like '%{0}%' Or TeamName Like '%{1}%' Or ClientName Like '%{2}%' Or ClientName Like '%{3}%' Or su.CnName Like '%{4}%')",
  81. tj, tj, tj, tj, tj);
  82. }
  83. string sql = string.Format(@"Select row_number() over(order by gdi.VisitDate Desc) as Row_Number,
  84. gdi.Id,TourCode,ssd1.Id TeamLevId,ssd1.Name TeamLev,TeamName,
  85. ClientName,ClientUnit,VisitDate,ssd.Id TeamTypeId, ssd.Name TeamType,
  86. VisitDays,VisitPNumber,su.CnName JietuanOperator,IsSure,gdi.CreateTime,
  87. pr.LastCollectionTime
  88. From Grp_DelegationInfo gdi
  89. Left Join Sys_SetData ssd On gdi.TeamDid = ssd.Id
  90. Left Join Sys_SetData ssd1 On gdi.TeamLevSId = ssd1.Id
  91. Left Join Sys_Users su On gdi.JietuanOperator = su.Id
  92. Left Join (
  93. SELECT Diid, MAX(CreateTime) LastCollectionTime
  94. FROM Fin_ProceedsReceived
  95. Where IsDel = 0
  96. GROUP BY Diid
  97. ) pr On gdi.Id = pr.Diid
  98. Where gdi.IsDel = 0 {0} ", sqlWhere);
  99. RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
  100. var _DelegationList = await _sqlSugar.SqlQueryable<GroupStatementItemView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);//ToPageAsync
  101. var _view = new
  102. {
  103. PageFuncAuth = pageFunAuthView,
  104. Data = _DelegationList
  105. };
  106. return Ok(JsonView(true, "查询成功!", _view, total));
  107. }
  108. else
  109. {
  110. return Ok(JsonView(false, "查询失败"));
  111. }
  112. }
  113. /// <summary>
  114. /// 团组报表
  115. /// Details
  116. /// </summary>
  117. /// <param name="_dto">团组列表请求dto</param>
  118. /// <returns></returns>
  119. [HttpPost("PostGroupStatementDetails")]
  120. //[JsonConverter(typeof(DecimalConverter), 2)]
  121. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  122. public async Task<IActionResult> PostGroupStatementDetails(GroupStatementDetailsDto _dto)
  123. {
  124. /*
  125. * 团组报表计算方式
  126. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  127. * 应收金额 = 应收表.Sum()
  128. * 已收金额 = 已收表.Sum()
  129. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  130. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  131. *
  132. */
  133. #region 参数验证
  134. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  135. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  136. if (_dto.DiId < 1) return Ok(JsonView(false, "团组Id为空"));
  137. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  138. #region 页面操作权限验证
  139. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  140. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  141. #endregion
  142. #endregion
  143. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  144. {
  145. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  146. #region 费用类型 币种,转账,客户信息
  147. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  148. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
  149. #endregion
  150. #region 团组收入
  151. GroupIncomeView _giView = new GroupIncomeView();
  152. /*
  153. * 应收报表
  154. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  155. */
  156. decimal frTotalAmount = 0.00M;//应收总金额
  157. string _frSql = string.Format(@" Select fr.Id,fr.AddingWay,fr.Status,u.CnName As Auditor,fr.AuditTime,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  158. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  159. From Fin_ForeignReceivables fr
  160. Left Join Sys_SetData sd On fr.Currency = sd.Id
  161. Left Join Sys_Users u On fr.Auditor = u.Id
  162. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  163. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  164. //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  165. //if (_frViews1.Count > 0)
  166. //{
  167. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  168. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  169. //}
  170. _frViews.ForEach(x =>
  171. {
  172. string namePrefix = string.Empty;
  173. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  174. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  175. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  176. x.PriceName = $"{namePrefix}{x.PriceName}";
  177. });
  178. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  179. _giView.Receivables = _frViews;
  180. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  181. /*
  182. * 已收报表
  183. */
  184. decimal prTotalAmount = 0.00M;//已收总金额
  185. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  186. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  187. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  188. From Fin_ProceedsReceived pr
  189. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  190. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  191. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  192. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  193. prTotalAmount = _prViews.Sum(it => it.Price);
  194. _giView.ProceedsReceivedViews = _prViews;
  195. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
  196. /*
  197. * 超支费用
  198. */
  199. decimal exTotalAmount = 0.00M;
  200. // string ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,(gec.PriceSum * gec.Coefficient) As PayMoney,sd1.Name As PaymentCurrency,
  201. // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  202. // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  203. //From OA2023DB.dbo.Fin_GroupExtraCost gec
  204. //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  205. // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  206. // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  207. // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  208. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  209. //Where ccp.IsDel = 0 And ccp.CTable = 1015 {1} And ccp.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1 And ccp.IsPay = 1 " : " ");
  210. // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
  211. // #region 超支费用 - 模拟数据
  212. // //if (_ExtraCostsViews.Count < 1)
  213. // //{
  214. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  215. // // {
  216. // // GECId = 0,
  217. // // GECDiId = 2334,
  218. // // PriceName = "模拟数据-超支费用名称",
  219. // // PayMoney = 1000.00M,
  220. // // PaymentCurrency = "CNY",
  221. // // DayRate = 1.0000M,
  222. // // CNYPrice = 1000.00M,
  223. // // Payee = "模拟数据-超支费用收款方",
  224. // // OrbitalPrivateTransfer = 1,
  225. // // PayWay = "刷卡",
  226. // // CardType = "招行卡",
  227. // // IsPay = 1,
  228. // // Applicant = "刘华举"
  229. // // });
  230. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  231. // // {
  232. // // GECId = 0,
  233. // // GECDiId = 2334,
  234. // // PriceName = "模拟数据-超支费用名称",
  235. // // PayMoney = 1000.00M,
  236. // // PaymentCurrency = "CNY",
  237. // // DayRate = 1.0000M,
  238. // // CNYPrice = 1000.00M,
  239. // // Payee = "模拟数据-超支费用收款方",
  240. // // OrbitalPrivateTransfer = 1,
  241. // // PayWay = "刷卡",
  242. // // CardType = "招行卡",
  243. // // IsPay = 1,
  244. // // Applicant = "刘华举"
  245. // // });
  246. // //}
  247. // #endregion
  248. // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  249. // _giView.ExtraCostsViews = _ExtraCostsViews;
  250. // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  251. /*
  252. * 收款退还
  253. */
  254. decimal promTotalAmount = 0.00M;// 收款退还总金额
  255. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  256. //删除了 And prom.PriceType = 1
  257. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  258. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  259. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  260. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
  261. From Fin_PaymentRefundAndOtherMoney prom
  262. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  263. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  264. Where prom.IsDel = 0
  265. And prom.PayType = 1
  266. And ccp.CTable = 285
  267. {1}
  268. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  269. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  270. foreach (var ropItem in _promDatas)
  271. {
  272. string thisCueencyCode = "Unknown";
  273. string thisCueencyName = "Unknown";
  274. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  275. if (currency != null)
  276. {
  277. thisCueencyCode = currency.Name;
  278. thisCueencyName = currency.Remark;
  279. }
  280. string orbitalPrivateTransferStr = "Unknown";
  281. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  282. if (orbitalPrivateTransfer != null)
  283. {
  284. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  285. }
  286. string payStr = "Unknown";
  287. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  288. if (pay != null)
  289. {
  290. payStr = pay.Name;
  291. }
  292. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  293. {
  294. Id = ropItem.Id,
  295. DiId = ropItem.DIId,
  296. PriceName = ropItem.PrPriceName,
  297. PayCurrencyCode = thisCueencyCode,
  298. PayCurrencyName = thisCueencyName,
  299. Price = ropItem.PrPrice,
  300. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  301. ThisRate = ropItem.DayRate,
  302. Payee = ropItem.Payee,
  303. PayTime = ropItem.AuditGMDate,
  304. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  305. PayType = payStr,
  306. IsPay = ropItem.IsPay,
  307. Applicant = ropItem.Appliction
  308. };
  309. _promView.Add(gsd_PaymentRefund);
  310. }
  311. #region 收款退还 - 模拟数据
  312. //if (_promView.Count < 1)
  313. //{
  314. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  315. // {
  316. // Id = 0,
  317. // DiId = 2334,
  318. // PriceName = "模拟数据-费用名称",
  319. // PayCurrencyCode = "CNY",
  320. // PayCurrencyName = "人民币",
  321. // Price = 1000.00M,
  322. // CNYPrice = 1000.00M,
  323. // ThisRate = 1.00M,
  324. // Payee = "模拟数据-收款方",
  325. // PayTime = "2023-01-01 15:20:01",
  326. // OrbitalPrivateTransfer = 1,
  327. // PayType = "刷卡",
  328. // IsPay = 1,
  329. // Applicant = "刘华举"
  330. // });
  331. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  332. // {
  333. // Id = 0,
  334. // DiId = 2334,
  335. // PriceName = "模拟数据-费用名称",
  336. // PayCurrencyCode = "CNY",
  337. // PayCurrencyName = "人民币",
  338. // Price = 1000.00M,
  339. // CNYPrice = 1000.00M,
  340. // ThisRate = 1.00M,
  341. // Payee = "模拟数据-收款方",
  342. // PayTime = "2023-01-01 15:20:01",
  343. // OrbitalPrivateTransfer = 1,
  344. // PayType = "刷卡",
  345. // IsPay = 1,
  346. // Applicant = "刘华举"
  347. // });
  348. //}
  349. #endregion
  350. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  351. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  352. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  353. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  354. _view.GroupIncome = _giView;
  355. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  356. #endregion
  357. #region 团组支出
  358. GroupExpenditureView _geView = new GroupExpenditureView();
  359. #region 酒店预定费用
  360. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  361. //ccp.RMBPrice As CNYPrice
  362. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  363. string hotelFeeSql = string.Format(@"
  364. SELECT
  365. hr.Id AS HrId,
  366. hr.DiId AS HrDiId,
  367. hr.City,
  368. hr.HotelName,
  369. hr.CheckInDate,
  370. hr.CheckOutDate,
  371. hr.CardPrice AS RoomPrice,
  372. sd1.Name AS PaymentCurrency,
  373. hr.SingleRoomPrice,
  374. hr.SingleRoomCount,
  375. hr.DoubleRoomPrice,
  376. hr.DoubleRoomCount,
  377. hr.SuiteRoomPrice,
  378. hr.SuiteRoomCount,
  379. hr.OtherRoomPrice,
  380. hr.OtherRoomCount,
  381. hr.BreakfastPrice,
  382. sd4.Name AS BreakfastCurrency,
  383. hr.Isoppay,
  384. hr.GovernmentRent,
  385. sd5.Name AS GovernmentRentCurrency,
  386. hr.CityTax,
  387. sd6.Name AS CityTaxCurrency,
  388. ccp.PayMoney,
  389. (
  390. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  391. ) AS CNYPrice,
  392. ccp.PayPercentage,
  393. ccp.DayRate,
  394. ccp.Payee,
  395. ccp.OrbitalPrivateTransfer,
  396. sd2.Name AS PayWay,
  397. sd3.Name AS CardType,
  398. ccp.IsPay,
  399. u.CnName AS Applicant
  400. FROM
  401. Grp_HotelReservations hr
  402. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  403. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  404. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  405. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  406. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  407. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  408. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  409. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  410. WHERE
  411. hr.IsDel = 0
  412. AND ccp.IsDel = 0
  413. AND ccp.CTable = 76 {1}
  414. AND ccp.PayMoney <> 0
  415. AND hr.DiId = {0}
  416. ORDER BY
  417. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  418. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  419. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  420. List<Grp_HotelReservationsContent> groupHotelContentFeeViews = new List<Grp_HotelReservationsContent>();
  421. groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  422. decimal HotelCNYTotalPrice = 0.00M;
  423. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  424. foreach (var item in groupHotelFeeViews)
  425. {
  426. if (groupHotelContentFeeViews.Count > 0)
  427. {
  428. string paymentStr = string.Empty;
  429. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  430. item.RoomPrice = roomData?.Price ?? 0.00M;
  431. if (item.RoomPrice != 0)
  432. {
  433. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  434. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  435. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  436. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  437. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  438. 收款方:{roomData?.Payee}<br/>
  439. 费用标识:{feeMark1} <br/>
  440. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  441. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  442. 是否由地接支付:{isFeeMark1} <br/>";
  443. }
  444. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  445. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  446. if (item.BreakfastPrice != 0)
  447. {
  448. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  449. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  450. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  451. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  452. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  453. 收款方:{breakfastData?.Payee}<br/>
  454. 费用标识:{feeMark2} <br/>
  455. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  456. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  457. 是否由地接支付:{isFeeMark2} <br/>";
  458. }
  459. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  460. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  461. if (item.GovernmentRent != 0)
  462. {
  463. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  464. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  465. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  466. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  467. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  468. 收款方:{landTaxData?.Payee}<br/>
  469. 费用标识:{feeMark3} <br/>
  470. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  471. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  472. 是否由地接支付:{isFeeMark3} <br/>";
  473. }
  474. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  475. item.CityTax = cityTaxData?.Price ?? 0.00M;
  476. if (item.CityTax != 0)
  477. {
  478. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  479. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  480. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  481. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  482. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  483. 收款方:{cityTaxData?.Payee}<br/>
  484. 费用标识:{feeMark4} <br/>
  485. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  486. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  487. 是否由地接支付:{isFeeMark4} <br/>";
  488. }
  489. if (!string.IsNullOrEmpty(paymentStr))
  490. {
  491. item.IsPay = 2;
  492. item.PayTips = paymentStr;
  493. }
  494. }
  495. else
  496. {
  497. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  498. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  499. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  500. (item.OtherRoomCount * item.OtherRoomPrice);
  501. //item.RoomPrice = item.CardPrice;
  502. item.RoomPriceCurrency = item.PaymentCurrency;
  503. }
  504. HotelCNYTotalPrice += item.CNYPrice;
  505. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  506. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  507. }
  508. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  509. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  510. #endregion
  511. #region 地接费用
  512. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  513. string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  514. sd2.name As PaymentCurrency,ccp.PayPercentage,
  515. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  516. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  517. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  518. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  519. From Grp_CarTouristGuideGroundReservations ctggr
  520. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  521. cggrc.DatePrice,cggrc.PriceContent
  522. From Grp_CarTouristGuideGroundReservationsContent cggrc
  523. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  524. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  525. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  526. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  527. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  528. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  529. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  530. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  531. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  532. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  533. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  534. string CTGGRFeeStr = "";
  535. decimal CTGGRCNYTotalPrice = 0.00M;
  536. //按1 地区,2 币种,3 汇率 分组计算
  537. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  538. foreach (var ctggfr in groupCTGGRFeeDatas)
  539. {
  540. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  541. if (ctggfr_curr.Count() > 0)
  542. {
  543. foreach (var curr in ctggfr_curr)
  544. {
  545. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  546. if (ctggfr_rate.Count() > 0)
  547. {
  548. foreach (var rate in ctggfr_rate)
  549. {
  550. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  551. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  552. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  553. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  554. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  555. }
  556. }
  557. else
  558. {
  559. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  560. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  561. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  562. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  563. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  564. }
  565. }
  566. }
  567. else
  568. {
  569. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  570. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  571. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  572. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  573. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  574. }
  575. }
  576. foreach (var item in groupCTGGRFeeViews)
  577. {
  578. if (!string.IsNullOrEmpty(item.AuditGMDate))
  579. {
  580. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  581. }
  582. if (item.DatePrice != null)
  583. {
  584. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  585. }
  586. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  587. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  588. //CTGGRCNYTotalPrice += item.CNYPrice;
  589. }
  590. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  591. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  592. #endregion
  593. #region 机票预订费用
  594. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  595. //ccp.RMBPrice As CNYPrice
  596. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  597. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  598. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  599. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  600. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  601. atr.CType
  602. From Grp_AirTicketReservations atr
  603. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  604. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  605. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  606. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  607. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  608. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  609. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  610. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  611. string str = "";
  612. List<dynamic> airClientPris = new List<dynamic>();
  613. decimal AirCNYTotalPrice = 0.00M;
  614. decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M, JJCAveragePrice = 0.00M;
  615. decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M, GWCAveragePrice = 0.00M;
  616. //if (groupAirFeeViews.Count > 0)
  617. //{
  618. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  619. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  620. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  621. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  622. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  623. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  624. //}
  625. int Index = 0;
  626. foreach (var item in groupAirFeeViews)
  627. {
  628. if (item.AirId > 2924)
  629. {
  630. string itemClientName = "";
  631. if (!string.IsNullOrEmpty(item.ClientName))
  632. {
  633. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  634. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  635. if (m_EnName.Success || m_ZHName.Success)
  636. {
  637. itemClientName = item.ClientName;
  638. decimal unitCost = 0.00M;
  639. AirCNYTotalPrice += item.CNYPrice;
  640. continue;
  641. }
  642. string[] clientIds = new string[] { };
  643. if (item.ClientName.Contains(','))
  644. {
  645. clientIds = item.ClientName.Split(',');
  646. }
  647. else
  648. {
  649. clientIds = new string[] { item.ClientName };
  650. }
  651. if (clientIds.Length > 0)
  652. {
  653. int[] output = Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  654. if (output.Contains(-1))
  655. {
  656. itemClientName += $@"行程单";
  657. output = output.Where(val => val != -1).ToArray();
  658. }
  659. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  660. decimal unitCost = 0.00M;
  661. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  662. int clienIndex = 1;
  663. foreach (var client in clients)
  664. {
  665. airClientPris.Add(new
  666. {
  667. CnName = client.LastName + client.FirstName,
  668. EnName = client.Pinyin,
  669. Price = unitCost,
  670. AirType = item.AirTypeName
  671. });
  672. string six = "";
  673. if (client.Sex == 0) six = "Mr";
  674. else if (client.Sex == 1) six = "Ms";
  675. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  676. clienIndex++;
  677. }
  678. }
  679. }
  680. item.ClientName = itemClientName;
  681. }
  682. else
  683. {
  684. string clientPinYinName = "";
  685. decimal unitCost = 0.00M;
  686. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  687. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  688. Regex r = new Regex("[0-9]");
  689. string name1 = item.ClientName;
  690. name1 = r.Replace(name1, "");
  691. string[] clientNames = name1.Split('.');
  692. for (int i = 0; i < item.ClientNum; i++)
  693. {
  694. string name = "";
  695. if (clientNames.Length > 0)
  696. {
  697. int index = i + 1;
  698. if (index < clientNames.Length)
  699. {
  700. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  701. if (!string.IsNullOrEmpty(name))
  702. {
  703. airClientPris.Add(new
  704. {
  705. CnName = name,
  706. EnName = name,
  707. Price = unitCost,
  708. AirType = item.AirTypeName
  709. });
  710. }
  711. //if (name.Length > 0)
  712. //{
  713. // string nameLastStr = name[name.Length - 1].ToString();
  714. // if (nameLastStr.IsNumeric())
  715. // {
  716. // name = name.Substring(0, name.Length - 1).Trim();
  717. // }
  718. //}
  719. }
  720. }
  721. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  722. }
  723. }
  724. if (!string.IsNullOrEmpty(item.AuditGMDate))
  725. {
  726. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  727. }
  728. AirCNYTotalPrice += item.CNYPrice;
  729. }
  730. _geView.GroupAirFeeViews = groupAirFeeViews;
  731. if (airClientPris.Count > 0)
  732. {
  733. var peoplePriStr = "";
  734. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  735. .Select(group => group.First())
  736. .ToList();
  737. int airClientPrisIndex = 1;
  738. foreach (var item in airClientPris1)
  739. {
  740. decimal price = 0.00M;
  741. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  742. foreach (var pri in prices)
  743. {
  744. price += pri.Price;
  745. }
  746. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  747. airClientPrisIndex++;
  748. }
  749. if (!string.IsNullOrEmpty(peoplePriStr))
  750. {
  751. str = $@"其中:{peoplePriStr}";
  752. }
  753. //经济舱均价
  754. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  755. if (airJJCPris.Count > 0)
  756. {
  757. decimal jjcTotalPrice = 0.00M;
  758. foreach (var item in airJJCPris)
  759. {
  760. jjcTotalPrice += item.Price;
  761. }
  762. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  763. .Select(group => group.First())
  764. .ToList().Count;
  765. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  766. }
  767. //公务舱均价
  768. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  769. if (airGWCPris.Count > 0)
  770. {
  771. decimal gwcTotalPrice = 0.00M;
  772. foreach (var item in airGWCPris)
  773. {
  774. gwcTotalPrice += item.Price;
  775. }
  776. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  777. .Select(group => group.First())
  778. .ToList().Count;
  779. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  780. }
  781. }
  782. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  783. #endregion
  784. #region 签证费用
  785. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  786. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  787. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  788. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  789. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  790. From Grp_VisaInfo vi
  791. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  792. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  793. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  794. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  795. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  796. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  797. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  798. decimal VisaCNYTotalPirce = 0.00M;
  799. foreach (var item in groupVisaFeeViews)
  800. {
  801. string itemClientName = "";
  802. string visaClients = item.VisaClient;
  803. if (!string.IsNullOrEmpty(visaClients))
  804. {
  805. string[] clientIds = new string[] { };
  806. if (visaClients.Contains(','))
  807. {
  808. clientIds = visaClients.Split(',');
  809. }
  810. else
  811. {
  812. clientIds = new string[] { visaClients };
  813. }
  814. if (clientIds.Length > 0)
  815. {
  816. List<int> clientIds1 = new List<int>() { };
  817. foreach (var clientIdStr in clientIds)
  818. {
  819. if (clientIdStr.IsNumeric())
  820. {
  821. clientIds1.Add(int.Parse(clientIdStr));
  822. }
  823. }
  824. if (clientIds1.Count > 0)
  825. {
  826. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  827. foreach (var client in clients)
  828. {
  829. itemClientName += $"{client.LastName + client.FirstName},";
  830. }
  831. }
  832. else
  833. {
  834. itemClientName = visaClients;
  835. }
  836. }
  837. }
  838. if (itemClientName.Length > 0)
  839. {
  840. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  841. }
  842. item.VisaClient = itemClientName;
  843. VisaCNYTotalPirce += item.CNYPrice;
  844. if (!string.IsNullOrEmpty(item.AuditGMDate))
  845. {
  846. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  847. }
  848. }
  849. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  850. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#.00"));
  851. #endregion
  852. #region 邀请/公务活动 CTable = 81
  853. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  854. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  855. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  856. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  857. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
  858. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  859. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  860. From Grp_InvitationOfficialActivities ioa
  861. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  862. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  863. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  864. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  865. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  866. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  867. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  868. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  869. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  870. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  871. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  872. #region 邀请/公务活动 - 模拟数据
  873. //if (groupInvitationalFeeViews.Count < 1)
  874. //{
  875. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  876. // {
  877. // IOAId = 0,
  878. // IOADiId = 2334,
  879. // InviterArea = "模拟数据-邀请方地区",
  880. // Inviter = "模拟数据-邀请方",
  881. // InviteTime = "2023-10-10",
  882. // InviteCost = 100.00M,
  883. // InviteCurrency = "EUR",
  884. // SendCost = 100.00M,
  885. // SendCurrency = "EUR",
  886. // EventsCost = 10000.00M,
  887. // EventsCurrency = "EUR",
  888. // TranslateCost = 300.00M,
  889. // TranslateCurrency = "EUR",
  890. // PayMoney = 10500.00M,
  891. // PaymentCurrency = "EUR",
  892. // CNYPrice = 76765.50M,
  893. // Payee = "模拟数据-收款方",
  894. // AuditGMDate = "2023-12-05",
  895. // OrbitalPrivateTransfer = 1,
  896. // PayWay = "刷卡",
  897. // IsPay = 1,
  898. // Applicant = "刘华举"
  899. // });
  900. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  901. // {
  902. // IOAId = 0,
  903. // IOADiId = 2334,
  904. // InviterArea = "模拟数据-邀请方地区",
  905. // Inviter = "模拟数据-邀请方",
  906. // InviteTime = "2023-10-10",
  907. // InviteCost = 100.00M,
  908. // InviteCurrency = "EUR",
  909. // SendCost = 100.00M,
  910. // SendCurrency = "EUR",
  911. // EventsCost = 10000.00M,
  912. // EventsCurrency = "EUR",
  913. // TranslateCost = 300.00M,
  914. // TranslateCurrency = "EUR",
  915. // PayMoney = 10500.00M,
  916. // PaymentCurrency = "EUR",
  917. // CNYPrice = 76765.50M,
  918. // Payee = "模拟数据-收款方",
  919. // AuditGMDate = "2023-12-05",
  920. // OrbitalPrivateTransfer = 1,
  921. // PayWay = "刷卡",
  922. // IsPay = 1,
  923. // Applicant = "刘华举"
  924. // });
  925. //}
  926. #endregion
  927. decimal InvitationalCNYTotalPrice = 0.00M;
  928. foreach (var item in groupInvitationalFeeViews)
  929. {
  930. InvitationalCNYTotalPrice += item.CNYPrice2;
  931. if (!string.IsNullOrEmpty(item.AuditGMDate))
  932. {
  933. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  934. }
  935. string currencyRateStr = "";
  936. List<string> currencys = new List<string>();
  937. if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
  938. if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
  939. if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
  940. if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
  941. if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
  942. currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
  943. item.CurrencyRateStr = currencyRateStr;
  944. }
  945. _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
  946. _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#.00"));
  947. #endregion
  948. #region 保险费用
  949. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  950. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
  951. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  952. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  953. From Grp_Customers ic
  954. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  955. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  956. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  957. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  958. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  959. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  960. decimal InsuranceCNYTotalPrice = 0.00M;
  961. foreach (var item in groupInsuranceFeeViews)
  962. {
  963. InsuranceCNYTotalPrice += item.CNYPrice;
  964. string itemClientName = "";
  965. string insClients = item.ClientName;
  966. if (!string.IsNullOrEmpty(insClients))
  967. {
  968. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  969. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  970. //if (m_EnName.Success || m_ZHName.Success)
  971. //{
  972. // itemClientName = insClients;
  973. // continue;
  974. //}
  975. string[] clientIds = new string[] { };
  976. if (insClients.Contains(','))
  977. {
  978. clientIds = insClients.Split(',');
  979. }
  980. else
  981. {
  982. clientIds = new string[] { insClients };
  983. }
  984. if (clientIds.Length > 0)
  985. {
  986. List<int> output = new List<int>();
  987. foreach (var clientId in clientIds)
  988. {
  989. if (clientId.IsNumeric())
  990. {
  991. output.Add(int.Parse(clientId));
  992. }
  993. }
  994. if (output.Count > 0)
  995. {
  996. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  997. foreach (var client in clients)
  998. {
  999. itemClientName += $"{client.LastName + client.FirstName},";
  1000. }
  1001. if (itemClientName.Length > 0)
  1002. {
  1003. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1004. }
  1005. }
  1006. else
  1007. {
  1008. itemClientName = insClients;
  1009. }
  1010. }
  1011. }
  1012. item.ClientName = itemClientName;
  1013. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1014. {
  1015. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1016. }
  1017. }
  1018. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  1019. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  1020. #endregion
  1021. #region 其他款项费用 98
  1022. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  1023. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1024. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  1025. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1026. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  1027. From Grp_DecreasePayments dp
  1028. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1029. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1030. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1031. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1032. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1033. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1034. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  1035. #region 保险费用 - 模拟数据
  1036. //if (groupDecreaseFeeViews.Count < 1)
  1037. //{
  1038. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1039. // {
  1040. // DPId = 0,
  1041. // DPDiId = 2334,
  1042. // PriceName = "模拟数据-费用名称",
  1043. // PayMoney = 1000.00M,
  1044. // PayMoneyCurrency = "CNY",
  1045. // DayRate = 1.0000M,
  1046. // CNYPrice = 1.0000M,
  1047. // AuditGMDate = "2023-12-10 12:13:00",
  1048. // Payee = "模拟数据-付款方",
  1049. // OrbitalPrivateTransfer = 1,
  1050. // PayWay = "现金",
  1051. // IsPay = 1,
  1052. // Applicant = "刘华举"
  1053. // });
  1054. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1055. // {
  1056. // DPId = 0,
  1057. // DPDiId = 2334,
  1058. // PriceName = "模拟数据-费用名称",
  1059. // PayMoney = 1000.00M,
  1060. // PayMoneyCurrency = "CNY",
  1061. // DayRate = 1.0000M,
  1062. // CNYPrice = 1.0000M,
  1063. // AuditGMDate = "2023-12-10 12:13:00",
  1064. // Payee = "模拟数据-付款方",
  1065. // OrbitalPrivateTransfer = 1,
  1066. // PayWay = "现金",
  1067. // IsPay = 1,
  1068. // Applicant = "刘华举"
  1069. // });
  1070. //}
  1071. #endregion
  1072. decimal DecreaseCNYTotalPrice = 0.00M;
  1073. foreach (var item in groupDecreaseFeeViews)
  1074. {
  1075. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  1076. DecreaseCNYTotalPrice += item.CNYPrice;
  1077. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1078. {
  1079. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1080. }
  1081. }
  1082. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  1083. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  1084. #endregion
  1085. _view.GroupExpenditure = _geView;
  1086. #endregion
  1087. /*
  1088. * 团组报表计算方式
  1089. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1090. * 应收金额 = 应收表.Sum()
  1091. * 已收金额 = 已收表.Sum()
  1092. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1093. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1094. *
  1095. */
  1096. decimal _totalExpenditure = 0.00M; //总支出
  1097. decimal _amountReceivable = 0.00M; //应收金额
  1098. decimal _amountReceived = 0.00M; //已收金额
  1099. decimal _receivableProfit = 0.00M; //应收利润
  1100. decimal _receivedProfit = 0.00M; //已收利润
  1101. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  1102. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  1103. _amountReceivable = frTotalAmount;
  1104. _amountReceived = prTotalAmount;
  1105. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  1106. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  1107. _view.FeeTotalStr = string.Format(@$"<span>
  1108. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  1109. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  1110. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  1111. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  1112. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  1113. </span>");
  1114. return Ok(JsonView(true, "查询成功!", _view));
  1115. }
  1116. else
  1117. {
  1118. return Ok(JsonView(false, "查询成功"));
  1119. }
  1120. }
  1121. #endregion
  1122. #region 报表/折线图统计
  1123. //企业利润-团组利润
  1124. //企业利润-会务利润
  1125. /// <summary>
  1126. /// 企业利润
  1127. /// Details
  1128. /// 待添加权限验证
  1129. /// </summary>
  1130. /// <param name="_dto">团组列表请求dto</param>
  1131. /// <returns></returns>
  1132. [HttpPost("PostCorporateProfit")]
  1133. //[JsonConverter(typeof(DecimalConverter), 2)]
  1134. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1135. public async Task<IActionResult> PostCorporateProfit(PostCorporateProfitDto _dto)
  1136. {
  1137. #region 参数验证
  1138. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1139. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  1140. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  1141. if (_dto.StatisticsType > 2 && _dto.StatisticsType < 1) return Ok(JsonView(false, "请输入有效的StatisticsType参数,1 月份 2 季度"));
  1142. if (_dto.BusinessType > 3 && _dto.BusinessType < 1) return Ok(JsonView(false, "请输入有效的BusinessType参数,1 所有 2 团组 3 会务"));
  1143. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1144. #region 页面操作权限验证
  1145. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  1146. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  1147. #endregion
  1148. string sqlWhere = string.Empty;
  1149. //起止时间
  1150. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  1151. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  1152. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  1153. //业务类型
  1154. List<int> groupTypeId = new List<int>();
  1155. if (_dto.BusinessType == 2) //团组
  1156. {
  1157. groupTypeId.AddRange(new List<int>() {
  1158. 38, // 政府团
  1159. 39, // 企业团
  1160. 40, // 散客团
  1161. 1048 // 高校团
  1162. });
  1163. }
  1164. else if (_dto.BusinessType == 3) //会务
  1165. {
  1166. groupTypeId.AddRange(new List<int>() {
  1167. 102, // 未知
  1168. 248, // 非团组
  1169. 302, // 成都-会务活动
  1170. 691, // 四川-会务活动
  1171. 762, // 四川-赛事项目收入
  1172. 1047 // 成都-赛事项目收入
  1173. });
  1174. }
  1175. if (groupTypeId.Count > 0)
  1176. {
  1177. sqlWhere += string.Format(@$" And TeamDid In ({string.Join(',', groupTypeId)})");
  1178. }
  1179. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  1180. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  1181. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  1182. List<int> diIds = groupInfos.Select(it => it.Id).ToList();
  1183. List<CorporateProfit> corporateProfits = await CorporateProfit(diIds);
  1184. List<MonthInfo> months = new List<MonthInfo>();
  1185. if (_dto.StatisticsType == 1) //月份
  1186. {
  1187. months = GeneralMethod.GetMonthInfos(Convert.ToInt32(_dto.Year));
  1188. }
  1189. else if (_dto.StatisticsType == 1) //季度
  1190. {
  1191. months = GeneralMethod.GetQuarter(Convert.ToInt32(_dto.Year));
  1192. }
  1193. List<CorporateProfitMonthView> _view = new List<CorporateProfitMonthView>();
  1194. foreach (var item in months)
  1195. {
  1196. DateTime monthBeginDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.BeginDays} 00:00:00");
  1197. DateTime monthEndDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.EndDays} 23:59:59");
  1198. var corporateProfit = corporateProfits.Where(it => it.CreateDt >= monthBeginDt && it.CreateDt <= monthEndDt).ToList();
  1199. _view.Add(new CorporateProfitMonthView()
  1200. {
  1201. Month = item.Month,
  1202. Profit = corporateProfit.Sum(it => it.ReceivedProfit),
  1203. GroupInfos = corporateProfit.OrderBy(it => it.CreateDt).ToList()
  1204. });
  1205. }
  1206. return Ok(JsonView(true, "操作成功!", _view));
  1207. #endregion
  1208. }
  1209. /// <summary>
  1210. /// 计算团组利润
  1211. /// </summary>
  1212. /// <param name="diIds"></param>
  1213. /// <returns></returns>
  1214. private async Task<List<CorporateProfit>> CorporateProfit(List<int> diIds)
  1215. {
  1216. List<CorporateProfit> corporateProfits = new List<CorporateProfit>();
  1217. if (diIds.Count < 1)
  1218. {
  1219. return corporateProfits;
  1220. }
  1221. #region 计算团组利润
  1222. /*
  1223. * 团组报表计算方式
  1224. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1225. * 应收金额 = 应收表.Sum()
  1226. * 已收金额 = 已收表.Sum()
  1227. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1228. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1229. *
  1230. */
  1231. string diIdStr = string.Join(",", diIds);
  1232. string sql = string.Format(@$"Select * From Grp_DelegationInfo Where Isdel = 0 And Id In ({diIdStr})");
  1233. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToListAsync();
  1234. #region 费用类型 币种,转账,客户信息
  1235. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1236. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
  1237. #endregion
  1238. foreach (var _diId in diIds)
  1239. {
  1240. List<ExpenditureInfo> expenditureInfos = new List<ExpenditureInfo>();
  1241. #region 团组收入
  1242. /*
  1243. * 应收报表
  1244. */
  1245. decimal frTotalAmount = 0.00M;//应收总金额
  1246. string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  1247. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  1248. From Fin_ForeignReceivables fr
  1249. Left Join Sys_SetData sd On fr.Currency = sd.Id
  1250. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _diId);
  1251. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  1252. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  1253. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "应收项", Amount = frTotalAmount });
  1254. /*
  1255. * 已收报表
  1256. */
  1257. decimal prTotalAmount = 0.00M;//已收总金额
  1258. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  1259. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  1260. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  1261. From Fin_ProceedsReceived pr
  1262. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  1263. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  1264. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _diId);
  1265. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  1266. prTotalAmount = _prViews.Sum(it => it.Price);
  1267. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "已收项", Amount = prTotalAmount });
  1268. /*
  1269. * 超支费用
  1270. */
  1271. decimal exTotalAmount = 0.00M;
  1272. string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,ccp.PayMoney,sd1.Name As PaymentCurrency,
  1273. ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  1274. sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  1275. From OA2023DB.dbo.Fin_GroupExtraCost gec
  1276. Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  1277. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1278. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1279. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1280. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1281. Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _diId);
  1282. List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();
  1283. exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  1284. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "超支费用", Amount = exTotalAmount });
  1285. /*
  1286. * 收款退还
  1287. */
  1288. decimal promTotalAmount = 0.00M;// 收款退还总金额
  1289. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  1290. //删除了 And prom.PriceType = 1
  1291. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  1292. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  1293. prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime
  1294. From Fin_PaymentRefundAndOtherMoney prom
  1295. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  1296. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1297. Where prom.IsDel = 0 And prom.PayType = 1 And ccp.CTable = 285
  1298. And ccp.IsAuditGM = 1 And ccp.IsPay = 1
  1299. And prom.DiId = {0} Order By PrCreateTime", _diId);
  1300. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  1301. foreach (var ropItem in _promDatas)
  1302. {
  1303. string thisCueencyCode = "Unknown";
  1304. string thisCueencyName = "Unknown";
  1305. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  1306. if (currency != null)
  1307. {
  1308. thisCueencyCode = currency.Name;
  1309. thisCueencyName = currency.Remark;
  1310. }
  1311. string orbitalPrivateTransferStr = "Unknown";
  1312. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  1313. if (orbitalPrivateTransfer != null)
  1314. {
  1315. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  1316. }
  1317. string payStr = "Unknown";
  1318. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  1319. if (pay != null)
  1320. {
  1321. payStr = pay.Name;
  1322. }
  1323. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  1324. {
  1325. Id = ropItem.Id,
  1326. DiId = ropItem.DIId,
  1327. PriceName = ropItem.PrPriceName,
  1328. PayCurrencyCode = thisCueencyCode,
  1329. PayCurrencyName = thisCueencyName,
  1330. Price = ropItem.PrPrice,
  1331. CNYPrice = ropItem.RMBPrice,
  1332. ThisRate = ropItem.DayRate,
  1333. Payee = ropItem.Payee,
  1334. PayTime = ropItem.AuditGMDate,
  1335. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  1336. PayType = payStr,
  1337. IsPay = ropItem.IsPay,
  1338. Applicant = ropItem.Appliction
  1339. };
  1340. _promView.Add(gsd_PaymentRefund);
  1341. }
  1342. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  1343. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "收款退还", Amount = promTotalAmount });
  1344. #endregion
  1345. #region 团组支出
  1346. GroupExpenditureView _geView = new GroupExpenditureView();
  1347. #region 酒店预定费用
  1348. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  1349. string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,
  1350. sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,
  1351. hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,
  1352. hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,
  1353. sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,
  1354. ccp.PayMoney,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,
  1355. sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant
  1356. From Grp_HotelReservations hr
  1357. Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId
  1358. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1359. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1360. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1361. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1362. Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id
  1363. Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id
  1364. Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id
  1365. Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And hr.DiId = {0}
  1366. Order By CheckInDate Asc", _diId);
  1367. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  1368. decimal HotelCNYTotalPrice = groupHotelFeeViews.Sum(it => it.CNYPrice);
  1369. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "酒店预定", Amount = HotelCNYTotalPrice });
  1370. #endregion
  1371. #region 地接费用
  1372. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  1373. string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.Area,ctggrc.*,ctggrc.Price As PayMoney,
  1374. sd2.name As PaymentCurrency,ccp.PayPercentage,
  1375. (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,
  1376. (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,
  1377. ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  1378. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1379. From Grp_CarTouristGuideGroundReservations ctggr
  1380. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,
  1381. cggrc.PriceContent
  1382. From Grp_CarTouristGuideGroundReservationsContent cggrc
  1383. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  1384. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  1385. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  1386. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  1387. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1388. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1389. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1390. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1391. Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ctggr.DiId = {0}
  1392. Order By CreateTime", _diId);
  1393. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  1394. decimal CTGGRCNYTotalPrice = groupCTGGRFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1395. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "地接", Amount = CTGGRCNYTotalPrice });
  1396. #endregion
  1397. #region 机票预订费用
  1398. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  1399. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  1400. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  1401. sd1.Name As PayMoneyCurrency,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  1402. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime
  1403. From Grp_AirTicketReservations atr
  1404. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  1405. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1406. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1407. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1408. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  1409. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1410. Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And atr.DiId = {0} Order By CreateTime", _diId);
  1411. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  1412. decimal AirCNYTotalPrice = groupAirFeeViews.Sum(it => it.CNYPrice);
  1413. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "机票预订", Amount = AirCNYTotalPrice });
  1414. #endregion
  1415. #region 签证费用
  1416. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  1417. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1418. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  1419. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime
  1420. From Grp_VisaInfo vi
  1421. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  1422. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1423. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1424. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1425. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1426. Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And vi.DIId = {0} Order By CreateTime", _diId);
  1427. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  1428. decimal VisaCNYTotalPirce = groupVisaFeeViews.Sum(it => it.PayMoney);
  1429. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "签证", Amount = VisaCNYTotalPirce });
  1430. #endregion
  1431. #region 邀请/公务活动 CTable = 81
  1432. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  1433. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  1434. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  1435. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  1436. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  1437. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  1438. From Grp_InvitationOfficialActivities ioa
  1439. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  1440. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1441. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1442. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  1443. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  1444. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  1445. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  1446. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  1447. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1448. Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ioa.Diid = {0} Order By CreateTime", _diId);
  1449. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  1450. decimal InvitationalCNYTotalPrice = groupInvitationalFeeViews.Sum(it => it.CNYPrice);
  1451. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "邀请/公务活动", Amount = InvitationalCNYTotalPrice });
  1452. #endregion
  1453. #region 保险费用
  1454. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  1455. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,
  1456. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1457. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  1458. From Grp_Customers ic
  1459. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1460. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1461. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1462. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1463. Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ic.DiId = {0} Order By CreateTime", _diId);
  1464. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  1465. decimal InsuranceCNYTotalPrice = groupInsuranceFeeViews.Sum(it => it.CNYPrice);
  1466. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "保险费用", Amount = InsuranceCNYTotalPrice });
  1467. #endregion
  1468. #region 其他款项费用 98
  1469. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  1470. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1471. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  1472. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1473. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  1474. From Grp_DecreasePayments dp
  1475. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1476. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1477. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1478. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1479. Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And dp.Diid = {0}
  1480. Order By CreateTime", _diId);
  1481. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  1482. decimal DecreaseCNYTotalPrice = groupDecreaseFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1483. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "其他款项", Amount = DecreaseCNYTotalPrice });
  1484. #endregion
  1485. #endregion
  1486. /*
  1487. * 团组报表计算方式
  1488. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1489. * 应收金额 = 应收表.Sum()
  1490. * 已收金额 = 已收表.Sum()
  1491. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1492. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1493. *
  1494. */
  1495. decimal _totalExpenditure = 0.00M; //总支出
  1496. decimal _amountReceivable = 0.00M; //应收金额
  1497. decimal _amountReceived = 0.00M; //已收金额
  1498. decimal _receivableProfit = 0.00M; //应收利润
  1499. decimal _receivedProfit = 0.00M; //已收利润
  1500. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  1501. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  1502. _amountReceivable = frTotalAmount;
  1503. _amountReceived = prTotalAmount;
  1504. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  1505. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  1506. var groupInfo = groupInfos.Find(it => it.Id == _diId);
  1507. corporateProfits.Add(new CorporateProfit()
  1508. {
  1509. DiId = _diId,
  1510. TeamName = groupInfo?.TeamName ?? "Unkwnon",
  1511. CreateDt = Convert.ToDateTime(groupInfo?.CreateTime),
  1512. TotalExpenditure = _totalExpenditure,
  1513. ExpenditureItem = expenditureInfos,
  1514. AmountReceivable = _amountReceivable,
  1515. AmountReceived = _amountReceived,
  1516. ReceivableProfit = _receivableProfit,
  1517. ReceivedProfit = _receivedProfit,
  1518. });
  1519. }
  1520. #endregion
  1521. return corporateProfits;
  1522. }
  1523. //未来预测-地区接团/出团量
  1524. //未来预测-地区酒店预订量
  1525. //未来预测-地区机票预订量
  1526. //未来预测-地区车辆预订量
  1527. /// <summary>
  1528. /// (国家/城市)地区预订数量(团,酒店,机票,车辆)
  1529. /// Details
  1530. /// 待添加权限验证
  1531. /// </summary>
  1532. /// <param name="_dto">团组列表请求dto</param>
  1533. /// <returns></returns>
  1534. [HttpPost("PostRegionalBookingsNumber")]
  1535. //[JsonConverter(typeof(DecimalConverter), 2)]
  1536. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1537. public async Task<IActionResult> PostRegionalBookingsNumber(PostRegionalBookingsNumberDto _dto)
  1538. {
  1539. #region 参数验证
  1540. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1541. //if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  1542. if (_dto.Type > 1 && _dto.Type > 5) return Ok(JsonView(false, "请输入有效的Type参数,1 团 2 酒店 3 机票 4 车辆"));
  1543. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  1544. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1545. #region 页面操作权限验证
  1546. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  1547. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  1548. #endregion
  1549. string sqlWhere = string.Empty;
  1550. //起止时间
  1551. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  1552. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  1553. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  1554. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  1555. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  1556. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  1557. List<GroupTypeNumberInfo> datas = new List<GroupTypeNumberInfo>();
  1558. foreach (var item in groupInfos)
  1559. {
  1560. var data = await GroupBookingsNumber(_dto.Type, item);
  1561. if (data.TypeItem.Count > 0)
  1562. {
  1563. datas.Add(data);
  1564. }
  1565. }
  1566. //类型处理
  1567. if (_dto.Type == 1)//接团
  1568. {
  1569. List<GroupBookingNumberView> views = new List<GroupBookingNumberView>();
  1570. dynamic groupData = null;
  1571. foreach (var item in datas)
  1572. {
  1573. if (item.TypeItem.Count > 0)
  1574. {
  1575. foreach (var item1 in item.TypeItem)
  1576. {
  1577. if (item1.RegionItem.Count > 0)
  1578. {
  1579. GroupInfo groupInfo = new GroupInfo()
  1580. {
  1581. DiId = item.DiId,
  1582. TeamName = item.GroupName,
  1583. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  1584. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  1585. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  1586. };
  1587. views.Add(new GroupBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, GroupItem = new List<GroupInfo>() { groupInfo } });
  1588. }
  1589. }
  1590. }
  1591. }
  1592. var viewsGroup = views.GroupBy(it => it.Name);
  1593. List<GroupBookingNumberView> _view = new List<GroupBookingNumberView>();
  1594. foreach (var item in viewsGroup)
  1595. {
  1596. List<GroupInfo> infos = new List<GroupInfo>();
  1597. foreach (var item1 in item)
  1598. {
  1599. infos.AddRange(item1.GroupItem);
  1600. }
  1601. infos = infos.OrderByDescending(it => it.CreateTime).ToList(); //
  1602. _view.Add(new GroupBookingNumberView() { Name = item.Key, Number = item.Count(), GroupItem = infos });
  1603. }
  1604. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  1605. return Ok(JsonView(true, "操作成功!", _view, _view.Count));
  1606. }
  1607. else if (_dto.Type == 2)
  1608. {
  1609. List<HotelBookingNumberView> views = new List<HotelBookingNumberView>();
  1610. foreach (var item in datas)
  1611. {
  1612. if (item.TypeItem.Count > 0)
  1613. {
  1614. foreach (var item1 in item.TypeItem)
  1615. {
  1616. if (item1.RegionItem.Count > 0)
  1617. {
  1618. foreach (var item2 in item1.RegionItem)
  1619. {
  1620. GroupInfo groupInfo = new GroupInfo()
  1621. {
  1622. DiId = item.DiId,
  1623. TeamName = item.GroupName,
  1624. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  1625. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  1626. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  1627. };
  1628. List<HotelInfo> hotels = new List<HotelInfo>();
  1629. foreach (var item3 in item2.Data)
  1630. {
  1631. StatisticsHotelInfo statisticsHotelInfos = JsonConvert.DeserializeObject<StatisticsHotelInfo>(JsonConvert.SerializeObject(item3));
  1632. HotelInfo hotelInfo = new HotelInfo()
  1633. {
  1634. HotelName = statisticsHotelInfos.HotelName,
  1635. SingleRoomNum = statisticsHotelInfos.SingleRoomNum,
  1636. DoubleRoomNum = statisticsHotelInfos.DoubleRoomNum,
  1637. SuiteRoomNum = statisticsHotelInfos.SuiteRoomNum,
  1638. OtherRoomNum = statisticsHotelInfos.OtherRoomNum,
  1639. GroupInfo = groupInfo
  1640. };
  1641. hotels.Add(hotelInfo);
  1642. }
  1643. views.Add(new HotelBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, HotelItem = hotels });
  1644. }
  1645. }
  1646. }
  1647. }
  1648. }
  1649. var viewsGroup = views.GroupBy(it => it.Name);
  1650. List<HotelBookingNumberView> _view = new List<HotelBookingNumberView>();
  1651. foreach (var item in viewsGroup)
  1652. {
  1653. List<HotelInfo> infos = new List<HotelInfo>();
  1654. foreach (var item1 in item)
  1655. {
  1656. infos.AddRange(item1.HotelItem);
  1657. }
  1658. _view.Add(new HotelBookingNumberView() { Name = item.Key, Number = item.Count(), HotelItem = infos });
  1659. }
  1660. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  1661. return Ok(JsonView(true, "操作成功!", views, views.Count));
  1662. }
  1663. return Ok(JsonView(false, "操作失败!"));
  1664. #endregion
  1665. }
  1666. /// <summary>
  1667. /// 计算团组ALLType预订数量
  1668. /// </summary>
  1669. /// <param name="diIds"></param>
  1670. /// <returns></returns>
  1671. private async Task<GroupTypeNumberInfo> GroupBookingsNumber(int type, Grp_DelegationInfo info)
  1672. {
  1673. GroupTypeNumberInfo _view = new GroupTypeNumberInfo();
  1674. if (info == null)
  1675. {
  1676. return _view;
  1677. }
  1678. _view.DiId = info.Id;
  1679. _view.GroupName = info.TeamName;
  1680. List<TypeInfo> _types = new List<TypeInfo>();
  1681. #region 计算团组ALLType预订数量
  1682. if (type == 1)
  1683. {
  1684. //接团 客户集团所在地区
  1685. string group_region = string.Empty;
  1686. int group_number = 0;
  1687. if (!string.IsNullOrEmpty(info.ClientUnit))
  1688. {
  1689. var _NewClientData = await _sqlSugar.Queryable<Crm_NewClientData>().Where(it => it.IsDel == 0 && it.Client.Equals(info.ClientUnit)).FirstAsync();
  1690. if (_NewClientData != null)
  1691. {
  1692. var regionInfo = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == _NewClientData.Lvlid).FirstAsync();
  1693. if (regionInfo != null)
  1694. {
  1695. group_region = regionInfo.Name.Replace("级", "");
  1696. group_number++;
  1697. }
  1698. }
  1699. }
  1700. if (group_number > 0)
  1701. {
  1702. _types.Add(new TypeInfo() { Id = 1, RegionItem = new List<RegionInfo>() { new RegionInfo() { Name = group_region, Number = group_number } } });
  1703. }
  1704. }
  1705. else if (type == 2)
  1706. {
  1707. //酒店
  1708. var hotelInfos = await _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  1709. if (hotelInfos.Count > 0)
  1710. {
  1711. List<RegionInfo> hotelRegions = new List<RegionInfo>();
  1712. foreach (var item in hotelInfos)
  1713. {
  1714. var hotelNumberInfo = new StatisticsHotelInfo()
  1715. {
  1716. HotelName = item.HotelName,
  1717. SingleRoomNum = item.SingleRoomCount,
  1718. DoubleRoomNum = item.DoubleRoomCount,
  1719. SuiteRoomNum = item.SuiteRoomCount,
  1720. OtherRoomNum = item.OtherRoomCount,
  1721. };
  1722. int hotelRoomTotal = item.SingleRoomCount + item.DoubleRoomCount + item.SuiteRoomCount + item.OtherRoomCount;
  1723. if (hotelRegions.Select(it => it.Name).ToList().Contains(item.City))
  1724. {
  1725. RegionInfo hotelRegion = hotelRegions.Find(it => it.Name.Equals(item.City));
  1726. if (hotelRegion != null)
  1727. {
  1728. hotelRegions.Remove(hotelRegion);
  1729. if (hotelRegion.Data.Count > 0)
  1730. {
  1731. hotelRegion.Data.Add(hotelNumberInfo);
  1732. }
  1733. hotelRegion.Number += hotelRoomTotal;
  1734. hotelRegions.Add(hotelRegion);
  1735. }
  1736. }
  1737. else
  1738. {
  1739. hotelRegions.Add(new RegionInfo() { Name = item.City, Number = hotelRoomTotal, Data = new List<dynamic>() { hotelNumberInfo } });
  1740. }
  1741. }
  1742. _types.Add(new TypeInfo() { Id = 2, RegionItem = hotelRegions });
  1743. }
  1744. }
  1745. else if (type == 3)
  1746. {
  1747. //机票
  1748. var airTicketInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  1749. .LeftJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId && ccp.IsPay == 1)
  1750. .LeftJoin<Sys_SetData>((atr, ccp, sd) => atr.CType == sd.Id)
  1751. .Where((atr, ccp, sd) => atr.IsDel == 0 && atr.DIId == info.Id)
  1752. .Select((atr, ccp, sd) => new { atr.ClientNum, atr.CType, ccp.Payee, AirType = sd.Name })
  1753. .ToListAsync();
  1754. if (airTicketInfos.Count > 0)
  1755. {
  1756. List<RegionInfo> airTicketRegions = new List<RegionInfo>();
  1757. foreach (var item in airTicketInfos)
  1758. {
  1759. var ticketClass = new
  1760. {
  1761. TiketClass = item.AirType,
  1762. Number = item.ClientNum
  1763. };
  1764. if (airTicketRegions.Select(it => it.Name).ToList().Contains(item.Payee))
  1765. {
  1766. RegionInfo airTicketRegion = airTicketRegions.Find(it => it.Name.Equals(item.Payee));
  1767. if (airTicketRegion != null)
  1768. {
  1769. airTicketRegions.Remove(airTicketRegion);
  1770. if (airTicketRegion.Data.Count > 0)
  1771. {
  1772. airTicketRegion.Data.Add(ticketClass);
  1773. }
  1774. airTicketRegion.Number += item.ClientNum;
  1775. airTicketRegions.Add(airTicketRegion);
  1776. }
  1777. }
  1778. else
  1779. {
  1780. airTicketRegions.Add(new RegionInfo() { Name = item.Payee, Number = item.ClientNum, Data = new List<dynamic>() { ticketClass } });
  1781. }
  1782. }
  1783. _types.Add(new TypeInfo() { Id = 3, RegionItem = airTicketRegions });
  1784. }
  1785. }
  1786. else if (type == 4)
  1787. {
  1788. //车辆
  1789. var opInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  1790. var opContentInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  1791. if (opInfos.Count > 0)
  1792. {
  1793. List<RegionInfo> opRegions = new List<RegionInfo>();
  1794. foreach (var item in opInfos)
  1795. {
  1796. int carNum = 0;
  1797. var opContentInfo = opContentInfos.Where(it => it.CTGGRId == item.Id && it.SId == 91).ToList();
  1798. if (opContentInfo.Count > 0)
  1799. {
  1800. foreach (var item1 in opContentInfo)
  1801. {
  1802. if (item1.Price > 0 && item1.Count > 0)
  1803. {
  1804. carNum += item1.Count;
  1805. }
  1806. }
  1807. }
  1808. if (carNum > 0)
  1809. {
  1810. var opData = new
  1811. {
  1812. ServiceCompany = item.ServiceCompany,
  1813. BusName = item.BusName,
  1814. Numbuer = carNum
  1815. };
  1816. if (opRegions.Select(it => it.Name).ToList().Contains(item.Area))
  1817. {
  1818. RegionInfo opRegion = opRegions.Find(it => it.Name.Equals(item.Area));
  1819. if (opRegion != null)
  1820. {
  1821. opRegions.Remove(opRegion);
  1822. if (opRegion.Data.Count > 0)
  1823. {
  1824. opRegion.Data.Add(opData);
  1825. }
  1826. opRegion.Number += carNum;
  1827. opRegions.Add(opRegion);
  1828. }
  1829. }
  1830. else
  1831. {
  1832. opRegions.Add(new RegionInfo() { Name = item.Area, Number = carNum, Data = new List<dynamic>() { opData } });
  1833. }
  1834. }
  1835. }
  1836. _types.Add(new TypeInfo() { Id = 4, RegionItem = opRegions });
  1837. }
  1838. }
  1839. #endregion
  1840. _view.TypeItem = _types;
  1841. return _view;
  1842. }
  1843. #endregion
  1844. #region 市场部销售额
  1845. /// <summary>
  1846. /// 市场部销售额
  1847. /// Init 基础数据(公司/人员/年份/季度/月份)
  1848. /// </summary>
  1849. /// <param name="_dto">市场部销售额请求dto</param>
  1850. /// <returns></returns>
  1851. [HttpPost("PostMarketingSalesInitData")]
  1852. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1853. public async Task<IActionResult> PostMarketingSalesInitData(MarketingSalesInitDataDto _dto)
  1854. {
  1855. #region 参数验证
  1856. MarketingSalesInitDataDtoFoalidator validationRules = new MarketingSalesInitDataDtoFoalidator();
  1857. var validResult = await validationRules.ValidateAsync(_dto);
  1858. if (!validResult.IsValid)
  1859. {
  1860. var errors = new StringBuilder();
  1861. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  1862. return Ok(JsonView(false, errors.ToString()));
  1863. }
  1864. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1865. #region 页面操作权限验证
  1866. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  1867. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  1868. #endregion
  1869. var companyData = _sqlSugar.Queryable<Sys_Company>().Where(it => it.IsDel == 0)
  1870. .Select(it => new { id = it.Id, name = it.CompanyName })
  1871. .ToList();
  1872. List<int> companyIds = companyData.Select(it => it.id).ToList();
  1873. List<int> pickGroupUserIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
  1874. .Select(it => it.JietuanOperator)
  1875. .ToList();
  1876. var userData = _sqlSugar.Queryable<Sys_Users>().Where(it => it.IsDel == 0 && (pickGroupUserIds.Contains(it.Id) || it.Id == 21))
  1877. .Select(it => new { id = it.Id, companyId = it.CompanyId, name = it.CnName })
  1878. .ToList();
  1879. companyData.Insert(0, new { id = -1, name = "全部" });
  1880. userData.Insert(0, new { id = -1, companyId = -1, name = "全部" });
  1881. #region 年份
  1882. var dtData = new List<dynamic>();
  1883. int dt = DateTime.Now.Year;
  1884. for (int y = dt; y >= dt - 4; y--)
  1885. {
  1886. //季度
  1887. var quarterDatas = new List<dynamic>();
  1888. quarterDatas.Add(new { name = "全部", beginDt = $"{y}-01-01", endDt = $"{y}-12-31" });
  1889. for (int q = 0; q < 4; q++)
  1890. {
  1891. dynamic quarterData = null;
  1892. if (q == 0)
  1893. {
  1894. var monthDatas = new List<dynamic>();
  1895. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-01-01", endDt = $" {y}-03-31" });
  1896. for (int m = 1; m < 4; m++)
  1897. {
  1898. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  1899. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  1900. }
  1901. //quarterData = new { name = "第一季度", beginDt = $"{y}-01-01", endDt = $" {y}-03-31", monthData = monthDatas };
  1902. quarterData = new { name = "第一季度", monthData = monthDatas };
  1903. }
  1904. else if (q == 1)
  1905. {
  1906. var monthDatas = new List<dynamic>();
  1907. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-04-01", endDt = $"{y}-06-30" });
  1908. for (int m = 4; m < 7; m++)
  1909. {
  1910. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  1911. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  1912. }
  1913. //quarterData = new { name = "第二季度", beginDt = $"{y}-04-01", endDt = $"{y}-06-30", monthData = monthDatas };
  1914. quarterData = new { name = "第二季度", monthData = monthDatas };
  1915. }
  1916. else if (q == 2)
  1917. {
  1918. var monthDatas = new List<dynamic>();
  1919. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-07-01", endDt = $"{y}-09-30" });
  1920. for (int m = 7; m < 10; m++)
  1921. {
  1922. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  1923. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  1924. }
  1925. //quarterData = new { name = "第三季度", beginDt = $"{y}-07-01", endDt = $"{y}-09-30", monthData = monthDatas };
  1926. quarterData = new { name = "第三季度", monthData = monthDatas };
  1927. }
  1928. else if (q == 3)
  1929. {
  1930. var monthDatas = new List<dynamic>();
  1931. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-10-01", endDt = $"{y}-12-31" });
  1932. for (int m = 10; m < 13; m++)
  1933. {
  1934. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  1935. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  1936. }
  1937. //quarterData = new { name = "第四季度", beginDt = $"{y}-10-01", endDt = $"{y}-12-31", monthData = monthDatas };
  1938. quarterData = new { name = "第四季度", monthData = monthDatas };
  1939. }
  1940. quarterDatas.Add(quarterData);
  1941. }
  1942. dtData.Add(new
  1943. {
  1944. year = y,
  1945. //yearData = new { beginDt = $"{y}-01-01", endDt = $"{y}-12-31" },
  1946. quarterData = quarterDatas,
  1947. });
  1948. }
  1949. #endregion
  1950. return Ok(JsonView(true, "操作成功!", new { companyData = companyData, userData = userData, dtData = dtData }));
  1951. #endregion
  1952. }
  1953. private static string ConvertToChinese(int month)
  1954. {
  1955. if (month < 1 || month > 12)
  1956. throw new ArgumentOutOfRangeException(nameof(month), "月份必须在1到12之间。");
  1957. var cultureInfo = new System.Globalization.CultureInfo("zh-CN");
  1958. var dateTimeFormat = cultureInfo.DateTimeFormat;
  1959. return dateTimeFormat.GetMonthName(month);
  1960. }
  1961. /// <summary>
  1962. /// 市场部销售额
  1963. /// 年度/季度/月度 报表(同比)
  1964. /// (增加团组查询条件 IsSure=1)
  1965. /// </summary>
  1966. /// <param name="_dto">市场部销售额请求dto</param>
  1967. /// <returns></returns>
  1968. [HttpPost("PostMarketingSalesStatistics")]
  1969. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1970. public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)
  1971. {
  1972. #region 参数验证
  1973. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  1974. var validResult = await validationRules.ValidateAsync(_dto);
  1975. if (!validResult.IsValid)
  1976. {
  1977. var errors = new StringBuilder();
  1978. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  1979. return Ok(JsonView(false, errors.ToString()));
  1980. }
  1981. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1982. #region 页面操作权限验证
  1983. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  1984. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  1985. #endregion
  1986. #endregion
  1987. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  1988. return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));
  1989. }
  1990. private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)
  1991. {
  1992. //全部人员Id
  1993. //查询所有公司的市场部
  1994. List<int> pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();
  1995. List<int> userIds = new List<int>();
  1996. var userDatas = await _sqlSugar.Queryable<Sys_Users>()
  1997. .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)
  1998. .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains(u.Id))
  1999. .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })
  2000. .ToListAsync();
  2001. userIds = userDatas.Select(it => it.Id).ToList();
  2002. if (companyId > 0)
  2003. {
  2004. userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();
  2005. }
  2006. if (groupPickupUserId > 0)
  2007. {
  2008. userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();
  2009. }
  2010. return userIds;
  2011. }
  2012. /// <summary>
  2013. /// 计算团组销售额
  2014. /// </summary>
  2015. /// <param name="companyId"></param>
  2016. /// <param name="groupPickupUserId"></param>
  2017. /// <param name="beginDt"></param>
  2018. /// <param name="endDt"></param>
  2019. /// <returns></returns>
  2020. private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId, string beginDt, string endDt)
  2021. {
  2022. decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;
  2023. var _view = new SalesYOYView();
  2024. List<int> userIds = new List<int>();
  2025. userIds = await GetUserIds(companyId, groupPickupUserId);
  2026. string userSqlWhere = "";
  2027. if (userIds.Count > 0)
  2028. {
  2029. userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");
  2030. }
  2031. else
  2032. {
  2033. _view = new SalesYOYView
  2034. {
  2035. thisYearSales = "0.00",
  2036. lastYearSales = "0.00",
  2037. };
  2038. return _view;
  2039. }
  2040. string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),
  2041. lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
  2042. // string salesSql = string.Format(@"
  2043. //SELECT
  2044. // 'ThisSales' As [Name],
  2045. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2046. //FROM
  2047. // (
  2048. // SELECT di.VisitDate,
  2049. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2050. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2051. // ) AS Sales
  2052. // FROM
  2053. // Grp_DelegationInfo di
  2054. // WHERE di.IsDel = 0 AND di.IsSure = 1
  2055. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  2056. // AND di.VisitDate BETWEEN '{1}' AND '{2}'
  2057. // ) temp
  2058. //Union ALL
  2059. //SELECT
  2060. // 'LastSales' As [Name],
  2061. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2062. //FROM
  2063. // (
  2064. // SELECT di.VisitDate,
  2065. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2066. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2067. // ) AS Sales
  2068. // FROM
  2069. // Grp_DelegationInfo di
  2070. // WHERE di.IsDel = 0 AND di.IsSure = 1
  2071. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  2072. // AND di.VisitDate BETWEEN '{4}' AND '{5}'
  2073. // ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  2074. string salesSql = string.Format(@"
  2075. SELECT
  2076. 'ThisSales' As [Name],
  2077. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2078. FROM
  2079. (
  2080. SELECT di.VisitDate,
  2081. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2082. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2083. ) AS Sales
  2084. FROM
  2085. Grp_DelegationInfo di
  2086. WHERE di.IsDel = 0
  2087. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  2088. AND di.VisitDate BETWEEN '{1}' AND '{2}'
  2089. ) temp
  2090. Union ALL
  2091. SELECT
  2092. 'LastSales' As [Name],
  2093. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2094. FROM
  2095. (
  2096. SELECT di.VisitDate,
  2097. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2098. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2099. ) AS Sales
  2100. FROM
  2101. Grp_DelegationInfo di
  2102. WHERE di.IsDel = 0
  2103. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  2104. AND di.VisitDate BETWEEN '{4}' AND '{5}'
  2105. ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  2106. var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();
  2107. thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;
  2108. lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;
  2109. if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;
  2110. return new SalesYOYView()
  2111. {
  2112. thisYearSales = thisSales.ToString("#0.00"),
  2113. lastYearSales = lastSales.ToString("#0.00"),
  2114. yoy = yoy.ToString("#0.00")
  2115. };
  2116. }
  2117. private class SalesView
  2118. {
  2119. public string Name { get; set; }
  2120. public decimal Sales { get; set; }
  2121. }
  2122. private class SalesYOYView
  2123. {
  2124. public string thisYearSales { get; set; }
  2125. public string lastYearSales { get; set; }
  2126. public string yoy { get; set; } = "1.00";
  2127. }
  2128. /// <summary>
  2129. /// 市场部销售额
  2130. /// 团组列表
  2131. /// </summary>
  2132. /// <param name="_dto">市场部销售额请求dto</param>
  2133. /// <returns></returns>
  2134. [HttpPost("PostMarketingSalesGroupList")]
  2135. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2136. public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)
  2137. {
  2138. #region 参数验证
  2139. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2140. var validResult = await validationRules.ValidateAsync(_dto);
  2141. if (!validResult.IsValid)
  2142. {
  2143. var errors = new StringBuilder();
  2144. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2145. return Ok(JsonView(false, errors.ToString()));
  2146. }
  2147. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2148. #region 页面操作权限验证
  2149. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2150. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2151. #endregion
  2152. #endregion
  2153. string userSql = "";
  2154. List<int> userIds = new List<int>();
  2155. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2156. if (userIds.Count <= 0)
  2157. {
  2158. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  2159. }
  2160. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  2161. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  2162. {
  2163. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  2164. }
  2165. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2166. // string sql = string.Format(@$"SELECT
  2167. // ROW_NUMBER() OVER (
  2168. // ORDER BY
  2169. // CollectionDays
  2170. // ) AS RowNumber,
  2171. // *
  2172. //FROM
  2173. // (
  2174. // SELECT
  2175. // di.Id,
  2176. // di.TeamName,
  2177. // di.ClientUnit,
  2178. // di.ClientName,
  2179. // di.VisitDate,
  2180. // di.VisitPNumber,
  2181. // di.JietuanOperator,
  2182. // di.VisitEndDate,
  2183. // (
  2184. // SELECT
  2185. // CAST(
  2186. // COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2187. // ) AS GroupSales
  2188. // FROM
  2189. // Fin_ForeignReceivables
  2190. // WHERE
  2191. // IsDel = 0
  2192. // AND di.Id = Diid
  2193. // AND AddingWay IN (0, 1, 2)
  2194. // ) AS GroupSales,
  2195. // u.CnName AS GroupPickupUser,
  2196. // DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  2197. // FROM
  2198. // Grp_DelegationInfo di
  2199. // WITH
  2200. // (NoLock)
  2201. // LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  2202. // WHERE
  2203. // di.Isdel = 0
  2204. // AND di.IsSure = 1 {userSql}
  2205. // AND VisitDate Between '{beginDt}' And '{endDt}'
  2206. // ) Temp ");
  2207. string sql = string.Format(@$"SELECT
  2208. ROW_NUMBER() OVER (
  2209. ORDER BY
  2210. CollectionDays
  2211. ) AS RowNumber,
  2212. *
  2213. FROM
  2214. (
  2215. SELECT
  2216. di.Id,
  2217. di.TeamName,
  2218. di.ClientUnit,
  2219. di.ClientName,
  2220. di.VisitDate,
  2221. di.VisitPNumber,
  2222. di.JietuanOperator,
  2223. di.VisitEndDate,
  2224. (
  2225. SELECT
  2226. CAST(
  2227. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2228. ) AS GroupSales
  2229. FROM
  2230. Fin_ForeignReceivables
  2231. WHERE
  2232. IsDel = 0
  2233. AND di.Id = Diid
  2234. AND AddingWay IN (0, 1, 2)
  2235. ) AS GroupSales,
  2236. u.CnName AS GroupPickupUser,
  2237. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  2238. FROM
  2239. Grp_DelegationInfo di
  2240. WITH
  2241. (NoLock)
  2242. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  2243. WHERE
  2244. di.Isdel = 0
  2245. {userSql}
  2246. AND VisitDate Between '{beginDt}' And '{endDt}'
  2247. ) Temp ");
  2248. RefAsync<int> total = 0;
  2249. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  2250. return Ok(JsonView(true, "操作成功!", groupData, total));
  2251. }
  2252. /// <summary>
  2253. /// 市场部销售额
  2254. /// 客户类型、客户等级 统计
  2255. /// </summary>
  2256. /// <param name="_dto">市场部销售额请求dto</param>
  2257. /// <returns></returns>
  2258. [HttpPost("PostMarketingSalesGroupStatistics")]
  2259. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2260. public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)
  2261. {
  2262. #region 参数验证
  2263. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2264. var validResult = await validationRules.ValidateAsync(_dto);
  2265. if (!validResult.IsValid)
  2266. {
  2267. var errors = new StringBuilder();
  2268. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2269. return Ok(JsonView(false, errors.ToString()));
  2270. }
  2271. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2272. #region 页面操作权限验证
  2273. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2274. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2275. #endregion
  2276. #endregion
  2277. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2278. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2279. string userSql = "";
  2280. if (userIds.Count > 0)
  2281. {
  2282. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  2283. }
  2284. else
  2285. {
  2286. if (_dto.PortType == 2 || _dto.PortType == 3)
  2287. {
  2288. return Ok(JsonView(true, "操作成功!", new List<object> { }));
  2289. }
  2290. else
  2291. {
  2292. return Ok(JsonView(true, "操作成功!", new
  2293. {
  2294. customerTypeData = new List<object> { },
  2295. clientGradeData = new List<object> { }
  2296. }));
  2297. }
  2298. }
  2299. string sql = "";
  2300. if (_dto.StatisticsType == 1)
  2301. {
  2302. sql = string.Format(@$"Select
  2303. sd.[Name],
  2304. Count(*) As [Count]
  2305. From Grp_DelegationInfo di
  2306. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  2307. Where di.Isdel = 0
  2308. {userSql}
  2309. And VisitDate Between '{beginDt}' And '{endDt}'
  2310. Group By [Name]
  2311. Order By Count Desc");
  2312. }
  2313. else if (_dto.StatisticsType == 2)
  2314. {
  2315. sql = string.Format(@$"Select
  2316. sd.[Name],
  2317. Count(*) As [Count]
  2318. From Grp_DelegationInfo di
  2319. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  2320. Where di.Isdel = 0
  2321. {userSql}
  2322. And VisitDate Between '{beginDt}' And '{endDt}'
  2323. Group By [Name]
  2324. Order By Count Desc");
  2325. }
  2326. else return Ok(JsonView(false, "StatisticsType不在可取范围!"));
  2327. if (_dto.PortType == 1)
  2328. {
  2329. string sql1 = string.Format(@$"Select
  2330. sd.[Name],
  2331. Count(*) As [Count]
  2332. From Grp_DelegationInfo di
  2333. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  2334. Where di.Isdel = 0
  2335. {userSql}
  2336. And VisitDate Between '{beginDt}' And '{endDt}'
  2337. Group By [Name]
  2338. Order By Count Desc");
  2339. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  2340. string sql2 = string.Format(@$"Select
  2341. sd.[Name],
  2342. Count(*) As [Count]
  2343. From Grp_DelegationInfo di
  2344. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  2345. Where di.Isdel = 0
  2346. {userSql}
  2347. And VisitDate Between '{beginDt}' And '{endDt}'
  2348. Group By [Name]
  2349. Order By Count Desc");
  2350. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  2351. return Ok(JsonView(true, "操作成功!", new
  2352. {
  2353. customerTypeData = customerTypeData,
  2354. clientGradeData = clientGradeData
  2355. }));
  2356. }
  2357. else if (_dto.PortType == 2 || _dto.PortType == 3)
  2358. {
  2359. var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();
  2360. return Ok(JsonView(true, "操作成功!", data, data.Count));
  2361. }
  2362. else return Ok(JsonView(false, MsgTips.Port));
  2363. }
  2364. /// <summary>
  2365. /// 市场部销售额
  2366. /// 接单排名
  2367. /// </summary>
  2368. /// <param name="_dto">市场部销售额请求dto</param>
  2369. /// <returns></returns>
  2370. [HttpPost("PostMarketingSalesOrderRanking")]
  2371. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2372. public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)
  2373. {
  2374. #region 参数验证
  2375. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2376. var validResult = await validationRules.ValidateAsync(_dto);
  2377. if (!validResult.IsValid)
  2378. {
  2379. var errors = new StringBuilder();
  2380. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2381. return Ok(JsonView(false, errors.ToString()));
  2382. }
  2383. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2384. #region 页面操作权限验证
  2385. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2386. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2387. #endregion
  2388. #endregion
  2389. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2390. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2391. string userSql = "";
  2392. if (userIds.Count > 0)
  2393. {
  2394. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  2395. }
  2396. else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  2397. string sql = string.Format(@$"Select
  2398. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  2399. u.CnName As UserName,
  2400. Count(*) As [Count]
  2401. From Grp_DelegationInfo di
  2402. Left Join Sys_Users u On di.JietuanOperator = u.Id
  2403. Where di.Isdel = 0
  2404. {userSql}
  2405. And VisitDate Between '{beginDt}' And '{endDt}'
  2406. Group By CnName");
  2407. RefAsync<int> total = 0;
  2408. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  2409. return Ok(JsonView(true, "操作成功!", rankingData, total));
  2410. }
  2411. /// <summary>
  2412. /// 市场部销售额
  2413. /// 团组列表、客户类型、客户等级、接单排名
  2414. /// </summary>
  2415. /// <param name="_dto">市场部销售额请求dto</param>
  2416. /// <returns></returns>
  2417. [HttpPost("PostMarketingSalesGroupItem")]
  2418. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2419. public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)
  2420. {
  2421. #region 参数验证
  2422. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2423. var validResult = await validationRules.ValidateAsync(_dto);
  2424. if (!validResult.IsValid)
  2425. {
  2426. var errors = new StringBuilder();
  2427. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2428. return Ok(JsonView(false, errors.ToString()));
  2429. }
  2430. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2431. #region 页面操作权限验证
  2432. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2433. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2434. #endregion
  2435. #endregion
  2436. string userSql = "";
  2437. List<int> userIds = new List<int>();
  2438. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2439. if (userIds.Count <= 0)
  2440. {
  2441. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  2442. }
  2443. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  2444. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  2445. {
  2446. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  2447. }
  2448. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2449. #region 团组List
  2450. string sql = string.Format(@$"SELECT
  2451. ROW_NUMBER() OVER (
  2452. ORDER BY
  2453. CollectionDays
  2454. ) AS RowNumber,
  2455. *
  2456. FROM
  2457. (
  2458. SELECT
  2459. di.Id,
  2460. di.TeamName,
  2461. di.ClientUnit,
  2462. di.ClientName,
  2463. di.VisitDate,
  2464. di.VisitPNumber,
  2465. di.JietuanOperator,
  2466. di.VisitEndDate,
  2467. (
  2468. SELECT
  2469. CAST(
  2470. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2471. ) AS GroupSales
  2472. FROM
  2473. Fin_ForeignReceivables
  2474. WHERE
  2475. IsDel = 0
  2476. AND di.Id = Diid
  2477. AND AddingWay IN (0, 1, 2)
  2478. ) AS GroupSales,
  2479. u.CnName AS GroupPickupUser,
  2480. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  2481. FROM
  2482. Grp_DelegationInfo di
  2483. WITH
  2484. (NoLock)
  2485. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  2486. WHERE
  2487. di.Isdel = 0
  2488. {userSql}
  2489. AND VisitDate Between '{beginDt}' And '{endDt}'
  2490. ) Temp ");
  2491. RefAsync<int> total = 0;
  2492. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  2493. #endregion
  2494. #region 客户类型、客户等级 统计
  2495. string sql1 = string.Format(@$"Select
  2496. sd.[Name],
  2497. Count(*) As [Count]
  2498. From Grp_DelegationInfo di
  2499. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  2500. Where di.Isdel = 0
  2501. {userSql}
  2502. And VisitDate Between '{beginDt}' And '{endDt}'
  2503. Group By [Name]
  2504. Order By Count Desc");
  2505. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  2506. string sql2 = string.Format(@$"Select
  2507. sd.[Name],
  2508. Count(*) As [Count]
  2509. From Grp_DelegationInfo di
  2510. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  2511. Where di.Isdel = 0
  2512. {userSql}
  2513. And VisitDate Between '{beginDt}' And '{endDt}'
  2514. Group By [Name]
  2515. Order By Count Desc");
  2516. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  2517. #endregion
  2518. #region 接单排名
  2519. string sql4 = string.Format(@$"Select
  2520. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  2521. u.CnName As UserName,
  2522. Count(*) As [Count]
  2523. From Grp_DelegationInfo di
  2524. Left Join Sys_Users u On di.JietuanOperator = u.Id
  2525. Where di.Isdel = 0
  2526. {userSql}
  2527. And VisitDate Between '{beginDt}' And '{endDt}'
  2528. Group By CnName");
  2529. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();
  2530. #endregion
  2531. var viewData = new
  2532. {
  2533. groupData = groupData,
  2534. groupTotal = total,
  2535. customerTypeData = customerTypeData,
  2536. clientGradeData = clientGradeData,
  2537. rankingData = rankingData
  2538. };
  2539. return Ok(JsonView(true, "操作成功!", viewData, total));
  2540. }
  2541. /// <summary>
  2542. /// 市场部销售额
  2543. /// 客户拜访列表
  2544. /// </summary>
  2545. /// <param name="_dto">市场部销售额请求dto</param>
  2546. /// <returns></returns>
  2547. [HttpPost("PostMarketingSalesVCList")]
  2548. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2549. public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)
  2550. {
  2551. #region 参数验证
  2552. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  2553. var validResult = await validationRules.ValidateAsync(_dto);
  2554. if (!validResult.IsValid)
  2555. {
  2556. var errors = new StringBuilder();
  2557. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2558. return Ok(JsonView(false, errors.ToString()));
  2559. }
  2560. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2561. #region 页面操作权限验证
  2562. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2563. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2564. #endregion
  2565. #endregion
  2566. return Ok(await _visitingClientsRep._List(_dto.PortType, _dto.PageIndex, _dto.PageSize, _dto.DiId, _dto.Search));
  2567. }
  2568. /// <summary>
  2569. /// 市场部销售额
  2570. /// 客户拜访 操作(添加 Or 编辑)
  2571. /// </summary>
  2572. /// <param name="_dto">市场部销售额请求dto</param>
  2573. /// <returns></returns>
  2574. [HttpPost("PostMarketingSalesVCOperate")]
  2575. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2576. public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)
  2577. {
  2578. #region 参数验证
  2579. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  2580. var validResult = await validationRules.ValidateAsync(_dto);
  2581. if (!validResult.IsValid)
  2582. {
  2583. var errors = new StringBuilder();
  2584. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2585. return Ok(JsonView(false, errors.ToString()));
  2586. }
  2587. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2588. #region 页面操作权限验证
  2589. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2590. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2591. #endregion
  2592. #endregion
  2593. return Ok(await _visitingClientsRep._AddOrEdit(_dto));
  2594. }
  2595. /// <summary>
  2596. /// 市场部销售额
  2597. /// 客户拜访 Del
  2598. /// </summary>
  2599. /// <param name="_dto">市场部销售额请求dto</param>
  2600. /// <returns></returns>
  2601. [HttpPost("PostMarketingSalesVCDel")]
  2602. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2603. public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)
  2604. {
  2605. return Ok(await _visitingClientsRep._Del(_dto.Id, _dto.UserId));
  2606. }
  2607. /// <summary>
  2608. /// 市场部销售额
  2609. /// 客户拜访 操作 save
  2610. /// </summary>
  2611. /// <param name="_dto">市场部销售额请求dto</param>
  2612. /// <returns></returns>
  2613. [HttpPost("PostMarketingSalesVCSave")]
  2614. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2615. public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)
  2616. {
  2617. #region 参数验证
  2618. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  2619. var validResult = await validationRules.ValidateAsync(_dto);
  2620. if (!validResult.IsValid)
  2621. {
  2622. var errors = new StringBuilder();
  2623. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2624. return Ok(JsonView(false, errors.ToString()));
  2625. }
  2626. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2627. #region 页面操作权限验证
  2628. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2629. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2630. #endregion
  2631. #endregion
  2632. return Ok(await _visitingClientsRep._Save(_dto));
  2633. }
  2634. #endregion
  2635. #region 日付报表
  2636. /// <summary>
  2637. /// 日付类型数据
  2638. /// </summary>
  2639. /// <param name="_dto"></param>
  2640. /// <returns></returns>
  2641. [HttpPost("DailypaymentTypeInit")]
  2642. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2643. public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)
  2644. {
  2645. #region 参数验证
  2646. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  2647. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2648. #region 页面操作权限验证
  2649. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2650. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2651. #endregion
  2652. #endregion
  2653. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  2654. {
  2655. var defaultParentIds = new List<int>() {
  2656. 48,// 人员费用
  2657. 49,// 办公费用
  2658. 50,// 销售费用
  2659. 51,// 其他费用
  2660. 55,// 大运会
  2661. };
  2662. var dailypaymentTypeData = await RedisRepository.RedisFactory
  2663. .CreateRedisRepository()
  2664. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  2665. var dailyTypeData = await _sqlSugar.Queryable<DailypaymentParentTypeView>()
  2666. .Includes(x => x.SubData)
  2667. .Where(x => defaultParentIds.Contains(x.Id))
  2668. .ToListAsync();
  2669. dailyTypeData.ForEach(x =>
  2670. {
  2671. x.SubData.ForEach(y =>
  2672. {
  2673. int currId = dailypaymentTypeData.Find(z => z == y.Id);
  2674. y.IsChecked = currId == 0 ? false : true;
  2675. });
  2676. });
  2677. var companyData = await _sqlSugar.Queryable<Sys_Company>()
  2678. .Where(x => x.IsDel == 0)
  2679. .Select(x => new { id = x.Id, name = x.CompanyName })
  2680. .ToListAsync();
  2681. return Ok(JsonView(true, "查询成功!", new { dailyTypeData = dailyTypeData, companyData = companyData }));
  2682. }
  2683. else
  2684. {
  2685. return Ok(JsonView(false, "查询失败"));
  2686. }
  2687. }
  2688. /// <summary>
  2689. /// 日付类型数据 Save
  2690. /// </summary>
  2691. /// <param name="_dto"></param>
  2692. /// <returns></returns>
  2693. [HttpPost("DailypaymentTypeDataSave")]
  2694. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2695. public async Task<IActionResult> DailypaymentTypeDataSave(DailypaymentTypeDataSaveDto _dto)
  2696. {
  2697. #region 参数验证
  2698. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  2699. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2700. #region 页面操作权限验证
  2701. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2702. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2703. #endregion
  2704. #endregion
  2705. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  2706. {
  2707. if (_dto.TypeIds.Count < 1) return Ok(JsonView(false, "请传入需要保存的TypeIds"));
  2708. var res = await RedisRepository.RedisFactory
  2709. .CreateRedisRepository()
  2710. .StringSetAsync(
  2711. key: "DailypaymentTypeData",
  2712. _dto.TypeIds,
  2713. timeout: null);
  2714. if (!res) return Ok(JsonView(false, "操作失败"));
  2715. return Ok(JsonView(true, "操作成功!"));
  2716. }
  2717. else return Ok(JsonView(false, "操作失败"));
  2718. }
  2719. /// <summary>
  2720. /// 日付数据列表
  2721. /// </summary>
  2722. /// <param name="_dto"></param>
  2723. /// <returns></returns>
  2724. [HttpPost("DailypaymentRange")]
  2725. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2726. public async Task<IActionResult> DailypaymentRange(DailypaymentRangeDto _dto)
  2727. {
  2728. #region 参数验证
  2729. var validator = new DailypaymentRangeDtoValidator();
  2730. var validationRes = validator.Validate(_dto);
  2731. if (!validationRes.IsValid)
  2732. {
  2733. StringBuilder sb = new StringBuilder();
  2734. foreach (var item in validationRes.Errors)
  2735. {
  2736. sb.AppendLine(item.ErrorMessage);
  2737. }
  2738. return Ok(JsonView(false, sb.ToString()));
  2739. }
  2740. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2741. #region 页面操作权限验证
  2742. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2743. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2744. #endregion
  2745. #endregion
  2746. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  2747. {
  2748. DateTime _beginDt = Convert.ToDateTime($"{_dto.BeginDt} 00:00:00"),
  2749. _endDt = Convert.ToDateTime($"{_dto.EndDt} 23:59:59");
  2750. var sqlWhere = string.Format(@" And dfp.CreateTime Between '{0}' And '{1}'", _beginDt, _endDt);
  2751. var dailypaymentTypeData = await RedisRepository.RedisFactory
  2752. .CreateRedisRepository()
  2753. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  2754. var sql = string.Format(@"
  2755. Select
  2756. dfp.Id,
  2757. dfp.Instructions,
  2758. dfp.PriceTypeId,
  2759. sd1.Name As FeeType,
  2760. dfp.TransferTypeId,
  2761. sd2.Name As TransferType,
  2762. dfp.SumPrice,
  2763. dfp.FAuditDate,
  2764. dfp.MAuditDate,
  2765. dfp.CompanyId,
  2766. c.CompanyName,
  2767. dfp.CreateUserId As ApplicantId,
  2768. u.CnName As Applicant,
  2769. dfp.CreateTime As ApplicantDt,
  2770. dfp.Instructions+u.CnName As ViewStr
  2771. From Fin_DailyFeePayment dfp
  2772. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  2773. Left Join Sys_SetData sd1 On dfp.TransferTypeId = sd1.Id
  2774. Left Join Sys_Company c On dfp.CompanyId = c.Id
  2775. Left Join Sys_SetData sd2 On dfp.PriceTypeId = sd2.Id
  2776. Where dfp.IsDel = 0 And dfp.IsPay = 1
  2777. ");//--Order By dfp.CreateTime Desc
  2778. if (_dto.Type == 1) //data
  2779. {
  2780. RefAsync<int> total = 0;
  2781. var _view = await _sqlSugar.SqlQueryable<DailyFeePaymentRangeView>(sql)
  2782. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  2783. .WhereIF(dailypaymentTypeData.Count > 0,
  2784. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  2785. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  2786. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  2787. .OrderByDescending(x => x.ApplicantDt)
  2788. .ToPageListAsync(
  2789. pageNumber: _dto.PageIndex,
  2790. pageSize: _dto.PageSize,
  2791. totalNumber: total
  2792. );
  2793. _sqlSugar.ThenMapper(_view, x =>
  2794. {
  2795. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  2796. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  2797. .ToList();
  2798. });
  2799. //单独处理
  2800. return Ok(JsonView(true, "操作成功!", new { data = _view, total = _view.Sum(x => x.SumPrice) }, total));
  2801. }
  2802. else if (_dto.Type == 2) //view
  2803. {
  2804. var _view = await _sqlSugar.SqlQueryable<ExcelView>(sql)
  2805. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  2806. .WhereIF(dailypaymentTypeData.Count > 0,
  2807. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  2808. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  2809. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  2810. .OrderByDescending(x => x.ApplicantDt)
  2811. .ToPageListAsync(
  2812. pageNumber: 1,
  2813. pageSize: 99999
  2814. );
  2815. _sqlSugar.ThenMapper(_view, x =>
  2816. {
  2817. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  2818. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  2819. .ToList();
  2820. string str = "";
  2821. int index = 1;
  2822. foreach (var item in x.Contents)
  2823. {
  2824. string str1 = $"{index}、费用名称:[{item.PriceName}] 单价:[{item.Price:#0.00}] 数量:[{item.Quantity:#0.00}] 小计:[{item.ItemTotal:#0.00}] 备注:[{item.Remark}]";
  2825. if (index == x.Contents.Count) str += str1;
  2826. else str += str1 + "\r\n";
  2827. index++;
  2828. }
  2829. x.ContentStr = str;
  2830. });
  2831. if (_view.Count > 0)
  2832. {
  2833. //DataTable dt = GeneralMethod.
  2834. DataTable dt = CommonFun.GetDataTableFromIList(_view);
  2835. dt.TableName = $"_view";
  2836. decimal total = _view.Sum(x => x.SumPrice);
  2837. WorkbookDesigner designer = new WorkbookDesigner();
  2838. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/日付报表模板.xls");
  2839. designer.SetDataSource(dt);
  2840. designer.SetDataSource("Total", total);
  2841. designer.Workbook.Worksheets[0].Name = "日付报表";
  2842. designer.Process();
  2843. string fileName = $"DailyPayment/日付报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  2844. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  2845. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  2846. return Ok(JsonView(true, "操作成功", new { url = rst }));
  2847. }
  2848. return Ok(JsonView(true, ",暂无数据"));
  2849. }
  2850. return Ok(JsonView(false, "操作失败"));
  2851. }
  2852. else return Ok(JsonView(false, "操作失败"));
  2853. }
  2854. #endregion
  2855. #region 统计模块
  2856. /// <summary>
  2857. /// 同比
  2858. /// 营业额(今年和去年的)、成本支出(今年和去年的)、毛利润(今年和去年的)
  2859. /// </summary>
  2860. /// <param name="_dto">市场部销售额请求dto</param>
  2861. /// <returns></returns>
  2862. [HttpPost("StatisticsYOY")]
  2863. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2864. public async Task<IActionResult> StatisticsYOY(YOYDto _dto)
  2865. {
  2866. //同比增长率 = (本期 - 同期) / 同期 * 100%;
  2867. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  2868. string beginDt = $"{_dto.Year - 1}-01-01 00:00:00",
  2869. endDt = $"{_dto.Year}-12-31 23:59:59";
  2870. string sql = string.Format(@"
  2871. SELECT
  2872. di.Id,
  2873. di.TeamName,
  2874. di.VisitDate,
  2875. YEAR(di.VisitDate) AS YEAR,
  2876. MONTH(di.VisitDate) AS MONTH,
  2877. (
  2878. SELECT
  2879. CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
  2880. FROM
  2881. Fin_ForeignReceivables
  2882. WHERE
  2883. IsDel = 0
  2884. AND AddingWay IN (0, 1, 2)
  2885. AND di.Id = Diid
  2886. ) AS SaleAmount,
  2887. (
  2888. SELECT
  2889. CAST(
  2890. SUM(
  2891. (
  2892. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  2893. )
  2894. ) AS DECIMAL(12, 2)
  2895. )
  2896. FROM
  2897. Grp_AirTicketReservations atr
  2898. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  2899. AND ccp.CTable = 85
  2900. AND atr.Id = ccp.CId
  2901. WHERE
  2902. atr.IsDel = 0
  2903. AND ccp.IsAuditGM = 1
  2904. AND ccp.IsPay = 1
  2905. AND di.Id = atr.DiId
  2906. ) AirTicketAmount,
  2907. (
  2908. SELECT
  2909. CAST(
  2910. SUM(
  2911. (
  2912. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  2913. )
  2914. ) AS DECIMAL(12, 2)
  2915. )
  2916. FROM
  2917. Grp_CarTouristGuideGroundReservations ctggr
  2918. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  2919. AND ccp.CTable = 79
  2920. AND ctggr.Id = ccp.CId
  2921. WHERE
  2922. ctggr.IsDel = 0
  2923. AND ccp.IsAuditGM = 1
  2924. AND ccp.IsPay = 1
  2925. AND di.Id = ctggr.DiId
  2926. ) AS OPAmount,
  2927. (
  2928. SELECT
  2929. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  2930. FROM
  2931. Grp_DecreasePayments dp
  2932. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  2933. AND ccp.CTable = 98
  2934. AND dp.Id = ccp.CId
  2935. WHERE
  2936. dp.IsDel = 0
  2937. AND ccp.Ctable = 98
  2938. AND ccp.IsAuditGM = 1
  2939. AND ccp.IsPay = 1
  2940. AND di.Id = dp.Diid
  2941. ) AS OtherCostAmount,
  2942. (
  2943. SELECT
  2944. CAST(
  2945. SUM(
  2946. (
  2947. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  2948. )
  2949. ) AS DECIMAL(12, 2)
  2950. )
  2951. FROM
  2952. Grp_VisaInfo vi
  2953. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  2954. AND ccp.CTable = 80
  2955. AND vi.Id = ccp.CId
  2956. WHERE
  2957. vi.IsDel = 0
  2958. AND ccp.IsAuditGM = 1
  2959. AND ccp.IsPay = 1
  2960. AND di.Id = vi.DIId
  2961. ) AS VisaAmount,
  2962. (
  2963. SELECT
  2964. CAST(
  2965. SUM(
  2966. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  2967. ) AS DECIMAL(12, 2)
  2968. )
  2969. FROM
  2970. Grp_InvitationOfficialActivities ioa
  2971. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  2972. AND ccp.CTable = 81
  2973. AND ioa.Id = ccp.CId
  2974. WHERE
  2975. ioa.IsDel = 0
  2976. AND ccp.IsAuditGM = 1
  2977. AND ccp.IsPay = 1
  2978. AND di.Id = ioa.Diid
  2979. ) AS OAAmount,
  2980. (
  2981. SELECT
  2982. CAST(
  2983. SUM(
  2984. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  2985. ) AS DECIMAL(12, 2)
  2986. )
  2987. FROM
  2988. Grp_Customers ic
  2989. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  2990. AND ccp.CTable = 82
  2991. AND ic.Id = ccp.CId
  2992. WHERE
  2993. ic.IsDel = 0
  2994. AND ccp.IsAuditGM = 1And ccp.IsPay = 1
  2995. AND di.Id = ic.DiId
  2996. ) AS InsureAmount,
  2997. (
  2998. SELECT
  2999. CAST(
  3000. SUM(
  3001. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  3002. ) AS DECIMAL(12, 2)
  3003. )
  3004. FROM
  3005. Grp_HotelReservations hr
  3006. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  3007. WHERE
  3008. hr.IsDel = 0
  3009. AND ccp.IsDel = 0
  3010. AND ccp.CTable = 76
  3011. AND ccp.IsAuditGM = 1
  3012. AND ccp.PayMoney <> 0
  3013. AND ccp.IsPay = 0
  3014. AND di.Id = hr.DiId
  3015. ) AS HotelAmount,
  3016. (
  3017. SELECT
  3018. CAST(
  3019. SUM((gec.PriceSum * gec.Coefficient * ccp.DayRate)) AS DECIMAL(12, 2)
  3020. )
  3021. FROM
  3022. OA2023DB.dbo.Fin_GroupExtraCost gec
  3023. INNER JOIN Grp_CreditCardPayment ccp ON gec.Id = ccp.CId
  3024. WHERE
  3025. ccp.IsDel = 0
  3026. AND ccp.CTable = 1015
  3027. AND ccp.IsAuditGM = 1
  3028. AND ccp.IsPay = 1
  3029. AND di.Id = gec.DiId
  3030. ) AS ExcessAmount,
  3031. (
  3032. SELECT
  3033. CAST(
  3034. SUM(
  3035. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  3036. ) AS DECIMAL(12, 2)
  3037. )
  3038. FROM
  3039. Fin_PaymentRefundAndOtherMoney prom
  3040. INNER JOIN Grp_CreditCardPayment ccp ON prom.DiId = ccp.DIId
  3041. AND prom.Id = ccp.CId
  3042. WHERE
  3043. prom.IsDel = 0
  3044. AND prom.PayType = 1
  3045. AND ccp.CTable = 285
  3046. AND ccp.IsAuditGM = 1
  3047. AND ccp.IsPay = 1
  3048. AND di.Id = prom.DiId
  3049. ) AS SKTHAmount
  3050. FROM
  3051. Grp_DelegationInfo di
  3052. WHERE
  3053. di.IsDel = 0
  3054. AND di.TeamDid IN (38,39,40,1048)
  3055. AND di.IsSure = 1
  3056. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  3057. ORDER BY
  3058. di.VisitDate
  3059. ", beginDt, endDt);
  3060. var data = await _sqlSugar.SqlQueryable<StatisticsYOYView>(sql).ToListAsync();
  3061. var thisYearData = data.Where(x => x.Year == _dto.Year).ToList();
  3062. var lastYearData = data.Where(x => x.Year == (_dto.Year - 1)).ToList();
  3063. List<YOYReturnView> salesYOYData = new List<YOYReturnView>();
  3064. List<YOYReturnView> costYOYData = new List<YOYReturnView>();
  3065. List<YOYReturnView> grossProfitYOYData = new List<YOYReturnView>();
  3066. int monthIndex = 1;
  3067. while (monthIndex < 13)
  3068. {
  3069. var thisMonthData = thisYearData.Where(x => x.Month == monthIndex).ToList();
  3070. var lastMonthData = lastYearData.Where(x => x.Month == monthIndex).ToList();
  3071. var thisGroupIds = thisMonthData.Select(x => x.Id).ToList();
  3072. var lastGroupIds = lastMonthData.Select(x => x.Id).ToList();
  3073. decimal thisSalesAmount = thisMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  3074. lastSalesAmount = lastMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  3075. thisCostAmount = thisMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  3076. lastCostAmount = lastMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  3077. thisgrossProfitAmount = thisMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M),
  3078. lastgrossProfitAmount = lastMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M);
  3079. salesYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisSalesAmount, lastSalesAmount, thisGroupIds, lastGroupIds));
  3080. costYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisCostAmount, lastCostAmount, thisGroupIds, lastGroupIds));
  3081. grossProfitYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisgrossProfitAmount, lastgrossProfitAmount, thisGroupIds, lastGroupIds));
  3082. monthIndex++;
  3083. }
  3084. salesYOYData = salesYOYData.OrderBy(x => x.Month).ToList();
  3085. costYOYData = costYOYData.OrderBy(x => x.Month).ToList();
  3086. grossProfitYOYData = grossProfitYOYData.OrderBy(x => x.Month).ToList();
  3087. return Ok(JsonView(true, "操作成功!", new { salesYOYData = salesYOYData, costYOYData = costYOYData, grossProfitYOYData = grossProfitYOYData }));
  3088. }
  3089. /// <summary>
  3090. /// 国交数据统计-机票相关
  3091. /// 1、机票票数、2、机票到达地
  3092. /// </summary>
  3093. /// <param name="_dto"></param>
  3094. /// <returns></returns>
  3095. [HttpPost("StatisticsAirTicket")]
  3096. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3097. public async Task<IActionResult> StatisticsAirTicket(YOYDto _dto)
  3098. {
  3099. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3100. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3101. endDt = $"{_dto.Year}-12-31 23:59:59";
  3102. string sql = string.Format(@"
  3103. SELECT
  3104. atr.DIId,
  3105. atr.FlightsDate,
  3106. YEAR(atr.FlightsDate) AS YEAR,
  3107. MONTH(atr.FlightsDate) AS MONTH,
  3108. atr.CType,
  3109. sd.Name As CTypeName,
  3110. atr.FlightsCity,
  3111. atr.ClientNum,
  3112. atr.ClientName
  3113. FROM
  3114. Grp_AirTicketReservations atr
  3115. INNER JOIN Grp_CreditCardPayment ccp ON atr.Id = ccp.CId
  3116. AND ccp.IsDel = 0
  3117. AND CTable = 85
  3118. INNER JOIN Grp_DelegationInfo di ON atr.DIId = di.Id
  3119. LEFT JOIN Sys_SetData sd On atr.CType = sd.Id
  3120. WHERE
  3121. atr.IsDel = 0
  3122. AND di.TeamDid IN (38,39,40,1048)
  3123. And atr.CType IN(457,458,459,460,574,575)
  3124. AND CHARINDEX('行程单',atr.ClientName) = 0
  3125. AND CHARINDEX('返点',atr.ClientName) = 0
  3126. AND CHARINDEX('-1',atr.ClientName) = 0
  3127. AND ccp.IsPay = 1
  3128. AND atr.FlightsDate BETWEEN '{0}' AND '{1}'
  3129. ORDER BY atr.FlightsDate
  3130. ", beginDt, endDt);
  3131. var data = await _sqlSugar.SqlQueryable<StatisticsAirTicketView>(sql).ToListAsync();
  3132. var groupIds = data.Select(x => x.DIId).ToList();
  3133. //处理城市数据
  3134. var threeCodeData = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  3135. //处理团组名称
  3136. var groupNames = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => groupIds.Contains(x.Id)).Select(x => new { Id = x.Id, GroupName = x.TeamName }).ToListAsync();
  3137. data.ForEach(x =>
  3138. {
  3139. string cityName = "";
  3140. if (!string.IsNullOrEmpty(x.FlightsCity))
  3141. {
  3142. string cityCode = x.FlightsCity.Replace("-", "").Replace("/", "");
  3143. int cityNum = cityCode.Length / 3;
  3144. if (cityCode.Length % 3 == 0)
  3145. {
  3146. for (int i = 0; i < cityNum; i++)
  3147. {
  3148. string code = "";
  3149. if (i == 0) code = cityCode.Substring(0, 3);
  3150. else code = cityCode.Substring(i * 3, 3);
  3151. if (!string.IsNullOrEmpty(code))
  3152. {
  3153. if (i == cityNum - 1)
  3154. {
  3155. cityName += threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  3156. }
  3157. else
  3158. {
  3159. var str1 = threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  3160. cityName += str1 + "、";
  3161. }
  3162. }
  3163. }
  3164. }
  3165. }
  3166. x.FlightsCityName = cityName;
  3167. });
  3168. var airTicketNumData = new List<AirTicketReturnView>();
  3169. var airTicketAreaData = new List<AirTicketCityReturnView>();
  3170. int monthIndex = 1;
  3171. while (monthIndex < 13)
  3172. {
  3173. var monthData = data.Where(x => x.Month == monthIndex).ToList();
  3174. //机票票数处理
  3175. int airticket_quantity = monthData.Sum(x => x.ClientNum);
  3176. var linkGroupIds = monthData.Select(x => x.DIId).ToList();
  3177. List<AitTicketInfo> aitTicketInfos = new List<AitTicketInfo>();
  3178. foreach (var item in monthData)
  3179. {
  3180. string groupName = groupNames.Find(x => item.DIId == x.Id)?.GroupName ?? "";
  3181. aitTicketInfos.Add(new AitTicketInfo(item.DIId, groupName, item.ClientNum));
  3182. }
  3183. var aitTicketInfosGroupBy = aitTicketInfos.GroupBy(x => x.Id);
  3184. List<AitTicketInfo> aitTicketInfos1 = new List<AitTicketInfo>();
  3185. foreach (var item in aitTicketInfosGroupBy)
  3186. {
  3187. aitTicketInfos1.Add(new AitTicketInfo(item.Key, item.First().GroupName, item.Sum(x => x.Quantity)));
  3188. }
  3189. aitTicketInfos1 = aitTicketInfos1.OrderBy(x => x.Quantity).ToList();
  3190. linkGroupIds = linkGroupIds.Distinct().ToList();
  3191. airTicketNumData.Add(new AirTicketReturnView(_dto.Year, monthIndex, airticket_quantity, aitTicketInfos1, linkGroupIds));
  3192. //机票城市处理
  3193. //城市处理
  3194. List<string> airTicketCityInfos = new List<string>();
  3195. foreach (var item in monthData)
  3196. {
  3197. if (!string.IsNullOrEmpty(item.FlightsCityName))
  3198. {
  3199. if (item.FlightsCityName.Contains("、"))
  3200. {
  3201. var cityArray = item.FlightsCityName.Split("、").ToList();
  3202. foreach (var item1 in cityArray)
  3203. {
  3204. if (!string.IsNullOrEmpty(item1))
  3205. {
  3206. airTicketCityInfos.Add(item1);
  3207. }
  3208. }
  3209. }
  3210. else
  3211. {
  3212. airTicketCityInfos.Add(item.FlightsCityName);
  3213. }
  3214. }
  3215. }
  3216. //int quantity1 = airTicketCityInfos.Count;
  3217. int city_totalquantity = 0;
  3218. var airTicketCityInfosGroupby = airTicketCityInfos.GroupBy(x => x);
  3219. var airTicketCityInfos1 = new List<AirTicketCityInfo>();
  3220. foreach (var item in airTicketCityInfosGroupby)
  3221. {
  3222. var city_quantity = item.ToList().Count;
  3223. city_totalquantity += city_quantity;
  3224. airTicketCityInfos1.Add(new AirTicketCityInfo(item.Key, city_quantity));
  3225. }
  3226. airTicketCityInfos1 = airTicketCityInfos1.OrderByDescending(x => x.Quantity).ToList();
  3227. airTicketAreaData.Add(new AirTicketCityReturnView(_dto.Year, monthIndex, city_totalquantity, airTicketCityInfos1, linkGroupIds));
  3228. monthIndex++;
  3229. }
  3230. return Ok(JsonView(true, "操作成功!", new { airTicketNumData = airTicketNumData, airTicketAreaData = airTicketAreaData }));
  3231. }
  3232. /// <summary>
  3233. /// 国交数据统计
  3234. /// 酒店预订地区TOP10
  3235. /// </summary>
  3236. /// <param name="_dto"></param>
  3237. /// <returns></returns>
  3238. [HttpPost("StatisticsHotel")]
  3239. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3240. public async Task<IActionResult> StatisticsHotel(YOYDto _dto)
  3241. {
  3242. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3243. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3244. endDt = $"{_dto.Year}-12-31 23:59:59";
  3245. string sql = string.Format(@"
  3246. SELECT
  3247. hr.DIId,
  3248. hr.City,
  3249. hr.HotelName,
  3250. sd.Name AS BookinSite,
  3251. hr.CheckInDate,
  3252. YEAR(hr.CheckInDate) AS YEAR,
  3253. MONTH(hr.CheckInDate) AS MONTH,
  3254. hr.CheckOutDate,
  3255. hr.SingleRoomCount,
  3256. hr.DoubleRoomCount,
  3257. hr.SuiteRoomCount,
  3258. hr.OtherRoomCount
  3259. FROM
  3260. Grp_HotelReservations hr
  3261. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  3262. AND ccp.IsDel = 0
  3263. AND CTable = 76
  3264. INNER JOIN Grp_DelegationInfo di ON hr.DiId = di.Id
  3265. LEFT JOIN Sys_SetData sd ON hr.ReservationsWebsite = sd.Id
  3266. WHERE
  3267. hr.IsDel = 0
  3268. AND di.TeamDid IN (38,39,40,1048)
  3269. AND ccp.IsPay = 1
  3270. AND (
  3271. hr.SingleRoomCount > 0
  3272. OR hr.DoubleRoomCount > 0
  3273. OR hr.SuiteRoomCount > 0
  3274. OR hr.OtherRoomCount > 0
  3275. )
  3276. AND CHARINDEX('早餐',hr.HotelName) = 0
  3277. AND CHARINDEX('晚餐',hr.HotelName) = 0
  3278. AND CHARINDEX('升级',hr.HotelName) = 0
  3279. AND CHARINDEX('饮料茶水费',hr.HotelName) = 0
  3280. AND CHARINDEX('城市税',hr.HotelName) = 0
  3281. AND CHARINDEX('退款',hr.HotelName) = 0
  3282. AND CHARINDEX('返现',hr.HotelName) = 0
  3283. AND CHARINDEX('会议室',hr.HotelName) = 0
  3284. AND CHARINDEX('迷你吧消费',hr.HotelName) = 0
  3285. AND CHARINDEX('运费',hr.HotelName) = 0
  3286. AND CHARINDEX('地接',hr.HotelName) = 0
  3287. AND CHARINDEX('损失',hr.HotelName) = 0
  3288. AND CHARINDEX('补差',hr.HotelName) = 0
  3289. AND hr.CheckInDate BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  3290. ORDER BY
  3291. hr.CheckInDate
  3292. ", beginDt, endDt);
  3293. var data = await _sqlSugar.SqlQueryable<StatisticsHotelView>(sql).ToListAsync();
  3294. var hotelData = data.OrderBy(x => x.CityStr).ToList();
  3295. var hotelCityGroupByData = data.GroupBy(x => x.CityStr)
  3296. .Select(g => new
  3297. {
  3298. city = g.Key,
  3299. BookingRoomNum = g.Sum(x => x.RoomTotal),
  3300. hotelData = g.GroupBy(x => x.HotelName)
  3301. .Select(g1 => new
  3302. {
  3303. hotelName = g1.Key,
  3304. roomNights = g1.Sum(x => x.RoomNights),
  3305. roomTotal = g1.Sum(x => x.RoomTotal),
  3306. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  3307. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  3308. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  3309. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  3310. })
  3311. .ToList(),
  3312. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  3313. })
  3314. .OrderByDescending(x => x.BookingRoomNum)
  3315. .Take(10)
  3316. .ToList();
  3317. return Ok(JsonView(true, "操作成功!", hotelCityGroupByData));
  3318. }
  3319. /// <summary>
  3320. /// 国交数据统计
  3321. /// 商邀邀请国家数量TOP10
  3322. /// </summary>
  3323. /// <param name="_dto"></param>
  3324. /// <returns></returns>
  3325. [HttpPost("StatisticsInvitation")]
  3326. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3327. public async Task<IActionResult> StatisticsInvitation(YOYDto _dto)
  3328. {
  3329. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3330. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3331. endDt = $"{_dto.Year}-12-31 23:59:59";
  3332. string sql = string.Format(@"
  3333. SELECT
  3334. ioa.DiId,
  3335. ioa.InviterArea AS Country
  3336. FROM
  3337. Grp_InvitationOfficialActivities ioa
  3338. INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
  3339. AND ccp.IsDel = 0
  3340. AND ccp.CTable = 81
  3341. INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
  3342. WHERE
  3343. ioa.IsDel = 0
  3344. AND di.TeamDid IN (38,39,40,1048)
  3345. AND ccp.IsPay = 1
  3346. AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
  3347. ", beginDt, endDt);
  3348. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
  3349. var groupByData = data.GroupBy(x => x.Country)
  3350. .Select(g => new
  3351. {
  3352. Country = g.Key,
  3353. TimeNum = g.Count(),
  3354. LinkGroupIds = g.Select(x => x.DIId).ToList()
  3355. })
  3356. .OrderByDescending(x => x.TimeNum)
  3357. .Take(10)
  3358. .ToList();
  3359. return Ok(JsonView(true, "操作成功!", groupByData));
  3360. }
  3361. /// <summary>
  3362. /// 会务数据统计
  3363. /// 会务城市TOP10排序
  3364. /// </summary>
  3365. /// <param name="_dto"></param>
  3366. /// <returns></returns>
  3367. [HttpPost("StatisticsConferenceCity")]
  3368. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3369. public async Task<IActionResult> StatisticsConferenceCity(YOYDto _dto)
  3370. {
  3371. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3372. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3373. endDt = $"{_dto.Year}-12-31 23:59:59";
  3374. string sql = string.Format(@"
  3375. SELECT
  3376. ioa.DiId,
  3377. ioa.InviterArea AS Country
  3378. FROM
  3379. Grp_InvitationOfficialActivities ioa
  3380. INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
  3381. AND ccp.IsDel = 0
  3382. AND ccp.CTable = 81
  3383. INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
  3384. WHERE
  3385. ioa.IsDel = 0
  3386. AND di.TeamDid IN (102,248,302,691,762,1047)
  3387. AND ccp.IsPay = 1
  3388. AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
  3389. ", beginDt, endDt);
  3390. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
  3391. var groupByData = data.GroupBy(x => x.Country)
  3392. .Select(g => new
  3393. {
  3394. Country = g.Key,
  3395. TimeNum = g.Count(),
  3396. LinkGroupIds = g.Select(x => x.DIId).ToList()
  3397. })
  3398. .OrderByDescending(x => x.TimeNum)
  3399. .Take(10)
  3400. .ToList();
  3401. return Ok(JsonView(true, "操作成功!", groupByData));
  3402. }
  3403. /// <summary>
  3404. /// 团组数据统计
  3405. /// 团组合作前十的客户TOP10排序
  3406. /// </summary>
  3407. /// <param name="_dto"></param>
  3408. /// <returns></returns>
  3409. [HttpPost("StatisticsCooperativeCustomer")]
  3410. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3411. public async Task<IActionResult> StatisticsCooperativeCustomer(YOYDto _dto)
  3412. {
  3413. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3414. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3415. endDt = $"{_dto.Year}-12-31 23:59:59";
  3416. DateTime _beginDt = Convert.ToDateTime(beginDt),
  3417. _endDt = Convert.ToDateTime(endDt);
  3418. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  3419. .Where(x => x.IsDel == 0)
  3420. .Where(x => x.IsSure == 1)
  3421. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  3422. .ToListAsync();
  3423. var groupInfos1 = groupInfos.GroupBy(x => x.ClientName);
  3424. var view = groupInfos1.Select(x =>
  3425. new
  3426. {
  3427. clienName = x.Key,
  3428. clientUnit = x.FirstOrDefault()?.ClientUnit ?? "",
  3429. visitsNum = x.Count()
  3430. }
  3431. )
  3432. .OrderByDescending(x => x.visitsNum)
  3433. .Take(10)
  3434. .ToList();
  3435. return Ok(JsonView(true, "操作成功!", view));
  3436. }
  3437. /// <summary>
  3438. /// 团组数据统计
  3439. /// 已出团客户单位的类型比例图(饼状图-政府团、企业团等)
  3440. /// </summary>
  3441. /// <param name="_dto"></param>
  3442. /// <returns></returns>
  3443. [HttpPost("StatisticsCooperativeCustomerType")]
  3444. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3445. public async Task<IActionResult> StatisticsCooperativeCustomerType(YOYDto _dto)
  3446. {
  3447. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3448. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3449. endDt = $"{_dto.Year}-12-31 23:59:59";
  3450. DateTime _beginDt = Convert.ToDateTime(beginDt),
  3451. _endDt = Convert.ToDateTime(endDt);
  3452. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  3453. .LeftJoin<Sys_SetData>((di, sd) => di.TeamDid == sd.Id)
  3454. .Where((di, sd) => di.IsDel == 0)
  3455. .Where((di, sd) => di.VisitDate >= _beginDt && di.VisitDate <= _endDt)
  3456. .Select((di, sd) => new
  3457. {
  3458. Id = di.Id,
  3459. GroupTypeId = di.TeamDid,
  3460. GroupTypeName = sd.Name,
  3461. })
  3462. .ToListAsync();
  3463. var groupInfos1 = groupInfos.GroupBy(x => x.GroupTypeName);
  3464. var view = groupInfos1.Select(x =>
  3465. new
  3466. {
  3467. groupTypeName = x.Key,
  3468. groupNum = x.Count(),
  3469. linkGroupId = x.Select(x1 => x1.Id).ToList()
  3470. }
  3471. )
  3472. .OrderByDescending(x => x.groupNum)
  3473. .ToList();
  3474. return Ok(JsonView(true, "操作成功!", view));
  3475. }
  3476. /// <summary>
  3477. /// 团组数据统计
  3478. /// 团组数量
  3479. /// </summary>
  3480. /// <param name="_dto"></param>
  3481. /// <returns></returns>
  3482. [HttpPost("StatisticsGroupNum")]
  3483. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3484. public async Task<IActionResult> StatisticsGroupNum(YOYDto _dto)
  3485. {
  3486. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3487. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3488. endDt = $"{_dto.Year}-12-31 23:59:59";
  3489. DateTime _beginDt = Convert.ToDateTime(beginDt),
  3490. _endDt = Convert.ToDateTime(endDt);
  3491. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  3492. .Where(x => x.IsDel == 0)
  3493. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  3494. .Select(x => new StatisticsGroupInfoEntity
  3495. {
  3496. Id = x.Id,
  3497. VisitDate = x.VisitDate,
  3498. Month = x.VisitDate.Month,
  3499. //MonthName = x.VisitDate.ToString("MMM", CultureInfo.GetCultureInfo("zh-CN")),
  3500. VisitPNumber = x.VisitPNumber
  3501. })
  3502. .MergeTable()
  3503. .OrderBy(x => new { x.Month })
  3504. .ToListAsync();
  3505. string groupNumStr = $"年度出访量:{groupInfos.Count}\r\n";
  3506. var groupNumYearData = new
  3507. {
  3508. year = _dto.Year,
  3509. yearName = _dto.Year + "年",
  3510. num = groupInfos.Count,
  3511. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  3512. };
  3513. var groupNumData = groupInfos.GroupBy(x => x.Quarter)
  3514. .Select(x => new
  3515. {
  3516. Quarter = x.Key,
  3517. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  3518. Num = x.Count(),
  3519. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  3520. })
  3521. .OrderBy(x => x.Quarter)
  3522. .ToList();
  3523. groupNumData.ForEach(x =>
  3524. {
  3525. groupNumStr += $"{x.QuarterName}出访量:{x.Num};";
  3526. });
  3527. var groupNumMonthData = groupInfos.GroupBy(x => x.Month)
  3528. .Select(x => new
  3529. {
  3530. Month = x.Key,
  3531. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  3532. Num = x.Count(),
  3533. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  3534. })
  3535. .OrderBy(x => x.Month)
  3536. .ToList();
  3537. return Ok(JsonView(true, "操作成功!", new
  3538. {
  3539. yearData = groupNumYearData,
  3540. quarterData = groupNumData,
  3541. monthData = groupNumMonthData,
  3542. remark = groupNumStr
  3543. }));
  3544. }
  3545. /// <summary>
  3546. /// 团组数据统计
  3547. /// 团组人数
  3548. /// </summary>
  3549. /// <param name="_dto"></param>
  3550. /// <returns></returns>
  3551. [HttpPost("StatisticsGroupPeopleNum")]
  3552. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3553. public async Task<IActionResult> StatisticsGroupPeopleNum(YOYDto _dto)
  3554. {
  3555. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3556. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3557. endDt = $"{_dto.Year}-12-31 23:59:59";
  3558. DateTime _beginDt = Convert.ToDateTime(beginDt),
  3559. _endDt = Convert.ToDateTime(endDt);
  3560. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  3561. .Where(x => x.IsDel == 0)
  3562. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  3563. .Select(x => new StatisticsGroupInfoEntity
  3564. {
  3565. Id = x.Id,
  3566. VisitDate = x.VisitDate,
  3567. Month = x.VisitDate.Month,
  3568. VisitPNumber = x.VisitPNumber
  3569. })
  3570. .MergeTable()
  3571. .OrderBy(x => new { x.Month })
  3572. .ToListAsync();
  3573. string groupPeopleNumStr = $"年度出访人数:{groupInfos.Sum(x => x.VisitPNumber)}\r\n";
  3574. var groupPeopleNumYearData = new
  3575. {
  3576. year = _dto.Year,
  3577. yearName = _dto.Year + "年",
  3578. num = groupInfos.Sum(x => x.VisitPNumber),
  3579. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  3580. };
  3581. var groupPeopleNumData = groupInfos.GroupBy(x => x.Quarter)
  3582. .Select(x => new
  3583. {
  3584. Quarter = x.Key,
  3585. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  3586. Num = x.Sum(x1 => x1.VisitPNumber),
  3587. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  3588. })
  3589. .OrderBy(x => x.Quarter)
  3590. .ToList();
  3591. groupPeopleNumData.ForEach(x =>
  3592. {
  3593. groupPeopleNumStr += $"{x.QuarterName}出访人数:{x.Num};";
  3594. });
  3595. var groupPeopleNumMonthData = groupInfos.GroupBy(x => x.Month)
  3596. .Select(x => new
  3597. {
  3598. Month = x.Key,
  3599. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  3600. Num = x.Sum(x1 => x1.VisitPNumber),
  3601. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  3602. })
  3603. .OrderBy(x => x.Month)
  3604. .ToList();
  3605. return Ok(JsonView(true, "操作成功!", new
  3606. {
  3607. yearData = groupPeopleNumYearData,
  3608. quarterData = groupPeopleNumData,
  3609. monthData = groupPeopleNumMonthData,
  3610. remark = groupPeopleNumStr
  3611. }));
  3612. }
  3613. /// <summary>
  3614. /// 团组数据统计
  3615. /// OP 成本
  3616. /// </summary>
  3617. /// <param name="_dto"></param>
  3618. /// <returns></returns>
  3619. [HttpPost("StatisticsOP")]
  3620. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3621. public async Task<IActionResult> StatisticsOP(StatisticsOPDto _dto)
  3622. {
  3623. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  3624. if (_dto.Type < 1 || _dto.Type > 2) return Ok(JsonView(false, "Type参数错误!"));
  3625. int thisYear = _dto.Year, lastYear = _dto.Year - 1;
  3626. string beginDt = $"{lastYear}-01-01 00:00:00",
  3627. endDt = $"{thisYear}-12-31 23:59:59";
  3628. string sql = string.Format(@"
  3629. SELECT
  3630. temp.Id,
  3631. DiId,
  3632. PaymentTime,
  3633. [Year],
  3634. [Quarter],
  3635. [Month],
  3636. Area,
  3637. FeeType,
  3638. sd1.Name AS FeeTypeName,
  3639. FeeSubType,
  3640. sd2.Name AS FeeSubTypeName,
  3641. CONVERT(DECIMAL(12, 2), Price * Qauntity * ExchangeRate) AS Price
  3642. FROM
  3643. (
  3644. SELECT
  3645. ctggr.Id,
  3646. ctggr.DiId,
  3647. ctggr.Area,
  3648. CASE
  3649. WHEN ctggr.PriceType IS NULL THEN 1069
  3650. ELSE ctggr.PriceType
  3651. END AS FeeType,
  3652. ctggrc.SId AS FeeSubType,
  3653. ctggrc.Price,
  3654. CASE
  3655. WHEN ctggrc.Count IS NULL THEN 1
  3656. ELSE ctggrc.Count
  3657. END AS Qauntity,
  3658. ccp.DayRate AS ExchangeRate,
  3659. ctggrc.CreateTime AS PaymentTime,
  3660. YEAR(ctggrc.CreateTime) AS [Year],
  3661. CONVERT(INT,DATENAME(QUARTER, ctggrc.CreateTime)) AS [Quarter],
  3662. MONTH(ctggrc.CreateTime) AS [Month]
  3663. FROM
  3664. Grp_CarTouristGuideGroundReservations ctggr
  3665. INNER JOIN Grp_CarTouristGuideGroundReservationsContent ctggrc ON ctggr.Id = ctggrc.CTGGRId
  3666. AND ctggrc.IsDel = 0
  3667. INNER JOIN Grp_CreditCardPayment ccp ON ctggr.Id = ccp.CId
  3668. AND ccp.CTable = 79
  3669. AND ccp.IsDel = 0
  3670. WHERE
  3671. ctggr.IsDel = 0
  3672. AND ctggrc.SId != 1070 --费用子项筛掉尾款
  3673. AND ctggrc.Price > 0 --筛选真实存在的数据
  3674. AND ccp.IsPay = 1
  3675. ) temp
  3676. LEFT JOIN Sys_SetData sd1 ON FeeType = sd1.Id
  3677. LEFT JOIN Sys_SetData sd2 ON FeeSubType = sd2.Id
  3678. WHERE
  3679. temp.Area NOT LIKE '%尾款%' -- 筛选掉尾款相关信息
  3680. AND temp.FeeType != 1062 --费用类型筛选掉全款和首付款数据
  3681. AND temp.PaymentTime BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  3682. ORDER BY
  3683. temp.[Year],
  3684. temp.[Quarter],
  3685. temp.[Month]
  3686. ", beginDt, endDt);
  3687. var opInfos = await _sqlSugar.SqlQueryable<StatisticsOP>(sql).ToListAsync();
  3688. //处理地区相关信息
  3689. var countrys = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0).ToListAsync();
  3690. for (int i = 0; i < opInfos.Count; i++)
  3691. {
  3692. string country = string.Empty, city = string.Empty;
  3693. int dataId = 0;
  3694. bool isCountryId = int.TryParse(opInfos[i].Area, out dataId);
  3695. string[] citySelecter = new string[] { "其他城市", "所有城市" };
  3696. if (isCountryId)
  3697. {
  3698. var countryInfo = countrys.Find(x => x.Id == dataId);
  3699. country = countryInfo?.Country ?? "";
  3700. if (citySelecter.Contains(countryInfo?.City)) city = country;
  3701. else city = countryInfo?.City ?? "";
  3702. }
  3703. else
  3704. {
  3705. var countryInfo1 = countrys.Find(x => opInfos[i].Area.Contains(x.Country));
  3706. if (countryInfo1 != null)
  3707. {
  3708. country = countryInfo1?.Country ?? "";
  3709. city = countryInfo1?.City ?? country;
  3710. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  3711. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  3712. else city = countryInfo2?.City ?? country;
  3713. }
  3714. else
  3715. {
  3716. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  3717. if (countryInfo2 != null)
  3718. {
  3719. country = countryInfo2?.Country ?? "";
  3720. city = countryInfo2?.City ?? "";
  3721. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  3722. }
  3723. }
  3724. }
  3725. opInfos[i].Country = country;
  3726. opInfos[i].City = city;
  3727. }
  3728. var opParentFeeData = new StatisticsOP()._OPParentFeeInfo;
  3729. if (_dto.Type == 1)
  3730. {
  3731. //同比增长率=(本期数-同期数)/ 同期数
  3732. var yearData = opInfos.GroupBy(x => x.ParentFeeName)
  3733. .Select(x => new StatisticsOPYOY(
  3734. feeId: x.FirstOrDefault()?.ParentFeeId ?? 0,
  3735. feeName: x.Key,
  3736. currPeriodFee: x.Where(x => x.Year == thisYear).Sum(x => x.Price),
  3737. samePeriodFee: x.Where(x => x.Year == lastYear).Sum(x => x.Price),
  3738. currPeriodGroupTotal: x.Where(x => x.Year == thisYear).Select(x => x.DiId).Distinct().Count(),
  3739. samePeriodGroupTotal: x.Where(x => x.Year == lastYear).Select(x => x.DiId).Distinct().Count(),
  3740. subFeeData: x.GroupBy(x1 => x1.FeeSubType)
  3741. .Select(x1 => new StatisticsOPSubFeeYOY(
  3742. feeId: x1.Key,
  3743. feeName: x1.FirstOrDefault()?.FeeSubTypeName ?? "",
  3744. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  3745. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  3746. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  3747. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  3748. cityData: x1.GroupBy(x2 => x2.City)
  3749. .Select(x2 => new StatisticsOPCityYOY(
  3750. cityName: x2.Key,
  3751. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  3752. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  3753. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  3754. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price)
  3755. ))
  3756. .ToArray()
  3757. ))
  3758. .ToArray()
  3759. ))
  3760. .OrderBy(x => x.FeeId)
  3761. .ToList();
  3762. var opParentYearIds = yearData.Select(x => x.FeeId).ToList();
  3763. var opParentYearDataSelector = opParentFeeData.Where(x => !opParentYearIds.Contains(x.Id)).ToList();
  3764. if (opParentYearDataSelector.Count > 0)
  3765. {
  3766. foreach (var item in opParentYearDataSelector)
  3767. {
  3768. yearData.Add(
  3769. new StatisticsOPYOY(feeId: item.Id,
  3770. feeName: item.Name,
  3771. currPeriodFee: 0.00M,
  3772. samePeriodFee: 0.00M,
  3773. currPeriodGroupTotal: 0,
  3774. samePeriodGroupTotal: 0,
  3775. subFeeData: new StatisticsOPSubFeeYOY[] { }
  3776. ));
  3777. }
  3778. yearData = yearData.OrderBy(x => x.FeeId).ToList();
  3779. }
  3780. return Ok(JsonView(true, "操作成功!", yearData));
  3781. }
  3782. else if (_dto.Type == 2)
  3783. {
  3784. var monthData = opInfos.GroupBy(x => x.Month)
  3785. .Select(x => new StatisticsOPMonthYOY(
  3786. monthId: x.Key,
  3787. monthName: Enum.IsDefined(typeof(MonthEnum), (int)x.Key) ? ((MonthEnum)(int)x.Key).GetEnumDescription() : "",
  3788. feeDatas: x.GroupBy(x1 => x1.ParentFeeId)
  3789. .Select(x1 => new StatisticsOPYOY(
  3790. feeId: x1.Key,
  3791. feeName: x1.FirstOrDefault()?.ParentFeeName ?? "",
  3792. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  3793. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  3794. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  3795. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  3796. subFeeData: x1.GroupBy(x2 => x2.FeeSubType)
  3797. .Select(x2 => new StatisticsOPSubFeeYOY(
  3798. feeId: x2.Key,
  3799. feeName: x2.FirstOrDefault()?.FeeSubTypeName ?? "",
  3800. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  3801. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price),
  3802. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  3803. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  3804. cityData: x2.GroupBy(x3 => x3.City)
  3805. .Select(x3 => new StatisticsOPCityYOY(
  3806. cityName: x3.Key,
  3807. currPeriodFee: x3.Where(x3 => x3.Year == thisYear).Sum(x3 => x3.Price),
  3808. samePeriodFee: x3.Where(x3 => x3.Year == lastYear).Sum(x3 => x3.Price),
  3809. currPeriodGroupTotal: x3.Where(x3 => x3.Year == thisYear).Select(x3 => x3.DiId).Distinct().Count(),
  3810. samePeriodGroupTotal: x3.Where(x3 => x3.Year == lastYear).Select(x3 => x3.DiId).Distinct().Count()
  3811. ))
  3812. .ToArray()
  3813. ))
  3814. .ToArray()
  3815. ))
  3816. .ToArray()
  3817. ))
  3818. //.OrderBy(x => x.MonthId)
  3819. .ToList();
  3820. //1、月份是否足够十二月
  3821. var monthIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  3822. var monthDataIds = monthData.Select(x => x.MonthId).ToArray();
  3823. var newMonthIds = monthIds.Where(x => !monthDataIds.Contains(x)).ToList();
  3824. if (newMonthIds.Count > 0)
  3825. {
  3826. foreach (var item in newMonthIds)
  3827. {
  3828. monthData.Add(new StatisticsOPMonthYOY(
  3829. monthId: item,
  3830. monthName: Enum.IsDefined(typeof(MonthEnum), (int)item) ? ((MonthEnum)(int)item).GetEnumDescription() : "",
  3831. feeDatas: Array.Empty<StatisticsOPYOY>()
  3832. ));
  3833. }
  3834. monthData = monthData.OrderBy(x => x.MonthId).ToList();
  3835. }
  3836. //2、费用父类是否足够
  3837. for (int i = 0; i < monthData.Count; i++)
  3838. {
  3839. var month = monthData[i];
  3840. var opParentFeeIds = month.FeeDatas.Select(x => x.FeeId).ToList();
  3841. var opParentFeeDataSelector = opParentFeeData.Where(x => !opParentFeeIds.Contains(x.Id)).ToList();
  3842. if (opParentFeeDataSelector.Count > 0)
  3843. {
  3844. var feeDatas = month.FeeDatas.ToList();
  3845. foreach (var item in opParentFeeDataSelector)
  3846. {
  3847. feeDatas.Add(new StatisticsOPYOY(
  3848. feeId: item.Id,
  3849. feeName: item.Name,
  3850. currPeriodFee: 0.00M,
  3851. samePeriodFee: 0.00M,
  3852. currPeriodGroupTotal: 0,
  3853. samePeriodGroupTotal: 0,
  3854. subFeeData: Array.Empty<StatisticsOPSubFeeYOY>()
  3855. ));
  3856. }
  3857. feeDatas = feeDatas.OrderBy(x => x.FeeId).ToList();
  3858. monthData[i].FeeDatas = feeDatas.ToArray();
  3859. }
  3860. }
  3861. //3、费用子类是否足够
  3862. return Ok(JsonView(true, "操作成功!", monthData));
  3863. }
  3864. return Ok(JsonView(false, "操作失败!"));
  3865. }
  3866. #endregion
  3867. }
  3868. }