StatisticsController.cs 255 KB

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