StatisticsController.cs 245 KB

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