StatisticsController.cs 159 KB

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