StatisticsController.cs 237 KB

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