StatisticsController.cs 243 KB

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