StatisticsController.cs 163 KB

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