StatisticsController.cs 238 KB

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