StatisticsController.cs 171 KB

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