StatisticsController.cs 211 KB

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