StatisticsController.cs 239 KB

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