StatisticsController.cs 306 KB

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