StatisticsController.cs 214 KB

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