StatisticsController.cs 216 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554
  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. /// </summary>
  1965. /// <param name="_dto">市场部销售额请求dto</param>
  1966. /// <returns></returns>
  1967. [HttpPost("PostMarketingSalesStatistics")]
  1968. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1969. public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)
  1970. {
  1971. #region 参数验证
  1972. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  1973. var validResult = await validationRules.ValidateAsync(_dto);
  1974. if (!validResult.IsValid)
  1975. {
  1976. var errors = new StringBuilder();
  1977. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  1978. return Ok(JsonView(false, errors.ToString()));
  1979. }
  1980. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1981. #region 页面操作权限验证
  1982. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  1983. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  1984. #endregion
  1985. #endregion
  1986. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  1987. return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));
  1988. }
  1989. private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)
  1990. {
  1991. //全部人员Id
  1992. //查询所有公司的市场部
  1993. List<int> pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();
  1994. List<int> userIds = new List<int>();
  1995. var userDatas = await _sqlSugar.Queryable<Sys_Users>()
  1996. .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)
  1997. .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains(u.Id))
  1998. .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })
  1999. .ToListAsync();
  2000. userIds = userDatas.Select(it => it.Id).ToList();
  2001. if (companyId > 0)
  2002. {
  2003. userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();
  2004. }
  2005. if (groupPickupUserId > 0)
  2006. {
  2007. userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();
  2008. }
  2009. return userIds;
  2010. }
  2011. /// <summary>
  2012. /// 计算团组销售额
  2013. /// </summary>
  2014. /// <param name="companyId"></param>
  2015. /// <param name="groupPickupUserId"></param>
  2016. /// <param name="beginDt"></param>
  2017. /// <param name="endDt"></param>
  2018. /// <returns></returns>
  2019. private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId, string beginDt, string endDt)
  2020. {
  2021. decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;
  2022. var _view = new SalesYOYView();
  2023. List<int> userIds = new List<int>();
  2024. userIds = await GetUserIds(companyId, groupPickupUserId);
  2025. string userSqlWhere = "";
  2026. if (userIds.Count > 0)
  2027. {
  2028. userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");
  2029. }
  2030. else
  2031. {
  2032. _view = new SalesYOYView
  2033. {
  2034. thisYearSales = "0.00",
  2035. lastYearSales = "0.00",
  2036. };
  2037. return _view;
  2038. }
  2039. string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),
  2040. lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
  2041. // string salesSql = string.Format(@"
  2042. //SELECT
  2043. // 'ThisSales' As [Name],
  2044. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2045. //FROM
  2046. // (
  2047. // SELECT di.VisitDate,
  2048. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2049. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2050. // ) AS Sales
  2051. // FROM
  2052. // Grp_DelegationInfo di
  2053. // WHERE di.IsDel = 0 AND di.IsSure = 1
  2054. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  2055. // AND di.VisitDate BETWEEN '{1}' AND '{2}'
  2056. // ) temp
  2057. //Union ALL
  2058. //SELECT
  2059. // 'LastSales' As [Name],
  2060. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2061. //FROM
  2062. // (
  2063. // SELECT di.VisitDate,
  2064. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2065. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2066. // ) AS Sales
  2067. // FROM
  2068. // Grp_DelegationInfo di
  2069. // WHERE di.IsDel = 0 AND di.IsSure = 1
  2070. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  2071. // AND di.VisitDate BETWEEN '{4}' AND '{5}'
  2072. // ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  2073. string salesSql = string.Format(@"
  2074. SELECT
  2075. 'ThisSales' As [Name],
  2076. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2077. FROM
  2078. (
  2079. SELECT di.VisitDate,
  2080. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2081. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2082. ) AS Sales
  2083. FROM
  2084. Grp_DelegationInfo di
  2085. WHERE di.IsDel = 0
  2086. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  2087. AND di.VisitDate BETWEEN '{1}' AND '{2}'
  2088. ) temp
  2089. Union ALL
  2090. SELECT
  2091. 'LastSales' As [Name],
  2092. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2093. FROM
  2094. (
  2095. SELECT di.VisitDate,
  2096. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2097. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2098. ) AS Sales
  2099. FROM
  2100. Grp_DelegationInfo di
  2101. WHERE di.IsDel = 0
  2102. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  2103. AND di.VisitDate BETWEEN '{4}' AND '{5}'
  2104. ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  2105. var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();
  2106. thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;
  2107. lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;
  2108. if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;
  2109. return new SalesYOYView()
  2110. {
  2111. thisYearSales = thisSales.ToString("#0.00"),
  2112. lastYearSales = lastSales.ToString("#0.00"),
  2113. yoy = yoy.ToString("#0.00")
  2114. };
  2115. }
  2116. private class SalesView
  2117. {
  2118. public string Name { get; set; }
  2119. public decimal Sales { get; set; }
  2120. }
  2121. private class SalesYOYView
  2122. {
  2123. public string thisYearSales { get; set; }
  2124. public string lastYearSales { get; set; }
  2125. public string yoy { get; set; } = "1.00";
  2126. }
  2127. /// <summary>
  2128. /// 市场部销售额
  2129. /// 团组列表
  2130. /// </summary>
  2131. /// <param name="_dto">市场部销售额请求dto</param>
  2132. /// <returns></returns>
  2133. [HttpPost("PostMarketingSalesGroupList")]
  2134. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2135. public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)
  2136. {
  2137. #region 参数验证
  2138. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2139. var validResult = await validationRules.ValidateAsync(_dto);
  2140. if (!validResult.IsValid)
  2141. {
  2142. var errors = new StringBuilder();
  2143. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2144. return Ok(JsonView(false, errors.ToString()));
  2145. }
  2146. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2147. #region 页面操作权限验证
  2148. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2149. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2150. #endregion
  2151. #endregion
  2152. string userSql = "";
  2153. List<int> userIds = new List<int>();
  2154. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2155. if (userIds.Count <= 0)
  2156. {
  2157. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  2158. }
  2159. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  2160. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  2161. {
  2162. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  2163. }
  2164. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2165. // string sql = string.Format(@$"SELECT
  2166. // ROW_NUMBER() OVER (
  2167. // ORDER BY
  2168. // CollectionDays
  2169. // ) AS RowNumber,
  2170. // *
  2171. //FROM
  2172. // (
  2173. // SELECT
  2174. // di.Id,
  2175. // di.TeamName,
  2176. // di.ClientUnit,
  2177. // di.ClientName,
  2178. // di.VisitDate,
  2179. // di.VisitPNumber,
  2180. // di.JietuanOperator,
  2181. // di.VisitEndDate,
  2182. // (
  2183. // SELECT
  2184. // CAST(
  2185. // COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2186. // ) AS GroupSales
  2187. // FROM
  2188. // Fin_ForeignReceivables
  2189. // WHERE
  2190. // IsDel = 0
  2191. // AND di.Id = Diid
  2192. // AND AddingWay IN (0, 1, 2)
  2193. // ) AS GroupSales,
  2194. // u.CnName AS GroupPickupUser,
  2195. // DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  2196. // FROM
  2197. // Grp_DelegationInfo di
  2198. // WITH
  2199. // (NoLock)
  2200. // LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  2201. // WHERE
  2202. // di.Isdel = 0
  2203. // AND di.IsSure = 1 {userSql}
  2204. // AND VisitDate Between '{beginDt}' And '{endDt}'
  2205. // ) Temp ");
  2206. string sql = string.Format(@$"SELECT
  2207. ROW_NUMBER() OVER (
  2208. ORDER BY
  2209. CollectionDays
  2210. ) AS RowNumber,
  2211. *
  2212. FROM
  2213. (
  2214. SELECT
  2215. di.Id,
  2216. di.TeamName,
  2217. di.ClientUnit,
  2218. di.ClientName,
  2219. di.VisitDate,
  2220. di.VisitPNumber,
  2221. di.JietuanOperator,
  2222. di.VisitEndDate,
  2223. (
  2224. SELECT
  2225. CAST(
  2226. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2227. ) AS GroupSales
  2228. FROM
  2229. Fin_ForeignReceivables
  2230. WHERE
  2231. IsDel = 0
  2232. AND di.Id = Diid
  2233. AND AddingWay IN (0, 1, 2)
  2234. ) AS GroupSales,
  2235. u.CnName AS GroupPickupUser,
  2236. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  2237. FROM
  2238. Grp_DelegationInfo di
  2239. WITH
  2240. (NoLock)
  2241. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  2242. WHERE
  2243. di.Isdel = 0
  2244. {userSql}
  2245. AND VisitDate Between '{beginDt}' And '{endDt}'
  2246. ) Temp ");
  2247. RefAsync<int> total = 0;
  2248. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql)
  2249. .Where(x => x.GroupSales > 0)
  2250. .ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  2251. return Ok(JsonView(true, "操作成功!", groupData, total));
  2252. }
  2253. /// <summary>
  2254. /// 市场部销售额
  2255. /// 客户类型、客户等级 统计
  2256. /// </summary>
  2257. /// <param name="_dto">市场部销售额请求dto</param>
  2258. /// <returns></returns>
  2259. [HttpPost("PostMarketingSalesGroupStatistics")]
  2260. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2261. public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)
  2262. {
  2263. #region 参数验证
  2264. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2265. var validResult = await validationRules.ValidateAsync(_dto);
  2266. if (!validResult.IsValid)
  2267. {
  2268. var errors = new StringBuilder();
  2269. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2270. return Ok(JsonView(false, errors.ToString()));
  2271. }
  2272. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2273. #region 页面操作权限验证
  2274. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2275. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2276. #endregion
  2277. #endregion
  2278. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2279. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2280. string userSql = "";
  2281. if (userIds.Count > 0)
  2282. {
  2283. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  2284. }
  2285. else
  2286. {
  2287. if (_dto.PortType == 2 || _dto.PortType == 3)
  2288. {
  2289. return Ok(JsonView(true, "操作成功!", new List<object> { }));
  2290. }
  2291. else
  2292. {
  2293. return Ok(JsonView(true, "操作成功!", new
  2294. {
  2295. customerTypeData = new List<object> { },
  2296. clientGradeData = new List<object> { }
  2297. }));
  2298. }
  2299. }
  2300. string sql = "";
  2301. if (_dto.StatisticsType == 1)
  2302. {
  2303. sql = string.Format(@$"Select
  2304. sd.[Name],
  2305. Count(*) As [Count]
  2306. From Grp_DelegationInfo di
  2307. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  2308. Where di.Isdel = 0
  2309. And (
  2310. SELECT
  2311. CAST(
  2312. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2313. ) AS GroupSales
  2314. FROM
  2315. Fin_ForeignReceivables fr
  2316. WHERE
  2317. fr.IsDel = 0
  2318. AND di.Id = fr.Diid
  2319. AND AddingWay IN (0, 1, 2)
  2320. ) > 0
  2321. {userSql}
  2322. And VisitDate Between '{beginDt}' And '{endDt}'
  2323. Group By [Name]
  2324. Order By Count Desc");
  2325. }
  2326. else if (_dto.StatisticsType == 2)
  2327. {
  2328. sql = string.Format(@$"Select
  2329. sd.[Name],
  2330. Count(*) As [Count]
  2331. From Grp_DelegationInfo di
  2332. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  2333. Where di.Isdel = 0
  2334. And (
  2335. SELECT
  2336. CAST(
  2337. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2338. ) AS GroupSales
  2339. FROM
  2340. Fin_ForeignReceivables fr
  2341. WHERE
  2342. fr.IsDel = 0
  2343. AND di.Id = fr.Diid
  2344. AND AddingWay IN (0, 1, 2)
  2345. ) > 0
  2346. {userSql}
  2347. And VisitDate Between '{beginDt}' And '{endDt}'
  2348. Group By [Name]
  2349. Order By Count Desc");
  2350. }
  2351. else return Ok(JsonView(false, "StatisticsType不在可取范围!"));
  2352. if (_dto.PortType == 1)
  2353. {
  2354. string sql1 = string.Format(@$"Select
  2355. sd.[Name],
  2356. Count(*) As [Count]
  2357. From Grp_DelegationInfo di
  2358. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  2359. Where di.Isdel = 0
  2360. And (
  2361. SELECT
  2362. CAST(
  2363. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2364. ) AS GroupSales
  2365. FROM
  2366. Fin_ForeignReceivables fr
  2367. WHERE
  2368. fr.IsDel = 0
  2369. AND di.Id = fr.Diid
  2370. AND AddingWay IN (0, 1, 2)
  2371. ) > 0
  2372. {userSql}
  2373. And VisitDate Between '{beginDt}' And '{endDt}'
  2374. Group By [Name]
  2375. Order By Count Desc");
  2376. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  2377. string sql2 = string.Format(@$"Select
  2378. sd.[Name],
  2379. Count(*) As [Count]
  2380. From Grp_DelegationInfo di
  2381. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  2382. Where di.Isdel = 0
  2383. And (
  2384. SELECT
  2385. CAST(
  2386. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2387. ) AS GroupSales
  2388. FROM
  2389. Fin_ForeignReceivables fr
  2390. WHERE
  2391. fr.IsDel = 0
  2392. AND di.Id = fr.Diid
  2393. AND AddingWay IN (0, 1, 2)
  2394. ) > 0
  2395. {userSql}
  2396. And VisitDate Between '{beginDt}' And '{endDt}'
  2397. Group By [Name]
  2398. Order By Count Desc");
  2399. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  2400. return Ok(JsonView(true, "操作成功!", new
  2401. {
  2402. customerTypeData = customerTypeData,
  2403. clientGradeData = clientGradeData
  2404. }));
  2405. }
  2406. else if (_dto.PortType == 2 || _dto.PortType == 3)
  2407. {
  2408. var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();
  2409. return Ok(JsonView(true, "操作成功!", data, data.Count));
  2410. }
  2411. else return Ok(JsonView(false, MsgTips.Port));
  2412. }
  2413. /// <summary>
  2414. /// 市场部销售额
  2415. /// 接单排名
  2416. /// </summary>
  2417. /// <param name="_dto">市场部销售额请求dto</param>
  2418. /// <returns></returns>
  2419. [HttpPost("PostMarketingSalesOrderRanking")]
  2420. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2421. public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)
  2422. {
  2423. #region 参数验证
  2424. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2425. var validResult = await validationRules.ValidateAsync(_dto);
  2426. if (!validResult.IsValid)
  2427. {
  2428. var errors = new StringBuilder();
  2429. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2430. return Ok(JsonView(false, errors.ToString()));
  2431. }
  2432. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2433. #region 页面操作权限验证
  2434. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2435. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2436. #endregion
  2437. #endregion
  2438. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2439. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2440. string userSql = "";
  2441. if (userIds.Count > 0)
  2442. {
  2443. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  2444. }
  2445. else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  2446. string sql = string.Format(@$"Select
  2447. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  2448. u.CnName As UserName,
  2449. Count(*) As [Count]
  2450. From Grp_DelegationInfo di
  2451. Left Join Sys_Users u On di.JietuanOperator = u.Id
  2452. Where di.Isdel = 0
  2453. And (
  2454. SELECT
  2455. CAST(
  2456. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2457. ) AS GroupSales
  2458. FROM
  2459. Fin_ForeignReceivables fr
  2460. WHERE
  2461. fr.IsDel = 0
  2462. AND di.Id = fr.Diid
  2463. AND AddingWay IN (0, 1, 2)
  2464. ) > 0
  2465. {userSql}
  2466. And VisitDate Between '{beginDt}' And '{endDt}'
  2467. Group By CnName");
  2468. RefAsync<int> total = 0;
  2469. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  2470. return Ok(JsonView(true, "操作成功!", rankingData, total));
  2471. }
  2472. /// <summary>
  2473. /// 市场部销售额
  2474. /// 团组列表、客户类型、客户等级、接单排名
  2475. /// </summary>
  2476. /// <param name="_dto">市场部销售额请求dto</param>
  2477. /// <returns></returns>
  2478. [HttpPost("PostMarketingSalesGroupItem")]
  2479. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2480. public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)
  2481. {
  2482. #region 参数验证
  2483. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2484. var validResult = await validationRules.ValidateAsync(_dto);
  2485. if (!validResult.IsValid)
  2486. {
  2487. var errors = new StringBuilder();
  2488. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2489. return Ok(JsonView(false, errors.ToString()));
  2490. }
  2491. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2492. #region 页面操作权限验证
  2493. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2494. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2495. #endregion
  2496. #endregion
  2497. string userSql = "";
  2498. List<int> userIds = new List<int>();
  2499. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2500. if (userIds.Count <= 0)
  2501. {
  2502. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  2503. }
  2504. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  2505. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  2506. {
  2507. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  2508. }
  2509. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2510. #region 团组List
  2511. string sql = string.Format(@$"SELECT
  2512. ROW_NUMBER() OVER (
  2513. ORDER BY
  2514. CollectionDays
  2515. ) AS RowNumber,
  2516. *
  2517. FROM
  2518. (
  2519. SELECT
  2520. di.Id,
  2521. di.TeamName,
  2522. di.ClientUnit,
  2523. di.ClientName,
  2524. di.VisitDate,
  2525. di.VisitPNumber,
  2526. di.JietuanOperator,
  2527. di.VisitEndDate,
  2528. (
  2529. SELECT
  2530. CAST(
  2531. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2532. ) AS GroupSales
  2533. FROM
  2534. Fin_ForeignReceivables
  2535. WHERE
  2536. IsDel = 0
  2537. AND di.Id = Diid
  2538. AND AddingWay IN (0, 1, 2)
  2539. ) AS GroupSales,
  2540. u.CnName AS GroupPickupUser,
  2541. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  2542. FROM
  2543. Grp_DelegationInfo di
  2544. WITH
  2545. (NoLock)
  2546. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  2547. WHERE
  2548. di.Isdel = 0
  2549. {userSql}
  2550. AND VisitDate Between '{beginDt}' And '{endDt}'
  2551. ) Temp ");
  2552. RefAsync<int> total = 0;
  2553. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql)
  2554. .Where(x => x.GroupSales > 0)
  2555. .ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  2556. #endregion
  2557. #region 客户类型、客户等级 统计
  2558. string sql1 = string.Format(@$"Select
  2559. sd.[Name],
  2560. Count(*) As [Count]
  2561. From Grp_DelegationInfo di
  2562. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  2563. Where di.Isdel = 0
  2564. And (
  2565. SELECT
  2566. CAST(
  2567. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2568. ) AS GroupSales
  2569. FROM
  2570. Fin_ForeignReceivables fr
  2571. WHERE
  2572. fr.IsDel = 0
  2573. AND di.Id = fr.Diid
  2574. AND AddingWay IN (0, 1, 2)
  2575. ) > 0
  2576. {userSql}
  2577. And VisitDate Between '{beginDt}' And '{endDt}'
  2578. Group By [Name]
  2579. Order By Count Desc");
  2580. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  2581. string sql2 = string.Format(@$"Select
  2582. sd.[Name],
  2583. Count(*) As [Count]
  2584. From Grp_DelegationInfo di
  2585. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  2586. Where di.Isdel = 0
  2587. And (
  2588. SELECT
  2589. CAST(
  2590. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2591. ) AS GroupSales
  2592. FROM
  2593. Fin_ForeignReceivables fr
  2594. WHERE
  2595. fr.IsDel = 0
  2596. AND di.Id = fr.Diid
  2597. AND AddingWay IN (0, 1, 2)
  2598. ) > 0
  2599. {userSql}
  2600. And VisitDate Between '{beginDt}' And '{endDt}'
  2601. Group By [Name]
  2602. Order By Count Desc");
  2603. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  2604. #endregion
  2605. #region 接单排名
  2606. string sql4 = string.Format(@$"Select
  2607. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  2608. u.CnName As UserName,
  2609. Count(*) As [Count]
  2610. From Grp_DelegationInfo di
  2611. Left Join Sys_Users u On di.JietuanOperator = u.Id
  2612. Where di.Isdel = 0
  2613. And (
  2614. SELECT
  2615. CAST(
  2616. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2617. ) AS GroupSales
  2618. FROM
  2619. Fin_ForeignReceivables fr
  2620. WHERE
  2621. fr.IsDel = 0
  2622. AND di.Id = fr.Diid
  2623. AND AddingWay IN (0, 1, 2)
  2624. ) > 0
  2625. {userSql}
  2626. And VisitDate Between '{beginDt}' And '{endDt}'
  2627. Group By CnName");
  2628. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();
  2629. #endregion
  2630. var viewData = new
  2631. {
  2632. groupData = groupData,
  2633. groupTotal = total,
  2634. customerTypeData = customerTypeData,
  2635. clientGradeData = clientGradeData,
  2636. rankingData = rankingData
  2637. };
  2638. return Ok(JsonView(true, "操作成功!", viewData, total));
  2639. }
  2640. /// <summary>
  2641. /// 市场部销售额
  2642. /// 客户拜访列表
  2643. /// </summary>
  2644. /// <param name="_dto">市场部销售额请求dto</param>
  2645. /// <returns></returns>
  2646. [HttpPost("PostMarketingSalesVCList")]
  2647. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2648. public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)
  2649. {
  2650. #region 参数验证
  2651. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  2652. var validResult = await validationRules.ValidateAsync(_dto);
  2653. if (!validResult.IsValid)
  2654. {
  2655. var errors = new StringBuilder();
  2656. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2657. return Ok(JsonView(false, errors.ToString()));
  2658. }
  2659. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2660. #region 页面操作权限验证
  2661. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2662. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2663. #endregion
  2664. #endregion
  2665. return Ok(await _visitingClientsRep._List(_dto.PortType, _dto.PageIndex, _dto.PageSize, _dto.DiId, _dto.Search));
  2666. }
  2667. /// <summary>
  2668. /// 市场部销售额
  2669. /// 客户拜访 操作(添加 Or 编辑)
  2670. /// </summary>
  2671. /// <param name="_dto">市场部销售额请求dto</param>
  2672. /// <returns></returns>
  2673. [HttpPost("PostMarketingSalesVCOperate")]
  2674. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2675. public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)
  2676. {
  2677. #region 参数验证
  2678. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  2679. var validResult = await validationRules.ValidateAsync(_dto);
  2680. if (!validResult.IsValid)
  2681. {
  2682. var errors = new StringBuilder();
  2683. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2684. return Ok(JsonView(false, errors.ToString()));
  2685. }
  2686. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2687. #region 页面操作权限验证
  2688. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2689. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2690. #endregion
  2691. #endregion
  2692. return Ok(await _visitingClientsRep._AddOrEdit(_dto));
  2693. }
  2694. /// <summary>
  2695. /// 市场部销售额
  2696. /// 客户拜访 Del
  2697. /// </summary>
  2698. /// <param name="_dto">市场部销售额请求dto</param>
  2699. /// <returns></returns>
  2700. [HttpPost("PostMarketingSalesVCDel")]
  2701. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2702. public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)
  2703. {
  2704. return Ok(await _visitingClientsRep._Del(_dto.Id, _dto.UserId));
  2705. }
  2706. /// <summary>
  2707. /// 市场部销售额
  2708. /// 客户拜访 操作 save
  2709. /// </summary>
  2710. /// <param name="_dto">市场部销售额请求dto</param>
  2711. /// <returns></returns>
  2712. [HttpPost("PostMarketingSalesVCSave")]
  2713. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2714. public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)
  2715. {
  2716. #region 参数验证
  2717. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  2718. var validResult = await validationRules.ValidateAsync(_dto);
  2719. if (!validResult.IsValid)
  2720. {
  2721. var errors = new StringBuilder();
  2722. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2723. return Ok(JsonView(false, errors.ToString()));
  2724. }
  2725. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2726. #region 页面操作权限验证
  2727. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2728. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2729. #endregion
  2730. #endregion
  2731. return Ok(await _visitingClientsRep._Save(_dto));
  2732. }
  2733. #endregion
  2734. #region 日付报表
  2735. /// <summary>
  2736. /// 日付类型数据
  2737. /// </summary>
  2738. /// <param name="_dto"></param>
  2739. /// <returns></returns>
  2740. [HttpPost("DailypaymentTypeInit")]
  2741. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2742. public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)
  2743. {
  2744. #region 参数验证
  2745. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  2746. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2747. #region 页面操作权限验证
  2748. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2749. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2750. #endregion
  2751. #endregion
  2752. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  2753. {
  2754. var defaultParentIds = new List<int>() {
  2755. 48,// 人员费用
  2756. 49,// 办公费用
  2757. 50,// 销售费用
  2758. 51,// 其他费用
  2759. 55,// 大运会
  2760. };
  2761. var dailypaymentTypeData = await RedisRepository.RedisFactory
  2762. .CreateRedisRepository()
  2763. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  2764. var dailyTypeData = await _sqlSugar.Queryable<DailypaymentParentTypeView>()
  2765. .Includes(x => x.SubData)
  2766. .Where(x => defaultParentIds.Contains(x.Id))
  2767. .ToListAsync();
  2768. dailyTypeData.ForEach(x =>
  2769. {
  2770. x.SubData.ForEach(y =>
  2771. {
  2772. int currId = dailypaymentTypeData.Find(z => z == y.Id);
  2773. y.IsChecked = currId == 0 ? false : true;
  2774. });
  2775. });
  2776. var companyData = await _sqlSugar.Queryable<Sys_Company>()
  2777. .Where(x => x.IsDel == 0)
  2778. .Select(x => new { id = x.Id, name = x.CompanyName })
  2779. .ToListAsync();
  2780. return Ok(JsonView(true, "查询成功!", new { dailyTypeData = dailyTypeData, companyData = companyData }));
  2781. }
  2782. else
  2783. {
  2784. return Ok(JsonView(false, "查询失败"));
  2785. }
  2786. }
  2787. /// <summary>
  2788. /// 日付类型数据 Save
  2789. /// </summary>
  2790. /// <param name="_dto"></param>
  2791. /// <returns></returns>
  2792. [HttpPost("DailypaymentTypeDataSave")]
  2793. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2794. public async Task<IActionResult> DailypaymentTypeDataSave(DailypaymentTypeDataSaveDto _dto)
  2795. {
  2796. #region 参数验证
  2797. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  2798. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2799. #region 页面操作权限验证
  2800. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2801. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2802. #endregion
  2803. #endregion
  2804. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  2805. {
  2806. if (_dto.TypeIds.Count < 1) return Ok(JsonView(false, "请传入需要保存的TypeIds"));
  2807. var res = await RedisRepository.RedisFactory
  2808. .CreateRedisRepository()
  2809. .StringSetAsync(
  2810. key: "DailypaymentTypeData",
  2811. _dto.TypeIds,
  2812. timeout: null);
  2813. if (!res) return Ok(JsonView(false, "操作失败"));
  2814. return Ok(JsonView(true, "操作成功!"));
  2815. }
  2816. else return Ok(JsonView(false, "操作失败"));
  2817. }
  2818. /// <summary>
  2819. /// 日付数据列表
  2820. /// </summary>
  2821. /// <param name="_dto"></param>
  2822. /// <returns></returns>
  2823. [HttpPost("DailypaymentRange")]
  2824. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2825. public async Task<IActionResult> DailypaymentRange(DailypaymentRangeDto _dto)
  2826. {
  2827. #region 参数验证
  2828. var validator = new DailypaymentRangeDtoValidator();
  2829. var validationRes = validator.Validate(_dto);
  2830. if (!validationRes.IsValid)
  2831. {
  2832. StringBuilder sb = new StringBuilder();
  2833. foreach (var item in validationRes.Errors)
  2834. {
  2835. sb.AppendLine(item.ErrorMessage);
  2836. }
  2837. return Ok(JsonView(false, sb.ToString()));
  2838. }
  2839. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2840. #region 页面操作权限验证
  2841. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2842. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2843. #endregion
  2844. #endregion
  2845. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  2846. {
  2847. DateTime _beginDt = Convert.ToDateTime($"{_dto.BeginDt} 00:00:00"),
  2848. _endDt = Convert.ToDateTime($"{_dto.EndDt} 23:59:59");
  2849. var sqlWhere = string.Format(@" And dfp.CreateTime Between '{0}' And '{1}'", _beginDt, _endDt);
  2850. var dailypaymentTypeData = await RedisRepository.RedisFactory
  2851. .CreateRedisRepository()
  2852. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  2853. var sql = string.Format(@"
  2854. Select
  2855. dfp.Id,
  2856. dfp.Instructions,
  2857. dfp.PriceTypeId,
  2858. sd1.Name As FeeType,
  2859. dfp.TransferTypeId,
  2860. sd2.Name As TransferType,
  2861. dfp.SumPrice,
  2862. dfp.FAuditDate,
  2863. dfp.MAuditDate,
  2864. dfp.CompanyId,
  2865. c.CompanyName,
  2866. dfp.CreateUserId As ApplicantId,
  2867. u.CnName As Applicant,
  2868. dfp.CreateTime As ApplicantDt,
  2869. dfp.Instructions+u.CnName As ViewStr
  2870. From Fin_DailyFeePayment dfp
  2871. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  2872. Left Join Sys_SetData sd1 On dfp.TransferTypeId = sd1.Id
  2873. Left Join Sys_Company c On dfp.CompanyId = c.Id
  2874. Left Join Sys_SetData sd2 On dfp.PriceTypeId = sd2.Id
  2875. Where dfp.IsDel = 0 And dfp.IsPay = 1
  2876. ");//--Order By dfp.CreateTime Desc
  2877. if (_dto.Type == 1) //data
  2878. {
  2879. RefAsync<int> total = 0;
  2880. var _view = await _sqlSugar.SqlQueryable<DailyFeePaymentRangeView>(sql)
  2881. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  2882. .WhereIF(dailypaymentTypeData.Count > 0,
  2883. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  2884. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  2885. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  2886. .OrderByDescending(x => x.ApplicantDt)
  2887. .ToPageListAsync(
  2888. pageNumber: _dto.PageIndex,
  2889. pageSize: _dto.PageSize,
  2890. totalNumber: total
  2891. );
  2892. _sqlSugar.ThenMapper(_view, x =>
  2893. {
  2894. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  2895. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  2896. .ToList();
  2897. });
  2898. //单独处理
  2899. return Ok(JsonView(true, "操作成功!", new { data = _view, total = _view.Sum(x => x.SumPrice) }, total));
  2900. }
  2901. else if (_dto.Type == 2) //view
  2902. {
  2903. var _view = await _sqlSugar.SqlQueryable<ExcelView>(sql)
  2904. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  2905. .WhereIF(dailypaymentTypeData.Count > 0,
  2906. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  2907. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  2908. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  2909. .OrderByDescending(x => x.ApplicantDt)
  2910. .ToPageListAsync(
  2911. pageNumber: 1,
  2912. pageSize: 99999
  2913. );
  2914. _sqlSugar.ThenMapper(_view, x =>
  2915. {
  2916. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  2917. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  2918. .ToList();
  2919. string str = "";
  2920. int index = 1;
  2921. foreach (var item in x.Contents)
  2922. {
  2923. string str1 = $"{index}、费用名称:[{item.PriceName}] 单价:[{item.Price:#0.00}] 数量:[{item.Quantity:#0.00}] 小计:[{item.ItemTotal:#0.00}] 备注:[{item.Remark}]";
  2924. if (index == x.Contents.Count) str += str1;
  2925. else str += str1 + "\r\n";
  2926. index++;
  2927. }
  2928. x.ContentStr = str;
  2929. });
  2930. if (_view.Count > 0)
  2931. {
  2932. //DataTable dt = GeneralMethod.
  2933. DataTable dt = CommonFun.GetDataTableFromIList(_view);
  2934. dt.TableName = $"_view";
  2935. decimal total = _view.Sum(x => x.SumPrice);
  2936. WorkbookDesigner designer = new WorkbookDesigner();
  2937. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/日付报表模板.xls");
  2938. designer.SetDataSource(dt);
  2939. designer.SetDataSource("Total", total);
  2940. designer.Workbook.Worksheets[0].Name = "日付报表";
  2941. designer.Process();
  2942. string fileName = $"DailyPayment/日付报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  2943. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  2944. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  2945. return Ok(JsonView(true, "操作成功", new { url = rst }));
  2946. }
  2947. return Ok(JsonView(true, ",暂无数据"));
  2948. }
  2949. return Ok(JsonView(false, "操作失败"));
  2950. }
  2951. else return Ok(JsonView(false, "操作失败"));
  2952. }
  2953. #endregion
  2954. #region 统计模块
  2955. /// <summary>
  2956. /// 同比
  2957. /// 营业额(今年和去年的)、成本支出(今年和去年的)、毛利润(今年和去年的)
  2958. /// </summary>
  2959. /// <param name="_dto">市场部销售额请求dto</param>
  2960. /// <returns></returns>
  2961. [HttpPost("StatisticsYOY")]
  2962. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2963. public async Task<IActionResult> StatisticsYOY(YOYDto _dto)
  2964. {
  2965. //同比增长率 = (本期 - 同期) / 同期 * 100%;
  2966. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  2967. string beginDt = $"{_dto.Year - 1}-01-01 00:00:00",
  2968. endDt = $"{_dto.Year}-12-31 23:59:59";
  2969. string sql = string.Format(@"
  2970. SELECT
  2971. di.Id,
  2972. di.TeamName,
  2973. di.VisitDate,
  2974. YEAR(di.VisitDate) AS YEAR,
  2975. MONTH(di.VisitDate) AS MONTH,
  2976. (
  2977. SELECT
  2978. CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
  2979. FROM
  2980. Fin_ForeignReceivables
  2981. WHERE
  2982. IsDel = 0
  2983. AND AddingWay IN (0, 1, 2)
  2984. AND di.Id = Diid
  2985. ) AS SaleAmount,
  2986. (
  2987. SELECT
  2988. CAST(
  2989. SUM(
  2990. (
  2991. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  2992. )
  2993. ) AS DECIMAL(12, 2)
  2994. )
  2995. FROM
  2996. Grp_AirTicketReservations atr
  2997. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  2998. AND ccp.CTable = 85
  2999. AND atr.Id = ccp.CId
  3000. WHERE
  3001. atr.IsDel = 0
  3002. AND ccp.IsAuditGM = 1
  3003. AND ccp.IsPay = 1
  3004. AND di.Id = atr.DiId
  3005. ) AirTicketAmount,
  3006. (
  3007. SELECT
  3008. CAST(
  3009. SUM(
  3010. (
  3011. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  3012. )
  3013. ) AS DECIMAL(12, 2)
  3014. )
  3015. FROM
  3016. Grp_CarTouristGuideGroundReservations ctggr
  3017. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  3018. AND ccp.CTable = 79
  3019. AND ctggr.Id = ccp.CId
  3020. WHERE
  3021. ctggr.IsDel = 0
  3022. AND ccp.IsAuditGM = 1
  3023. AND ccp.IsPay = 1
  3024. AND di.Id = ctggr.DiId
  3025. ) AS OPAmount,
  3026. (
  3027. SELECT
  3028. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  3029. FROM
  3030. Grp_DecreasePayments dp
  3031. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  3032. AND ccp.CTable = 98
  3033. AND dp.Id = ccp.CId
  3034. WHERE
  3035. dp.IsDel = 0
  3036. AND ccp.Ctable = 98
  3037. AND ccp.IsAuditGM = 1
  3038. AND ccp.IsPay = 1
  3039. AND di.Id = dp.Diid
  3040. ) AS OtherCostAmount,
  3041. (
  3042. SELECT
  3043. CAST(
  3044. SUM(
  3045. (
  3046. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  3047. )
  3048. ) AS DECIMAL(12, 2)
  3049. )
  3050. FROM
  3051. Grp_VisaInfo vi
  3052. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  3053. AND ccp.CTable = 80
  3054. AND vi.Id = ccp.CId
  3055. WHERE
  3056. vi.IsDel = 0
  3057. AND ccp.IsAuditGM = 1
  3058. AND ccp.IsPay = 1
  3059. AND di.Id = vi.DIId
  3060. ) AS VisaAmount,
  3061. (
  3062. SELECT
  3063. CAST(
  3064. SUM(
  3065. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  3066. ) AS DECIMAL(12, 2)
  3067. )
  3068. FROM
  3069. Grp_InvitationOfficialActivities ioa
  3070. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  3071. AND ccp.CTable = 81
  3072. AND ioa.Id = ccp.CId
  3073. WHERE
  3074. ioa.IsDel = 0
  3075. AND ccp.IsAuditGM = 1
  3076. AND ccp.IsPay = 1
  3077. AND di.Id = ioa.Diid
  3078. ) AS OAAmount,
  3079. (
  3080. SELECT
  3081. CAST(
  3082. SUM(
  3083. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  3084. ) AS DECIMAL(12, 2)
  3085. )
  3086. FROM
  3087. Grp_Customers ic
  3088. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  3089. AND ccp.CTable = 82
  3090. AND ic.Id = ccp.CId
  3091. WHERE
  3092. ic.IsDel = 0
  3093. AND ccp.IsAuditGM = 1And ccp.IsPay = 1
  3094. AND di.Id = ic.DiId
  3095. ) AS InsureAmount,
  3096. (
  3097. SELECT
  3098. CAST(
  3099. SUM(
  3100. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  3101. ) AS DECIMAL(12, 2)
  3102. )
  3103. FROM
  3104. Grp_HotelReservations hr
  3105. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  3106. WHERE
  3107. hr.IsDel = 0
  3108. AND ccp.IsDel = 0
  3109. AND ccp.CTable = 76
  3110. AND ccp.IsAuditGM = 1
  3111. AND ccp.PayMoney <> 0
  3112. AND ccp.IsPay = 0
  3113. AND di.Id = hr.DiId
  3114. ) AS HotelAmount,
  3115. (
  3116. SELECT
  3117. CAST(
  3118. SUM((gec.PriceSum * gec.Coefficient * ccp.DayRate)) AS DECIMAL(12, 2)
  3119. )
  3120. FROM
  3121. OA2023DB.dbo.Fin_GroupExtraCost gec
  3122. INNER JOIN Grp_CreditCardPayment ccp ON gec.Id = ccp.CId
  3123. WHERE
  3124. ccp.IsDel = 0
  3125. AND ccp.CTable = 1015
  3126. AND ccp.IsAuditGM = 1
  3127. AND ccp.IsPay = 1
  3128. AND di.Id = gec.DiId
  3129. ) AS ExcessAmount,
  3130. (
  3131. SELECT
  3132. CAST(
  3133. SUM(
  3134. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  3135. ) AS DECIMAL(12, 2)
  3136. )
  3137. FROM
  3138. Fin_PaymentRefundAndOtherMoney prom
  3139. INNER JOIN Grp_CreditCardPayment ccp ON prom.DiId = ccp.DIId
  3140. AND prom.Id = ccp.CId
  3141. WHERE
  3142. prom.IsDel = 0
  3143. AND prom.PayType = 1
  3144. AND ccp.CTable = 285
  3145. AND ccp.IsAuditGM = 1
  3146. AND ccp.IsPay = 1
  3147. AND di.Id = prom.DiId
  3148. ) AS SKTHAmount
  3149. FROM
  3150. Grp_DelegationInfo di
  3151. WHERE
  3152. di.IsDel = 0
  3153. AND di.TeamDid IN (38,39,40,1048)
  3154. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  3155. ORDER BY
  3156. di.VisitDate
  3157. ", beginDt, endDt);
  3158. var data = await _sqlSugar.SqlQueryable<StatisticsYOYView>(sql).ToListAsync();
  3159. var thisYearData = data.Where(x => x.Year == _dto.Year).ToList();
  3160. var lastYearData = data.Where(x => x.Year == (_dto.Year - 1)).ToList();
  3161. List<YOYReturnView> salesYOYData = new List<YOYReturnView>();
  3162. List<YOYReturnView> costYOYData = new List<YOYReturnView>();
  3163. List<YOYReturnView> grossProfitYOYData = new List<YOYReturnView>();
  3164. int monthIndex = 1;
  3165. while (monthIndex < 13)
  3166. {
  3167. var thisMonthData = thisYearData.Where(x => x.Month == monthIndex).ToList();
  3168. var lastMonthData = lastYearData.Where(x => x.Month == monthIndex).ToList();
  3169. var thisGroupIds = thisMonthData.Select(x => x.Id).ToList();
  3170. var lastGroupIds = lastMonthData.Select(x => x.Id).ToList();
  3171. decimal thisSalesAmount = thisMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  3172. lastSalesAmount = lastMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  3173. thisCostAmount = thisMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  3174. lastCostAmount = lastMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  3175. thisgrossProfitAmount = thisMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M),
  3176. lastgrossProfitAmount = lastMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M);
  3177. salesYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisSalesAmount, lastSalesAmount, thisGroupIds, lastGroupIds));
  3178. costYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisCostAmount, lastCostAmount, thisGroupIds, lastGroupIds));
  3179. grossProfitYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisgrossProfitAmount, lastgrossProfitAmount, thisGroupIds, lastGroupIds));
  3180. monthIndex++;
  3181. }
  3182. salesYOYData = salesYOYData.OrderBy(x => x.Month).ToList();
  3183. costYOYData = costYOYData.OrderBy(x => x.Month).ToList();
  3184. grossProfitYOYData = grossProfitYOYData.OrderBy(x => x.Month).ToList();
  3185. return Ok(JsonView(true, "操作成功!", new { salesYOYData = salesYOYData, costYOYData = costYOYData, grossProfitYOYData = grossProfitYOYData }));
  3186. }
  3187. /// <summary>
  3188. /// 国交数据统计-机票相关
  3189. /// 1、机票票数、2、机票到达地
  3190. /// </summary>
  3191. /// <param name="_dto"></param>
  3192. /// <returns></returns>
  3193. [HttpPost("StatisticsAirTicket")]
  3194. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3195. public async Task<IActionResult> StatisticsAirTicket(YOYDto _dto)
  3196. {
  3197. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3198. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3199. endDt = $"{_dto.Year}-12-31 23:59:59";
  3200. string sql = string.Format(@"
  3201. SELECT
  3202. atr.DIId,
  3203. atr.FlightsDate,
  3204. YEAR(atr.FlightsDate) AS YEAR,
  3205. MONTH(atr.FlightsDate) AS MONTH,
  3206. atr.CType,
  3207. sd.Name As CTypeName,
  3208. atr.FlightsCity,
  3209. atr.ClientNum,
  3210. atr.ClientName
  3211. FROM
  3212. Grp_AirTicketReservations atr
  3213. INNER JOIN Grp_CreditCardPayment ccp ON atr.Id = ccp.CId
  3214. AND ccp.IsDel = 0
  3215. AND CTable = 85
  3216. INNER JOIN Grp_DelegationInfo di ON atr.DIId = di.Id
  3217. LEFT JOIN Sys_SetData sd On atr.CType = sd.Id
  3218. WHERE
  3219. atr.IsDel = 0
  3220. AND di.TeamDid IN (38,39,40,1048)
  3221. And atr.CType IN(457,458,459,460,574,575)
  3222. AND CHARINDEX('行程单',atr.ClientName) = 0
  3223. AND CHARINDEX('返点',atr.ClientName) = 0
  3224. AND CHARINDEX('-1',atr.ClientName) = 0
  3225. AND ccp.IsPay = 1
  3226. AND atr.FlightsDate BETWEEN '{0}' AND '{1}'
  3227. ORDER BY atr.FlightsDate
  3228. ", beginDt, endDt);
  3229. var data = await _sqlSugar.SqlQueryable<StatisticsAirTicketView>(sql).ToListAsync();
  3230. var groupIds = data.Select(x => x.DIId).ToList();
  3231. //处理城市数据
  3232. var threeCodeData = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  3233. //处理团组名称
  3234. var groupNames = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => groupIds.Contains(x.Id)).Select(x => new { Id = x.Id, GroupName = x.TeamName }).ToListAsync();
  3235. data.ForEach(x =>
  3236. {
  3237. string cityName = "";
  3238. if (!string.IsNullOrEmpty(x.FlightsCity))
  3239. {
  3240. string cityCode = x.FlightsCity.Replace("-", "").Replace("/", "");
  3241. int cityNum = cityCode.Length / 3;
  3242. if (cityCode.Length % 3 == 0)
  3243. {
  3244. for (int i = 0; i < cityNum; i++)
  3245. {
  3246. string code = "";
  3247. if (i == 0) code = cityCode.Substring(0, 3);
  3248. else code = cityCode.Substring(i * 3, 3);
  3249. if (!string.IsNullOrEmpty(code))
  3250. {
  3251. if (i == cityNum - 1)
  3252. {
  3253. cityName += threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  3254. }
  3255. else
  3256. {
  3257. var str1 = threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  3258. cityName += str1 + "、";
  3259. }
  3260. }
  3261. }
  3262. }
  3263. }
  3264. x.FlightsCityName = cityName;
  3265. });
  3266. var airTicketNumData = new List<AirTicketReturnView>();
  3267. var airTicketAreaData = new List<AirTicketCityReturnView>();
  3268. int monthIndex = 1;
  3269. while (monthIndex < 13)
  3270. {
  3271. var monthData = data.Where(x => x.Month == monthIndex).ToList();
  3272. //机票票数处理
  3273. int airticket_quantity = monthData.Sum(x => x.ClientNum);
  3274. var linkGroupIds = monthData.Select(x => x.DIId).ToList();
  3275. List<AitTicketInfo> aitTicketInfos = new List<AitTicketInfo>();
  3276. foreach (var item in monthData)
  3277. {
  3278. string groupName = groupNames.Find(x => item.DIId == x.Id)?.GroupName ?? "";
  3279. aitTicketInfos.Add(new AitTicketInfo(item.DIId, groupName, item.ClientNum));
  3280. }
  3281. var aitTicketInfosGroupBy = aitTicketInfos.GroupBy(x => x.Id);
  3282. List<AitTicketInfo> aitTicketInfos1 = new List<AitTicketInfo>();
  3283. foreach (var item in aitTicketInfosGroupBy)
  3284. {
  3285. aitTicketInfos1.Add(new AitTicketInfo(item.Key, item.First().GroupName, item.Sum(x => x.Quantity)));
  3286. }
  3287. aitTicketInfos1 = aitTicketInfos1.OrderBy(x => x.Quantity).ToList();
  3288. linkGroupIds = linkGroupIds.Distinct().ToList();
  3289. airTicketNumData.Add(new AirTicketReturnView(_dto.Year, monthIndex, airticket_quantity, aitTicketInfos1, linkGroupIds));
  3290. //机票城市处理
  3291. //城市处理
  3292. List<string> airTicketCityInfos = new List<string>();
  3293. foreach (var item in monthData)
  3294. {
  3295. if (!string.IsNullOrEmpty(item.FlightsCityName))
  3296. {
  3297. if (item.FlightsCityName.Contains("、"))
  3298. {
  3299. var cityArray = item.FlightsCityName.Split("、").ToList();
  3300. foreach (var item1 in cityArray)
  3301. {
  3302. if (!string.IsNullOrEmpty(item1))
  3303. {
  3304. airTicketCityInfos.Add(item1);
  3305. }
  3306. }
  3307. }
  3308. else
  3309. {
  3310. airTicketCityInfos.Add(item.FlightsCityName);
  3311. }
  3312. }
  3313. }
  3314. //int quantity1 = airTicketCityInfos.Count;
  3315. int city_totalquantity = 0;
  3316. var airTicketCityInfosGroupby = airTicketCityInfos.GroupBy(x => x);
  3317. var airTicketCityInfos1 = new List<AirTicketCityInfo>();
  3318. foreach (var item in airTicketCityInfosGroupby)
  3319. {
  3320. var city_quantity = item.ToList().Count;
  3321. city_totalquantity += city_quantity;
  3322. airTicketCityInfos1.Add(new AirTicketCityInfo(item.Key, city_quantity));
  3323. }
  3324. airTicketCityInfos1 = airTicketCityInfos1.OrderByDescending(x => x.Quantity).ToList();
  3325. airTicketAreaData.Add(new AirTicketCityReturnView(_dto.Year, monthIndex, city_totalquantity, airTicketCityInfos1, linkGroupIds));
  3326. monthIndex++;
  3327. }
  3328. return Ok(JsonView(true, "操作成功!", new { airTicketNumData = airTicketNumData, airTicketAreaData = airTicketAreaData }));
  3329. }
  3330. /// <summary>
  3331. /// 国交数据统计
  3332. /// 酒店预订地区TOP10
  3333. /// </summary>
  3334. /// <param name="_dto"></param>
  3335. /// <returns></returns>
  3336. [HttpPost("StatisticsHotel")]
  3337. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3338. public async Task<IActionResult> StatisticsHotel(YOYDto _dto)
  3339. {
  3340. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3341. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3342. endDt = $"{_dto.Year}-12-31 23:59:59";
  3343. string sql = string.Format(@"
  3344. SELECT
  3345. hr.DIId,
  3346. hr.City,
  3347. hr.HotelName,
  3348. sd.Name AS BookinSite,
  3349. hr.CheckInDate,
  3350. YEAR(hr.CheckInDate) AS YEAR,
  3351. MONTH(hr.CheckInDate) AS MONTH,
  3352. hr.CheckOutDate,
  3353. hr.SingleRoomCount,
  3354. hr.DoubleRoomCount,
  3355. hr.SuiteRoomCount,
  3356. hr.OtherRoomCount
  3357. FROM
  3358. Grp_HotelReservations hr
  3359. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  3360. AND ccp.IsDel = 0
  3361. AND CTable = 76
  3362. INNER JOIN Grp_DelegationInfo di ON hr.DiId = di.Id
  3363. LEFT JOIN Sys_SetData sd ON hr.ReservationsWebsite = sd.Id
  3364. WHERE
  3365. hr.IsDel = 0
  3366. AND di.TeamDid IN (38,39,40,1048)
  3367. AND ccp.IsPay = 1
  3368. AND (
  3369. hr.SingleRoomCount > 0
  3370. OR hr.DoubleRoomCount > 0
  3371. OR hr.SuiteRoomCount > 0
  3372. OR hr.OtherRoomCount > 0
  3373. )
  3374. AND CHARINDEX('早餐',hr.HotelName) = 0
  3375. AND CHARINDEX('晚餐',hr.HotelName) = 0
  3376. AND CHARINDEX('升级',hr.HotelName) = 0
  3377. AND CHARINDEX('饮料茶水费',hr.HotelName) = 0
  3378. AND CHARINDEX('城市税',hr.HotelName) = 0
  3379. AND CHARINDEX('退款',hr.HotelName) = 0
  3380. AND CHARINDEX('返现',hr.HotelName) = 0
  3381. AND CHARINDEX('会议室',hr.HotelName) = 0
  3382. AND CHARINDEX('迷你吧消费',hr.HotelName) = 0
  3383. AND CHARINDEX('运费',hr.HotelName) = 0
  3384. AND CHARINDEX('地接',hr.HotelName) = 0
  3385. AND CHARINDEX('损失',hr.HotelName) = 0
  3386. AND CHARINDEX('补差',hr.HotelName) = 0
  3387. AND hr.CheckInDate BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  3388. ORDER BY
  3389. hr.CheckInDate
  3390. ", beginDt, endDt);
  3391. var data = await _sqlSugar.SqlQueryable<StatisticsHotelView>(sql).ToListAsync();
  3392. var hotelData = data.OrderBy(x => x.CityStr).ToList();
  3393. var hotelCityGroupByData = data.GroupBy(x => x.CityStr)
  3394. .Select(g => new
  3395. {
  3396. city = g.Key,
  3397. BookingRoomNum = g.Sum(x => x.RoomTotal),
  3398. hotelData = g.GroupBy(x => x.HotelName)
  3399. .Select(g1 => new
  3400. {
  3401. hotelName = g1.Key,
  3402. roomNights = g1.Sum(x => x.RoomNights),
  3403. roomTotal = g1.Sum(x => x.RoomTotal),
  3404. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  3405. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  3406. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  3407. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  3408. })
  3409. .ToList(),
  3410. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  3411. })
  3412. .OrderByDescending(x => x.BookingRoomNum)
  3413. .Take(10)
  3414. .ToList();
  3415. return Ok(JsonView(true, "操作成功!", hotelCityGroupByData));
  3416. }
  3417. /// <summary>
  3418. /// 国交数据统计
  3419. /// 商邀邀请国家数量TOP10
  3420. /// </summary>
  3421. /// <param name="_dto"></param>
  3422. /// <returns></returns>
  3423. [HttpPost("StatisticsInvitation")]
  3424. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3425. public async Task<IActionResult> StatisticsInvitation(YOYDto _dto)
  3426. {
  3427. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3428. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3429. endDt = $"{_dto.Year}-12-31 23:59:59";
  3430. string sql = string.Format(@"
  3431. SELECT
  3432. ioa.DiId,
  3433. ioa.InviterArea AS Country
  3434. FROM
  3435. Grp_InvitationOfficialActivities ioa
  3436. INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
  3437. AND ccp.IsDel = 0
  3438. AND ccp.CTable = 81
  3439. INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
  3440. WHERE
  3441. ioa.IsDel = 0
  3442. AND di.TeamDid IN (38,39,40,1048)
  3443. AND ccp.IsPay = 1
  3444. AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
  3445. ", beginDt, endDt);
  3446. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
  3447. var groupByData = data.GroupBy(x => x.Country)
  3448. .Select(g => new
  3449. {
  3450. Country = g.Key,
  3451. TimeNum = g.Count(),
  3452. LinkGroupIds = g.Select(x => x.DIId).ToList()
  3453. })
  3454. .OrderByDescending(x => x.TimeNum)
  3455. .Take(10)
  3456. .ToList();
  3457. return Ok(JsonView(true, "操作成功!", groupByData));
  3458. }
  3459. /// <summary>
  3460. /// 会务数据统计
  3461. /// 会务城市TOP10排序
  3462. /// </summary>
  3463. /// <param name="_dto"></param>
  3464. /// <returns></returns>
  3465. [HttpPost("StatisticsConferenceCity")]
  3466. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3467. public async Task<IActionResult> StatisticsConferenceCity(YOYDto _dto)
  3468. {
  3469. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3470. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3471. endDt = $"{_dto.Year}-12-31 23:59:59";
  3472. string sql = string.Format(@"
  3473. SELECT
  3474. ioa.DiId,
  3475. ioa.InviterArea AS Country
  3476. FROM
  3477. Grp_InvitationOfficialActivities ioa
  3478. INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
  3479. AND ccp.IsDel = 0
  3480. AND ccp.CTable = 81
  3481. INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
  3482. WHERE
  3483. ioa.IsDel = 0
  3484. AND di.TeamDid IN (102,248,302,691,762,1047)
  3485. AND ccp.IsPay = 1
  3486. AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
  3487. ", beginDt, endDt);
  3488. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
  3489. var groupByData = data.GroupBy(x => x.Country)
  3490. .Select(g => new
  3491. {
  3492. Country = g.Key,
  3493. TimeNum = g.Count(),
  3494. LinkGroupIds = g.Select(x => x.DIId).ToList()
  3495. })
  3496. .OrderByDescending(x => x.TimeNum)
  3497. .Take(10)
  3498. .ToList();
  3499. return Ok(JsonView(true, "操作成功!", groupByData));
  3500. }
  3501. /// <summary>
  3502. /// 团组数据统计
  3503. /// 团组合作前十的客户TOP10排序
  3504. /// </summary>
  3505. /// <param name="_dto"></param>
  3506. /// <returns></returns>
  3507. [HttpPost("StatisticsCooperativeCustomer")]
  3508. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3509. public async Task<IActionResult> StatisticsCooperativeCustomer(YOYDto _dto)
  3510. {
  3511. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3512. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3513. endDt = $"{_dto.Year}-12-31 23:59:59";
  3514. DateTime _beginDt = Convert.ToDateTime(beginDt),
  3515. _endDt = Convert.ToDateTime(endDt);
  3516. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  3517. .Where(x => x.IsDel == 0)
  3518. //.Where(x => x.IsSure == 1)
  3519. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  3520. .ToListAsync();
  3521. var groupInfos1 = groupInfos.GroupBy(x => x.ClientName);
  3522. var view = groupInfos1.Select(x =>
  3523. new
  3524. {
  3525. clienName = x.Key,
  3526. clientUnit = x.FirstOrDefault()?.ClientUnit ?? "",
  3527. visitsNum = x.Count()
  3528. }
  3529. )
  3530. .OrderByDescending(x => x.visitsNum)
  3531. .Take(10)
  3532. .ToList();
  3533. return Ok(JsonView(true, "操作成功!", view));
  3534. }
  3535. /// <summary>
  3536. /// 团组数据统计
  3537. /// 已出团客户单位的类型比例图(饼状图-政府团、企业团等)
  3538. /// </summary>
  3539. /// <param name="_dto"></param>
  3540. /// <returns></returns>
  3541. [HttpPost("StatisticsCooperativeCustomerType")]
  3542. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3543. public async Task<IActionResult> StatisticsCooperativeCustomerType(YOYDto _dto)
  3544. {
  3545. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3546. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3547. endDt = $"{_dto.Year}-12-31 23:59:59";
  3548. DateTime _beginDt = Convert.ToDateTime(beginDt),
  3549. _endDt = Convert.ToDateTime(endDt);
  3550. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  3551. .LeftJoin<Sys_SetData>((di, sd) => di.TeamDid == sd.Id)
  3552. .Where((di, sd) => di.IsDel == 0)
  3553. .Where((di, sd) => di.VisitDate >= _beginDt && di.VisitDate <= _endDt)
  3554. .Select((di, sd) => new
  3555. {
  3556. Id = di.Id,
  3557. GroupTypeId = di.TeamDid,
  3558. GroupTypeName = sd.Name,
  3559. })
  3560. .ToListAsync();
  3561. var groupInfos1 = groupInfos.GroupBy(x => x.GroupTypeName);
  3562. var view = groupInfos1.Select(x =>
  3563. new
  3564. {
  3565. groupTypeName = x.Key,
  3566. groupNum = x.Count(),
  3567. linkGroupId = x.Select(x1 => x1.Id).ToList()
  3568. }
  3569. )
  3570. .OrderByDescending(x => x.groupNum)
  3571. .ToList();
  3572. return Ok(JsonView(true, "操作成功!", view));
  3573. }
  3574. /// <summary>
  3575. /// 团组数据统计
  3576. /// 团组数量
  3577. /// </summary>
  3578. /// <param name="_dto"></param>
  3579. /// <returns></returns>
  3580. [HttpPost("StatisticsGroupNum")]
  3581. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3582. public async Task<IActionResult> StatisticsGroupNum(YOYDto _dto)
  3583. {
  3584. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3585. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3586. endDt = $"{_dto.Year}-12-31 23:59:59";
  3587. DateTime _beginDt = Convert.ToDateTime(beginDt),
  3588. _endDt = Convert.ToDateTime(endDt);
  3589. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  3590. .Where(x => x.IsDel == 0)
  3591. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  3592. .Select(x => new StatisticsGroupInfoEntity
  3593. {
  3594. Id = x.Id,
  3595. VisitDate = x.VisitDate,
  3596. Month = x.VisitDate.Month,
  3597. //MonthName = x.VisitDate.ToString("MMM", CultureInfo.GetCultureInfo("zh-CN")),
  3598. VisitPNumber = x.VisitPNumber
  3599. })
  3600. .MergeTable()
  3601. .OrderBy(x => new { x.Month })
  3602. .ToListAsync();
  3603. string groupNumStr = $"年度出访量:{groupInfos.Count}\r\n";
  3604. var groupNumYearData = new
  3605. {
  3606. year = _dto.Year,
  3607. yearName = _dto.Year + "年",
  3608. num = groupInfos.Count,
  3609. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  3610. };
  3611. var groupNumData = groupInfos.GroupBy(x => x.Quarter)
  3612. .Select(x => new
  3613. {
  3614. Quarter = x.Key,
  3615. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  3616. Num = x.Count(),
  3617. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  3618. })
  3619. .OrderBy(x => x.Quarter)
  3620. .ToList();
  3621. groupNumData.ForEach(x =>
  3622. {
  3623. groupNumStr += $"{x.QuarterName}出访量:{x.Num};";
  3624. });
  3625. var groupNumMonthData = groupInfos.GroupBy(x => x.Month)
  3626. .Select(x => new
  3627. {
  3628. Month = x.Key,
  3629. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  3630. Num = x.Count(),
  3631. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  3632. })
  3633. .OrderBy(x => x.Month)
  3634. .ToList();
  3635. return Ok(JsonView(true, "操作成功!", new
  3636. {
  3637. yearData = groupNumYearData,
  3638. quarterData = groupNumData,
  3639. monthData = groupNumMonthData,
  3640. remark = groupNumStr
  3641. }));
  3642. }
  3643. /// <summary>
  3644. /// 团组数据统计
  3645. /// 团组人数
  3646. /// </summary>
  3647. /// <param name="_dto"></param>
  3648. /// <returns></returns>
  3649. [HttpPost("StatisticsGroupPeopleNum")]
  3650. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3651. public async Task<IActionResult> StatisticsGroupPeopleNum(YOYDto _dto)
  3652. {
  3653. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3654. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  3655. endDt = $"{_dto.Year}-12-31 23:59:59";
  3656. DateTime _beginDt = Convert.ToDateTime(beginDt),
  3657. _endDt = Convert.ToDateTime(endDt);
  3658. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  3659. .Where(x => x.IsDel == 0)
  3660. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  3661. .Select(x => new StatisticsGroupInfoEntity
  3662. {
  3663. Id = x.Id,
  3664. VisitDate = x.VisitDate,
  3665. Month = x.VisitDate.Month,
  3666. VisitPNumber = x.VisitPNumber
  3667. })
  3668. .MergeTable()
  3669. .OrderBy(x => new { x.Month })
  3670. .ToListAsync();
  3671. string groupPeopleNumStr = $"年度出访人数:{groupInfos.Sum(x => x.VisitPNumber)}\r\n";
  3672. var groupPeopleNumYearData = new
  3673. {
  3674. year = _dto.Year,
  3675. yearName = _dto.Year + "年",
  3676. num = groupInfos.Sum(x => x.VisitPNumber),
  3677. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  3678. };
  3679. var groupPeopleNumData = groupInfos.GroupBy(x => x.Quarter)
  3680. .Select(x => new
  3681. {
  3682. Quarter = x.Key,
  3683. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  3684. Num = x.Sum(x1 => x1.VisitPNumber),
  3685. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  3686. })
  3687. .OrderBy(x => x.Quarter)
  3688. .ToList();
  3689. groupPeopleNumData.ForEach(x =>
  3690. {
  3691. groupPeopleNumStr += $"{x.QuarterName}出访人数:{x.Num};";
  3692. });
  3693. var groupPeopleNumMonthData = groupInfos.GroupBy(x => x.Month)
  3694. .Select(x => new
  3695. {
  3696. Month = x.Key,
  3697. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  3698. Num = x.Sum(x1 => x1.VisitPNumber),
  3699. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  3700. })
  3701. .OrderBy(x => x.Month)
  3702. .ToList();
  3703. return Ok(JsonView(true, "操作成功!", new
  3704. {
  3705. yearData = groupPeopleNumYearData,
  3706. quarterData = groupPeopleNumData,
  3707. monthData = groupPeopleNumMonthData,
  3708. remark = groupPeopleNumStr
  3709. }));
  3710. }
  3711. /// <summary>
  3712. /// 团组数据统计
  3713. /// OP 成本
  3714. /// </summary>
  3715. /// <param name="_dto"></param>
  3716. /// <returns></returns>
  3717. [HttpPost("StatisticsOP")]
  3718. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3719. public async Task<IActionResult> StatisticsOP(StatisticsOPDto _dto)
  3720. {
  3721. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  3722. if (_dto.Type < 1 || _dto.Type > 2) return Ok(JsonView(false, "Type参数错误!"));
  3723. int thisYear = _dto.Year, lastYear = _dto.Year - 1;
  3724. string beginDt = $"{lastYear}-01-01 00:00:00",
  3725. endDt = $"{thisYear}-12-31 23:59:59";
  3726. string sql = string.Format(@"
  3727. SELECT
  3728. temp.Id,
  3729. DiId,
  3730. PaymentTime,
  3731. [Year],
  3732. [Quarter],
  3733. [Month],
  3734. Area,
  3735. FeeType,
  3736. sd1.Name AS FeeTypeName,
  3737. FeeSubType,
  3738. sd2.Name AS FeeSubTypeName,
  3739. CONVERT(DECIMAL(12, 2), Price * Qauntity * ExchangeRate) AS Price
  3740. FROM
  3741. (
  3742. SELECT
  3743. ctggr.Id,
  3744. ctggr.DiId,
  3745. ctggr.Area,
  3746. CASE
  3747. WHEN ctggr.PriceType IS NULL THEN 1069
  3748. ELSE ctggr.PriceType
  3749. END AS FeeType,
  3750. ctggrc.SId AS FeeSubType,
  3751. ctggrc.Price,
  3752. CASE
  3753. WHEN ctggrc.Count IS NULL THEN 1
  3754. ELSE ctggrc.Count
  3755. END AS Qauntity,
  3756. ccp.DayRate AS ExchangeRate,
  3757. ctggrc.CreateTime AS PaymentTime,
  3758. YEAR(ctggrc.CreateTime) AS [Year],
  3759. CONVERT(INT,DATENAME(QUARTER, ctggrc.CreateTime)) AS [Quarter],
  3760. MONTH(ctggrc.CreateTime) AS [Month]
  3761. FROM
  3762. Grp_CarTouristGuideGroundReservations ctggr
  3763. INNER JOIN Grp_CarTouristGuideGroundReservationsContent ctggrc ON ctggr.Id = ctggrc.CTGGRId
  3764. AND ctggrc.IsDel = 0
  3765. INNER JOIN Grp_CreditCardPayment ccp ON ctggr.Id = ccp.CId
  3766. AND ccp.CTable = 79
  3767. AND ccp.IsDel = 0
  3768. WHERE
  3769. ctggr.IsDel = 0
  3770. AND ctggrc.SId != 1070 --费用子项筛掉尾款
  3771. AND ctggrc.Price > 0 --筛选真实存在的数据
  3772. AND ccp.IsPay = 1
  3773. ) temp
  3774. LEFT JOIN Sys_SetData sd1 ON FeeType = sd1.Id
  3775. LEFT JOIN Sys_SetData sd2 ON FeeSubType = sd2.Id
  3776. WHERE
  3777. temp.Area NOT LIKE '%尾款%' -- 筛选掉尾款相关信息
  3778. AND temp.FeeType != 1062 --费用类型筛选掉全款和首付款数据
  3779. AND temp.PaymentTime BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  3780. ORDER BY
  3781. temp.[Year],
  3782. temp.[Quarter],
  3783. temp.[Month]
  3784. ", beginDt, endDt);
  3785. var opInfos = await _sqlSugar.SqlQueryable<StatisticsOP>(sql).ToListAsync();
  3786. //处理地区相关信息
  3787. var countrys = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0).ToListAsync();
  3788. for (int i = 0; i < opInfos.Count; i++)
  3789. {
  3790. string country = string.Empty, city = string.Empty;
  3791. int dataId = 0;
  3792. bool isCountryId = int.TryParse(opInfos[i].Area, out dataId);
  3793. string[] citySelecter = new string[] { "其他城市", "所有城市" };
  3794. if (isCountryId)
  3795. {
  3796. var countryInfo = countrys.Find(x => x.Id == dataId);
  3797. country = countryInfo?.Country ?? "";
  3798. if (citySelecter.Contains(countryInfo?.City)) city = country;
  3799. else city = countryInfo?.City ?? "";
  3800. }
  3801. else
  3802. {
  3803. var countryInfo1 = countrys.Find(x => opInfos[i].Area.Contains(x.Country));
  3804. if (countryInfo1 != null)
  3805. {
  3806. country = countryInfo1?.Country ?? "";
  3807. city = countryInfo1?.City ?? country;
  3808. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  3809. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  3810. else city = countryInfo2?.City ?? country;
  3811. }
  3812. else
  3813. {
  3814. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  3815. if (countryInfo2 != null)
  3816. {
  3817. country = countryInfo2?.Country ?? "";
  3818. city = countryInfo2?.City ?? "";
  3819. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  3820. }
  3821. }
  3822. }
  3823. opInfos[i].Country = country;
  3824. opInfos[i].City = city;
  3825. }
  3826. var opParentFeeData = new StatisticsOP()._OPParentFeeInfo;
  3827. if (_dto.Type == 1)
  3828. {
  3829. //同比增长率=(本期数-同期数)/ 同期数
  3830. var yearData = opInfos.GroupBy(x => x.ParentFeeName)
  3831. .Select(x => new StatisticsOPYOY(
  3832. feeId: x.FirstOrDefault()?.ParentFeeId ?? 0,
  3833. feeName: x.Key,
  3834. currPeriodFee: x.Where(x => x.Year == thisYear).Sum(x => x.Price),
  3835. samePeriodFee: x.Where(x => x.Year == lastYear).Sum(x => x.Price),
  3836. currPeriodGroupTotal: x.Where(x => x.Year == thisYear).Select(x => x.DiId).Distinct().Count(),
  3837. samePeriodGroupTotal: x.Where(x => x.Year == lastYear).Select(x => x.DiId).Distinct().Count(),
  3838. subFeeData: x.GroupBy(x1 => x1.FeeSubType)
  3839. .Select(x1 => new StatisticsOPSubFeeYOY(
  3840. feeId: x1.Key,
  3841. feeName: x1.FirstOrDefault()?.FeeSubTypeName ?? "",
  3842. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  3843. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  3844. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  3845. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  3846. cityData: x1.GroupBy(x2 => x2.City)
  3847. .Select(x2 => new StatisticsOPCityYOY(
  3848. cityName: x2.Key,
  3849. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  3850. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  3851. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  3852. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price)
  3853. ))
  3854. .ToArray()
  3855. ))
  3856. .ToArray()
  3857. ))
  3858. .OrderBy(x => x.FeeId)
  3859. .ToList();
  3860. var opParentYearIds = yearData.Select(x => x.FeeId).ToList();
  3861. var opParentYearDataSelector = opParentFeeData.Where(x => !opParentYearIds.Contains(x.Id)).ToList();
  3862. if (opParentYearDataSelector.Count > 0)
  3863. {
  3864. foreach (var item in opParentYearDataSelector)
  3865. {
  3866. yearData.Add(
  3867. new StatisticsOPYOY(feeId: item.Id,
  3868. feeName: item.Name,
  3869. currPeriodFee: 0.00M,
  3870. samePeriodFee: 0.00M,
  3871. currPeriodGroupTotal: 0,
  3872. samePeriodGroupTotal: 0,
  3873. subFeeData: new StatisticsOPSubFeeYOY[] { }
  3874. ));
  3875. }
  3876. yearData = yearData.OrderBy(x => x.FeeId).ToList();
  3877. }
  3878. return Ok(JsonView(true, "操作成功!", yearData));
  3879. }
  3880. else if (_dto.Type == 2)
  3881. {
  3882. var monthData = opInfos.GroupBy(x => x.Month)
  3883. .Select(x => new StatisticsOPMonthYOY(
  3884. monthId: x.Key,
  3885. monthName: Enum.IsDefined(typeof(MonthEnum), (int)x.Key) ? ((MonthEnum)(int)x.Key).GetEnumDescription() : "",
  3886. feeDatas: x.GroupBy(x1 => x1.ParentFeeId)
  3887. .Select(x1 => new StatisticsOPYOY(
  3888. feeId: x1.Key,
  3889. feeName: x1.FirstOrDefault()?.ParentFeeName ?? "",
  3890. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  3891. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  3892. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  3893. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  3894. subFeeData: x1.GroupBy(x2 => x2.FeeSubType)
  3895. .Select(x2 => new StatisticsOPSubFeeYOY(
  3896. feeId: x2.Key,
  3897. feeName: x2.FirstOrDefault()?.FeeSubTypeName ?? "",
  3898. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  3899. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price),
  3900. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  3901. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  3902. cityData: x2.GroupBy(x3 => x3.City)
  3903. .Select(x3 => new StatisticsOPCityYOY(
  3904. cityName: x3.Key,
  3905. currPeriodFee: x3.Where(x3 => x3.Year == thisYear).Sum(x3 => x3.Price),
  3906. samePeriodFee: x3.Where(x3 => x3.Year == lastYear).Sum(x3 => x3.Price),
  3907. currPeriodGroupTotal: x3.Where(x3 => x3.Year == thisYear).Select(x3 => x3.DiId).Distinct().Count(),
  3908. samePeriodGroupTotal: x3.Where(x3 => x3.Year == lastYear).Select(x3 => x3.DiId).Distinct().Count()
  3909. ))
  3910. .ToArray()
  3911. ))
  3912. .ToArray()
  3913. ))
  3914. .ToArray()
  3915. ))
  3916. //.OrderBy(x => x.MonthId)
  3917. .ToList();
  3918. //1、月份是否足够十二月
  3919. var monthIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  3920. var monthDataIds = monthData.Select(x => x.MonthId).ToArray();
  3921. var newMonthIds = monthIds.Where(x => !monthDataIds.Contains(x)).ToList();
  3922. if (newMonthIds.Count > 0)
  3923. {
  3924. foreach (var item in newMonthIds)
  3925. {
  3926. monthData.Add(new StatisticsOPMonthYOY(
  3927. monthId: item,
  3928. monthName: Enum.IsDefined(typeof(MonthEnum), (int)item) ? ((MonthEnum)(int)item).GetEnumDescription() : "",
  3929. feeDatas: Array.Empty<StatisticsOPYOY>()
  3930. ));
  3931. }
  3932. monthData = monthData.OrderBy(x => x.MonthId).ToList();
  3933. }
  3934. //2、费用父类是否足够
  3935. for (int i = 0; i < monthData.Count; i++)
  3936. {
  3937. var month = monthData[i];
  3938. var opParentFeeIds = month.FeeDatas.Select(x => x.FeeId).ToList();
  3939. var opParentFeeDataSelector = opParentFeeData.Where(x => !opParentFeeIds.Contains(x.Id)).ToList();
  3940. if (opParentFeeDataSelector.Count > 0)
  3941. {
  3942. var feeDatas = month.FeeDatas.ToList();
  3943. foreach (var item in opParentFeeDataSelector)
  3944. {
  3945. feeDatas.Add(new StatisticsOPYOY(
  3946. feeId: item.Id,
  3947. feeName: item.Name,
  3948. currPeriodFee: 0.00M,
  3949. samePeriodFee: 0.00M,
  3950. currPeriodGroupTotal: 0,
  3951. samePeriodGroupTotal: 0,
  3952. subFeeData: Array.Empty<StatisticsOPSubFeeYOY>()
  3953. ));
  3954. }
  3955. feeDatas = feeDatas.OrderBy(x => x.FeeId).ToList();
  3956. monthData[i].FeeDatas = feeDatas.ToArray();
  3957. }
  3958. }
  3959. //3、费用子类是否足够
  3960. return Ok(JsonView(true, "操作成功!", monthData));
  3961. }
  3962. return Ok(JsonView(false, "操作失败!"));
  3963. }
  3964. #endregion
  3965. }
  3966. }