StatisticsController.cs 245 KB

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