StatisticsController.cs 436 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028
  1. using Aspose.Cells;
  2. using FluentValidation;
  3. using OASystem.API.OAMethodLib;
  4. using OASystem.API.OAMethodLib.JuHeAPI;
  5. using OASystem.Domain.AesEncryption;
  6. using OASystem.Domain.Dtos.Statistics;
  7. using OASystem.Domain.Entities.Customer;
  8. using OASystem.Domain.Entities.Financial;
  9. using OASystem.Domain.Entities.Groups;
  10. using OASystem.Domain.ViewModels.Financial;
  11. using OASystem.Domain.ViewModels.Statistics;
  12. using OASystem.Infrastructure.Repositories.Groups;
  13. using SqlSugar;
  14. using System.Data;
  15. using static OASystem.API.OAMethodLib.GeneralMethod;
  16. using TypeInfo = OASystem.Domain.ViewModels.Statistics.TypeInfo;
  17. namespace OASystem.API.Controllers
  18. {
  19. /// <summary>
  20. /// 统计模块
  21. /// </summary>
  22. [Route("api/[controller]")]
  23. [ApiController]
  24. public class StatisticsController : ControllerBase
  25. {
  26. //private readonly int _decimalPlaces;
  27. private readonly IConfiguration _config;
  28. private readonly IMapper _mapper;
  29. private readonly SqlSugarClient _sqlSugar;
  30. private readonly DelegationInfoRepository _groupRep;
  31. private readonly SetDataRepository _setDataRep;
  32. private readonly TeamRateRepository _teamRateRep;
  33. private readonly VisitingClientsRepository _visitingClientsRep;
  34. private readonly IJuHeApiService _juHeApiService;
  35. /// <summary>
  36. /// Init
  37. /// </summary>
  38. /// <param name="mapper"></param>
  39. /// <param name="config"></param>
  40. /// <param name="sqlSugar"></param>
  41. /// <param name="groupRep"></param>
  42. /// <param name="setDataRep"></param>
  43. /// <param name="teamRate"></param>
  44. /// <param name="visitingClientsRep"></param>
  45. /// <param name="juHeApiService"></param>
  46. public StatisticsController(
  47. IMapper mapper,
  48. IConfiguration config,
  49. SqlSugarClient sqlSugar,
  50. DelegationInfoRepository groupRep,
  51. SetDataRepository setDataRep,
  52. TeamRateRepository teamRate,
  53. VisitingClientsRepository visitingClientsRep,
  54. IJuHeApiService juHeApiService
  55. )
  56. {
  57. _mapper = mapper;
  58. _config = config;
  59. _groupRep = groupRep;
  60. _setDataRep = setDataRep;
  61. _sqlSugar = sqlSugar;
  62. _teamRateRep = teamRate;
  63. _visitingClientsRep = visitingClientsRep;
  64. _juHeApiService = juHeApiService;
  65. }
  66. #region 团组报表
  67. /// <summary>
  68. /// 团组报表
  69. /// Items
  70. /// </summary>
  71. /// <param name="_dto">团组列表请求dto</param>
  72. /// <returns></returns>
  73. [HttpPost("PostGroupStatementItems")]
  74. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  75. public async Task<IActionResult> PostGroupStatementItems(GroupStatementItemsDto _dto)
  76. {
  77. #region 参数验证
  78. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  79. if (_dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
  80. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  81. #region 页面操作权限验证
  82. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  83. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  84. #endregion
  85. #endregion
  86. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  87. {
  88. string sqlWhere = string.Empty;
  89. if (_dto.IsSure == 0) //未完成
  90. {
  91. sqlWhere += string.Format(@" And IsSure = 0");
  92. }
  93. else if (_dto.IsSure == 1) //已完成
  94. {
  95. sqlWhere += string.Format(@" And IsSure = 1");
  96. }
  97. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  98. {
  99. string tj = _dto.SearchCriteria;
  100. 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}%')",
  101. tj, tj, tj, tj, tj);
  102. }
  103. string sql = string.Format(@"Select row_number() over(order by gdi.VisitStartDate Desc) as Row_Number,
  104. gdi.Id,TourCode,ssd1.Id TeamLevId,ssd1.Name TeamLev,TeamName,
  105. ClientName,ClientUnit,VisitDate,ssd.Id TeamTypeId, ssd.Name TeamType,
  106. VisitDays,VisitPNumber,su.CnName JietuanOperator,IsSure,gdi.CreateTime,
  107. pr.LastCollectionTime
  108. From Grp_DelegationInfo gdi
  109. Left Join Sys_SetData ssd On gdi.TeamDid = ssd.Id
  110. Left Join Sys_SetData ssd1 On gdi.TeamLevSId = ssd1.Id
  111. Left Join Sys_Users su On gdi.JietuanOperator = su.Id
  112. Left Join (
  113. SELECT Diid, MAX(CreateTime) LastCollectionTime
  114. FROM Fin_ProceedsReceived
  115. Where IsDel = 0
  116. GROUP BY Diid
  117. ) pr On gdi.Id = pr.Diid
  118. Where gdi.IsDel = 0 {0} ", sqlWhere);
  119. RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
  120. var _DelegationList = await _sqlSugar.SqlQueryable<GroupStatementItemView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);//ToPageAsync
  121. var _view = new
  122. {
  123. PageFuncAuth = pageFunAuthView,
  124. Data = _DelegationList
  125. };
  126. return Ok(JsonView(true, "查询成功!", _view, total));
  127. }
  128. else
  129. {
  130. return Ok(JsonView(false, "查询失败"));
  131. }
  132. }
  133. /// <summary>
  134. /// 团组报表
  135. /// Details
  136. /// </summary>
  137. /// <param name="_dto">团组列表请求dto</param>
  138. /// <returns></returns>
  139. [HttpPost("PostGroupStatementDetails")]
  140. //[JsonConverter(typeof(DecimalConverter), 2)]
  141. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  142. public async Task<IActionResult> PostGroupStatementDetails(GroupStatementDetailsDto _dto)
  143. {
  144. /*
  145. * 团组报表计算方式
  146. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  147. * 应收金额 = 应收表.Sum()
  148. * 已收金额 = 已收表.Sum()
  149. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  150. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  151. *
  152. */
  153. #region 参数验证
  154. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  155. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  156. if (_dto.DiId < 1) return Ok(JsonView(false, "团组Id为空"));
  157. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  158. #region 页面操作权限验证
  159. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  160. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  161. #endregion
  162. #endregion
  163. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  164. {
  165. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  166. #region 费用类型 币种,转账,客户信息
  167. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  168. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>()
  169. .Where(it => it.IsDel == 0)
  170. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  171. .ToListAsync();
  172. foreach (var item in _clientDatas) EncryptionProcessor.DecryptProperties(item);
  173. var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.Id == _dto.DiId).FirstAsync();
  174. var visitDate = groupInfo.VisitDate;
  175. #endregion
  176. #region 团组收入
  177. GroupIncomeView _giView = new GroupIncomeView();
  178. /*
  179. * 应收报表
  180. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  181. */
  182. decimal frTotalAmount = 0.00M;//应收总金额
  183. 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,
  184. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  185. From Fin_ForeignReceivables fr
  186. Left Join Sys_SetData sd On fr.Currency = sd.Id
  187. Left Join Sys_Users u On fr.Auditor = u.Id
  188. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  189. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  190. //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  191. //if (_frViews1.Count > 0)
  192. //{
  193. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  194. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  195. //}
  196. _frViews.ForEach(x =>
  197. {
  198. string namePrefix = string.Empty;
  199. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  200. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  201. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  202. x.PriceName = $"{namePrefix}{x.PriceName}";
  203. });
  204. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  205. _giView.Receivables = _frViews;
  206. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  207. /*
  208. * 已收报表
  209. */
  210. decimal prTotalAmount = 0.00M;//已收总金额
  211. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  212. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  213. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  214. From Fin_ProceedsReceived pr
  215. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  216. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  217. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  218. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  219. prTotalAmount = _prViews.Sum(it => it.Price);
  220. _giView.ProceedsReceivedViews = _prViews;
  221. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
  222. /*
  223. * 超支费用
  224. */
  225. decimal exTotalAmount = 0.00M;
  226. // 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,
  227. // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  228. // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  229. //From OA2023DB.dbo.Fin_GroupExtraCost gec
  230. //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  231. // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  232. // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  233. // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  234. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  235. //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 " : " ");
  236. // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
  237. // #region 超支费用 - 模拟数据
  238. // //if (_ExtraCostsViews.Count < 1)
  239. // //{
  240. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  241. // // {
  242. // // GECId = 0,
  243. // // GECDiId = 2334,
  244. // // PriceName = "模拟数据-超支费用名称",
  245. // // PayMoney = 1000.00M,
  246. // // PaymentCurrency = "CNY",
  247. // // DayRate = 1.0000M,
  248. // // CNYPrice = 1000.00M,
  249. // // Payee = "模拟数据-超支费用收款方",
  250. // // OrbitalPrivateTransfer = 1,
  251. // // PayWay = "刷卡",
  252. // // CardType = "招行卡",
  253. // // IsPay = 1,
  254. // // Applicant = "刘华举"
  255. // // });
  256. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  257. // // {
  258. // // GECId = 0,
  259. // // GECDiId = 2334,
  260. // // PriceName = "模拟数据-超支费用名称",
  261. // // PayMoney = 1000.00M,
  262. // // PaymentCurrency = "CNY",
  263. // // DayRate = 1.0000M,
  264. // // CNYPrice = 1000.00M,
  265. // // Payee = "模拟数据-超支费用收款方",
  266. // // OrbitalPrivateTransfer = 1,
  267. // // PayWay = "刷卡",
  268. // // CardType = "招行卡",
  269. // // IsPay = 1,
  270. // // Applicant = "刘华举"
  271. // // });
  272. // //}
  273. // #endregion
  274. // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  275. // _giView.ExtraCostsViews = _ExtraCostsViews;
  276. // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  277. /*
  278. * 收款退还
  279. */
  280. decimal promTotalAmount = 0.00M;// 收款退还总金额
  281. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  282. //删除了 And prom.PriceType = 1
  283. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  284. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  285. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  286. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
  287. From Fin_PaymentRefundAndOtherMoney prom
  288. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  289. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  290. Where prom.IsDel = 0
  291. And prom.PayType = 1
  292. And ccp.CTable = 285
  293. {1}
  294. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  295. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  296. foreach (var ropItem in _promDatas)
  297. {
  298. string thisCueencyCode = "Unknown";
  299. string thisCueencyName = "Unknown";
  300. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  301. if (currency != null)
  302. {
  303. thisCueencyCode = currency.Name;
  304. thisCueencyName = currency.Remark;
  305. }
  306. string orbitalPrivateTransferStr = "Unknown";
  307. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  308. if (orbitalPrivateTransfer != null)
  309. {
  310. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  311. }
  312. string payStr = "Unknown";
  313. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  314. if (pay != null)
  315. {
  316. payStr = pay.Name;
  317. }
  318. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  319. {
  320. Id = ropItem.Id,
  321. DiId = ropItem.DIId,
  322. PriceName = ropItem.PrPriceName,
  323. PayCurrencyCode = thisCueencyCode,
  324. PayCurrencyName = thisCueencyName,
  325. Price = ropItem.PrPrice,
  326. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  327. ThisRate = ropItem.DayRate,
  328. Payee = ropItem.Payee,
  329. PayTime = ropItem.AuditGMDate,
  330. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  331. PayType = payStr,
  332. IsPay = ropItem.IsPay,
  333. Applicant = ropItem.Appliction
  334. };
  335. _promView.Add(gsd_PaymentRefund);
  336. }
  337. #region 收款退还 - 模拟数据
  338. //if (_promView.Count < 1)
  339. //{
  340. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  341. // {
  342. // Id = 0,
  343. // DiId = 2334,
  344. // PriceName = "模拟数据-费用名称",
  345. // PayCurrencyCode = "CNY",
  346. // PayCurrencyName = "人民币",
  347. // Price = 1000.00M,
  348. // CNYPrice = 1000.00M,
  349. // ThisRate = 1.00M,
  350. // Payee = "模拟数据-收款方",
  351. // PayTime = "2023-01-01 15:20:01",
  352. // OrbitalPrivateTransfer = 1,
  353. // PayType = "刷卡",
  354. // IsPay = 1,
  355. // Applicant = "刘华举"
  356. // });
  357. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  358. // {
  359. // Id = 0,
  360. // DiId = 2334,
  361. // PriceName = "模拟数据-费用名称",
  362. // PayCurrencyCode = "CNY",
  363. // PayCurrencyName = "人民币",
  364. // Price = 1000.00M,
  365. // CNYPrice = 1000.00M,
  366. // ThisRate = 1.00M,
  367. // Payee = "模拟数据-收款方",
  368. // PayTime = "2023-01-01 15:20:01",
  369. // OrbitalPrivateTransfer = 1,
  370. // PayType = "刷卡",
  371. // IsPay = 1,
  372. // Applicant = "刘华举"
  373. // });
  374. //}
  375. #endregion
  376. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  377. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  378. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  379. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  380. _view.GroupIncome = _giView;
  381. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  382. #endregion
  383. #region 团组支出
  384. GroupExpenditureView _geView = new GroupExpenditureView();
  385. var isAudit = _dto.isAudit;
  386. var isAuditSql = string.Format($" AND (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3) ");
  387. var isAuditStatus = new int[] {
  388. 1, //已通过
  389. 3, //自动审核
  390. };
  391. #region 酒店预定费用 76 isAuditSql
  392. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  393. //ccp.RMBPrice As CNYPrice
  394. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  395. string hotelFeeSql = string.Format(@"
  396. SELECT
  397. hr.Id AS HrId,
  398. hr.DiId AS HrDiId,
  399. hr.City,
  400. hr.HotelName,
  401. hr.CheckInDate,
  402. hr.CheckOutDate,
  403. hr.CardPrice AS RoomPrice,
  404. sd1.Name AS PaymentCurrency,
  405. hr.SingleRoomPrice,
  406. hr.SingleRoomCount,
  407. hr.DoubleRoomPrice,
  408. hr.DoubleRoomCount,
  409. hr.SuiteRoomPrice,
  410. hr.SuiteRoomCount,
  411. hr.OtherRoomPrice,
  412. hr.OtherRoomCount,
  413. hr.BreakfastPrice,
  414. sd4.Name AS BreakfastCurrency,
  415. hr.Isoppay,
  416. hr.GovernmentRent,
  417. sd5.Name AS GovernmentRentCurrency,
  418. hr.CityTax,
  419. sd6.Name AS CityTaxCurrency,
  420. ccp.PayMoney,
  421. (
  422. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  423. ) AS CNYPrice,
  424. ccp.PayPercentage,
  425. ccp.DayRate,
  426. ccp.Payee,
  427. ccp.OrbitalPrivateTransfer,
  428. sd2.Name AS PayWay,
  429. sd3.Name AS CardType,
  430. ccp.IsPay,
  431. u.CnName AS Applicant
  432. FROM
  433. Grp_HotelReservations hr
  434. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  435. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  436. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  437. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  438. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  439. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  440. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  441. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  442. WHERE
  443. hr.IsDel = 0
  444. AND ccp.IsDel = 0
  445. AND ccp.CTable = 76 {1}
  446. AND ccp.PayMoney <> 0
  447. AND hr.DiId = {0}
  448. ORDER BY
  449. CheckInDate Asc",
  450. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  451. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  452. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  453. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  454. decimal HotelCNYTotalPrice = 0.00M;
  455. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  456. foreach (var item in groupHotelFeeViews)
  457. {
  458. if (groupHotelContentFeeViews.Count > 0)
  459. {
  460. string paymentStr = string.Empty;
  461. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  462. item.RoomPrice = roomData?.Price ?? 0.00M;
  463. if (item.RoomPrice != 0)
  464. {
  465. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  466. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  467. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  468. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  469. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  470. 收款方:{roomData?.Payee}<br/>
  471. 费用标识:{feeMark1} <br/>
  472. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  473. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  474. 是否由地接支付:{isFeeMark1} <br/>";
  475. }
  476. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  477. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  478. if (item.BreakfastPrice != 0)
  479. {
  480. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  481. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  482. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  483. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  484. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  485. 收款方:{breakfastData?.Payee}<br/>
  486. 费用标识:{feeMark2} <br/>
  487. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  488. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  489. 是否由地接支付:{isFeeMark2} <br/>";
  490. }
  491. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  492. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  493. if (item.GovernmentRent != 0)
  494. {
  495. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  496. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  497. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  498. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  499. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  500. 收款方:{landTaxData?.Payee}<br/>
  501. 费用标识:{feeMark3} <br/>
  502. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  503. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  504. 是否由地接支付:{isFeeMark3} <br/>";
  505. }
  506. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  507. item.CityTax = cityTaxData?.Price ?? 0.00M;
  508. if (item.CityTax != 0)
  509. {
  510. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  511. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  512. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  513. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  514. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  515. 收款方:{cityTaxData?.Payee}<br/>
  516. 费用标识:{feeMark4} <br/>
  517. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  518. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  519. 是否由地接支付:{isFeeMark4} <br/>";
  520. }
  521. if (!string.IsNullOrEmpty(paymentStr))
  522. {
  523. item.IsPay = 2;
  524. item.PayTips = paymentStr;
  525. }
  526. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  527. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  528. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  529. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  530. }
  531. else
  532. {
  533. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  534. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  535. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  536. (item.OtherRoomCount * item.OtherRoomPrice);
  537. //item.RoomPrice = item.CardPrice;
  538. item.RoomPriceCurrency = item.PaymentCurrency;
  539. }
  540. HotelCNYTotalPrice += item.CNYPrice;
  541. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  542. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  543. }
  544. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  545. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  546. #endregion
  547. #region 地接费用 79 isAuditSql
  548. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  549. string CTGGRFeeSql = string.Empty;
  550. if (visitDate > Convert.ToDateTime("2024-04-17"))
  551. {
  552. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  553. sd2.name As PaymentCurrency,ccp.PayPercentage,
  554. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  555. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  556. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  557. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  558. From Grp_CarTouristGuideGroundReservations ctggr
  559. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  560. cggrc.DatePrice,cggrc.PriceContent
  561. From Grp_CarTouristGuideGroundReservationsContent cggrc
  562. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  563. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  564. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  565. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  566. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  567. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  568. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  569. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  570. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  571. Order By CreateTime", _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  572. }
  573. else
  574. {
  575. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  576. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  577. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  578. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  579. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  580. ccp.Payee,ccp.AuditGMDate,
  581. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  582. From Grp_CarTouristGuideGroundReservations ctggr
  583. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  584. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  585. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  586. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  587. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  588. Order By CreateTime", _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  589. }
  590. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  591. string CTGGRFeeStr = "";
  592. decimal CTGGRCNYTotalPrice = 0.00M;
  593. //按1 地区,2 币种,3 汇率 分组计算
  594. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  595. foreach (var ctggfr in groupCTGGRFeeDatas)
  596. {
  597. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  598. if (ctggfr_curr.Count() > 0)
  599. {
  600. foreach (var curr in ctggfr_curr)
  601. {
  602. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  603. if (ctggfr_rate.Count() > 0)
  604. {
  605. foreach (var rate in ctggfr_rate)
  606. {
  607. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  608. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  609. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  610. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  611. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  612. }
  613. }
  614. else
  615. {
  616. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  617. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  618. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  619. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  620. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  621. }
  622. }
  623. }
  624. else
  625. {
  626. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  627. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  628. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  629. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  630. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  631. }
  632. }
  633. foreach (var item in groupCTGGRFeeViews)
  634. {
  635. if (!string.IsNullOrEmpty(item.AuditGMDate))
  636. {
  637. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  638. }
  639. if (item.DatePrice != DateTime.MinValue)
  640. {
  641. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  642. }
  643. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  644. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  645. //CTGGRCNYTotalPrice += item.CNYPrice;
  646. }
  647. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  648. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  649. #endregion
  650. #region 机票预订费用 85 isAuditSql
  651. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  652. //ccp.RMBPrice As CNYPrice
  653. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  654. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  655. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  656. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  657. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  658. atr.CType
  659. From Grp_AirTicketReservations atr
  660. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  661. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  662. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  663. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  664. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  665. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  666. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime",
  667. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  668. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  669. string str = "";
  670. List<dynamic> airClientPris = new List<dynamic>();
  671. decimal AirCNYTotalPrice = 0.00M;
  672. //decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M;
  673. decimal JJCAveragePrice = 0.00M;
  674. //decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M;
  675. decimal GWCAveragePrice = 0.00M;
  676. //if (groupAirFeeViews.Count > 0)
  677. //{
  678. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  679. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  680. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  681. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  682. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  683. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  684. //}
  685. int Index = 0;
  686. foreach (var item in groupAirFeeViews)
  687. {
  688. if (item.AirId > 2924)
  689. {
  690. string itemClientName = "";
  691. if (!string.IsNullOrEmpty(item.ClientName))
  692. {
  693. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  694. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  695. if (m_EnName.Success || m_ZHName.Success)
  696. {
  697. itemClientName = item.ClientName;
  698. AirCNYTotalPrice += item.CNYPrice;
  699. continue;
  700. }
  701. string[] clientIds = new string[] { };
  702. if (item.ClientName.Contains(','))
  703. {
  704. clientIds = item.ClientName.Split(',');
  705. }
  706. else
  707. {
  708. clientIds = new string[] { item.ClientName };
  709. }
  710. if (clientIds.Length > 0)
  711. {
  712. int[] output = System.Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  713. if (output.Contains(-1))
  714. {
  715. itemClientName += $@"行程单";
  716. output = output.Where(val => val != -1).ToArray();
  717. }
  718. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  719. decimal unitCost = 0.00M;
  720. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  721. int clienIndex = 1;
  722. foreach (var client in clients)
  723. {
  724. airClientPris.Add(new
  725. {
  726. CnName = client.LastName + client.FirstName,
  727. EnName = client.Pinyin,
  728. Price = unitCost,
  729. AirType = item.AirTypeName
  730. });
  731. string six = "";
  732. if (client.Sex == 0) six = "Mr";
  733. else if (client.Sex == 1) six = "Ms";
  734. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  735. clienIndex++;
  736. }
  737. }
  738. }
  739. item.ClientName = itemClientName;
  740. }
  741. else
  742. {
  743. string clientPinYinName = "";
  744. decimal unitCost = 0.00M;
  745. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  746. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  747. Regex r = new Regex("[0-9]");
  748. string name1 = item.ClientName;
  749. name1 = r.Replace(name1, "");
  750. string[] clientNames = name1.Split('.');
  751. for (int i = 0; i < item.ClientNum; i++)
  752. {
  753. string name = "";
  754. if (clientNames.Length > 0)
  755. {
  756. int index = i + 1;
  757. if (index < clientNames.Length)
  758. {
  759. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  760. if (!string.IsNullOrEmpty(name))
  761. {
  762. airClientPris.Add(new
  763. {
  764. CnName = name,
  765. EnName = name,
  766. Price = unitCost,
  767. AirType = item.AirTypeName
  768. });
  769. }
  770. //if (name.Length > 0)
  771. //{
  772. // string nameLastStr = name[name.Length - 1].ToString();
  773. // if (nameLastStr.IsNumeric())
  774. // {
  775. // name = name.Substring(0, name.Length - 1).Trim();
  776. // }
  777. //}
  778. }
  779. }
  780. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  781. }
  782. }
  783. if (!string.IsNullOrEmpty(item.AuditGMDate))
  784. {
  785. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  786. }
  787. AirCNYTotalPrice += item.CNYPrice;
  788. }
  789. _geView.GroupAirFeeViews = groupAirFeeViews;
  790. if (airClientPris.Count > 0)
  791. {
  792. var peoplePriStr = "";
  793. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  794. .Select(group => group.First())
  795. .ToList();
  796. int airClientPrisIndex = 1;
  797. foreach (var item in airClientPris1)
  798. {
  799. decimal price = 0.00M;
  800. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  801. foreach (var pri in prices)
  802. {
  803. price += pri.Price;
  804. }
  805. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  806. airClientPrisIndex++;
  807. }
  808. if (!string.IsNullOrEmpty(peoplePriStr))
  809. {
  810. str = $@"其中:{peoplePriStr}";
  811. }
  812. //经济舱均价
  813. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  814. if (airJJCPris.Count > 0)
  815. {
  816. decimal jjcTotalPrice = 0.00M;
  817. foreach (var item in airJJCPris)
  818. {
  819. jjcTotalPrice += item.Price;
  820. }
  821. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  822. .Select(group => group.First())
  823. .ToList().Count;
  824. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  825. }
  826. //公务舱均价
  827. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  828. if (airGWCPris.Count > 0)
  829. {
  830. decimal gwcTotalPrice = 0.00M;
  831. foreach (var item in airGWCPris)
  832. {
  833. gwcTotalPrice += item.Price;
  834. }
  835. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  836. .Select(group => group.First())
  837. .ToList().Count;
  838. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  839. }
  840. }
  841. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  842. #endregion
  843. #region 签证费用 80 isAuditSql
  844. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  845. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  846. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  847. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  848. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  849. From Grp_VisaInfo vi
  850. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  851. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  852. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  853. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  854. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  855. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime",
  856. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  857. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  858. decimal VisaCNYTotalPirce = 0.00M;
  859. foreach (var item in groupVisaFeeViews)
  860. {
  861. string itemClientName = "";
  862. string visaClients = item.VisaClient;
  863. if (!string.IsNullOrEmpty(visaClients))
  864. {
  865. string[] clientIds = new string[] { };
  866. if (visaClients.Contains(','))
  867. {
  868. clientIds = visaClients.Split(',');
  869. }
  870. else
  871. {
  872. clientIds = new string[] { visaClients };
  873. }
  874. if (clientIds.Length > 0)
  875. {
  876. List<int> clientIds1 = new List<int>() { };
  877. foreach (var clientIdStr in clientIds)
  878. {
  879. if (clientIdStr.IsNumeric())
  880. {
  881. clientIds1.Add(int.Parse(clientIdStr));
  882. }
  883. }
  884. if (clientIds1.Count > 0)
  885. {
  886. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  887. foreach (var client in clients)
  888. {
  889. itemClientName += $"{client.LastName + client.FirstName},";
  890. }
  891. }
  892. else
  893. {
  894. itemClientName = visaClients;
  895. }
  896. }
  897. }
  898. if (itemClientName.Length > 0)
  899. {
  900. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  901. }
  902. item.VisaClient = itemClientName;
  903. VisaCNYTotalPirce += item.CNYPrice;
  904. if (!string.IsNullOrEmpty(item.AuditGMDate))
  905. {
  906. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  907. }
  908. }
  909. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  910. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#.00"));
  911. #endregion
  912. #region 邀请/公务活动 81 isAuditSql
  913. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  914. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  915. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  916. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  917. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
  918. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  919. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  920. From Grp_InvitationOfficialActivities ioa
  921. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  922. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  923. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  924. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  925. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  926. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  927. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  928. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  929. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  930. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime",
  931. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty );
  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 保险费用 82 isAuditSql
  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",
  1020. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  1021. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  1022. decimal InsuranceCNYTotalPrice = 0.00M;
  1023. foreach (var item in groupInsuranceFeeViews)
  1024. {
  1025. InsuranceCNYTotalPrice += item.CNYPrice;
  1026. string itemClientName = "";
  1027. string insClients = item.ClientName;
  1028. if (!string.IsNullOrEmpty(insClients))
  1029. {
  1030. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  1031. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  1032. //if (m_EnName.Success || m_ZHName.Success)
  1033. //{
  1034. // itemClientName = insClients;
  1035. // continue;
  1036. //}
  1037. string[] clientIds = new string[] { };
  1038. if (insClients.Contains(','))
  1039. {
  1040. clientIds = insClients.Split(',');
  1041. }
  1042. else
  1043. {
  1044. clientIds = new string[] { insClients };
  1045. }
  1046. if (clientIds.Length > 0)
  1047. {
  1048. List<int> output = new List<int>();
  1049. foreach (var clientId in clientIds)
  1050. {
  1051. if (clientId.IsNumeric())
  1052. {
  1053. output.Add(int.Parse(clientId));
  1054. }
  1055. }
  1056. if (output.Count > 0)
  1057. {
  1058. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1059. foreach (var client in clients)
  1060. {
  1061. itemClientName += $"{client.LastName + client.FirstName},";
  1062. }
  1063. if (itemClientName.Length > 0)
  1064. {
  1065. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1066. }
  1067. }
  1068. else
  1069. {
  1070. itemClientName = insClients;
  1071. }
  1072. }
  1073. }
  1074. item.ClientName = itemClientName;
  1075. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1076. {
  1077. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1078. }
  1079. }
  1080. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  1081. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  1082. #endregion
  1083. #region 其他款项费用 98 isAuditSql
  1084. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  1085. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1086. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  1087. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1088. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  1089. From Grp_DecreasePayments dp
  1090. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1091. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1092. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1093. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1094. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1095. Order By CreateTime", _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  1096. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  1097. #region 保险费用 - 模拟数据
  1098. //if (groupDecreaseFeeViews.Count < 1)
  1099. //{
  1100. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1101. // {
  1102. // DPId = 0,
  1103. // DPDiId = 2334,
  1104. // PriceName = "模拟数据-费用名称",
  1105. // PayMoney = 1000.00M,
  1106. // PayMoneyCurrency = "CNY",
  1107. // DayRate = 1.0000M,
  1108. // CNYPrice = 1.0000M,
  1109. // AuditGMDate = "2023-12-10 12:13:00",
  1110. // Payee = "模拟数据-付款方",
  1111. // OrbitalPrivateTransfer = 1,
  1112. // PayWay = "现金",
  1113. // IsPay = 1,
  1114. // Applicant = "刘华举"
  1115. // });
  1116. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1117. // {
  1118. // DPId = 0,
  1119. // DPDiId = 2334,
  1120. // PriceName = "模拟数据-费用名称",
  1121. // PayMoney = 1000.00M,
  1122. // PayMoneyCurrency = "CNY",
  1123. // DayRate = 1.0000M,
  1124. // CNYPrice = 1.0000M,
  1125. // AuditGMDate = "2023-12-10 12:13:00",
  1126. // Payee = "模拟数据-付款方",
  1127. // OrbitalPrivateTransfer = 1,
  1128. // PayWay = "现金",
  1129. // IsPay = 1,
  1130. // Applicant = "刘华举"
  1131. // });
  1132. //}
  1133. #endregion
  1134. decimal DecreaseCNYTotalPrice = 0.00M;
  1135. foreach (var item in groupDecreaseFeeViews)
  1136. {
  1137. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  1138. DecreaseCNYTotalPrice += item.CNYPrice;
  1139. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1140. {
  1141. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1142. }
  1143. }
  1144. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  1145. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  1146. #endregion
  1147. #region 公司内部操作人员提成(提成表) isAudit
  1148. var royaltyDatas = await _sqlSugar
  1149. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  1150. new JoinQueryInfos(
  1151. JoinType.Left, rc.UserId == u1.Id,
  1152. JoinType.Left, rc.CreateUserId == u2.Id
  1153. ))
  1154. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId)
  1155. .WhereIF(isAudit, (rc, u1, u2) => rc.IsConfirm == 1)
  1156. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  1157. {
  1158. GroupId = rc.TeamId,
  1159. OverviewInfo = rc.Temp,
  1160. DetailedInfo = rc.ChiArr,
  1161. Amount = rc.Price,
  1162. IsConfirm = rc.IsConfirm,
  1163. IsSeed = rc.IsSeed,
  1164. RoyaltyUserName = u1.CnName,
  1165. CreateUserName = u2.CnName,
  1166. CreateTime = rc.CreateTime
  1167. })
  1168. .ToListAsync();
  1169. decimal royaltyCNYTotalPrice = royaltyDatas.Sum(x => x.Amount);
  1170. _geView.GroupRoyaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeView>>(royaltyDatas);
  1171. _geView.GroupRoyaltyFeeStr = string.Format(@"人民币总费用:{0} CNY", royaltyCNYTotalPrice.ToString("#0.00"));
  1172. #endregion
  1173. #region 公司内部人员报销(日付表) isAuditStatus
  1174. var reimburseDatas = await _sqlSugar
  1175. .Queryable<Fin_DailyFeePayment, Sys_Users, Sys_SetData, Sys_Company>((dfp, u, sd1, c) =>
  1176. new JoinQueryInfos(
  1177. JoinType.Left, dfp.CreateUserId == u.Id,
  1178. JoinType.Left, dfp.TransferTypeId == sd1.Id,
  1179. JoinType.Left, dfp.CompanyId == c.Id
  1180. ))
  1181. .Where((dfp, u, sd1, c) => dfp.IsDel == 0 && dfp.PriceTypeId == 1353 && dfp.GroupId == _dto.DiId)
  1182. .WhereIF(isAudit, (dfp, u, sd1, c) => isAuditStatus.Contains(dfp.FAudit) && isAuditStatus.Contains(dfp.MAudit))
  1183. .Select((dfp, u, sd1, c) => new GroupReimburseFeeInfoView()
  1184. {
  1185. TotalAmt = dfp.SumPrice,
  1186. //FeeItems = SqlFunc.Subqueryable<Fin_DailyFeePaymentContent>()
  1187. // .Where(x => x.DFPId == dfp.Id && x.IsDel == 0)
  1188. // .Select(x => new GroupReimburseFeeSubInfo()
  1189. // {
  1190. // PriceName = x.PriceName,
  1191. // Quantity = x.Quantity,
  1192. // Price = x.Price,
  1193. // SubTotal = x.ItemTotal,
  1194. // Remark = x.Remark
  1195. // })
  1196. // .ToList(),
  1197. AppReason = dfp.Instructions,
  1198. TransferLabel = sd1.Name,
  1199. ApplyComp = c.CompanyName,
  1200. FAudit = dfp.FAudit,
  1201. MAudit = dfp.MAudit,
  1202. PayStatusFlag = dfp.IsPay == 0 ? "未付款" : "已付款",
  1203. ApplyName = u.CnName,
  1204. ApplyTime = dfp.CreateTime
  1205. })
  1206. .ToListAsync();
  1207. var reimburseTotalPrice = reimburseDatas.Sum(x => x.TotalAmt);
  1208. _geView.GroupReimburseFeeViews = reimburseDatas;
  1209. _geView.GroupReimburseFeeStr = string.Format(@"人民币总费用:{0} CNY", reimburseTotalPrice.ToString("#0.00"));
  1210. #endregion
  1211. _view.GroupExpenditure = _geView;
  1212. #endregion
  1213. /*
  1214. * 团组报表计算方式
  1215. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1216. * 应收金额 = 应收表.Sum()
  1217. * 已收金额 = 已收表.Sum()
  1218. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1219. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1220. *
  1221. */
  1222. decimal _totalExpenditure = 0.00M; //总支出
  1223. decimal _amountReceivable = 0.00M; //应收金额
  1224. decimal _amountReceived = 0.00M; //已收金额
  1225. decimal _receivableProfit = 0.00M; //应收利润
  1226. decimal _receivedProfit = 0.00M; //已收利润
  1227. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  1228. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount + royaltyCNYTotalPrice + reimburseTotalPrice;
  1229. _amountReceivable = frTotalAmount;
  1230. _amountReceived = prTotalAmount;
  1231. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  1232. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  1233. _view.FeeTotalStr = string.Format(@$"<span>
  1234. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  1235. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  1236. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  1237. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  1238. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  1239. </span>");
  1240. return Ok(JsonView(true, "查询成功!", _view));
  1241. }
  1242. else
  1243. {
  1244. return Ok(JsonView(false, "查询成功"));
  1245. }
  1246. }
  1247. /// <summary>
  1248. /// 团组报表
  1249. /// Excel 下载
  1250. /// </summary>
  1251. /// <param name="_dto">团组列表请求dto</param>
  1252. /// <returns></returns>
  1253. [HttpPost("PostGroupStatementExportExcel")]
  1254. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1255. public async Task<IActionResult> PostGroupStatementExportExcel(GroupStatementDetailsDto _dto)
  1256. {
  1257. //pageId 38
  1258. int currUserId = _dto.UserId, pageId = _dto.PageId, diId = _dto.DiId;
  1259. bool isAudit = _dto.isAudit;
  1260. #region 参数验证
  1261. if (currUserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1262. if (pageId < 1) return Ok(JsonView(false, "页面Id为空"));
  1263. if (diId < 1) return Ok(JsonView(false, "数据Id为空"));
  1264. #region 页面操作权限验证
  1265. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(currUserId, pageId);
  1266. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
  1267. #endregion
  1268. #endregion
  1269. var groupInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.IsDel == 0 && x.Id == diId).First();
  1270. if (groupInfo == null) return Ok(JsonView(false, "暂无该条团组信息!"));
  1271. var userInfo = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.Id == currUserId).First();
  1272. string groupNo = groupInfo.TourCode,
  1273. groupName = groupInfo.TeamName.Replace("|", "、"),
  1274. lister = userInfo?.CnName ?? "-";
  1275. var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
  1276. .Where(it => it.IsDel == 0)
  1277. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  1278. .ToList();
  1279. //获取模板
  1280. string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/团组费用统计模板.xls");
  1281. var designer = new WorkbookDesigner();
  1282. designer.Workbook = new Workbook(tempPath);
  1283. // 获取工作簿中的工作表集合
  1284. var worksheets = designer.Workbook.Worksheets;
  1285. #region 获取sheet,定义datatable,局部变量
  1286. //酒店费用相关
  1287. var hotelFeeSheet = worksheets["酒店费用"];
  1288. var hotelFeeDt = new DataTable($"HotelFeeView");
  1289. decimal hotelCNYTotalCost = 0.00M;
  1290. //地接费用相关
  1291. var OPFeeSheet = worksheets["地接费用"];
  1292. var OPFeeDt = new DataTable($"OPFeeView");
  1293. var OPFeeLabel = string.Empty;
  1294. decimal OPCNYTotalCost = 0.00M;
  1295. //签证费用相关
  1296. var visaFeeSheet = worksheets["签证费用"];
  1297. var visaFeeDt = new DataTable($"VisaFeeView");
  1298. decimal visaCNYTotalCost = 0.00M;
  1299. //邀请费用相关
  1300. var OAFeeSheet = worksheets["邀请费用"];
  1301. var OAFeeDt = new DataTable($"OAFeeView");
  1302. decimal OACNYTotalCost = 0.00M;
  1303. //机票费用相关
  1304. var airTicketFeeSheet = worksheets["机票费用"];
  1305. var airTicketFeeDt = new DataTable($"AirTicketFeeView");
  1306. decimal airTicketCNYTotalCost = 0.00M;
  1307. //保险费用相关
  1308. var insureFeeSheet = worksheets["保险费用"];
  1309. var insureFeeDt = new DataTable($"InsureFeeView");
  1310. decimal insureCNYTotalCost = 0.00M;
  1311. //其他费用相关
  1312. var otherFeeSheet = worksheets["其他费用"];
  1313. var otherFeeDt = new DataTable($"OtherFeeView");
  1314. decimal otherCNYTotalCost = 0.00M;
  1315. //收款退还相关
  1316. var SKTHFeeSheet = worksheets["收款退还"];
  1317. var SKTHFeeDt = new DataTable($"SKTHFeeView");
  1318. decimal SKTHCNYTotalCost = 0.00M;
  1319. //操作提成
  1320. var royaltyFeeSheet = worksheets["操作提成"];
  1321. var royaltyFeeDt = new DataTable($"royaltyFeeView");
  1322. decimal royaltyCNYTotalCost = 0.00M;
  1323. var totalAmount = 0.00M; //支出成本合计
  1324. var accountsAmount = 0.00M; //应收金额合计
  1325. var receivedAmount = 0.00M; //已收金额合计
  1326. var accountsProfit = 0.00M; //应收利润合计
  1327. var receiveProfit = 0.00M; //已收利润合计
  1328. var profitMargin = 0.00M; //利润差合计
  1329. //应收合计相关
  1330. var receivableFeeSheet = worksheets["团组收入(未收)"];
  1331. var receivableFeeDt = new DataTable($"ReceivableFeeView");
  1332. //已收合计相关
  1333. var receivedFeeSheet = worksheets["团组收入(已收)"];
  1334. var receivedFeeDt = new DataTable($"ReceivedFeeView");
  1335. //团组收入支出利润
  1336. var groupIEProfitDt = new DataTable($"IEProfitFeeView");
  1337. #endregion
  1338. #region 酒店费用
  1339. if (hotelFeeSheet != null)
  1340. {
  1341. string hotelFeeSql = string.Format(@"
  1342. SELECT
  1343. hr.Id AS HrId,
  1344. hr.DiId AS HrDiId,
  1345. hr.City,
  1346. hr.HotelName,
  1347. hr.CheckInDate,
  1348. hr.CheckOutDate,
  1349. hr.CardPrice AS RoomPrice,
  1350. sd1.Name AS PaymentCurrency,
  1351. hr.SingleRoomPrice,
  1352. hr.SingleRoomCount,
  1353. hr.DoubleRoomPrice,
  1354. hr.DoubleRoomCount,
  1355. hr.SuiteRoomPrice,
  1356. hr.SuiteRoomCount,
  1357. hr.OtherRoomPrice,
  1358. hr.OtherRoomCount,
  1359. hr.BreakfastPrice,
  1360. sd4.Name AS BreakfastCurrency,
  1361. hr.Isoppay,
  1362. hr.GovernmentRent,
  1363. sd5.Name AS GovernmentRentCurrency,
  1364. hr.CityTax,
  1365. sd6.Name AS CityTaxCurrency,
  1366. ccp.PayMoney,
  1367. (
  1368. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  1369. ) AS CNYPrice,
  1370. ccp.PayPercentage,
  1371. ccp.DayRate,
  1372. ccp.Payee,
  1373. ccp.OrbitalPrivateTransfer,
  1374. sd2.Name AS PayWay,
  1375. sd3.Name AS CardType,
  1376. ccp.IsPay,
  1377. u.CnName AS Applicant,
  1378. hr.Remark
  1379. FROM
  1380. Grp_HotelReservations hr
  1381. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  1382. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  1383. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  1384. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  1385. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  1386. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  1387. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  1388. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  1389. WHERE
  1390. hr.IsDel = 0
  1391. AND ccp.IsDel = 0
  1392. AND ccp.CTable = 76 {1}
  1393. AND ccp.PayMoney <> 0
  1394. AND hr.DiId = {0}
  1395. ORDER BY
  1396. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1397. var groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  1398. if (groupHotelFeeViews.Any())
  1399. {
  1400. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1401. var hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  1402. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  1403. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  1404. foreach (var item in groupHotelFeeViews)
  1405. {
  1406. if (groupHotelContentFeeViews.Count > 0)
  1407. {
  1408. string paymentStr = string.Empty;
  1409. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  1410. item.RoomPrice = roomData?.Price ?? 0.00M;
  1411. if (item.RoomPrice != 0)
  1412. {
  1413. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  1414. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  1415. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1416. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  1417. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  1418. 收款方:{roomData?.Payee}<br/>
  1419. 费用标识:{feeMark1} <br/>
  1420. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1421. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  1422. 是否由地接支付:{isFeeMark1} <br/>";
  1423. }
  1424. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  1425. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  1426. if (item.BreakfastPrice != 0)
  1427. {
  1428. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  1429. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  1430. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1431. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  1432. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  1433. 收款方:{breakfastData?.Payee}<br/>
  1434. 费用标识:{feeMark2} <br/>
  1435. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1436. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  1437. 是否由地接支付:{isFeeMark2} <br/>";
  1438. }
  1439. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  1440. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  1441. if (item.GovernmentRent != 0)
  1442. {
  1443. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  1444. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  1445. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1446. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1447. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  1448. 收款方:{landTaxData?.Payee}<br/>
  1449. 费用标识:{feeMark3} <br/>
  1450. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  1451. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  1452. 是否由地接支付:{isFeeMark3} <br/>";
  1453. }
  1454. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  1455. item.CityTax = cityTaxData?.Price ?? 0.00M;
  1456. if (item.CityTax != 0)
  1457. {
  1458. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  1459. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  1460. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1461. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1462. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  1463. 收款方:{cityTaxData?.Payee}<br/>
  1464. 费用标识:{feeMark4} <br/>
  1465. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  1466. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  1467. 是否由地接支付:{isFeeMark4} <br/>";
  1468. }
  1469. if (!string.IsNullOrEmpty(paymentStr))
  1470. {
  1471. item.IsPay = 2;
  1472. item.PayTips = paymentStr;
  1473. }
  1474. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  1475. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  1476. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  1477. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  1478. }
  1479. else
  1480. {
  1481. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  1482. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  1483. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  1484. (item.OtherRoomCount * item.OtherRoomPrice);
  1485. //item.RoomPrice = item.CardPrice;
  1486. item.RoomPriceCurrency = item.PaymentCurrency;
  1487. }
  1488. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  1489. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  1490. }
  1491. }
  1492. hotelCNYTotalCost = groupHotelFeeViews.Sum(x => x.CNYPrice);
  1493. hotelFeeDt = CommonFun.ToDataTableArray(groupHotelFeeViews);
  1494. hotelFeeDt.TableName = $"HotelFeeView";
  1495. }
  1496. #endregion
  1497. #region 地接费用
  1498. if (OPFeeSheet != null)
  1499. {
  1500. string CTGGRFeeSql = string.Empty;
  1501. if (groupInfo.VisitDate > Convert.ToDateTime("2024-04-17"))
  1502. {
  1503. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  1504. sd2.name As PaymentCurrency,ccp.PayPercentage,
  1505. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  1506. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  1507. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  1508. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1509. From Grp_CarTouristGuideGroundReservations ctggr
  1510. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  1511. cggrc.DatePrice,cggrc.PriceContent
  1512. From Grp_CarTouristGuideGroundReservationsContent cggrc
  1513. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  1514. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  1515. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  1516. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  1517. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1518. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1519. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1520. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1521. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1522. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1523. }
  1524. else
  1525. {
  1526. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  1527. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  1528. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  1529. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  1530. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  1531. ccp.Payee,ccp.AuditGMDate,
  1532. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1533. From Grp_CarTouristGuideGroundReservations ctggr
  1534. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1535. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1536. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1537. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1538. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1539. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1540. }
  1541. var groupOPFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  1542. string CTGGRFeeStr = "";
  1543. var OPToDataTableViews = groupOPFeeViews;
  1544. decimal CTGGRCNYTotalPrice = 0.00M;
  1545. //按1 地区,2 币种,3 汇率 分组计算
  1546. var groupCTGGRFeeDatas = groupOPFeeViews.GroupBy(it => it.Area);
  1547. foreach (var ctggfr in groupCTGGRFeeDatas)
  1548. {
  1549. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  1550. if (ctggfr_curr.Count() > 0)
  1551. {
  1552. foreach (var curr in ctggfr_curr)
  1553. {
  1554. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  1555. if (ctggfr_rate.Count() > 0)
  1556. {
  1557. foreach (var rate in ctggfr_rate)
  1558. {
  1559. 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");
  1560. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1561. }
  1562. }
  1563. else
  1564. {
  1565. 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");
  1566. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1567. }
  1568. }
  1569. }
  1570. else
  1571. {
  1572. 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");
  1573. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1574. }
  1575. }
  1576. foreach (var item in groupOPFeeViews)
  1577. {
  1578. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1579. {
  1580. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1581. }
  1582. if (item.DatePrice != DateTime.MinValue)
  1583. {
  1584. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  1585. }
  1586. }
  1587. OPCNYTotalCost = CTGGRCNYTotalPrice;
  1588. OPFeeDt = CommonFun.ToDataTableArray(OPToDataTableViews);
  1589. OPFeeLabel = CTGGRFeeStr;
  1590. OPFeeDt.TableName = $"OPFeeView";
  1591. }
  1592. #endregion
  1593. #region 签证费用
  1594. if (visaFeeSheet != null)
  1595. {
  1596. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1597. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,sd2.Name As PaymentModes,sd3.Name As CardTypeName,u.CnName As Applicant,vi.CreateTime,
  1598. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1599. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1600. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,vi.Remark
  1601. From Grp_VisaInfo vi
  1602. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  1603. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1604. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1605. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1606. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1607. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1608. var groupVisaFeeViews = _sqlSugar.SqlQueryable<GroupVisaFeeExcelView>(groupVisaFeeSql).ToList();
  1609. foreach (var item in groupVisaFeeViews)
  1610. {
  1611. string names = string.Empty;
  1612. string visaClients = item.VisaClient;
  1613. if (!string.IsNullOrEmpty(visaClients))
  1614. {
  1615. var clientIds = new string[] { };
  1616. if (visaClients.Contains(',')) clientIds = visaClients.Split(',');
  1617. else clientIds = new string[] { visaClients };
  1618. if (clientIds.Length > 0)
  1619. {
  1620. var clientIds1 = new List<int>() { };
  1621. foreach (var clientIdStr in clientIds)
  1622. {
  1623. var isInt = int.TryParse(clientIdStr, out int id);
  1624. if (isInt) clientIds1.Add(id);
  1625. }
  1626. if (clientIds1.Count > 0)
  1627. {
  1628. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  1629. foreach (var client in clients)
  1630. {
  1631. EncryptionProcessor.DecryptProperties(client);
  1632. names += $"{client.LastName + client.FirstName},";
  1633. }
  1634. }
  1635. else names = visaClients;
  1636. }
  1637. if (names.Length > 0) names = names.Substring(0, names.Length - 1);
  1638. item.VisaClient = names;
  1639. }
  1640. }
  1641. visaCNYTotalCost = groupVisaFeeViews.Sum(x => x.CNYPrice);
  1642. visaFeeDt = CommonFun.ToDataTableArray(groupVisaFeeViews);
  1643. visaFeeDt.TableName = $"VisaFeeView";
  1644. }
  1645. #endregion
  1646. #region 邀请费用
  1647. if (OAFeeSheet != null)
  1648. {
  1649. string feeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,CONVERT(DATE, ioa.InviteTime) AS InviteTime,
  1650. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  1651. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  1652. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.ConsumptionDate,
  1653. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1654. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1655. ccp.Payee,ioa.Remark,ccp.AuditGMDate,u.CnName As Applicant,ioa.CreateTime
  1656. From Grp_InvitationOfficialActivities ioa
  1657. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  1658. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1659. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1660. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  1661. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  1662. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  1663. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  1664. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  1665. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1666. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1667. var feeViews = _sqlSugar.SqlQueryable<GroupOAFeeExcelView>(feeSql).ToList();
  1668. OACNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1669. OAFeeDt = CommonFun.ToDataTableArray(feeViews);
  1670. OAFeeDt.TableName = $"OAFeeView";
  1671. }
  1672. #endregion
  1673. #region 机票费用
  1674. if (airTicketFeeSheet != null)
  1675. {
  1676. string feeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,
  1677. sd4.Name As AirTypeName,atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,
  1678. atr.PriceDescription,ccp.PayMoney,ccp.DayRate,sd1.Name As PayMoneyCurrency,
  1679. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1680. ccp.Payee,Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1681. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1682. sd3.Name As CardType,ccp.AuditGMDate,u.CnName As Applicant,atr.CreateTime,atr.Remark
  1683. From Grp_AirTicketReservations atr
  1684. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  1685. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1686. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1687. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1688. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  1689. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1690. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1691. var feeViews = _sqlSugar.SqlQueryable<GroupAirTicketExcelView>(feeSql).ToList();
  1692. airTicketCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1693. airTicketFeeDt = CommonFun.ToDataTableArray(feeViews);
  1694. airTicketFeeDt.TableName = $"AirTicketFeeView";
  1695. }
  1696. #endregion
  1697. #region 保险费用
  1698. if (insureFeeSheet != null)
  1699. {
  1700. string feeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,
  1701. sd1.Name As PayMoneyCurrency,ccp.DayRate,ccp.PayMoney * ccp.DayRate As CNYPrice,ccp.ConsumptionDate,
  1702. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1703. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1704. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,ic.CreateTime,ic.Remark
  1705. From Grp_Customers ic
  1706. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1707. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1708. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1709. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1710. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1711. var feeViews = _sqlSugar.SqlQueryable<GroupInsureExcelView>(feeSql).ToList();
  1712. foreach (var item in feeViews)
  1713. {
  1714. string itemClientName = "";
  1715. string insClients = item.ClientName;
  1716. if (!string.IsNullOrEmpty(insClients))
  1717. {
  1718. string[] clientIds = new string[] { };
  1719. if (insClients.Contains(',')) clientIds = insClients.Split(',');
  1720. else clientIds = new string[] { insClients };
  1721. if (clientIds.Length > 0)
  1722. {
  1723. List<int> output = new List<int>();
  1724. foreach (var clientId in clientIds)
  1725. if (int.TryParse(clientId, out int id))
  1726. output.Add(id);
  1727. if (output.Count > 0)
  1728. {
  1729. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1730. foreach (var client in clients)
  1731. {
  1732. EncryptionProcessor.DecryptProperties(client);
  1733. itemClientName += $"{client.LastName + client.FirstName},";
  1734. }
  1735. if (itemClientName.Length > 0)
  1736. {
  1737. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1738. }
  1739. }
  1740. else itemClientName = insClients;
  1741. }
  1742. }
  1743. item.ClientName = itemClientName;
  1744. }
  1745. insureCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1746. insureFeeDt = CommonFun.ToDataTableArray(feeViews);
  1747. insureFeeDt.TableName = $"InsureFeeView";
  1748. }
  1749. #endregion
  1750. #region 其他费用
  1751. if (insureFeeSheet != null)
  1752. {
  1753. string feeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1754. ccp.DayRate,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1755. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1756. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1757. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,dp.CreateTime,dp.Remark
  1758. From Grp_DecreasePayments dp
  1759. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1760. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1761. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1762. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1763. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1764. Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1765. var feeViews = _sqlSugar.SqlQueryable<GroupOtherFeeExcelView>(feeSql).ToList();
  1766. otherCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1767. otherFeeDt = CommonFun.ToDataTableArray(feeViews);
  1768. otherFeeDt.TableName = $"OtherFeeView";
  1769. }
  1770. #endregion
  1771. #region 收款退还
  1772. if (SKTHFeeSheet != null)
  1773. {
  1774. //删除了 And prom.PriceType = 1
  1775. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  1776. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  1777. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  1778. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime,prom.Remark AS SKTHRemark
  1779. From Fin_PaymentRefundAndOtherMoney prom
  1780. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  1781. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1782. Where prom.IsDel = 0
  1783. And prom.PayType = 1
  1784. And ccp.CTable = 285
  1785. {1}
  1786. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1787. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  1788. if (_promDatas.Any())
  1789. {
  1790. var _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  1791. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1792. foreach (var ropItem in _promDatas)
  1793. {
  1794. string thisCueencyCode = "Unknown";
  1795. string thisCueencyName = "Unknown";
  1796. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  1797. if (currency != null)
  1798. {
  1799. thisCueencyCode = currency.Name;
  1800. thisCueencyName = currency.Remark;
  1801. }
  1802. string orbitalPrivateTransferStr = "Unknown";
  1803. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  1804. if (orbitalPrivateTransfer != null)
  1805. {
  1806. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  1807. }
  1808. string payStr = "Unknown";
  1809. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  1810. if (pay != null)
  1811. {
  1812. payStr = pay.Name;
  1813. }
  1814. var gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  1815. {
  1816. Id = ropItem.Id,
  1817. DiId = ropItem.DIId,
  1818. PriceName = ropItem.PrPriceName,
  1819. PayCurrencyCode = thisCueencyCode,
  1820. PayCurrencyName = thisCueencyName,
  1821. Price = ropItem.PrPrice,
  1822. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  1823. ThisRate = ropItem.DayRate,
  1824. Payee = ropItem.Payee,
  1825. PayTime = ropItem.AuditGMDate,
  1826. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  1827. PayType = payStr,
  1828. IsPay = ropItem.IsPay,
  1829. Applicant = ropItem.Appliction,
  1830. Remark = ropItem.SKTHRemark
  1831. };
  1832. _promView.Add(gsd_PaymentRefund);
  1833. }
  1834. SKTHCNYTotalCost = _promView.Sum(x => x.CNYPrice);
  1835. SKTHFeeDt = CommonFun.ToDataTableArray(_promView);
  1836. SKTHFeeDt.TableName = $"SKTHFeeView";
  1837. }
  1838. }
  1839. #endregion
  1840. #region 操作提成
  1841. if (SKTHFeeSheet != null)
  1842. {
  1843. var _royaltyDatas = await _sqlSugar
  1844. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  1845. new JoinQueryInfos(
  1846. JoinType.Left, rc.UserId == u1.Id,
  1847. JoinType.Left, rc.CreateUserId == u2.Id
  1848. ))
  1849. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
  1850. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  1851. {
  1852. GroupId = rc.TeamId,
  1853. OverviewInfo = rc.Temp,
  1854. DetailedInfo = rc.ChiArr,
  1855. Amount = rc.Price,
  1856. IsConfirm = rc.IsConfirm,
  1857. IsSeed = rc.IsSeed,
  1858. RoyaltyUserName = u1.CnName,
  1859. CreateUserName = u2.CnName,
  1860. CreateTime = rc.CreateTime
  1861. })
  1862. .ToListAsync();
  1863. if (_royaltyDatas.Any())
  1864. {
  1865. decimal royaltyCNYTotalPrice = _royaltyDatas.Sum(x => x.Amount);
  1866. var _royaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeExcelView>>(_royaltyDatas);
  1867. royaltyCNYTotalCost = _royaltyFeeViews.Sum(x => x.Amount);
  1868. royaltyFeeDt = CommonFun.ToDataTableArray(_royaltyFeeViews);
  1869. royaltyFeeDt.TableName = $"RoyaltyFeeView";
  1870. }
  1871. }
  1872. #endregion
  1873. #region 应收金额(增加方式=实际报价时 费用必须审核才能进入团组报表)
  1874. //decimal frTotalAmount = 0.00M;//应收总金额
  1875. 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,
  1876. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime,fr.Remark
  1877. From Fin_ForeignReceivables fr
  1878. Left Join Sys_SetData sd On fr.Currency = sd.Id
  1879. Left Join Sys_Users u On fr.Auditor = u.Id
  1880. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  1881. var _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  1882. _frViews.ForEach(x =>
  1883. {
  1884. string namePrefix = string.Empty;
  1885. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  1886. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  1887. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  1888. x.PriceName = $"{namePrefix}{x.PriceName}";
  1889. });
  1890. if (_frViews.Any())
  1891. {
  1892. accountsAmount = _frViews.Sum(it => it.ItemSumPrice);
  1893. receivableFeeDt = CommonFun.ToDataTableArray(_frViews);
  1894. receivableFeeDt.TableName = $"ReceivedFeeView";
  1895. }
  1896. #endregion
  1897. #region 已收金额
  1898. //decimal prTotalAmount = 0.00M;//已收总金额
  1899. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  1900. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  1901. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  1902. From Fin_ProceedsReceived pr
  1903. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  1904. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  1905. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  1906. var _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  1907. if (_prViews.Any())
  1908. {
  1909. receivedAmount = _prViews.Sum(it => it.Price);
  1910. receivedFeeDt = CommonFun.ToDataTableArray(_prViews);
  1911. receivedFeeDt.TableName = $"ReceivableFeeView";
  1912. }
  1913. #endregion
  1914. #region 团组收入支出利润
  1915. groupIEProfitDt.Columns.AddRange(new DataColumn[] {
  1916. new DataColumn(){ ColumnName = "ModuleName"},
  1917. new DataColumn(){ ColumnName = "FeeTotal",DataType = typeof(decimal)},
  1918. new DataColumn(){ ColumnName = "FeeCurrency"},
  1919. });
  1920. var groupIEProfitDt_rows = new[] {
  1921. new object[] { $"签证费用", visaCNYTotalCost, $"CNY" },
  1922. new object[] { $"酒店费用", hotelCNYTotalCost, $"CNY" },
  1923. new object[] { $"地接费用", OPCNYTotalCost, $"CNY" },
  1924. new object[] { $"商邀费用", OACNYTotalCost, $"CNY" },
  1925. new object[] { $"机票费用", airTicketCNYTotalCost, $"CNY" },
  1926. new object[] { $"保险费用", insureCNYTotalCost, $"CNY" },
  1927. new object[] { $"其他费用", otherCNYTotalCost, $"CNY" },
  1928. new object[] { $"收款退还费用", SKTHCNYTotalCost, $"CNY" },
  1929. new object[] { $"操作提成费用", royaltyCNYTotalCost, $"CNY" },
  1930. };
  1931. // 批量添加
  1932. foreach (var rowData in groupIEProfitDt_rows)
  1933. {
  1934. groupIEProfitDt.Rows.Add(rowData);
  1935. }
  1936. #endregion
  1937. #region 统一填充数据源
  1938. designer.SetDataSource("GroupNo", groupNo);
  1939. designer.SetDataSource("GroupName", groupName);
  1940. designer.SetDataSource("Lister", lister);
  1941. //酒店
  1942. designer.SetDataSource(hotelFeeDt);
  1943. designer.SetDataSource("HotelCNYTotalCost", $"{hotelCNYTotalCost.ToString("#0.00")} CNY");
  1944. //地接
  1945. designer.SetDataSource(OPFeeDt);
  1946. designer.SetDataSource("OPFeeLabel", OPFeeLabel);
  1947. designer.SetDataSource("OPCNYTotalCost", $"{OPCNYTotalCost.ToString("#0.00")} CNY");
  1948. //签证
  1949. designer.SetDataSource(visaFeeDt);
  1950. designer.SetDataSource("VisaCNYTotalCost", $"{visaCNYTotalCost.ToString("#0.00")} CNY");
  1951. //商邀
  1952. designer.SetDataSource(OAFeeDt);
  1953. designer.SetDataSource("OACNYTotalCost", $"{OACNYTotalCost.ToString("#0.00")} CNY");
  1954. //机票
  1955. designer.SetDataSource(airTicketFeeDt);
  1956. designer.SetDataSource("AirTicketCNYTotalCost", $"{airTicketCNYTotalCost.ToString("#0.00")} CNY");
  1957. //保险
  1958. designer.SetDataSource(insureFeeDt);
  1959. designer.SetDataSource("InsureCNYTotalCost", $"{insureCNYTotalCost.ToString("#0.00")} CNY");
  1960. //其他费用
  1961. designer.SetDataSource(otherFeeDt);
  1962. designer.SetDataSource("OtherCNYTotalCost", $"{otherCNYTotalCost.ToString("#0.00")} CNY");
  1963. //收款退还
  1964. designer.SetDataSource(SKTHFeeDt);
  1965. designer.SetDataSource("SKTHCNYTotalCost", $"{SKTHCNYTotalCost.ToString("#0.00")}");
  1966. //操作提成
  1967. designer.SetDataSource(royaltyFeeDt);
  1968. designer.SetDataSource("RoyaltyCNYTotalCost", $"{royaltyCNYTotalCost.ToString("#0.00")} CNY");
  1969. //已收金额
  1970. designer.SetDataSource(receivedFeeDt);
  1971. designer.SetDataSource("ReceivedAmount", $"{receivedAmount.ToString("#0.00")}");
  1972. //应收金额
  1973. designer.SetDataSource(receivableFeeDt);
  1974. designer.SetDataSource("AccountsAmount", $"{accountsAmount.ToString("#0.00")}");
  1975. //应收已收 -- 尾款
  1976. var balancePayment = accountsAmount - SKTHCNYTotalCost - receivedAmount;
  1977. designer.SetDataSource("BalancePayment", $"{balancePayment.ToString("#0.00")}");
  1978. //团组收入支出利润
  1979. designer.SetDataSource(groupIEProfitDt);
  1980. #region 各项费用计算
  1981. /*
  1982. * 团组报表计算方式
  1983. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1984. * 应收金额 = 应收表.Sum() - 收款退还
  1985. * 已收金额 = 已收表.Sum() - 收款退还
  1986. * 应收利润(应收-支出) = 应收金额 - 当前总支出
  1987. * 已收利润(已收-支出) = 已收金额 - 当前总支出
  1988. * 利润差 = 应收利润 - 已收利润
  1989. */
  1990. totalAmount = visaCNYTotalCost + hotelCNYTotalCost + OPCNYTotalCost + OACNYTotalCost + airTicketCNYTotalCost + insureCNYTotalCost + otherCNYTotalCost + royaltyCNYTotalCost;//合计金额
  1991. accountsProfit = accountsAmount - totalAmount - SKTHCNYTotalCost; //应收利润
  1992. receiveProfit = receivedAmount - totalAmount - SKTHCNYTotalCost; //已收利润
  1993. profitMargin = accountsProfit - receiveProfit; //利润差
  1994. designer.SetDataSource("TotalAmount", $"{totalAmount.ToString("#0.00")}");
  1995. designer.SetDataSource("AccountsProfit", $"{accountsProfit.ToString("#0.00")}");
  1996. designer.SetDataSource("ReceiveProfit", $"{receiveProfit.ToString("#0.00")}");
  1997. designer.SetDataSource("ProfitMargin", $"{profitMargin.ToString("#0.00")}");
  1998. #endregion
  1999. designer.Process();
  2000. #endregion
  2001. #region 单元格样式设置 未付款设置为红色
  2002. /*
  2003. * 设置单元格样式
  2004. */
  2005. //背景颜色
  2006. Style style = designer.Workbook.CreateStyle();
  2007. style.ForegroundColor = Color.FromArgb(254, 242, 203);
  2008. style.Pattern = BackgroundType.Solid;
  2009. //字体
  2010. style.Font.Name = "微软雅黑"; // 字体名称
  2011. style.Font.Size = 10; // 字体大小
  2012. style.Font.Color = System.Drawing.Color.Black; // 字体颜色
  2013. StatementExportExcelSetCell(designer, hotelFeeSheet, hotelFeeDt, style, "IsPayLable", 8, "A", "V"); //酒店
  2014. StatementExportExcelSetCell(designer, OPFeeSheet, OPFeeDt, style, "IsPayLabel", 6, "A", "M"); //OP
  2015. StatementExportExcelSetCell(designer, visaFeeSheet, visaFeeDt, style, "IsPay", 6, "A", "I"); //签证
  2016. StatementExportExcelSetCell(designer, OAFeeSheet, OAFeeDt, style, "IsPay", 6, "A", "R"); //商邀
  2017. StatementExportExcelSetCell(designer, airTicketFeeSheet, airTicketFeeDt, style, "IsPay", 6, "A", "M"); //机票
  2018. StatementExportExcelSetCell(designer, insureFeeSheet, insureFeeDt, style, "IsPay", 6, "A", "I"); //保险
  2019. StatementExportExcelSetCell(designer, otherFeeSheet, otherFeeDt, style, "IsPay", 6, "A", "J"); //其他
  2020. StatementExportExcelSetCell(designer, SKTHFeeSheet, SKTHFeeDt, style, "IsPayLable", 6, "A", "K"); //首款退还
  2021. #endregion
  2022. //文件名
  2023. string fileName = $"{groupName}[{groupNo}]_团组费用清单{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  2024. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "GroupStatement/" + fileName);
  2025. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/GroupStatement/" + fileName;
  2026. return Ok(JsonView(true, "成功", url));
  2027. }
  2028. /// <summary>
  2029. /// 团组报表
  2030. /// 利润相关数据
  2031. /// </summary>
  2032. /// <returns></returns>
  2033. [HttpPost("PostGroupStatementDetails1")]
  2034. //[JsonConverter(typeof(DecimalConverter), 2)]
  2035. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2036. public async Task<IActionResult> PostGroupStatementDetails1()
  2037. {
  2038. var groupInfos = _sqlSugar.Queryable<Grp_DelegationInfo>()
  2039. .Where(x => x.IsDel == 0 && x.VisitDate >= DateTime.Parse("2024-01-01") && x.VisitDate <= DateTime.Parse("2024-12-31"))
  2040. .OrderByDescending(x => x.VisitDate)
  2041. .ToList();
  2042. #region 费用类型 币种,转账,客户信息
  2043. List<Sys_SetData> _setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  2044. var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
  2045. .Where(it => it.IsDel == 0)
  2046. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  2047. .ToList();
  2048. // foreach (var item1 in _clientDatas) EncryptionProcessor.DecryptProperties(item1);
  2049. #endregion
  2050. var _views = new List<GroupStatisticsInfo>();
  2051. int index1 = 0;
  2052. foreach (var info in groupInfos)
  2053. {
  2054. var _dto = new { DiId = info.Id, isAudit = false };
  2055. /*
  2056. * 团组报表计算方式
  2057. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  2058. * 应收金额 = 应收表.Sum()
  2059. * 已收金额 = 已收表.Sum()
  2060. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  2061. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  2062. *
  2063. */
  2064. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  2065. var groupInfo = info;
  2066. var visitDate = info.VisitDate;
  2067. #region 团组收入
  2068. GroupIncomeView _giView = new GroupIncomeView();
  2069. /*
  2070. * 应收报表
  2071. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  2072. */
  2073. decimal frTotalAmount = 0.00M;//应收总金额
  2074. 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,
  2075. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  2076. From Fin_ForeignReceivables fr
  2077. Left Join Sys_SetData sd On fr.Currency = sd.Id
  2078. Left Join Sys_Users u On fr.Auditor = u.Id
  2079. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  2080. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  2081. //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  2082. //if (_frViews1.Count > 0)
  2083. //{
  2084. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  2085. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  2086. //}
  2087. _frViews.ForEach(x =>
  2088. {
  2089. string namePrefix = string.Empty;
  2090. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  2091. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  2092. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  2093. x.PriceName = $"{namePrefix}{x.PriceName}";
  2094. });
  2095. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  2096. _giView.Receivables = _frViews;
  2097. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  2098. /*
  2099. * 已收报表
  2100. */
  2101. decimal prTotalAmount = 0.00M;//已收总金额
  2102. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  2103. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  2104. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  2105. From Fin_ProceedsReceived pr
  2106. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  2107. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  2108. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  2109. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  2110. prTotalAmount = _prViews.Sum(it => it.Price);
  2111. _giView.ProceedsReceivedViews = _prViews;
  2112. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
  2113. /*
  2114. * 超支费用
  2115. */
  2116. decimal exTotalAmount = 0.00M;
  2117. // 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,
  2118. // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2119. // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  2120. //From OA2023DB.dbo.Fin_GroupExtraCost gec
  2121. //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  2122. // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2123. // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2124. // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2125. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2126. //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 " : " ");
  2127. // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
  2128. // #region 超支费用 - 模拟数据
  2129. // //if (_ExtraCostsViews.Count < 1)
  2130. // //{
  2131. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  2132. // // {
  2133. // // GECId = 0,
  2134. // // GECDiId = 2334,
  2135. // // PriceName = "模拟数据-超支费用名称",
  2136. // // PayMoney = 1000.00M,
  2137. // // PaymentCurrency = "CNY",
  2138. // // DayRate = 1.0000M,
  2139. // // CNYPrice = 1000.00M,
  2140. // // Payee = "模拟数据-超支费用收款方",
  2141. // // OrbitalPrivateTransfer = 1,
  2142. // // PayWay = "刷卡",
  2143. // // CardType = "招行卡",
  2144. // // IsPay = 1,
  2145. // // Applicant = "刘华举"
  2146. // // });
  2147. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  2148. // // {
  2149. // // GECId = 0,
  2150. // // GECDiId = 2334,
  2151. // // PriceName = "模拟数据-超支费用名称",
  2152. // // PayMoney = 1000.00M,
  2153. // // PaymentCurrency = "CNY",
  2154. // // DayRate = 1.0000M,
  2155. // // CNYPrice = 1000.00M,
  2156. // // Payee = "模拟数据-超支费用收款方",
  2157. // // OrbitalPrivateTransfer = 1,
  2158. // // PayWay = "刷卡",
  2159. // // CardType = "招行卡",
  2160. // // IsPay = 1,
  2161. // // Applicant = "刘华举"
  2162. // // });
  2163. // //}
  2164. // #endregion
  2165. // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  2166. // _giView.ExtraCostsViews = _ExtraCostsViews;
  2167. // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  2168. /*
  2169. * 收款退还
  2170. */
  2171. decimal promTotalAmount = 0.00M;// 收款退还总金额
  2172. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  2173. //删除了 And prom.PriceType = 1
  2174. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  2175. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  2176. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  2177. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
  2178. From Fin_PaymentRefundAndOtherMoney prom
  2179. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  2180. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2181. Where prom.IsDel = 0
  2182. And prom.PayType = 1
  2183. And ccp.CTable = 285
  2184. {1}
  2185. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2186. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  2187. foreach (var ropItem in _promDatas)
  2188. {
  2189. string thisCueencyCode = "Unknown";
  2190. string thisCueencyName = "Unknown";
  2191. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  2192. if (currency != null)
  2193. {
  2194. thisCueencyCode = currency.Name;
  2195. thisCueencyName = currency.Remark;
  2196. }
  2197. string orbitalPrivateTransferStr = "Unknown";
  2198. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  2199. if (orbitalPrivateTransfer != null)
  2200. {
  2201. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  2202. }
  2203. string payStr = "Unknown";
  2204. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  2205. if (pay != null)
  2206. {
  2207. payStr = pay.Name;
  2208. }
  2209. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  2210. {
  2211. Id = ropItem.Id,
  2212. DiId = ropItem.DIId,
  2213. PriceName = ropItem.PrPriceName,
  2214. PayCurrencyCode = thisCueencyCode,
  2215. PayCurrencyName = thisCueencyName,
  2216. Price = ropItem.PrPrice,
  2217. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  2218. ThisRate = ropItem.DayRate,
  2219. Payee = ropItem.Payee,
  2220. PayTime = ropItem.AuditGMDate,
  2221. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  2222. PayType = payStr,
  2223. IsPay = ropItem.IsPay,
  2224. Applicant = ropItem.Appliction
  2225. };
  2226. _promView.Add(gsd_PaymentRefund);
  2227. }
  2228. #region 收款退还 - 模拟数据
  2229. //if (_promView.Count < 1)
  2230. //{
  2231. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  2232. // {
  2233. // Id = 0,
  2234. // DiId = 2334,
  2235. // PriceName = "模拟数据-费用名称",
  2236. // PayCurrencyCode = "CNY",
  2237. // PayCurrencyName = "人民币",
  2238. // Price = 1000.00M,
  2239. // CNYPrice = 1000.00M,
  2240. // ThisRate = 1.00M,
  2241. // Payee = "模拟数据-收款方",
  2242. // PayTime = "2023-01-01 15:20:01",
  2243. // OrbitalPrivateTransfer = 1,
  2244. // PayType = "刷卡",
  2245. // IsPay = 1,
  2246. // Applicant = "刘华举"
  2247. // });
  2248. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  2249. // {
  2250. // Id = 0,
  2251. // DiId = 2334,
  2252. // PriceName = "模拟数据-费用名称",
  2253. // PayCurrencyCode = "CNY",
  2254. // PayCurrencyName = "人民币",
  2255. // Price = 1000.00M,
  2256. // CNYPrice = 1000.00M,
  2257. // ThisRate = 1.00M,
  2258. // Payee = "模拟数据-收款方",
  2259. // PayTime = "2023-01-01 15:20:01",
  2260. // OrbitalPrivateTransfer = 1,
  2261. // PayType = "刷卡",
  2262. // IsPay = 1,
  2263. // Applicant = "刘华举"
  2264. // });
  2265. //}
  2266. #endregion
  2267. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  2268. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  2269. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  2270. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  2271. _view.GroupIncome = _giView;
  2272. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  2273. #endregion
  2274. #region 团组支出
  2275. GroupExpenditureView _geView = new GroupExpenditureView();
  2276. #region 酒店预定费用
  2277. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  2278. //ccp.RMBPrice As CNYPrice
  2279. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  2280. string hotelFeeSql = string.Format(@"
  2281. SELECT
  2282. hr.Id AS HrId,
  2283. hr.DiId AS HrDiId,
  2284. hr.City,
  2285. hr.HotelName,
  2286. hr.CheckInDate,
  2287. hr.CheckOutDate,
  2288. hr.CardPrice AS RoomPrice,
  2289. sd1.Name AS PaymentCurrency,
  2290. hr.SingleRoomPrice,
  2291. hr.SingleRoomCount,
  2292. hr.DoubleRoomPrice,
  2293. hr.DoubleRoomCount,
  2294. hr.SuiteRoomPrice,
  2295. hr.SuiteRoomCount,
  2296. hr.OtherRoomPrice,
  2297. hr.OtherRoomCount,
  2298. hr.BreakfastPrice,
  2299. sd4.Name AS BreakfastCurrency,
  2300. hr.Isoppay,
  2301. hr.GovernmentRent,
  2302. sd5.Name AS GovernmentRentCurrency,
  2303. hr.CityTax,
  2304. sd6.Name AS CityTaxCurrency,
  2305. ccp.PayMoney,
  2306. (
  2307. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  2308. ) AS CNYPrice,
  2309. ccp.PayPercentage,
  2310. ccp.DayRate,
  2311. ccp.Payee,
  2312. ccp.OrbitalPrivateTransfer,
  2313. sd2.Name AS PayWay,
  2314. sd3.Name AS CardType,
  2315. ccp.IsPay,
  2316. u.CnName AS Applicant
  2317. FROM
  2318. Grp_HotelReservations hr
  2319. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  2320. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  2321. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  2322. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  2323. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  2324. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  2325. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  2326. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  2327. WHERE
  2328. hr.IsDel = 0
  2329. AND ccp.IsDel = 0
  2330. AND ccp.CTable = 76 {1}
  2331. AND ccp.PayMoney <> 0
  2332. AND hr.DiId = {0}
  2333. ORDER BY
  2334. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  2335. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  2336. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  2337. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  2338. decimal HotelCNYTotalPrice = 0.00M;
  2339. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  2340. foreach (var item in groupHotelFeeViews)
  2341. {
  2342. if (groupHotelContentFeeViews.Count > 0)
  2343. {
  2344. string paymentStr = string.Empty;
  2345. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  2346. item.RoomPrice = roomData?.Price ?? 0.00M;
  2347. if (item.RoomPrice != 0)
  2348. {
  2349. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  2350. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  2351. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2352. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  2353. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  2354. 收款方:{roomData?.Payee}<br/>
  2355. 费用标识:{feeMark1} <br/>
  2356. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  2357. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  2358. 是否由地接支付:{isFeeMark1} <br/>";
  2359. }
  2360. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  2361. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  2362. if (item.BreakfastPrice != 0)
  2363. {
  2364. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  2365. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  2366. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2367. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  2368. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  2369. 收款方:{breakfastData?.Payee}<br/>
  2370. 费用标识:{feeMark2} <br/>
  2371. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  2372. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  2373. 是否由地接支付:{isFeeMark2} <br/>";
  2374. }
  2375. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  2376. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  2377. if (item.GovernmentRent != 0)
  2378. {
  2379. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  2380. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  2381. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2382. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  2383. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  2384. 收款方:{landTaxData?.Payee}<br/>
  2385. 费用标识:{feeMark3} <br/>
  2386. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  2387. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  2388. 是否由地接支付:{isFeeMark3} <br/>";
  2389. }
  2390. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  2391. item.CityTax = cityTaxData?.Price ?? 0.00M;
  2392. if (item.CityTax != 0)
  2393. {
  2394. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  2395. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  2396. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2397. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  2398. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  2399. 收款方:{cityTaxData?.Payee}<br/>
  2400. 费用标识:{feeMark4} <br/>
  2401. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  2402. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  2403. 是否由地接支付:{isFeeMark4} <br/>";
  2404. }
  2405. if (!string.IsNullOrEmpty(paymentStr))
  2406. {
  2407. item.IsPay = 2;
  2408. item.PayTips = paymentStr;
  2409. }
  2410. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  2411. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  2412. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  2413. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  2414. }
  2415. else
  2416. {
  2417. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  2418. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  2419. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  2420. (item.OtherRoomCount * item.OtherRoomPrice);
  2421. //item.RoomPrice = item.CardPrice;
  2422. item.RoomPriceCurrency = item.PaymentCurrency;
  2423. }
  2424. HotelCNYTotalPrice += item.CNYPrice;
  2425. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  2426. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  2427. }
  2428. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  2429. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  2430. #endregion
  2431. #region 地接费用
  2432. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  2433. string CTGGRFeeSql = string.Empty;
  2434. if (visitDate > Convert.ToDateTime("2024-04-17"))
  2435. {
  2436. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  2437. sd2.name As PaymentCurrency,ccp.PayPercentage,
  2438. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  2439. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  2440. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  2441. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  2442. From Grp_CarTouristGuideGroundReservations ctggr
  2443. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  2444. cggrc.DatePrice,cggrc.PriceContent
  2445. From Grp_CarTouristGuideGroundReservationsContent cggrc
  2446. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  2447. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  2448. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  2449. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  2450. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  2451. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  2452. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  2453. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2454. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  2455. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  2456. }
  2457. else
  2458. {
  2459. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  2460. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  2461. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  2462. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  2463. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  2464. ccp.Payee,ccp.AuditGMDate,
  2465. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  2466. From Grp_CarTouristGuideGroundReservations ctggr
  2467. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  2468. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  2469. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  2470. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2471. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  2472. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  2473. }
  2474. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  2475. string CTGGRFeeStr = "";
  2476. decimal CTGGRCNYTotalPrice = 0.00M;
  2477. //按1 地区,2 币种,3 汇率 分组计算
  2478. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  2479. foreach (var ctggfr in groupCTGGRFeeDatas)
  2480. {
  2481. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  2482. if (ctggfr_curr.Count() > 0)
  2483. {
  2484. foreach (var curr in ctggfr_curr)
  2485. {
  2486. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  2487. if (ctggfr_rate.Count() > 0)
  2488. {
  2489. foreach (var rate in ctggfr_rate)
  2490. {
  2491. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  2492. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  2493. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  2494. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  2495. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2496. }
  2497. }
  2498. else
  2499. {
  2500. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  2501. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  2502. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  2503. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  2504. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2505. }
  2506. }
  2507. }
  2508. else
  2509. {
  2510. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  2511. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  2512. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  2513. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  2514. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2515. }
  2516. }
  2517. foreach (var item in groupCTGGRFeeViews)
  2518. {
  2519. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2520. {
  2521. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2522. }
  2523. if (item.DatePrice != DateTime.MinValue)
  2524. {
  2525. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  2526. }
  2527. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  2528. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  2529. //CTGGRCNYTotalPrice += item.CNYPrice;
  2530. }
  2531. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  2532. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  2533. #endregion
  2534. #region 机票预订费用
  2535. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  2536. //ccp.RMBPrice As CNYPrice
  2537. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  2538. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  2539. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  2540. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  2541. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  2542. atr.CType
  2543. From Grp_AirTicketReservations atr
  2544. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  2545. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2546. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2547. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2548. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  2549. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2550. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2551. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  2552. string str = "";
  2553. List<dynamic> airClientPris = new List<dynamic>();
  2554. decimal AirCNYTotalPrice = 0.00M;
  2555. //decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M;
  2556. decimal JJCAveragePrice = 0.00M;
  2557. //decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M;
  2558. decimal GWCAveragePrice = 0.00M;
  2559. //if (groupAirFeeViews.Count > 0)
  2560. //{
  2561. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  2562. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  2563. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  2564. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  2565. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  2566. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  2567. //}
  2568. int Index = 0;
  2569. foreach (var item in groupAirFeeViews)
  2570. {
  2571. if (item.AirId > 2924)
  2572. {
  2573. string itemClientName = "";
  2574. if (!string.IsNullOrEmpty(item.ClientName))
  2575. {
  2576. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  2577. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  2578. if (m_EnName.Success || m_ZHName.Success)
  2579. {
  2580. itemClientName = item.ClientName;
  2581. AirCNYTotalPrice += item.CNYPrice;
  2582. continue;
  2583. }
  2584. string[] clientIds = new string[] { };
  2585. if (item.ClientName.Contains(','))
  2586. {
  2587. clientIds = item.ClientName.Split(',');
  2588. }
  2589. else
  2590. {
  2591. clientIds = new string[] { item.ClientName };
  2592. }
  2593. if (clientIds.Length > 0)
  2594. {
  2595. int[] output = System.Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  2596. if (output.Contains(-1))
  2597. {
  2598. itemClientName += $@"行程单";
  2599. output = output.Where(val => val != -1).ToArray();
  2600. }
  2601. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  2602. decimal unitCost = 0.00M;
  2603. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  2604. int clienIndex = 1;
  2605. foreach (var client in clients)
  2606. {
  2607. airClientPris.Add(new
  2608. {
  2609. CnName = client.LastName + client.FirstName,
  2610. EnName = client.Pinyin,
  2611. Price = unitCost,
  2612. AirType = item.AirTypeName
  2613. });
  2614. string six = "";
  2615. if (client.Sex == 0) six = "Mr";
  2616. else if (client.Sex == 1) six = "Ms";
  2617. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  2618. clienIndex++;
  2619. }
  2620. }
  2621. }
  2622. item.ClientName = itemClientName;
  2623. }
  2624. else
  2625. {
  2626. string clientPinYinName = "";
  2627. decimal unitCost = 0.00M;
  2628. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  2629. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  2630. Regex r = new Regex("[0-9]");
  2631. string name1 = item.ClientName;
  2632. name1 = r.Replace(name1, "");
  2633. string[] clientNames = name1.Split('.');
  2634. for (int i = 0; i < item.ClientNum; i++)
  2635. {
  2636. string name = "";
  2637. if (clientNames.Length > 0)
  2638. {
  2639. int index = i + 1;
  2640. if (index < clientNames.Length)
  2641. {
  2642. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  2643. if (!string.IsNullOrEmpty(name))
  2644. {
  2645. airClientPris.Add(new
  2646. {
  2647. CnName = name,
  2648. EnName = name,
  2649. Price = unitCost,
  2650. AirType = item.AirTypeName
  2651. });
  2652. }
  2653. //if (name.Length > 0)
  2654. //{
  2655. // string nameLastStr = name[name.Length - 1].ToString();
  2656. // if (nameLastStr.IsNumeric())
  2657. // {
  2658. // name = name.Substring(0, name.Length - 1).Trim();
  2659. // }
  2660. //}
  2661. }
  2662. }
  2663. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  2664. }
  2665. }
  2666. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2667. {
  2668. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2669. }
  2670. AirCNYTotalPrice += item.CNYPrice;
  2671. }
  2672. _geView.GroupAirFeeViews = groupAirFeeViews;
  2673. if (airClientPris.Count > 0)
  2674. {
  2675. var peoplePriStr = "";
  2676. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  2677. .Select(group => group.First())
  2678. .ToList();
  2679. int airClientPrisIndex = 1;
  2680. foreach (var item in airClientPris1)
  2681. {
  2682. decimal price = 0.00M;
  2683. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  2684. foreach (var pri in prices)
  2685. {
  2686. price += pri.Price;
  2687. }
  2688. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  2689. airClientPrisIndex++;
  2690. }
  2691. if (!string.IsNullOrEmpty(peoplePriStr))
  2692. {
  2693. str = $@"其中:{peoplePriStr}";
  2694. }
  2695. //经济舱均价
  2696. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  2697. if (airJJCPris.Count > 0)
  2698. {
  2699. decimal jjcTotalPrice = 0.00M;
  2700. foreach (var item in airJJCPris)
  2701. {
  2702. jjcTotalPrice += item.Price;
  2703. }
  2704. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  2705. .Select(group => group.First())
  2706. .ToList().Count;
  2707. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  2708. }
  2709. //公务舱均价
  2710. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  2711. if (airGWCPris.Count > 0)
  2712. {
  2713. decimal gwcTotalPrice = 0.00M;
  2714. foreach (var item in airGWCPris)
  2715. {
  2716. gwcTotalPrice += item.Price;
  2717. }
  2718. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  2719. .Select(group => group.First())
  2720. .ToList().Count;
  2721. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  2722. }
  2723. }
  2724. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  2725. #endregion
  2726. #region 签证费用
  2727. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  2728. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  2729. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2730. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  2731. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  2732. From Grp_VisaInfo vi
  2733. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  2734. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2735. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2736. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2737. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2738. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2739. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  2740. decimal VisaCNYTotalPirce = 0.00M;
  2741. foreach (var item in groupVisaFeeViews)
  2742. {
  2743. string itemClientName = "";
  2744. string visaClients = item.VisaClient;
  2745. if (!string.IsNullOrEmpty(visaClients))
  2746. {
  2747. string[] clientIds = new string[] { };
  2748. if (visaClients.Contains(','))
  2749. {
  2750. clientIds = visaClients.Split(',');
  2751. }
  2752. else
  2753. {
  2754. clientIds = new string[] { visaClients };
  2755. }
  2756. if (clientIds.Length > 0)
  2757. {
  2758. List<int> clientIds1 = new List<int>() { };
  2759. foreach (var clientIdStr in clientIds)
  2760. {
  2761. if (clientIdStr.IsNumeric())
  2762. {
  2763. clientIds1.Add(int.Parse(clientIdStr));
  2764. }
  2765. }
  2766. if (clientIds1.Count > 0)
  2767. {
  2768. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  2769. foreach (var client in clients)
  2770. {
  2771. itemClientName += $"{client.LastName + client.FirstName},";
  2772. }
  2773. }
  2774. else
  2775. {
  2776. itemClientName = visaClients;
  2777. }
  2778. }
  2779. }
  2780. if (itemClientName.Length > 0)
  2781. {
  2782. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  2783. }
  2784. item.VisaClient = itemClientName;
  2785. VisaCNYTotalPirce += item.CNYPrice;
  2786. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2787. {
  2788. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2789. }
  2790. }
  2791. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  2792. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#.00"));
  2793. #endregion
  2794. #region 邀请/公务活动 CTable = 81
  2795. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  2796. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  2797. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  2798. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  2799. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
  2800. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  2801. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  2802. From Grp_InvitationOfficialActivities ioa
  2803. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  2804. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2805. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2806. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  2807. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  2808. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  2809. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  2810. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  2811. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2812. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2813. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  2814. #region 邀请/公务活动 - 模拟数据
  2815. //if (groupInvitationalFeeViews.Count < 1)
  2816. //{
  2817. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  2818. // {
  2819. // IOAId = 0,
  2820. // IOADiId = 2334,
  2821. // InviterArea = "模拟数据-邀请方地区",
  2822. // Inviter = "模拟数据-邀请方",
  2823. // InviteTime = "2023-10-10",
  2824. // InviteCost = 100.00M,
  2825. // InviteCurrency = "EUR",
  2826. // SendCost = 100.00M,
  2827. // SendCurrency = "EUR",
  2828. // EventsCost = 10000.00M,
  2829. // EventsCurrency = "EUR",
  2830. // TranslateCost = 300.00M,
  2831. // TranslateCurrency = "EUR",
  2832. // PayMoney = 10500.00M,
  2833. // PaymentCurrency = "EUR",
  2834. // CNYPrice = 76765.50M,
  2835. // Payee = "模拟数据-收款方",
  2836. // AuditGMDate = "2023-12-05",
  2837. // OrbitalPrivateTransfer = 1,
  2838. // PayWay = "刷卡",
  2839. // IsPay = 1,
  2840. // Applicant = "刘华举"
  2841. // });
  2842. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  2843. // {
  2844. // IOAId = 0,
  2845. // IOADiId = 2334,
  2846. // InviterArea = "模拟数据-邀请方地区",
  2847. // Inviter = "模拟数据-邀请方",
  2848. // InviteTime = "2023-10-10",
  2849. // InviteCost = 100.00M,
  2850. // InviteCurrency = "EUR",
  2851. // SendCost = 100.00M,
  2852. // SendCurrency = "EUR",
  2853. // EventsCost = 10000.00M,
  2854. // EventsCurrency = "EUR",
  2855. // TranslateCost = 300.00M,
  2856. // TranslateCurrency = "EUR",
  2857. // PayMoney = 10500.00M,
  2858. // PaymentCurrency = "EUR",
  2859. // CNYPrice = 76765.50M,
  2860. // Payee = "模拟数据-收款方",
  2861. // AuditGMDate = "2023-12-05",
  2862. // OrbitalPrivateTransfer = 1,
  2863. // PayWay = "刷卡",
  2864. // IsPay = 1,
  2865. // Applicant = "刘华举"
  2866. // });
  2867. //}
  2868. #endregion
  2869. decimal InvitationalCNYTotalPrice = 0.00M;
  2870. foreach (var item in groupInvitationalFeeViews)
  2871. {
  2872. InvitationalCNYTotalPrice += item.CNYPrice2;
  2873. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2874. {
  2875. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2876. }
  2877. string currencyRateStr = "";
  2878. List<string> currencys = new List<string>();
  2879. if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
  2880. if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
  2881. if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
  2882. if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
  2883. if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
  2884. currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
  2885. item.CurrencyRateStr = currencyRateStr;
  2886. }
  2887. _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
  2888. _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#.00"));
  2889. #endregion
  2890. #region 保险费用
  2891. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  2892. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
  2893. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  2894. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  2895. From Grp_Customers ic
  2896. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  2897. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2898. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2899. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2900. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2901. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  2902. decimal InsuranceCNYTotalPrice = 0.00M;
  2903. foreach (var item in groupInsuranceFeeViews)
  2904. {
  2905. InsuranceCNYTotalPrice += item.CNYPrice;
  2906. string itemClientName = "";
  2907. string insClients = item.ClientName;
  2908. if (!string.IsNullOrEmpty(insClients))
  2909. {
  2910. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  2911. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  2912. //if (m_EnName.Success || m_ZHName.Success)
  2913. //{
  2914. // itemClientName = insClients;
  2915. // continue;
  2916. //}
  2917. string[] clientIds = new string[] { };
  2918. if (insClients.Contains(','))
  2919. {
  2920. clientIds = insClients.Split(',');
  2921. }
  2922. else
  2923. {
  2924. clientIds = new string[] { insClients };
  2925. }
  2926. if (clientIds.Length > 0)
  2927. {
  2928. List<int> output = new List<int>();
  2929. foreach (var clientId in clientIds)
  2930. {
  2931. if (clientId.IsNumeric())
  2932. {
  2933. output.Add(int.Parse(clientId));
  2934. }
  2935. }
  2936. if (output.Count > 0)
  2937. {
  2938. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  2939. foreach (var client in clients)
  2940. {
  2941. itemClientName += $"{client.LastName + client.FirstName},";
  2942. }
  2943. if (itemClientName.Length > 0)
  2944. {
  2945. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  2946. }
  2947. }
  2948. else
  2949. {
  2950. itemClientName = insClients;
  2951. }
  2952. }
  2953. }
  2954. item.ClientName = itemClientName;
  2955. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2956. {
  2957. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2958. }
  2959. }
  2960. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  2961. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  2962. #endregion
  2963. #region 其他款项费用 98
  2964. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  2965. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  2966. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  2967. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  2968. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  2969. From Grp_DecreasePayments dp
  2970. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  2971. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2972. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2973. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2974. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  2975. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2976. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  2977. #region 保险费用 - 模拟数据
  2978. //if (groupDecreaseFeeViews.Count < 1)
  2979. //{
  2980. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  2981. // {
  2982. // DPId = 0,
  2983. // DPDiId = 2334,
  2984. // PriceName = "模拟数据-费用名称",
  2985. // PayMoney = 1000.00M,
  2986. // PayMoneyCurrency = "CNY",
  2987. // DayRate = 1.0000M,
  2988. // CNYPrice = 1.0000M,
  2989. // AuditGMDate = "2023-12-10 12:13:00",
  2990. // Payee = "模拟数据-付款方",
  2991. // OrbitalPrivateTransfer = 1,
  2992. // PayWay = "现金",
  2993. // IsPay = 1,
  2994. // Applicant = "刘华举"
  2995. // });
  2996. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  2997. // {
  2998. // DPId = 0,
  2999. // DPDiId = 2334,
  3000. // PriceName = "模拟数据-费用名称",
  3001. // PayMoney = 1000.00M,
  3002. // PayMoneyCurrency = "CNY",
  3003. // DayRate = 1.0000M,
  3004. // CNYPrice = 1.0000M,
  3005. // AuditGMDate = "2023-12-10 12:13:00",
  3006. // Payee = "模拟数据-付款方",
  3007. // OrbitalPrivateTransfer = 1,
  3008. // PayWay = "现金",
  3009. // IsPay = 1,
  3010. // Applicant = "刘华举"
  3011. // });
  3012. //}
  3013. #endregion
  3014. decimal DecreaseCNYTotalPrice = 0.00M;
  3015. foreach (var item in groupDecreaseFeeViews)
  3016. {
  3017. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  3018. DecreaseCNYTotalPrice += item.CNYPrice;
  3019. if (!string.IsNullOrEmpty(item.AuditGMDate))
  3020. {
  3021. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  3022. }
  3023. }
  3024. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  3025. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  3026. #endregion
  3027. #region 公司内部操作人员提成
  3028. var royaltyDatas = await _sqlSugar
  3029. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  3030. new JoinQueryInfos(
  3031. JoinType.Left, rc.UserId == u1.Id,
  3032. JoinType.Left, rc.CreateUserId == u2.Id
  3033. ))
  3034. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
  3035. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  3036. {
  3037. GroupId = rc.TeamId,
  3038. OverviewInfo = rc.Temp,
  3039. DetailedInfo = rc.ChiArr,
  3040. Amount = rc.Price,
  3041. IsConfirm = rc.IsConfirm,
  3042. IsSeed = rc.IsSeed,
  3043. RoyaltyUserName = u1.CnName,
  3044. CreateUserName = u2.CnName,
  3045. CreateTime = rc.CreateTime
  3046. })
  3047. .ToListAsync();
  3048. decimal royaltyCNYTotalPrice = royaltyDatas.Sum(x => x.Amount);
  3049. _geView.GroupRoyaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeView>>(royaltyDatas);
  3050. _geView.GroupRoyaltyFeeStr = string.Format(@"人民币总费用:{0} CNY", royaltyCNYTotalPrice.ToString("#0.00"));
  3051. #endregion
  3052. _view.GroupExpenditure = _geView;
  3053. #endregion
  3054. /*
  3055. * 团组报表计算方式
  3056. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3057. * 应收金额 = 应收表.Sum()
  3058. * 已收金额 = 已收表.Sum()
  3059. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3060. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3061. *
  3062. */
  3063. decimal _totalExpenditure = 0.00M; //总支出
  3064. decimal _amountReceivable = 0.00M; //应收金额
  3065. decimal _amountReceived = 0.00M; //已收金额
  3066. decimal _receivableProfit = 0.00M; //应收利润
  3067. decimal _receivedProfit = 0.00M; //已收利润
  3068. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  3069. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount + royaltyCNYTotalPrice;
  3070. _amountReceivable = frTotalAmount;
  3071. _amountReceived = prTotalAmount;
  3072. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  3073. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  3074. _view.FeeTotalStr = string.Format(@$"<span>
  3075. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  3076. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  3077. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  3078. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  3079. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  3080. </span>");
  3081. index1++;
  3082. _views.Add(new GroupStatisticsInfo()
  3083. {
  3084. Index = index1,
  3085. Id = info.Id,
  3086. GroupName = info.TeamName,
  3087. VisitDate = info.VisitDate,
  3088. Receivable = Math.Floor(_amountReceivable * 100) / 100,
  3089. Cost = Math.Floor(_totalExpenditure * 100) / 100,
  3090. Grossprofit = Math.Floor((_amountReceivable - _totalExpenditure) * 100) / 100,
  3091. });
  3092. }
  3093. return Ok(JsonView(true, "查询成功!", _views));
  3094. }
  3095. private class GroupStatisticsInfo
  3096. {
  3097. public int Index { get; set; }
  3098. public int Id { get; set; }
  3099. public string GroupName { get; set; }
  3100. public DateTime VisitDate { get; set; }
  3101. public decimal Receivable { get; set; }
  3102. public decimal Cost { get; set; }
  3103. public decimal Grossprofit { get; set; }
  3104. }
  3105. private void StatementExportExcelSetCell(WorkbookDesigner designer, Worksheet sheet, DataTable dt, Style style, string judgeLable, int startIndex, string startRange, string endRange)
  3106. {
  3107. if (designer == null) return;
  3108. if (sheet == null) return;
  3109. if (style == null) return;
  3110. if (dt == null) return;
  3111. if (string.IsNullOrEmpty(startRange)) return;
  3112. if (string.IsNullOrEmpty(endRange)) return;
  3113. for (int i = 0; i < dt.Rows.Count; i++)
  3114. {
  3115. var isPayStr = dt.Rows[i][$"{judgeLable}"].ToString();
  3116. if (string.IsNullOrEmpty(isPayStr)) continue;
  3117. if (isPayStr.Contains("未付款"))
  3118. {
  3119. var excelIndex = startIndex + i;
  3120. Aspose.Cells.Range range = sheet.Cells.CreateRange($"{startRange}{excelIndex}", $"{endRange}{excelIndex}");
  3121. range.ApplyStyle(style, new StyleFlag() { CellShading = true, Font = true });
  3122. }
  3123. }
  3124. }
  3125. #endregion
  3126. #region 报表/折线图统计
  3127. //企业利润-团组利润
  3128. //企业利润-会务利润
  3129. /// <summary>
  3130. /// 企业利润
  3131. /// Details
  3132. /// 待添加权限验证
  3133. /// </summary>
  3134. /// <param name="_dto">团组列表请求dto</param>
  3135. /// <returns></returns>
  3136. [HttpPost("PostCorporateProfit")]
  3137. //[JsonConverter(typeof(DecimalConverter), 2)]
  3138. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3139. public async Task<IActionResult> PostCorporateProfit(PostCorporateProfitDto _dto)
  3140. {
  3141. #region 参数验证
  3142. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  3143. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  3144. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  3145. if (_dto.StatisticsType > 2 && _dto.StatisticsType < 1) return Ok(JsonView(false, "请输入有效的StatisticsType参数,1 月份 2 季度"));
  3146. if (_dto.BusinessType > 3 && _dto.BusinessType < 1) return Ok(JsonView(false, "请输入有效的BusinessType参数,1 所有 2 团组 3 会务"));
  3147. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3148. #region 页面操作权限验证
  3149. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3150. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3151. #endregion
  3152. string sqlWhere = string.Empty;
  3153. //起止时间
  3154. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  3155. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  3156. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  3157. //业务类型
  3158. List<int> groupTypeId = new List<int>();
  3159. if (_dto.BusinessType == 2) //团组
  3160. {
  3161. groupTypeId.AddRange(new List<int>() {
  3162. 38, // 政府团
  3163. 39, // 企业团
  3164. 40, // 散客团
  3165. 1048 // 高校团
  3166. });
  3167. }
  3168. else if (_dto.BusinessType == 3) //会务
  3169. {
  3170. groupTypeId.AddRange(new List<int>() {
  3171. 102, // 未知
  3172. 248, // 非团组
  3173. 302, // 成都-会务活动
  3174. 691, // 四川-会务活动
  3175. 762, // 四川-赛事项目收入
  3176. 1047 // 成都-赛事项目收入
  3177. });
  3178. }
  3179. if (groupTypeId.Count > 0)
  3180. {
  3181. sqlWhere += string.Format(@$" And TeamDid In ({string.Join(',', groupTypeId)})");
  3182. }
  3183. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  3184. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  3185. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  3186. List<int> diIds = groupInfos.Select(it => it.Id).ToList();
  3187. List<CorporateProfit> corporateProfits = await CorporateProfit(diIds);
  3188. List<MonthInfo> months = new List<MonthInfo>();
  3189. if (_dto.StatisticsType == 1) //月份
  3190. {
  3191. months = GeneralMethod.GetMonthInfos(Convert.ToInt32(_dto.Year));
  3192. }
  3193. else if (_dto.StatisticsType == 1) //季度
  3194. {
  3195. months = GeneralMethod.GetQuarter(Convert.ToInt32(_dto.Year));
  3196. }
  3197. List<CorporateProfitMonthView> _view = new List<CorporateProfitMonthView>();
  3198. foreach (var item in months)
  3199. {
  3200. DateTime monthBeginDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.BeginDays} 00:00:00");
  3201. DateTime monthEndDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.EndDays} 23:59:59");
  3202. var corporateProfit = corporateProfits.Where(it => it.CreateDt >= monthBeginDt && it.CreateDt <= monthEndDt).ToList();
  3203. _view.Add(new CorporateProfitMonthView()
  3204. {
  3205. Month = item.Month,
  3206. Profit = corporateProfit.Sum(it => it.ReceivedProfit),
  3207. GroupInfos = corporateProfit.OrderBy(it => it.CreateDt).ToList()
  3208. });
  3209. }
  3210. return Ok(JsonView(true, "操作成功!", _view));
  3211. #endregion
  3212. }
  3213. /// <summary>
  3214. /// 计算团组利润
  3215. /// </summary>
  3216. /// <param name="diIds"></param>
  3217. /// <returns></returns>
  3218. private async Task<List<CorporateProfit>> CorporateProfit(List<int> diIds)
  3219. {
  3220. List<CorporateProfit> corporateProfits = new List<CorporateProfit>();
  3221. if (diIds.Count < 1)
  3222. {
  3223. return corporateProfits;
  3224. }
  3225. #region 计算团组利润
  3226. /*
  3227. * 团组报表计算方式
  3228. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3229. * 应收金额 = 应收表.Sum()
  3230. * 已收金额 = 已收表.Sum()
  3231. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3232. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3233. *
  3234. */
  3235. string diIdStr = string.Join(",", diIds);
  3236. string sql = string.Format(@$"Select * From Grp_DelegationInfo Where Isdel = 0 And Id In ({diIdStr})");
  3237. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToListAsync();
  3238. #region 费用类型 币种,转账,客户信息
  3239. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  3240. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
  3241. #endregion
  3242. foreach (var _diId in diIds)
  3243. {
  3244. List<ExpenditureInfo> expenditureInfos = new List<ExpenditureInfo>();
  3245. #region 团组收入
  3246. /*
  3247. * 应收报表
  3248. */
  3249. decimal frTotalAmount = 0.00M;//应收总金额
  3250. string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  3251. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  3252. From Fin_ForeignReceivables fr
  3253. Left Join Sys_SetData sd On fr.Currency = sd.Id
  3254. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _diId);
  3255. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  3256. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  3257. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "应收项", Amount = frTotalAmount });
  3258. /*
  3259. * 已收报表
  3260. */
  3261. decimal prTotalAmount = 0.00M;//已收总金额
  3262. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  3263. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  3264. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  3265. From Fin_ProceedsReceived pr
  3266. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  3267. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  3268. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _diId);
  3269. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  3270. prTotalAmount = _prViews.Sum(it => it.Price);
  3271. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "已收项", Amount = prTotalAmount });
  3272. /*
  3273. * 超支费用
  3274. */
  3275. decimal exTotalAmount = 0.00M;
  3276. string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,ccp.PayMoney,sd1.Name As PaymentCurrency,
  3277. ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  3278. sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  3279. From OA2023DB.dbo.Fin_GroupExtraCost gec
  3280. Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  3281. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3282. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3283. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3284. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3285. Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _diId);
  3286. List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();
  3287. exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  3288. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "超支费用", Amount = exTotalAmount });
  3289. /*
  3290. * 收款退还
  3291. */
  3292. decimal promTotalAmount = 0.00M;// 收款退还总金额
  3293. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  3294. //删除了 And prom.PriceType = 1
  3295. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  3296. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  3297. prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime
  3298. From Fin_PaymentRefundAndOtherMoney prom
  3299. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  3300. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3301. Where prom.IsDel = 0 And prom.PayType = 1 And ccp.CTable = 285
  3302. And ccp.IsAuditGM = 1 And ccp.IsPay = 1
  3303. And prom.DiId = {0} Order By PrCreateTime", _diId);
  3304. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  3305. foreach (var ropItem in _promDatas)
  3306. {
  3307. string thisCueencyCode = "Unknown";
  3308. string thisCueencyName = "Unknown";
  3309. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  3310. if (currency != null)
  3311. {
  3312. thisCueencyCode = currency.Name;
  3313. thisCueencyName = currency.Remark;
  3314. }
  3315. string orbitalPrivateTransferStr = "Unknown";
  3316. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  3317. if (orbitalPrivateTransfer != null)
  3318. {
  3319. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  3320. }
  3321. string payStr = "Unknown";
  3322. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  3323. if (pay != null)
  3324. {
  3325. payStr = pay.Name;
  3326. }
  3327. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  3328. {
  3329. Id = ropItem.Id,
  3330. DiId = ropItem.DIId,
  3331. PriceName = ropItem.PrPriceName,
  3332. PayCurrencyCode = thisCueencyCode,
  3333. PayCurrencyName = thisCueencyName,
  3334. Price = ropItem.PrPrice,
  3335. CNYPrice = ropItem.RMBPrice,
  3336. ThisRate = ropItem.DayRate,
  3337. Payee = ropItem.Payee,
  3338. PayTime = ropItem.AuditGMDate,
  3339. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  3340. PayType = payStr,
  3341. IsPay = ropItem.IsPay,
  3342. Applicant = ropItem.Appliction
  3343. };
  3344. _promView.Add(gsd_PaymentRefund);
  3345. }
  3346. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  3347. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "收款退还", Amount = promTotalAmount });
  3348. #endregion
  3349. #region 团组支出
  3350. GroupExpenditureView _geView = new GroupExpenditureView();
  3351. #region 酒店预定费用
  3352. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  3353. string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,
  3354. sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,
  3355. hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,
  3356. hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,
  3357. sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,
  3358. ccp.PayMoney,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,
  3359. sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant
  3360. From Grp_HotelReservations hr
  3361. Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId
  3362. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3363. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3364. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3365. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3366. Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id
  3367. Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id
  3368. Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id
  3369. Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And hr.DiId = {0}
  3370. Order By CheckInDate Asc", _diId);
  3371. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  3372. decimal HotelCNYTotalPrice = groupHotelFeeViews.Sum(it => it.CNYPrice);
  3373. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "酒店预定", Amount = HotelCNYTotalPrice });
  3374. #endregion
  3375. #region 地接费用
  3376. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  3377. string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.Area,ctggrc.*,ctggrc.Price As PayMoney,
  3378. sd2.name As PaymentCurrency,ccp.PayPercentage,
  3379. (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,
  3380. (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,
  3381. ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  3382. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  3383. From Grp_CarTouristGuideGroundReservations ctggr
  3384. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,
  3385. cggrc.PriceContent
  3386. From Grp_CarTouristGuideGroundReservationsContent cggrc
  3387. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  3388. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  3389. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  3390. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  3391. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  3392. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  3393. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  3394. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3395. Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ctggr.DiId = {0}
  3396. Order By CreateTime", _diId);
  3397. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  3398. decimal CTGGRCNYTotalPrice = groupCTGGRFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  3399. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "地接", Amount = CTGGRCNYTotalPrice });
  3400. #endregion
  3401. #region 机票预订费用
  3402. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  3403. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  3404. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  3405. sd1.Name As PayMoneyCurrency,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  3406. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime
  3407. From Grp_AirTicketReservations atr
  3408. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  3409. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3410. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3411. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3412. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  3413. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3414. Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And atr.DiId = {0} Order By CreateTime", _diId);
  3415. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  3416. decimal AirCNYTotalPrice = groupAirFeeViews.Sum(it => it.CNYPrice);
  3417. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "机票预订", Amount = AirCNYTotalPrice });
  3418. #endregion
  3419. #region 签证费用
  3420. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  3421. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  3422. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  3423. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime
  3424. From Grp_VisaInfo vi
  3425. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  3426. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3427. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3428. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3429. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3430. Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And vi.DIId = {0} Order By CreateTime", _diId);
  3431. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  3432. decimal VisaCNYTotalPirce = groupVisaFeeViews.Sum(it => it.PayMoney);
  3433. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "签证", Amount = VisaCNYTotalPirce });
  3434. #endregion
  3435. #region 邀请/公务活动 CTable = 81
  3436. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  3437. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  3438. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  3439. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  3440. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  3441. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  3442. From Grp_InvitationOfficialActivities ioa
  3443. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  3444. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3445. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3446. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  3447. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  3448. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  3449. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  3450. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  3451. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3452. Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ioa.Diid = {0} Order By CreateTime", _diId);
  3453. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  3454. decimal InvitationalCNYTotalPrice = groupInvitationalFeeViews.Sum(it => it.CNYPrice);
  3455. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "邀请/公务活动", Amount = InvitationalCNYTotalPrice });
  3456. #endregion
  3457. #region 保险费用
  3458. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  3459. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,
  3460. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3461. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  3462. From Grp_Customers ic
  3463. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  3464. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3465. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3466. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3467. Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ic.DiId = {0} Order By CreateTime", _diId);
  3468. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  3469. decimal InsuranceCNYTotalPrice = groupInsuranceFeeViews.Sum(it => it.CNYPrice);
  3470. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "保险费用", Amount = InsuranceCNYTotalPrice });
  3471. #endregion
  3472. #region 其他款项费用 98
  3473. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  3474. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  3475. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  3476. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3477. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  3478. From Grp_DecreasePayments dp
  3479. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  3480. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3481. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3482. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3483. Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And dp.Diid = {0}
  3484. Order By CreateTime", _diId);
  3485. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  3486. decimal DecreaseCNYTotalPrice = groupDecreaseFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  3487. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "其他款项", Amount = DecreaseCNYTotalPrice });
  3488. #endregion
  3489. #endregion
  3490. /*
  3491. * 团组报表计算方式
  3492. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3493. * 应收金额 = 应收表.Sum()
  3494. * 已收金额 = 已收表.Sum()
  3495. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3496. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3497. *
  3498. */
  3499. decimal _totalExpenditure = 0.00M; //总支出
  3500. decimal _amountReceivable = 0.00M; //应收金额
  3501. decimal _amountReceived = 0.00M; //已收金额
  3502. decimal _receivableProfit = 0.00M; //应收利润
  3503. decimal _receivedProfit = 0.00M; //已收利润
  3504. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  3505. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  3506. _amountReceivable = frTotalAmount;
  3507. _amountReceived = prTotalAmount;
  3508. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  3509. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  3510. var groupInfo = groupInfos.Find(it => it.Id == _diId);
  3511. corporateProfits.Add(new CorporateProfit()
  3512. {
  3513. DiId = _diId,
  3514. TeamName = groupInfo?.TeamName ?? "Unkwnon",
  3515. CreateDt = Convert.ToDateTime(groupInfo?.CreateTime),
  3516. TotalExpenditure = _totalExpenditure,
  3517. ExpenditureItem = expenditureInfos,
  3518. AmountReceivable = _amountReceivable,
  3519. AmountReceived = _amountReceived,
  3520. ReceivableProfit = _receivableProfit,
  3521. ReceivedProfit = _receivedProfit,
  3522. });
  3523. }
  3524. #endregion
  3525. return corporateProfits;
  3526. }
  3527. //未来预测-地区接团/出团量
  3528. //未来预测-地区酒店预订量
  3529. //未来预测-地区机票预订量
  3530. //未来预测-地区车辆预订量
  3531. /// <summary>
  3532. /// (国家/城市)地区预订数量(团,酒店,机票,车辆)
  3533. /// Details
  3534. /// 待添加权限验证
  3535. /// </summary>
  3536. /// <param name="_dto">团组列表请求dto</param>
  3537. /// <returns></returns>
  3538. [HttpPost("PostRegionalBookingsNumber")]
  3539. //[JsonConverter(typeof(DecimalConverter), 2)]
  3540. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3541. public async Task<IActionResult> PostRegionalBookingsNumber(PostRegionalBookingsNumberDto _dto)
  3542. {
  3543. #region 参数验证
  3544. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  3545. //if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  3546. if (_dto.Type > 1 && _dto.Type > 5) return Ok(JsonView(false, "请输入有效的Type参数,1 团 2 酒店 3 机票 4 车辆"));
  3547. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  3548. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3549. #region 页面操作权限验证
  3550. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3551. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3552. #endregion
  3553. string sqlWhere = string.Empty;
  3554. //起止时间
  3555. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  3556. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  3557. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  3558. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  3559. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  3560. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  3561. List<GroupTypeNumberInfo> datas = new List<GroupTypeNumberInfo>();
  3562. foreach (var item in groupInfos)
  3563. {
  3564. var data = await GroupBookingsNumber(_dto.Type, item);
  3565. if (data.TypeItem.Count > 0)
  3566. {
  3567. datas.Add(data);
  3568. }
  3569. }
  3570. //类型处理
  3571. if (_dto.Type == 1)//接团
  3572. {
  3573. List<GroupBookingNumberView> views = new List<GroupBookingNumberView>();
  3574. //dynamic groupData = null;
  3575. foreach (var item in datas)
  3576. {
  3577. if (item.TypeItem.Count > 0)
  3578. {
  3579. foreach (var item1 in item.TypeItem)
  3580. {
  3581. if (item1.RegionItem.Count > 0)
  3582. {
  3583. GroupInfo groupInfo = new GroupInfo()
  3584. {
  3585. DiId = item.DiId,
  3586. TeamName = item.GroupName,
  3587. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  3588. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  3589. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  3590. };
  3591. views.Add(new GroupBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, GroupItem = new List<GroupInfo>() { groupInfo } });
  3592. }
  3593. }
  3594. }
  3595. }
  3596. var viewsGroup = views.GroupBy(it => it.Name);
  3597. List<GroupBookingNumberView> _view = new List<GroupBookingNumberView>();
  3598. foreach (var item in viewsGroup)
  3599. {
  3600. List<GroupInfo> infos = new List<GroupInfo>();
  3601. foreach (var item1 in item)
  3602. {
  3603. infos.AddRange(item1.GroupItem);
  3604. }
  3605. infos = infos.OrderByDescending(it => it.CreateTime).ToList(); //
  3606. _view.Add(new GroupBookingNumberView() { Name = item.Key, Number = item.Count(), GroupItem = infos });
  3607. }
  3608. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  3609. return Ok(JsonView(true, "操作成功!", _view, _view.Count));
  3610. }
  3611. else if (_dto.Type == 2)
  3612. {
  3613. List<HotelBookingNumberView> views = new List<HotelBookingNumberView>();
  3614. foreach (var item in datas)
  3615. {
  3616. if (item.TypeItem.Count > 0)
  3617. {
  3618. foreach (var item1 in item.TypeItem)
  3619. {
  3620. if (item1.RegionItem.Count > 0)
  3621. {
  3622. foreach (var item2 in item1.RegionItem)
  3623. {
  3624. GroupInfo groupInfo = new GroupInfo()
  3625. {
  3626. DiId = item.DiId,
  3627. TeamName = item.GroupName,
  3628. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  3629. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  3630. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  3631. };
  3632. List<HotelInfo> hotels = new List<HotelInfo>();
  3633. foreach (var item3 in item2.Data)
  3634. {
  3635. StatisticsHotelInfo statisticsHotelInfos = JsonConvert.DeserializeObject<StatisticsHotelInfo>(JsonConvert.SerializeObject(item3));
  3636. HotelInfo hotelInfo = new HotelInfo()
  3637. {
  3638. HotelName = statisticsHotelInfos.HotelName,
  3639. SingleRoomNum = statisticsHotelInfos.SingleRoomNum,
  3640. DoubleRoomNum = statisticsHotelInfos.DoubleRoomNum,
  3641. SuiteRoomNum = statisticsHotelInfos.SuiteRoomNum,
  3642. OtherRoomNum = statisticsHotelInfos.OtherRoomNum,
  3643. GroupInfo = groupInfo
  3644. };
  3645. hotels.Add(hotelInfo);
  3646. }
  3647. views.Add(new HotelBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, HotelItem = hotels });
  3648. }
  3649. }
  3650. }
  3651. }
  3652. }
  3653. var viewsGroup = views.GroupBy(it => it.Name);
  3654. List<HotelBookingNumberView> _view = new List<HotelBookingNumberView>();
  3655. foreach (var item in viewsGroup)
  3656. {
  3657. List<HotelInfo> infos = new List<HotelInfo>();
  3658. foreach (var item1 in item)
  3659. {
  3660. infos.AddRange(item1.HotelItem);
  3661. }
  3662. _view.Add(new HotelBookingNumberView() { Name = item.Key, Number = item.Count(), HotelItem = infos });
  3663. }
  3664. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  3665. return Ok(JsonView(true, "操作成功!", views, views.Count));
  3666. }
  3667. return Ok(JsonView(false, "操作失败!"));
  3668. #endregion
  3669. }
  3670. /// <summary>
  3671. /// 计算团组ALLType预订数量
  3672. /// </summary>
  3673. /// <param name="type"></param>
  3674. /// <param name="info"></param>
  3675. /// <returns></returns>
  3676. private async Task<GroupTypeNumberInfo> GroupBookingsNumber(int type, Grp_DelegationInfo info)
  3677. {
  3678. GroupTypeNumberInfo _view = new GroupTypeNumberInfo();
  3679. if (info == null)
  3680. {
  3681. return _view;
  3682. }
  3683. _view.DiId = info.Id;
  3684. _view.GroupName = info.TeamName;
  3685. List<TypeInfo> _types = new List<TypeInfo>();
  3686. #region 计算团组ALLType预订数量
  3687. if (type == 1)
  3688. {
  3689. //接团 客户集团所在地区
  3690. string group_region = string.Empty;
  3691. int group_number = 0;
  3692. if (!string.IsNullOrEmpty(info.ClientUnit))
  3693. {
  3694. var _NewClientData = await _sqlSugar.Queryable<Crm_NewClientData>()
  3695. .Where(it => it.IsDel == 0 && it.Client.Equals(AesEncryptionHelper.Encrypt(info.ClientUnit)))
  3696. .FirstAsync();
  3697. if (_NewClientData != null)
  3698. {
  3699. var regionInfo = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == _NewClientData.Lvlid).FirstAsync();
  3700. if (regionInfo != null)
  3701. {
  3702. group_region = regionInfo.Name.Replace("级", "");
  3703. group_number++;
  3704. }
  3705. }
  3706. }
  3707. if (group_number > 0)
  3708. {
  3709. _types.Add(new TypeInfo() { Id = 1, RegionItem = new List<RegionInfo>() { new RegionInfo() { Name = group_region, Number = group_number } } });
  3710. }
  3711. }
  3712. else if (type == 2)
  3713. {
  3714. //酒店
  3715. var hotelInfos = await _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  3716. if (hotelInfos.Count > 0)
  3717. {
  3718. List<RegionInfo> hotelRegions = new List<RegionInfo>();
  3719. foreach (var item in hotelInfos)
  3720. {
  3721. var hotelNumberInfo = new StatisticsHotelInfo()
  3722. {
  3723. HotelName = item.HotelName,
  3724. SingleRoomNum = item.SingleRoomCount,
  3725. DoubleRoomNum = item.DoubleRoomCount,
  3726. SuiteRoomNum = item.SuiteRoomCount,
  3727. OtherRoomNum = item.OtherRoomCount,
  3728. };
  3729. int hotelRoomTotal = item.SingleRoomCount + item.DoubleRoomCount + item.SuiteRoomCount + item.OtherRoomCount;
  3730. if (hotelRegions.Select(it => it.Name).ToList().Contains(item.City))
  3731. {
  3732. RegionInfo hotelRegion = hotelRegions.Find(it => it.Name.Equals(item.City));
  3733. if (hotelRegion != null)
  3734. {
  3735. hotelRegions.Remove(hotelRegion);
  3736. if (hotelRegion.Data.Count > 0)
  3737. {
  3738. hotelRegion.Data.Add(hotelNumberInfo);
  3739. }
  3740. hotelRegion.Number += hotelRoomTotal;
  3741. hotelRegions.Add(hotelRegion);
  3742. }
  3743. }
  3744. else
  3745. {
  3746. hotelRegions.Add(new RegionInfo() { Name = item.City, Number = hotelRoomTotal, Data = new List<dynamic>() { hotelNumberInfo } });
  3747. }
  3748. }
  3749. _types.Add(new TypeInfo() { Id = 2, RegionItem = hotelRegions });
  3750. }
  3751. }
  3752. else if (type == 3)
  3753. {
  3754. //机票
  3755. var airTicketInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  3756. .LeftJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId && ccp.IsPay == 1)
  3757. .LeftJoin<Sys_SetData>((atr, ccp, sd) => atr.CType == sd.Id)
  3758. .Where((atr, ccp, sd) => atr.IsDel == 0 && atr.DIId == info.Id)
  3759. .Select((atr, ccp, sd) => new { atr.ClientNum, atr.CType, ccp.Payee, AirType = sd.Name })
  3760. .ToListAsync();
  3761. if (airTicketInfos.Count > 0)
  3762. {
  3763. List<RegionInfo> airTicketRegions = new List<RegionInfo>();
  3764. foreach (var item in airTicketInfos)
  3765. {
  3766. var ticketClass = new
  3767. {
  3768. TiketClass = item.AirType,
  3769. Number = item.ClientNum
  3770. };
  3771. if (airTicketRegions.Select(it => it.Name).ToList().Contains(item.Payee))
  3772. {
  3773. RegionInfo airTicketRegion = airTicketRegions.Find(it => it.Name.Equals(item.Payee));
  3774. if (airTicketRegion != null)
  3775. {
  3776. airTicketRegions.Remove(airTicketRegion);
  3777. if (airTicketRegion.Data.Count > 0)
  3778. {
  3779. airTicketRegion.Data.Add(ticketClass);
  3780. }
  3781. airTicketRegion.Number += item.ClientNum;
  3782. airTicketRegions.Add(airTicketRegion);
  3783. }
  3784. }
  3785. else
  3786. {
  3787. airTicketRegions.Add(new RegionInfo() { Name = item.Payee, Number = item.ClientNum, Data = new List<dynamic>() { ticketClass } });
  3788. }
  3789. }
  3790. _types.Add(new TypeInfo() { Id = 3, RegionItem = airTicketRegions });
  3791. }
  3792. }
  3793. else if (type == 4)
  3794. {
  3795. //车辆
  3796. var opInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  3797. var opContentInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  3798. if (opInfos.Count > 0)
  3799. {
  3800. List<RegionInfo> opRegions = new List<RegionInfo>();
  3801. foreach (var item in opInfos)
  3802. {
  3803. int carNum = 0;
  3804. var opContentInfo = opContentInfos.Where(it => it.CTGGRId == item.Id && it.SId == 91).ToList();
  3805. if (opContentInfo.Count > 0)
  3806. {
  3807. foreach (var item1 in opContentInfo)
  3808. {
  3809. if (item1.Price > 0 && item1.Count > 0)
  3810. {
  3811. carNum += item1.Count;
  3812. }
  3813. }
  3814. }
  3815. if (carNum > 0)
  3816. {
  3817. var opData = new
  3818. {
  3819. ServiceCompany = item.ServiceCompany,
  3820. BusName = item.BusName,
  3821. Numbuer = carNum
  3822. };
  3823. if (opRegions.Select(it => it.Name).ToList().Contains(item.Area))
  3824. {
  3825. RegionInfo opRegion = opRegions.Find(it => it.Name.Equals(item.Area));
  3826. if (opRegion != null)
  3827. {
  3828. opRegions.Remove(opRegion);
  3829. if (opRegion.Data.Count > 0)
  3830. {
  3831. opRegion.Data.Add(opData);
  3832. }
  3833. opRegion.Number += carNum;
  3834. opRegions.Add(opRegion);
  3835. }
  3836. }
  3837. else
  3838. {
  3839. opRegions.Add(new RegionInfo() { Name = item.Area, Number = carNum, Data = new List<dynamic>() { opData } });
  3840. }
  3841. }
  3842. }
  3843. _types.Add(new TypeInfo() { Id = 4, RegionItem = opRegions });
  3844. }
  3845. }
  3846. #endregion
  3847. _view.TypeItem = _types;
  3848. return _view;
  3849. }
  3850. #endregion
  3851. #region 市场部销售额
  3852. /// <summary>
  3853. /// 市场部销售额
  3854. /// Init 基础数据(公司/人员/年份/季度/月份)
  3855. /// </summary>
  3856. /// <param name="_dto">市场部销售额请求dto</param>
  3857. /// <returns></returns>
  3858. [HttpPost("PostMarketingSalesInitData")]
  3859. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3860. public async Task<IActionResult> PostMarketingSalesInitData(MarketingSalesInitDataDto _dto)
  3861. {
  3862. #region 参数验证
  3863. MarketingSalesInitDataDtoFoalidator validationRules = new MarketingSalesInitDataDtoFoalidator();
  3864. var validResult = await validationRules.ValidateAsync(_dto);
  3865. if (!validResult.IsValid)
  3866. {
  3867. var errors = new StringBuilder();
  3868. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3869. return Ok(JsonView(false, errors.ToString()));
  3870. }
  3871. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3872. #region 页面操作权限验证
  3873. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3874. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3875. #endregion
  3876. var companyData = _sqlSugar.Queryable<Sys_Company>().Where(it => it.IsDel == 0)
  3877. .Select(it => new { id = it.Id, name = it.CompanyName })
  3878. .ToList();
  3879. List<int> companyIds = companyData.Select(it => it.id).ToList();
  3880. List<int> pickGroupUserIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
  3881. .Select(it => it.JietuanOperator)
  3882. .ToList();
  3883. var userData = _sqlSugar.Queryable<Sys_Users>()
  3884. .Where(it => it.IsDel == 0 && (pickGroupUserIds.Contains(it.Id) || it.Id == 21))
  3885. .Select(it => new { id = it.Id, companyId = it.CompanyId, name = it.CnName })
  3886. .ToList();
  3887. companyData.Insert(0, new { id = -1, name = "全部" });
  3888. userData.Insert(0, new { id = -1, companyId = -1, name = "全部" });
  3889. #region 年份
  3890. var dtData = new List<dynamic>();
  3891. int dt = DateTime.Now.Year;
  3892. for (int y = dt; y >= dt - 4; y--)
  3893. {
  3894. //季度
  3895. var quarterDatas = new List<dynamic>();
  3896. quarterDatas.Add(new { name = "全部", beginDt = $"{y}-01-01", endDt = $"{y}-12-31" });
  3897. for (int q = 0; q < 4; q++)
  3898. {
  3899. dynamic quarterData = null;
  3900. if (q == 0)
  3901. {
  3902. var monthDatas = new List<dynamic>();
  3903. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-01-01", endDt = $" {y}-03-31" });
  3904. for (int m = 1; m < 4; m++)
  3905. {
  3906. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  3907. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  3908. }
  3909. //quarterData = new { name = "第一季度", beginDt = $"{y}-01-01", endDt = $" {y}-03-31", monthData = monthDatas };
  3910. quarterData = new { name = "第一季度", monthData = monthDatas };
  3911. }
  3912. else if (q == 1)
  3913. {
  3914. var monthDatas = new List<dynamic>();
  3915. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-04-01", endDt = $"{y}-06-30" });
  3916. for (int m = 4; m < 7; m++)
  3917. {
  3918. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  3919. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  3920. }
  3921. //quarterData = new { name = "第二季度", beginDt = $"{y}-04-01", endDt = $"{y}-06-30", monthData = monthDatas };
  3922. quarterData = new { name = "第二季度", monthData = monthDatas };
  3923. }
  3924. else if (q == 2)
  3925. {
  3926. var monthDatas = new List<dynamic>();
  3927. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-07-01", endDt = $"{y}-09-30" });
  3928. for (int m = 7; m < 10; m++)
  3929. {
  3930. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  3931. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  3932. }
  3933. //quarterData = new { name = "第三季度", beginDt = $"{y}-07-01", endDt = $"{y}-09-30", monthData = monthDatas };
  3934. quarterData = new { name = "第三季度", monthData = monthDatas };
  3935. }
  3936. else if (q == 3)
  3937. {
  3938. var monthDatas = new List<dynamic>();
  3939. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-10-01", endDt = $"{y}-12-31" });
  3940. for (int m = 10; m < 13; m++)
  3941. {
  3942. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  3943. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  3944. }
  3945. //quarterData = new { name = "第四季度", beginDt = $"{y}-10-01", endDt = $"{y}-12-31", monthData = monthDatas };
  3946. quarterData = new { name = "第四季度", monthData = monthDatas };
  3947. }
  3948. quarterDatas.Add(quarterData);
  3949. }
  3950. dtData.Add(new
  3951. {
  3952. year = y,
  3953. //yearData = new { beginDt = $"{y}-01-01", endDt = $"{y}-12-31" },
  3954. quarterData = quarterDatas,
  3955. });
  3956. }
  3957. #endregion
  3958. return Ok(JsonView(true, "操作成功!", new { companyData = companyData, userData = userData, dtData = dtData }));
  3959. #endregion
  3960. }
  3961. private static string ConvertToChinese(int month)
  3962. {
  3963. if (month < 1 || month > 12)
  3964. throw new ArgumentOutOfRangeException(nameof(month), "月份必须在1到12之间。");
  3965. var cultureInfo = new System.Globalization.CultureInfo("zh-CN");
  3966. var dateTimeFormat = cultureInfo.DateTimeFormat;
  3967. return dateTimeFormat.GetMonthName(month);
  3968. }
  3969. /// <summary>
  3970. /// 市场部销售额
  3971. /// 年度/季度/月度 报表(同比)
  3972. /// </summary>
  3973. /// <param name="_dto">市场部销售额请求dto</param>
  3974. /// <returns></returns>
  3975. [HttpPost("PostMarketingSalesStatistics")]
  3976. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3977. public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)
  3978. {
  3979. #region 参数验证
  3980. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3981. var validResult = await validationRules.ValidateAsync(_dto);
  3982. if (!validResult.IsValid)
  3983. {
  3984. var errors = new StringBuilder();
  3985. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3986. return Ok(JsonView(false, errors.ToString()));
  3987. }
  3988. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3989. #region 页面操作权限验证
  3990. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3991. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3992. #endregion
  3993. #endregion
  3994. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  3995. return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));
  3996. }
  3997. private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)
  3998. {
  3999. //全部人员Id
  4000. //查询所有公司的市场部
  4001. var pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();
  4002. var userIds = new List<int>();
  4003. var userDatas = await _sqlSugar.Queryable<Sys_Users>()
  4004. .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)
  4005. .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains(u.Id))
  4006. .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })
  4007. .ToListAsync();
  4008. userIds = userDatas.Select(it => it.Id).ToList();
  4009. if (companyId > 0)
  4010. {
  4011. userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();
  4012. }
  4013. if (groupPickupUserId > 0)
  4014. {
  4015. userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();
  4016. }
  4017. return userIds;
  4018. }
  4019. /// <summary>
  4020. /// 计算团组销售额
  4021. /// </summary>
  4022. /// <param name="companyId"></param>
  4023. /// <param name="groupPickupUserId"></param>
  4024. /// <param name="beginDt"></param>
  4025. /// <param name="endDt"></param>
  4026. /// <returns></returns>
  4027. private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId, string beginDt, string endDt)
  4028. {
  4029. decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;
  4030. var _view = new SalesYOYView();
  4031. List<int> userIds = new List<int>();
  4032. userIds = await GetUserIds(companyId, groupPickupUserId);
  4033. string userSqlWhere = "";
  4034. if (userIds.Count > 0)
  4035. {
  4036. userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");
  4037. }
  4038. else
  4039. {
  4040. _view = new SalesYOYView
  4041. {
  4042. thisYearSales = "0.00",
  4043. lastYearSales = "0.00",
  4044. };
  4045. return _view;
  4046. }
  4047. string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),
  4048. lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
  4049. // string salesSql = string.Format(@"
  4050. //SELECT
  4051. // 'ThisSales' As [Name],
  4052. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4053. //FROM
  4054. // (
  4055. // SELECT di.VisitDate,
  4056. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4057. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4058. // ) AS Sales
  4059. // FROM
  4060. // Grp_DelegationInfo di
  4061. // WHERE di.IsDel = 0 AND di.IsSure = 1
  4062. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  4063. // AND di.VisitDate BETWEEN '{1}' AND '{2}'
  4064. // ) temp
  4065. //Union ALL
  4066. //SELECT
  4067. // 'LastSales' As [Name],
  4068. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4069. //FROM
  4070. // (
  4071. // SELECT di.VisitDate,
  4072. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4073. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4074. // ) AS Sales
  4075. // FROM
  4076. // Grp_DelegationInfo di
  4077. // WHERE di.IsDel = 0 AND di.IsSure = 1
  4078. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  4079. // AND di.VisitDate BETWEEN '{4}' AND '{5}'
  4080. // ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  4081. string salesSql = string.Format(@"
  4082. SELECT
  4083. 'ThisSales' As [Name],
  4084. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4085. FROM
  4086. (
  4087. SELECT di.VisitDate,
  4088. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4089. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4090. ) AS Sales
  4091. FROM
  4092. Grp_DelegationInfo di
  4093. WHERE di.IsDel = 0
  4094. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  4095. AND di.VisitDate BETWEEN '{1}' AND '{2}'
  4096. ) temp
  4097. Union ALL
  4098. SELECT
  4099. 'LastSales' As [Name],
  4100. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4101. FROM
  4102. (
  4103. SELECT di.VisitDate,
  4104. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4105. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4106. ) AS Sales
  4107. FROM
  4108. Grp_DelegationInfo di
  4109. WHERE di.IsDel = 0
  4110. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  4111. AND di.IsBid = 0
  4112. AND di.TeamName Not Like '%投标%'
  4113. AND di.VisitDate BETWEEN '{4}' AND '{5}'
  4114. ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  4115. var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();
  4116. thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;
  4117. lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;
  4118. if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;
  4119. return new SalesYOYView()
  4120. {
  4121. thisYearSales = thisSales.ToString("#0.00"),
  4122. lastYearSales = lastSales.ToString("#0.00"),
  4123. yoy = yoy.ToString("#0.00")
  4124. };
  4125. }
  4126. private class SalesView
  4127. {
  4128. public string Name { get; set; }
  4129. public decimal Sales { get; set; }
  4130. }
  4131. private class SalesYOYView
  4132. {
  4133. public string thisYearSales { get; set; }
  4134. public string lastYearSales { get; set; }
  4135. public string yoy { get; set; } = "1.00";
  4136. }
  4137. /// <summary>
  4138. /// 市场部销售额
  4139. /// 团组列表
  4140. /// </summary>
  4141. /// <param name="_dto">市场部销售额请求dto</param>
  4142. /// <returns></returns>
  4143. [HttpPost("PostMarketingSalesGroupList")]
  4144. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4145. public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)
  4146. {
  4147. #region 参数验证
  4148. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4149. var validResult = await validationRules.ValidateAsync(_dto);
  4150. if (!validResult.IsValid)
  4151. {
  4152. var errors = new StringBuilder();
  4153. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4154. return Ok(JsonView(false, errors.ToString()));
  4155. }
  4156. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4157. #region 页面操作权限验证
  4158. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4159. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4160. #endregion
  4161. #endregion
  4162. string userSql = "";
  4163. List<int> userIds = new List<int>();
  4164. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4165. if (userIds.Count <= 0)
  4166. {
  4167. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4168. }
  4169. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4170. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4171. {
  4172. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4173. }
  4174. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4175. // string sql = string.Format(@$"SELECT
  4176. // ROW_NUMBER() OVER (
  4177. // ORDER BY
  4178. // CollectionDays
  4179. // ) AS RowNumber,
  4180. // *
  4181. //FROM
  4182. // (
  4183. // SELECT
  4184. // di.Id,
  4185. // di.TeamName,
  4186. // di.ClientUnit,
  4187. // di.ClientName,
  4188. // di.VisitDate,
  4189. // di.VisitPNumber,
  4190. // di.JietuanOperator,
  4191. // di.VisitEndDate,
  4192. // (
  4193. // SELECT
  4194. // CAST(
  4195. // COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4196. // ) AS GroupSales
  4197. // FROM
  4198. // Fin_ForeignReceivables
  4199. // WHERE
  4200. // IsDel = 0
  4201. // AND di.Id = Diid
  4202. // AND AddingWay IN (0, 1, 2)
  4203. // ) AS GroupSales,
  4204. // u.CnName AS GroupPickupUser,
  4205. // DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4206. // FROM
  4207. // Grp_DelegationInfo di
  4208. // WITH
  4209. // (NoLock)
  4210. // LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4211. // WHERE
  4212. // di.Isdel = 0
  4213. // AND di.IsSure = 1 {userSql}
  4214. // AND VisitDate Between '{beginDt}' And '{endDt}'
  4215. // ) Temp ");
  4216. string sql = string.Format(@$"SELECT
  4217. ROW_NUMBER() OVER (
  4218. ORDER BY
  4219. CollectionDays
  4220. ) AS RowNumber,
  4221. *
  4222. FROM
  4223. (
  4224. SELECT
  4225. di.Id,
  4226. di.TeamName,
  4227. di.ClientUnit,
  4228. di.ClientName,
  4229. di.VisitDate,
  4230. di.VisitPNumber,
  4231. di.JietuanOperator,
  4232. di.VisitEndDate,
  4233. (
  4234. SELECT
  4235. CAST(
  4236. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4237. ) AS GroupSales
  4238. FROM
  4239. Fin_ForeignReceivables
  4240. WHERE
  4241. IsDel = 0
  4242. AND di.Id = Diid
  4243. AND AddingWay IN (0, 1, 2)
  4244. ) AS GroupSales,
  4245. u.CnName AS GroupPickupUser,
  4246. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4247. FROM
  4248. Grp_DelegationInfo di
  4249. WITH
  4250. (NoLock)
  4251. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4252. WHERE
  4253. di.Isdel = 0
  4254. AND (
  4255. SELECT
  4256. CAST(
  4257. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4258. ) AS GroupSales
  4259. FROM
  4260. Fin_ForeignReceivables
  4261. WHERE
  4262. IsDel = 0
  4263. AND di.Id = Diid
  4264. AND AddingWay IN (0, 1, 2)
  4265. ) > 0
  4266. {userSql}
  4267. AND di.IsBid = 0
  4268. AND di.TeamName Not Like '%投标%'
  4269. AND VisitDate Between '{beginDt}' And '{endDt}'
  4270. ) Temp ");
  4271. RefAsync<int> total = 0;
  4272. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4273. return Ok(JsonView(true, "操作成功!", groupData, total));
  4274. }
  4275. /// <summary>
  4276. /// 市场部销售额
  4277. /// 团组列表Excel下载
  4278. /// </summary>
  4279. /// <param name="_dto">市场部销售额请求dto</param>
  4280. /// <returns></returns>
  4281. [HttpPost("PostMarketingSalesGroupExcel")]
  4282. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4283. public async Task<IActionResult> PostMarketingSalesGroupExcel(MarketingSalesGroupListDto _dto)
  4284. {
  4285. #region 参数验证
  4286. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4287. var validResult = await validationRules.ValidateAsync(_dto);
  4288. if (!validResult.IsValid)
  4289. {
  4290. var errors = new StringBuilder();
  4291. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4292. return Ok(JsonView(false, errors.ToString()));
  4293. }
  4294. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4295. #region 页面操作权限验证
  4296. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4297. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4298. #endregion
  4299. #endregion
  4300. string userSql = "";
  4301. var userIds = new List<int>();
  4302. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4303. if (userIds.Count <= 0)
  4304. {
  4305. return Ok(JsonView(false));
  4306. }
  4307. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4308. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4309. {
  4310. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4311. }
  4312. string beginDt = $"{_dto.BeginDt} 00:00:00",
  4313. endDt = $"{_dto.EndDt} 23:59:59";
  4314. string sql = string.Format(@$"SELECT
  4315. ROW_NUMBER() OVER (
  4316. ORDER BY
  4317. CollectionDays
  4318. ) AS RowNumber,
  4319. *
  4320. FROM
  4321. (
  4322. SELECT
  4323. di.Id,
  4324. di.TeamName,
  4325. di.ClientUnit,
  4326. di.ClientName,
  4327. di.VisitDate,
  4328. di.VisitPNumber,
  4329. di.JietuanOperator,
  4330. di.VisitEndDate,
  4331. (
  4332. SELECT
  4333. CAST(
  4334. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4335. ) AS GroupSales
  4336. FROM
  4337. Fin_ForeignReceivables
  4338. WHERE
  4339. IsDel = 0
  4340. AND di.Id = Diid
  4341. AND AddingWay IN (0, 1, 2)
  4342. ) AS GroupSales,
  4343. u.CnName AS GroupPickupUser,
  4344. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4345. FROM
  4346. Grp_DelegationInfo di
  4347. WITH
  4348. (NoLock)
  4349. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4350. WHERE
  4351. di.Isdel = 0
  4352. AND (
  4353. SELECT
  4354. CAST(
  4355. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4356. ) AS GroupSales
  4357. FROM
  4358. Fin_ForeignReceivables
  4359. WHERE
  4360. IsDel = 0
  4361. AND di.Id = Diid
  4362. AND AddingWay IN (0, 1, 2)
  4363. ) > 0
  4364. {userSql}
  4365. AND di.IsBid = 0
  4366. AND di.TeamName Not Like '%投标%'
  4367. AND VisitDate Between '{beginDt}' And '{endDt}'
  4368. ) Temp ");
  4369. var view = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToListAsync();
  4370. if (view.Count < 1) return Ok(JsonView(false, "暂无数据!"));
  4371. //DataTable dt = GeneralMethod.
  4372. DataTable dt = CommonFun.GetDataTableFromIList(view);
  4373. dt.TableName = $"_view";
  4374. WorkbookDesigner designer = new WorkbookDesigner();
  4375. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/营业额团组报表模板.xls");
  4376. designer.SetDataSource(dt);
  4377. designer.SetDataSource("Total", view.Sum(x => x.GroupSales));
  4378. designer.Workbook.Worksheets[0].Name = "营业额团组报表";
  4379. designer.Process();
  4380. string fileName = $"MarketingSales/{_dto.BeginDt}~{_dto.EndDt}营业额团组报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  4381. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  4382. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  4383. return Ok(JsonView(true, "操作成功", new { url = rst }));
  4384. }
  4385. /// <summary>
  4386. /// 市场部销售额
  4387. /// 客户类型、客户等级 统计
  4388. /// </summary>
  4389. /// <param name="_dto">市场部销售额请求dto</param>
  4390. /// <returns></returns>
  4391. [HttpPost("PostMarketingSalesGroupStatistics")]
  4392. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4393. public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)
  4394. {
  4395. #region 参数验证
  4396. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4397. var validResult = await validationRules.ValidateAsync(_dto);
  4398. if (!validResult.IsValid)
  4399. {
  4400. var errors = new StringBuilder();
  4401. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4402. return Ok(JsonView(false, errors.ToString()));
  4403. }
  4404. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4405. #region 页面操作权限验证
  4406. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4407. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4408. #endregion
  4409. #endregion
  4410. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4411. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4412. string userSql = "";
  4413. if (userIds.Count > 0)
  4414. {
  4415. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  4416. }
  4417. else
  4418. {
  4419. if (_dto.PortType == 2 || _dto.PortType == 3)
  4420. {
  4421. return Ok(JsonView(true, "操作成功!", new List<object> { }));
  4422. }
  4423. else
  4424. {
  4425. return Ok(JsonView(true, "操作成功!", new
  4426. {
  4427. customerTypeData = new List<object> { },
  4428. clientGradeData = new List<object> { }
  4429. }));
  4430. }
  4431. }
  4432. string sql = "";
  4433. if (_dto.StatisticsType == 1)
  4434. {
  4435. sql = string.Format(@$"Select
  4436. sd.[Name],
  4437. Count(*) As [Count]
  4438. From Grp_DelegationInfo di
  4439. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4440. Where di.Isdel = 0
  4441. And (
  4442. SELECT
  4443. CAST(
  4444. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4445. ) AS GroupSales
  4446. FROM
  4447. Fin_ForeignReceivables fr
  4448. WHERE
  4449. fr.IsDel = 0
  4450. AND di.Id = fr.Diid
  4451. AND AddingWay IN (0, 1, 2)
  4452. ) > 0
  4453. {userSql}
  4454. AND di.IsBid = 0
  4455. AND di.TeamName Not Like '%投标%'
  4456. And VisitDate Between '{beginDt}' And '{endDt}'
  4457. Group By [Name]
  4458. Order By Count Desc");
  4459. }
  4460. else if (_dto.StatisticsType == 2)
  4461. {
  4462. sql = string.Format(@$"Select
  4463. sd.[Name],
  4464. Count(*) As [Count]
  4465. From Grp_DelegationInfo di
  4466. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4467. Where di.Isdel = 0
  4468. And (
  4469. SELECT
  4470. CAST(
  4471. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4472. ) AS GroupSales
  4473. FROM
  4474. Fin_ForeignReceivables fr
  4475. WHERE
  4476. fr.IsDel = 0
  4477. AND di.Id = fr.Diid
  4478. AND AddingWay IN (0, 1, 2)
  4479. ) > 0
  4480. {userSql}
  4481. AND di.IsBid = 0
  4482. AND di.TeamName Not Like '%投标%'
  4483. And VisitDate Between '{beginDt}' And '{endDt}'
  4484. Group By [Name]
  4485. Order By Count Desc");
  4486. }
  4487. else return Ok(JsonView(false, "StatisticsType不在可取范围!"));
  4488. if (_dto.PortType == 1)
  4489. {
  4490. string sql1 = string.Format(@$"Select
  4491. sd.[Name],
  4492. Count(*) As [Count]
  4493. From Grp_DelegationInfo di
  4494. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4495. Where di.Isdel = 0
  4496. And (
  4497. SELECT
  4498. CAST(
  4499. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4500. ) AS GroupSales
  4501. FROM
  4502. Fin_ForeignReceivables fr
  4503. WHERE
  4504. fr.IsDel = 0
  4505. AND di.Id = fr.Diid
  4506. AND AddingWay IN (0, 1, 2)
  4507. ) > 0
  4508. {userSql}
  4509. AND di.IsBid = 0
  4510. AND di.TeamName Not Like '%投标%'
  4511. And VisitDate Between '{beginDt}' And '{endDt}'
  4512. Group By [Name]
  4513. Order By Count Desc");
  4514. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  4515. string sql2 = string.Format(@$"Select
  4516. sd.[Name],
  4517. Count(*) As [Count]
  4518. From Grp_DelegationInfo di
  4519. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4520. Where di.Isdel = 0
  4521. And (
  4522. SELECT
  4523. CAST(
  4524. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4525. ) AS GroupSales
  4526. FROM
  4527. Fin_ForeignReceivables fr
  4528. WHERE
  4529. fr.IsDel = 0
  4530. AND di.Id = fr.Diid
  4531. AND AddingWay IN (0, 1, 2)
  4532. ) > 0
  4533. {userSql}
  4534. AND di.IsBid = 0
  4535. AND di.TeamName Not Like '%投标%'
  4536. And VisitDate Between '{beginDt}' And '{endDt}'
  4537. Group By [Name]
  4538. Order By Count Desc");
  4539. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  4540. return Ok(JsonView(true, "操作成功!", new
  4541. {
  4542. customerTypeData = customerTypeData,
  4543. clientGradeData = clientGradeData
  4544. }));
  4545. }
  4546. else if (_dto.PortType == 2 || _dto.PortType == 3)
  4547. {
  4548. var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();
  4549. return Ok(JsonView(true, "操作成功!", data, data.Count));
  4550. }
  4551. else return Ok(JsonView(false, MsgTips.Port));
  4552. }
  4553. /// <summary>
  4554. /// 市场部销售额
  4555. /// 接单排名
  4556. /// </summary>
  4557. /// <param name="_dto">市场部销售额请求dto</param>
  4558. /// <returns></returns>
  4559. [HttpPost("PostMarketingSalesOrderRanking")]
  4560. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4561. public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)
  4562. {
  4563. #region 参数验证
  4564. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4565. var validResult = await validationRules.ValidateAsync(_dto);
  4566. if (!validResult.IsValid)
  4567. {
  4568. var errors = new StringBuilder();
  4569. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4570. return Ok(JsonView(false, errors.ToString()));
  4571. }
  4572. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4573. #region 页面操作权限验证
  4574. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4575. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4576. #endregion
  4577. #endregion
  4578. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4579. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4580. string userSql = "";
  4581. if (userIds.Count > 0)
  4582. {
  4583. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  4584. }
  4585. else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4586. string sql = string.Format(@$"Select
  4587. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  4588. u.CnName As UserName,
  4589. Count(*) As [Count]
  4590. From Grp_DelegationInfo di
  4591. Left Join Sys_Users u On di.JietuanOperator = u.Id
  4592. Where di.Isdel = 0
  4593. AND (
  4594. SELECT
  4595. CAST(
  4596. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4597. ) AS GroupSales
  4598. FROM
  4599. Fin_ForeignReceivables fr
  4600. WHERE
  4601. fr.IsDel = 0
  4602. AND di.Id = fr.Diid
  4603. AND AddingWay IN (0, 1, 2)
  4604. ) > 0
  4605. {userSql}
  4606. AND di.IsBid = 0
  4607. AND di.TeamName Not Like '%投标%'
  4608. AND VisitDate Between '{beginDt}' AND '{endDt}'
  4609. Group By CnName");
  4610. RefAsync<int> total = 0;
  4611. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4612. return Ok(JsonView(true, "操作成功!", rankingData, total));
  4613. }
  4614. /// <summary>
  4615. /// 市场部销售额
  4616. /// 团组列表、客户类型、客户等级、接单排名
  4617. /// </summary>
  4618. /// <param name="_dto">市场部销售额请求dto</param>
  4619. /// <returns></returns>
  4620. [HttpPost("PostMarketingSalesGroupItem")]
  4621. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4622. public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)
  4623. {
  4624. #region 参数验证
  4625. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4626. var validResult = await validationRules.ValidateAsync(_dto);
  4627. if (!validResult.IsValid)
  4628. {
  4629. var errors = new StringBuilder();
  4630. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4631. return Ok(JsonView(false, errors.ToString()));
  4632. }
  4633. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4634. #region 页面操作权限验证
  4635. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4636. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4637. #endregion
  4638. #endregion
  4639. string userSql = "";
  4640. List<int> userIds = new List<int>();
  4641. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4642. if (userIds.Count <= 0)
  4643. {
  4644. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4645. }
  4646. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4647. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4648. {
  4649. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4650. }
  4651. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4652. #region 团组List
  4653. string sql = string.Format(@$"SELECT
  4654. ROW_NUMBER() OVER (
  4655. ORDER BY
  4656. CollectionDays
  4657. ) AS RowNumber,
  4658. *
  4659. FROM
  4660. (
  4661. SELECT
  4662. di.Id,
  4663. di.TeamName,
  4664. di.ClientUnit,
  4665. di.ClientName,
  4666. di.VisitDate,
  4667. di.VisitPNumber,
  4668. di.JietuanOperator,
  4669. di.VisitEndDate,
  4670. (
  4671. SELECT
  4672. CAST(
  4673. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4674. ) AS GroupSales
  4675. FROM
  4676. Fin_ForeignReceivables
  4677. WHERE
  4678. IsDel = 0
  4679. AND di.Id = Diid
  4680. AND AddingWay IN (0, 1, 2)
  4681. ) AS GroupSales,
  4682. u.CnName AS GroupPickupUser,
  4683. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4684. FROM
  4685. Grp_DelegationInfo di
  4686. WITH
  4687. (NoLock)
  4688. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4689. WHERE
  4690. di.Isdel = 0
  4691. AND (
  4692. SELECT
  4693. CAST(
  4694. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4695. ) AS GroupSales
  4696. FROM
  4697. Fin_ForeignReceivables fr
  4698. WHERE
  4699. fr.IsDel = 0
  4700. AND di.Id = fr.Diid
  4701. AND AddingWay IN (0, 1, 2)
  4702. ) > 0
  4703. {userSql}
  4704. AND di.IsBid = 0
  4705. AND di.TeamName Not Like '%投标%'
  4706. AND VisitDate Between '{beginDt}' And '{endDt}'
  4707. ) Temp ");
  4708. RefAsync<int> total = 0;
  4709. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4710. #endregion
  4711. #region 客户类型、客户等级 统计
  4712. string sql1 = string.Format(@$"Select
  4713. sd.[Name],
  4714. Count(*) As [Count]
  4715. From Grp_DelegationInfo di
  4716. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4717. Where di.Isdel = 0
  4718. And (
  4719. SELECT
  4720. CAST(
  4721. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4722. ) AS GroupSales
  4723. FROM
  4724. Fin_ForeignReceivables fr
  4725. WHERE
  4726. fr.IsDel = 0
  4727. AND di.Id = fr.Diid
  4728. AND AddingWay IN (0, 1, 2)
  4729. ) > 0
  4730. {userSql}
  4731. AND di.IsBid = 0
  4732. AND di.TeamName Not Like '%投标%'
  4733. And VisitDate Between '{beginDt}' And '{endDt}'
  4734. Group By [Name]
  4735. Order By Count Desc");
  4736. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  4737. string sql2 = string.Format(@$"Select
  4738. sd.[Name],
  4739. Count(*) As [Count]
  4740. From Grp_DelegationInfo di
  4741. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4742. Where di.Isdel = 0
  4743. And (
  4744. SELECT
  4745. CAST(
  4746. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4747. ) AS GroupSales
  4748. FROM
  4749. Fin_ForeignReceivables fr
  4750. WHERE
  4751. fr.IsDel = 0
  4752. AND di.Id = fr.Diid
  4753. AND AddingWay IN (0, 1, 2)
  4754. ) > 0
  4755. {userSql}
  4756. AND di.IsBid = 0
  4757. AND di.TeamName Not Like '%投标%'
  4758. And VisitDate Between '{beginDt}' And '{endDt}'
  4759. Group By [Name]
  4760. Order By Count Desc");
  4761. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  4762. #endregion
  4763. #region 接单排名
  4764. string sql4 = string.Format(@$"Select
  4765. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  4766. u.CnName As UserName,
  4767. Count(*) As [Count]
  4768. From Grp_DelegationInfo di
  4769. Left Join Sys_Users u On di.JietuanOperator = u.Id
  4770. Where di.Isdel = 0
  4771. And (
  4772. SELECT
  4773. CAST(
  4774. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4775. ) AS GroupSales
  4776. FROM
  4777. Fin_ForeignReceivables fr
  4778. WHERE
  4779. fr.IsDel = 0
  4780. AND di.Id = fr.Diid
  4781. AND AddingWay IN (0, 1, 2)
  4782. ) > 0
  4783. {userSql}
  4784. AND di.IsBid = 0
  4785. AND di.TeamName Not Like '%投标%'
  4786. And VisitDate Between '{beginDt}' And '{endDt}'
  4787. Group By CnName");
  4788. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();
  4789. #endregion
  4790. var viewData = new
  4791. {
  4792. groupData = groupData,
  4793. groupTotal = total,
  4794. customerTypeData = customerTypeData,
  4795. clientGradeData = clientGradeData,
  4796. rankingData = rankingData
  4797. };
  4798. return Ok(JsonView(true, "操作成功!", viewData, total));
  4799. }
  4800. /// <summary>
  4801. /// 市场部销售额
  4802. /// 客户拜访列表
  4803. /// </summary>
  4804. /// <param name="_dto">市场部销售额请求dto</param>
  4805. /// <returns></returns>
  4806. [HttpPost("PostMarketingSalesVCList")]
  4807. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4808. public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)
  4809. {
  4810. #region 参数验证
  4811. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  4812. var validResult = await validationRules.ValidateAsync(_dto);
  4813. if (!validResult.IsValid)
  4814. {
  4815. var errors = new StringBuilder();
  4816. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4817. return Ok(JsonView(false, errors.ToString()));
  4818. }
  4819. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4820. #region 页面操作权限验证
  4821. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4822. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4823. #endregion
  4824. #endregion
  4825. return Ok(await _visitingClientsRep._List(_dto.PortType, _dto.PageIndex, _dto.PageSize, _dto.DiId, _dto.Search));
  4826. }
  4827. /// <summary>
  4828. /// 市场部销售额
  4829. /// 客户拜访 操作(添加 Or 编辑)
  4830. /// </summary>
  4831. /// <param name="_dto">市场部销售额请求dto</param>
  4832. /// <returns></returns>
  4833. [HttpPost("PostMarketingSalesVCOperate")]
  4834. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4835. public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)
  4836. {
  4837. #region 参数验证
  4838. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  4839. var validResult = await validationRules.ValidateAsync(_dto);
  4840. if (!validResult.IsValid)
  4841. {
  4842. var errors = new StringBuilder();
  4843. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4844. return Ok(JsonView(false, errors.ToString()));
  4845. }
  4846. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4847. #region 页面操作权限验证
  4848. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4849. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4850. #endregion
  4851. #endregion
  4852. return Ok(await _visitingClientsRep._AddOrEdit(_dto));
  4853. }
  4854. /// <summary>
  4855. /// 市场部销售额
  4856. /// 客户拜访 Del
  4857. /// </summary>
  4858. /// <param name="_dto">市场部销售额请求dto</param>
  4859. /// <returns></returns>
  4860. [HttpPost("PostMarketingSalesVCDel")]
  4861. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4862. public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)
  4863. {
  4864. return Ok(await _visitingClientsRep._Del(_dto.Id, _dto.UserId));
  4865. }
  4866. /// <summary>
  4867. /// 市场部销售额
  4868. /// 客户拜访 操作 save
  4869. /// </summary>
  4870. /// <param name="_dto">市场部销售额请求dto</param>
  4871. /// <returns></returns>
  4872. [HttpPost("PostMarketingSalesVCSave")]
  4873. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4874. public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)
  4875. {
  4876. #region 参数验证
  4877. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  4878. var validResult = await validationRules.ValidateAsync(_dto);
  4879. if (!validResult.IsValid)
  4880. {
  4881. var errors = new StringBuilder();
  4882. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4883. return Ok(JsonView(false, errors.ToString()));
  4884. }
  4885. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4886. #region 页面操作权限验证
  4887. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4888. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4889. #endregion
  4890. #endregion
  4891. return Ok(await _visitingClientsRep._Save(_dto));
  4892. }
  4893. #endregion
  4894. #region 日付报表
  4895. /// <summary>
  4896. /// 日付类型数据
  4897. /// </summary>
  4898. /// <param name="_dto"></param>
  4899. /// <returns></returns>
  4900. [HttpPost("DailypaymentTypeInit")]
  4901. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4902. public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)
  4903. {
  4904. #region 参数验证
  4905. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  4906. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4907. #region 页面操作权限验证
  4908. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4909. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  4910. #endregion
  4911. #endregion
  4912. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  4913. {
  4914. var defaultParentIds = new List<int>()
  4915. {
  4916. 48,// 人员费用
  4917. 49,// 办公费用
  4918. 50,// 销售费用
  4919. 51,// 其他费用
  4920. 55,// 大运会
  4921. };
  4922. var dailypaymentTypeData = await RedisRepository.RedisFactory
  4923. .CreateRedisRepository()
  4924. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  4925. var dailyTypeData = await _sqlSugar.Queryable<DailypaymentParentTypeView>()
  4926. .Includes(x => x.SubData)
  4927. .Where(x => defaultParentIds.Contains(x.Id))
  4928. .ToListAsync();
  4929. dailyTypeData.ForEach(x =>
  4930. {
  4931. x.SubData.ForEach(y =>
  4932. {
  4933. int currId = dailypaymentTypeData.Find(z => z == y.Id);
  4934. y.IsChecked = currId != 0;
  4935. });
  4936. });
  4937. var companyData = await _sqlSugar.Queryable<Sys_Company>()
  4938. .Where(x => x.IsDel == 0)
  4939. .Select(x => new { id = x.Id, name = x.CompanyName })
  4940. .ToListAsync();
  4941. return Ok(JsonView(true, "查询成功!", new { dailyTypeData, companyData }));
  4942. }
  4943. else return Ok(JsonView(false, "查询失败"));
  4944. }
  4945. /// <summary>
  4946. /// 日付类型数据 Save
  4947. /// </summary>
  4948. /// <param name="_dto"></param>
  4949. /// <returns></returns>
  4950. [HttpPost("DailypaymentTypeDataSave")]
  4951. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4952. public async Task<IActionResult> DailypaymentTypeDataSave(DailypaymentTypeDataSaveDto _dto)
  4953. {
  4954. #region 参数验证
  4955. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  4956. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4957. #region 页面操作权限验证
  4958. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4959. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  4960. #endregion
  4961. #endregion
  4962. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  4963. {
  4964. if (_dto.TypeIds.Count < 1) return Ok(JsonView(false, "请传入需要保存的TypeIds"));
  4965. var res = await RedisRepository.RedisFactory
  4966. .CreateRedisRepository()
  4967. .StringSetAsync(
  4968. key: "DailypaymentTypeData",
  4969. _dto.TypeIds,
  4970. timeout: null);
  4971. if (!res) return Ok(JsonView(false, "操作失败"));
  4972. return Ok(JsonView(true, "操作成功!"));
  4973. }
  4974. else return Ok(JsonView(false, "操作失败"));
  4975. }
  4976. /// <summary>
  4977. /// 日付数据列表
  4978. /// </summary>
  4979. /// <param name="_dto"></param>
  4980. /// <returns></returns>
  4981. [HttpPost("DailypaymentRange")]
  4982. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4983. public async Task<IActionResult> DailypaymentRange(DailypaymentRangeDto _dto)
  4984. {
  4985. #region 参数验证
  4986. var validator = new DailypaymentRangeDtoValidator();
  4987. var validationRes = validator.Validate(_dto);
  4988. if (!validationRes.IsValid)
  4989. {
  4990. StringBuilder sb = new StringBuilder();
  4991. foreach (var item in validationRes.Errors)
  4992. {
  4993. sb.AppendLine(item.ErrorMessage);
  4994. }
  4995. return Ok(JsonView(false, sb.ToString()));
  4996. }
  4997. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4998. #region 页面操作权限验证
  4999. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5000. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  5001. #endregion
  5002. #endregion
  5003. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  5004. {
  5005. DateTime _beginDt = Convert.ToDateTime($"{_dto.BeginDt} 00:00:00"),
  5006. _endDt = Convert.ToDateTime($"{_dto.EndDt} 23:59:59");
  5007. var sqlWhere = string.Format(@" And dfp.CreateTime Between '{0}' And '{1}'", _beginDt, _endDt);
  5008. var dailypaymentTypeData = await RedisRepository.RedisFactory
  5009. .CreateRedisRepository()
  5010. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  5011. var sql = string.Format(@"
  5012. Select
  5013. dfp.Id,
  5014. dfp.Instructions,
  5015. dfp.PriceTypeId,
  5016. sd1.Name As FeeType,
  5017. dfp.TransferTypeId,
  5018. sd2.Name As TransferType,
  5019. dfp.SumPrice,
  5020. dfp.FAuditDate,
  5021. dfp.MAuditDate,
  5022. dfp.CompanyId,
  5023. c.CompanyName,
  5024. dfp.CreateUserId As ApplicantId,
  5025. u.CnName As Applicant,
  5026. dfp.CreateTime As ApplicantDt,
  5027. dfp.Instructions+u.CnName As ViewStr
  5028. From Fin_DailyFeePayment dfp
  5029. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  5030. Left Join Sys_SetData sd1 On dfp.TransferTypeId = sd1.Id
  5031. Left Join Sys_Company c On dfp.CompanyId = c.Id
  5032. Left Join Sys_SetData sd2 On dfp.PriceTypeId = sd2.Id
  5033. Where dfp.IsDel = 0 And dfp.IsPay = 1
  5034. ");//--Order By dfp.CreateTime Desc
  5035. if (_dto.Type == 1) //data
  5036. {
  5037. RefAsync<int> total = 0;
  5038. var _view = await _sqlSugar.SqlQueryable<DailyFeePaymentRangeView>(sql)
  5039. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  5040. .WhereIF(dailypaymentTypeData.Count > 0,
  5041. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  5042. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  5043. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  5044. .OrderByDescending(x => x.ApplicantDt)
  5045. .ToPageListAsync(
  5046. pageNumber: _dto.PageIndex,
  5047. pageSize: _dto.PageSize,
  5048. totalNumber: total
  5049. );
  5050. _sqlSugar.ThenMapper(_view, x =>
  5051. {
  5052. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  5053. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  5054. .ToList();
  5055. });
  5056. //单独处理
  5057. return Ok(JsonView(true, "操作成功!", new { data = _view, total = _view.Sum(x => x.SumPrice) }, total));
  5058. }
  5059. else if (_dto.Type == 2) //view
  5060. {
  5061. var _view = await _sqlSugar.SqlQueryable<ExcelView>(sql)
  5062. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  5063. .WhereIF(dailypaymentTypeData.Count > 0,
  5064. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  5065. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  5066. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  5067. .OrderByDescending(x => x.ApplicantDt)
  5068. .ToPageListAsync(
  5069. pageNumber: 1,
  5070. pageSize: 99999
  5071. );
  5072. _sqlSugar.ThenMapper(_view, x =>
  5073. {
  5074. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  5075. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  5076. .ToList();
  5077. string str = "";
  5078. int index = 1;
  5079. foreach (var item in x.Contents)
  5080. {
  5081. string str1 = $"{index}、费用名称:[{item.PriceName}] 单价:[{item.Price:#0.00}] 数量:[{item.Quantity:#0.00}] 小计:[{item.ItemTotal:#0.00}] 备注:[{item.Remark}]";
  5082. if (index == x.Contents.Count) str += str1;
  5083. else str += str1 + "\r\n";
  5084. index++;
  5085. }
  5086. x.ContentStr = str;
  5087. });
  5088. if (_view.Count > 0)
  5089. {
  5090. //DataTable dt = GeneralMethod.
  5091. DataTable dt = CommonFun.GetDataTableFromIList(_view);
  5092. dt.TableName = $"_view";
  5093. decimal total = _view.Sum(x => x.SumPrice);
  5094. WorkbookDesigner designer = new WorkbookDesigner();
  5095. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/日付报表模板.xls");
  5096. designer.SetDataSource(dt);
  5097. designer.SetDataSource("Total", total);
  5098. designer.Workbook.Worksheets[0].Name = "日付报表";
  5099. designer.Process();
  5100. string fileName = $"DailyPayment/日付报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  5101. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  5102. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  5103. return Ok(JsonView(true, "操作成功", new { url = rst }));
  5104. }
  5105. return Ok(JsonView(true, ",暂无数据"));
  5106. }
  5107. return Ok(JsonView(false, "操作失败"));
  5108. }
  5109. else return Ok(JsonView(false, "操作失败"));
  5110. }
  5111. #endregion
  5112. #region 统计模块
  5113. /// <summary>
  5114. /// 同比
  5115. /// 营业额(今年和去年的)、成本支出(今年和去年的)、毛利润(今年和去年的)
  5116. /// </summary>
  5117. /// <param name="_dto">市场部销售额请求dto</param>
  5118. /// <returns></returns>
  5119. [HttpPost("StatisticsYOY")]
  5120. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5121. public async Task<IActionResult> StatisticsYOY(YOYDto _dto)
  5122. {
  5123. //同比增长率 = (本期 - 同期) / 同期 * 100%;
  5124. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5125. string beginDt = $"{_dto.Year - 1}-01-01 00:00:00",
  5126. endDt = $"{_dto.Year}-12-31 23:59:59";
  5127. string sql = string.Format(@"
  5128. SELECT
  5129. di.Id,
  5130. di.TeamName,
  5131. di.VisitDate,
  5132. YEAR(di.VisitDate) AS YEAR,
  5133. MONTH(di.VisitDate) AS MONTH,
  5134. (
  5135. SELECT
  5136. CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
  5137. FROM
  5138. Fin_ForeignReceivables
  5139. WHERE
  5140. IsDel = 0
  5141. AND AddingWay IN (0, 1, 2)
  5142. AND di.Id = Diid
  5143. ) AS SaleAmount,
  5144. (
  5145. SELECT
  5146. CAST(
  5147. SUM(
  5148. (
  5149. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  5150. )
  5151. ) AS DECIMAL(12, 2)
  5152. )
  5153. FROM
  5154. Grp_AirTicketReservations atr
  5155. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5156. AND ccp.CTable = 85
  5157. AND atr.Id = ccp.CId
  5158. WHERE
  5159. atr.IsDel = 0
  5160. AND ccp.IsAuditGM = 1
  5161. AND ccp.IsPay = 1
  5162. AND di.Id = atr.DiId
  5163. ) AirTicketAmount,
  5164. (
  5165. SELECT
  5166. CAST(
  5167. SUM(
  5168. (
  5169. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  5170. )
  5171. ) AS DECIMAL(12, 2)
  5172. )
  5173. FROM
  5174. Grp_CarTouristGuideGroundReservations ctggr
  5175. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  5176. AND ccp.CTable = 79
  5177. AND ctggr.Id = ccp.CId
  5178. WHERE
  5179. ctggr.IsDel = 0
  5180. AND ccp.IsAuditGM = 1
  5181. AND ccp.IsPay = 1
  5182. AND di.Id = ctggr.DiId
  5183. ) AS OPAmount,
  5184. (
  5185. SELECT
  5186. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  5187. FROM
  5188. Grp_DecreasePayments dp
  5189. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5190. AND ccp.CTable = 98
  5191. AND dp.Id = ccp.CId
  5192. WHERE
  5193. dp.IsDel = 0
  5194. AND ccp.Ctable = 98
  5195. AND ccp.IsAuditGM = 1
  5196. AND ccp.IsPay = 1
  5197. AND di.Id = dp.Diid
  5198. ) AS OtherCostAmount,
  5199. (
  5200. SELECT
  5201. CAST(
  5202. SUM(
  5203. (
  5204. (ccp.PayMoney * ccp.DayRate)
  5205. )
  5206. ) AS DECIMAL(12, 2)
  5207. )
  5208. FROM
  5209. Grp_VisaInfo vi
  5210. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5211. AND ccp.CTable = 80
  5212. AND vi.Id = ccp.CId
  5213. WHERE
  5214. vi.IsDel = 0
  5215. AND ccp.IsAuditGM = 1
  5216. AND ccp.IsPay = 1
  5217. AND di.Id = vi.DIId
  5218. ) AS VisaAmount,
  5219. (
  5220. SELECT
  5221. CAST(
  5222. SUM(
  5223. (ccp.PayMoney * ccp.DayRate)
  5224. ) AS DECIMAL(12, 2)
  5225. )
  5226. FROM
  5227. Grp_InvitationOfficialActivities ioa
  5228. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5229. AND ccp.CTable = 81
  5230. AND ioa.Id = ccp.CId
  5231. WHERE
  5232. ioa.IsDel = 0
  5233. AND ccp.IsAuditGM = 1
  5234. AND ccp.IsPay = 1
  5235. AND di.Id = ioa.Diid
  5236. ) AS OAAmount,
  5237. (
  5238. SELECT
  5239. CAST(
  5240. SUM(
  5241. (ccp.PayMoney * ccp.DayRate)
  5242. ) AS DECIMAL(12, 2)
  5243. )
  5244. FROM
  5245. Grp_Customers ic
  5246. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5247. AND ccp.CTable = 82
  5248. AND ic.Id = ccp.CId
  5249. WHERE
  5250. ic.IsDel = 0
  5251. AND ccp.IsAuditGM = 1
  5252. AND ccp.IsPay = 1
  5253. AND di.Id = ic.DiId
  5254. ) AS InsureAmount,
  5255. (
  5256. SELECT
  5257. CAST(
  5258. SUM(
  5259. (ccp.PayMoney * ccp.DayRate)
  5260. ) AS DECIMAL(12, 2)
  5261. )
  5262. FROM
  5263. Grp_HotelReservations hr
  5264. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5265. WHERE
  5266. hr.IsDel = 0
  5267. AND ccp.IsDel = 0
  5268. AND ccp.CTable = 76
  5269. AND ccp.IsAuditGM = 1
  5270. AND ccp.PayMoney <> 0
  5271. AND ccp.IsPay = 1
  5272. AND di.Id = hr.DiId
  5273. ) AS HotelAmount,
  5274. (
  5275. SELECT
  5276. CAST(
  5277. SUM((gec.PriceSum * gec.Coefficient * ccp.DayRate)) AS DECIMAL(12, 2)
  5278. )
  5279. FROM
  5280. OA2023DB.dbo.Fin_GroupExtraCost gec
  5281. INNER JOIN Grp_CreditCardPayment ccp ON gec.Id = ccp.CId
  5282. WHERE
  5283. ccp.IsDel = 0
  5284. AND ccp.CTable = 1015
  5285. AND ccp.IsAuditGM = 1
  5286. AND ccp.IsPay = 1
  5287. AND di.Id = gec.DiId
  5288. ) AS ExcessAmount,
  5289. (
  5290. SELECT
  5291. CAST(
  5292. SUM(
  5293. (ccp.PayMoney * ccp.DayRate)
  5294. ) AS DECIMAL(12, 2)
  5295. )
  5296. FROM
  5297. Fin_PaymentRefundAndOtherMoney prom
  5298. INNER JOIN Grp_CreditCardPayment ccp ON prom.DiId = ccp.DIId
  5299. AND prom.Id = ccp.CId
  5300. WHERE
  5301. prom.IsDel = 0
  5302. AND prom.PayType = 1
  5303. AND ccp.CTable = 285
  5304. AND ccp.IsAuditGM = 1
  5305. AND ccp.IsPay = 1
  5306. AND di.Id = prom.DiId
  5307. ) AS SKTHAmount
  5308. FROM
  5309. Grp_DelegationInfo di
  5310. WHERE
  5311. di.IsDel = 0
  5312. AND di.TeamDid IN (38,39,40,1048)
  5313. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  5314. ORDER BY
  5315. di.VisitDate
  5316. ", beginDt, endDt);
  5317. var data = await _sqlSugar.SqlQueryable<StatisticsYOYView>(sql).ToListAsync();
  5318. var thisYearData = data.Where(x => x.Year == _dto.Year).ToList();
  5319. var lastYearData = data.Where(x => x.Year == (_dto.Year - 1)).ToList();
  5320. List<YOYReturnView> salesYOYData = new List<YOYReturnView>();
  5321. List<YOYReturnView> costYOYData = new List<YOYReturnView>();
  5322. List<YOYReturnView> grossProfitYOYData = new List<YOYReturnView>();
  5323. int monthIndex = 1;
  5324. while (monthIndex < 13)
  5325. {
  5326. var thisMonthData = thisYearData.Where(x => x.Month == monthIndex).ToList();
  5327. var lastMonthData = lastYearData.Where(x => x.Month == monthIndex).ToList();
  5328. var thisGroupIds = thisMonthData.Select(x => x.Id).ToList();
  5329. var lastGroupIds = lastMonthData.Select(x => x.Id).ToList();
  5330. decimal thisSalesAmount = thisMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  5331. lastSalesAmount = lastMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  5332. thisCostAmount = thisMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  5333. lastCostAmount = lastMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  5334. thisgrossProfitAmount = thisMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M),
  5335. lastgrossProfitAmount = lastMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M);
  5336. salesYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisSalesAmount, lastSalesAmount, thisGroupIds, lastGroupIds));
  5337. costYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisCostAmount, lastCostAmount, thisGroupIds, lastGroupIds));
  5338. grossProfitYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisgrossProfitAmount, lastgrossProfitAmount, thisGroupIds, lastGroupIds));
  5339. monthIndex++;
  5340. }
  5341. salesYOYData = salesYOYData.OrderBy(x => x.Month).ToList();
  5342. costYOYData = costYOYData.OrderBy(x => x.Month).ToList();
  5343. grossProfitYOYData = grossProfitYOYData.OrderBy(x => x.Month).ToList();
  5344. return Ok(JsonView(true, "操作成功!", new { salesYOYData = salesYOYData, costYOYData = costYOYData, grossProfitYOYData = grossProfitYOYData }));
  5345. }
  5346. /// <summary>
  5347. /// 国交数据统计-机票相关
  5348. /// 机票票数、机票到达地、预订平台
  5349. /// </summary>
  5350. /// <param name="_dto"></param>
  5351. /// <returns></returns>
  5352. [HttpPost("StatisticsAirTicket")]
  5353. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5354. public async Task<IActionResult> StatisticsAirTicket(YOYDto _dto)
  5355. {
  5356. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5357. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5358. endDt = $"{_dto.Year}-12-31 23:59:59";
  5359. string sql = string.Format(@"
  5360. SELECT
  5361. atr.DIId,
  5362. atr.FlightsDate,
  5363. YEAR(atr.FlightsDate) AS YEAR,
  5364. MONTH(atr.FlightsDate) AS MONTH,
  5365. atr.CType,
  5366. sd.Name As CTypeName,
  5367. atr.FlightsCity,
  5368. atr.ClientNum,
  5369. atr.ClientName,
  5370. di.TeamName As 'GroupName',
  5371. CASE
  5372. WHEN ccp.Payee = '' OR ccp.Payee IS NULL THEN '未知'
  5373. ELSE ccp.Payee
  5374. END AS 'Platform'
  5375. FROM
  5376. Grp_AirTicketReservations atr
  5377. INNER JOIN Grp_CreditCardPayment ccp ON atr.Id = ccp.CId
  5378. AND ccp.IsDel = 0
  5379. AND CTable = 85
  5380. INNER JOIN Grp_DelegationInfo di ON atr.DIId = di.Id
  5381. LEFT JOIN Sys_SetData sd On atr.CType = sd.Id
  5382. WHERE
  5383. atr.IsDel = 0
  5384. AND di.TeamDid IN (38,39,40,1048)
  5385. AND atr.CType IN(457,458,459,460,574,575)
  5386. AND CHARINDEX('行程单',atr.ClientName) = 0
  5387. AND CHARINDEX('返点',atr.ClientName) = 0
  5388. AND CHARINDEX('-1',atr.ClientName) = 0
  5389. AND ccp.IsPay = 1
  5390. AND atr.FlightsDate BETWEEN '{0}' AND '{1}'
  5391. ORDER BY atr.FlightsDate
  5392. ", beginDt, endDt);
  5393. var data = await _sqlSugar.SqlQueryable<StatisticsAirTicketView>(sql).ToListAsync();
  5394. var groupIds = data.Select(x => x.DIId).ToList();
  5395. //处理城市数据
  5396. var threeCodeData = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  5397. //处理团组名称
  5398. var groupNames = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => groupIds.Contains(x.Id)).Select(x => new { Id = x.Id, GroupName = x.TeamName }).ToListAsync();
  5399. data.ForEach(x =>
  5400. {
  5401. string cityName = "";
  5402. if (!string.IsNullOrEmpty(x.FlightsCity))
  5403. {
  5404. string cityCode = x.FlightsCity.Replace("-", "").Replace("/", "");
  5405. int cityNum = cityCode.Length / 3;
  5406. if (cityCode.Length % 3 == 0)
  5407. {
  5408. for (int i = 0; i < cityNum; i++)
  5409. {
  5410. string code = "";
  5411. if (i == 0) code = cityCode.Substring(0, 3);
  5412. else code = cityCode.Substring(i * 3, 3);
  5413. if (!string.IsNullOrEmpty(code))
  5414. {
  5415. if (i == cityNum - 1)
  5416. {
  5417. cityName += threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  5418. }
  5419. else
  5420. {
  5421. var str1 = threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  5422. cityName += str1 + "、";
  5423. }
  5424. }
  5425. }
  5426. }
  5427. }
  5428. x.FlightsCityName = cityName;
  5429. });
  5430. var airTicketNumData = new List<AirTicketReturnView>();
  5431. var airTicketAreaData = new List<AirTicketCityReturnView>();
  5432. int monthIndex = 1;
  5433. while (monthIndex < 13)
  5434. {
  5435. var monthData = data.Where(x => x.Month == monthIndex).ToList();
  5436. //机票票数处理
  5437. int airticket_quantity = monthData.Sum(x => x.ClientNum);
  5438. var linkGroupIds = monthData.Select(x => x.DIId).ToList();
  5439. List<AitTicketInfo> aitTicketInfos = new List<AitTicketInfo>();
  5440. foreach (var item in monthData)
  5441. {
  5442. string groupName = groupNames.Find(x => item.DIId == x.Id)?.GroupName ?? "";
  5443. aitTicketInfos.Add(new AitTicketInfo(item.DIId, groupName, item.ClientNum));
  5444. }
  5445. var aitTicketInfosGroupBy = aitTicketInfos.GroupBy(x => x.Id);
  5446. List<AitTicketInfo> aitTicketInfos1 = new List<AitTicketInfo>();
  5447. foreach (var item in aitTicketInfosGroupBy)
  5448. {
  5449. aitTicketInfos1.Add(new AitTicketInfo(item.Key, item.First().GroupName, item.Sum(x => x.Quantity)));
  5450. }
  5451. aitTicketInfos1 = aitTicketInfos1.OrderBy(x => x.Quantity).ToList();
  5452. linkGroupIds = linkGroupIds.Distinct().ToList();
  5453. airTicketNumData.Add(new AirTicketReturnView(_dto.Year, monthIndex, airticket_quantity, aitTicketInfos1, linkGroupIds));
  5454. //机票城市处理
  5455. //城市处理
  5456. var airTicketCityInfos = new List<string>();
  5457. foreach (var item in monthData)
  5458. {
  5459. if (!string.IsNullOrEmpty(item.FlightsCityName))
  5460. {
  5461. if (item.FlightsCityName.Contains("、"))
  5462. {
  5463. var cityArray = item.FlightsCityName.Split("、").ToList();
  5464. foreach (var item1 in cityArray)
  5465. {
  5466. if (!string.IsNullOrEmpty(item1))
  5467. {
  5468. airTicketCityInfos.Add(item1);
  5469. }
  5470. }
  5471. }
  5472. else
  5473. {
  5474. airTicketCityInfos.Add(item.FlightsCityName);
  5475. }
  5476. }
  5477. }
  5478. //int quantity1 = airTicketCityInfos.Count;
  5479. int city_totalquantity = 0;
  5480. var airTicketCityInfosGroupby = airTicketCityInfos.GroupBy(x => x);
  5481. var airTicketCityInfos1 = new List<AirTicketCityInfo>();
  5482. foreach (var item in airTicketCityInfosGroupby)
  5483. {
  5484. var city_quantity = item.ToList().Count;
  5485. city_totalquantity += city_quantity;
  5486. airTicketCityInfos1.Add(new AirTicketCityInfo(item.Key, city_quantity));
  5487. }
  5488. airTicketCityInfos1 = airTicketCityInfos1.OrderByDescending(x => x.Quantity).ToList();
  5489. airTicketAreaData.Add(new AirTicketCityReturnView(_dto.Year, monthIndex, city_totalquantity, airTicketCityInfos1, linkGroupIds));
  5490. monthIndex++;
  5491. }
  5492. var airTicketPlatformData = data.GroupBy(g => g.Platform)
  5493. .Select(g => new
  5494. {
  5495. platform = g.Key,
  5496. total = g.Sum(x => x.ClientNum),
  5497. children = g.GroupBy(g1 => g1.DIId)
  5498. .Select(g1 => new
  5499. {
  5500. diId = g1.Key,
  5501. groupName = g1.FirstOrDefault()?.GroupName ?? "-",
  5502. total = g1.Sum(x1 => x1.ClientNum),
  5503. children = g1.Select(x1 => new
  5504. {
  5505. //diId = x1.DIId,
  5506. //groupName = x1.GroupName,
  5507. flightsCityName = x1.FlightsCityName,
  5508. total = x1.ClientNum
  5509. })
  5510. .ToList()
  5511. })
  5512. .OrderByDescending(x1 => x1.total)
  5513. .ToList()
  5514. })
  5515. .OrderByDescending(x => x.total)
  5516. .ToList();
  5517. return Ok(JsonView(true, "操作成功!", new
  5518. {
  5519. airTicketNumData = airTicketNumData,
  5520. airTicketAreaData = airTicketAreaData,
  5521. airTicketPlatformData = airTicketPlatformData
  5522. }));
  5523. }
  5524. /// <summary>
  5525. /// 国交数据统计-酒店
  5526. /// 国家TOP10、地区TOP10、预订平台
  5527. /// </summary>
  5528. /// <param name="_dto"></param>
  5529. /// <returns></returns>
  5530. [HttpPost("StatisticsHotel")]
  5531. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5532. public async Task<IActionResult> StatisticsHotel(YOYDto _dto)
  5533. {
  5534. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5535. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5536. endDt = $"{_dto.Year}-12-31 23:59:59";
  5537. string sql = string.Format(@"
  5538. SELECT
  5539. hr.DIId,
  5540. CASE
  5541. WHEN ntf.Country IS NULL THEN '未选择'
  5542. ELSE ntf.Country
  5543. END AS 'Country',
  5544. hr.City,
  5545. hr.HotelName,
  5546. sd.Name AS BookinSite,
  5547. hr.CheckInDate,
  5548. YEAR(hr.CheckInDate) AS YEAR,
  5549. MONTH(hr.CheckInDate) AS MONTH,
  5550. hr.CheckOutDate,
  5551. hr.SingleRoomCount,
  5552. hr.DoubleRoomCount,
  5553. hr.SuiteRoomCount,
  5554. hr.OtherRoomCount
  5555. FROM
  5556. Grp_HotelReservations hr
  5557. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5558. AND ccp.IsDel = 0
  5559. AND CTable = 76
  5560. INNER JOIN Grp_DelegationInfo di ON hr.DiId = di.Id
  5561. LEFT JOIN Sys_SetData sd ON hr.ReservationsWebsite = sd.Id
  5562. LEFT JOIN Grp_NationalTravelFee ntf ON hr.AreaId = ntf.Id
  5563. WHERE
  5564. hr.IsDel = 0
  5565. AND di.TeamDid IN (38,39,40,1048)
  5566. AND ccp.IsPay = 1
  5567. AND (
  5568. hr.SingleRoomCount > 0
  5569. OR hr.DoubleRoomCount > 0
  5570. OR hr.SuiteRoomCount > 0
  5571. OR hr.OtherRoomCount > 0
  5572. )
  5573. AND CHARINDEX('早餐',hr.HotelName) = 0
  5574. AND CHARINDEX('晚餐',hr.HotelName) = 0
  5575. AND CHARINDEX('升级',hr.HotelName) = 0
  5576. AND CHARINDEX('饮料茶水费',hr.HotelName) = 0
  5577. AND CHARINDEX('城市税',hr.HotelName) = 0
  5578. AND CHARINDEX('退款',hr.HotelName) = 0
  5579. AND CHARINDEX('返现',hr.HotelName) = 0
  5580. AND CHARINDEX('会议室',hr.HotelName) = 0
  5581. AND CHARINDEX('迷你吧消费',hr.HotelName) = 0
  5582. AND CHARINDEX('运费',hr.HotelName) = 0
  5583. AND CHARINDEX('地接',hr.HotelName) = 0
  5584. AND CHARINDEX('损失',hr.HotelName) = 0
  5585. AND CHARINDEX('补差',hr.HotelName) = 0
  5586. AND hr.CheckInDate BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  5587. ORDER BY
  5588. hr.CheckInDate
  5589. ", beginDt, endDt);
  5590. var data = await _sqlSugar.SqlQueryable<StatisticsHotelView>(sql).ToListAsync();
  5591. var hotelCountryGroupByData = data.GroupBy(x => x.Country)
  5592. .Select(g => new
  5593. {
  5594. Country = g.Key,
  5595. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5596. hotelData = g.GroupBy(x => x.HotelName)
  5597. .Select(g1 => new
  5598. {
  5599. hotelName = g1.Key,
  5600. roomNights = g1.Sum(x => x.RoomNights),
  5601. roomTotal = g1.Sum(x => x.RoomTotal),
  5602. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5603. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5604. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5605. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5606. })
  5607. .ToList(),
  5608. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5609. })
  5610. .OrderByDescending(x => x.BookingRoomNum)
  5611. .Take(10)
  5612. .ToList();
  5613. var hotelData = data.OrderBy(x => x.CityStr).ToList();
  5614. var hotelCityGroupByData = data.GroupBy(x => x.CityStr)
  5615. .Select(g => new
  5616. {
  5617. city = g.Key,
  5618. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5619. hotelData = g.GroupBy(x => x.HotelName)
  5620. .Select(g1 => new
  5621. {
  5622. hotelName = g1.Key,
  5623. roomNights = g1.Sum(x => x.RoomNights),
  5624. roomTotal = g1.Sum(x => x.RoomTotal),
  5625. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5626. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5627. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5628. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5629. })
  5630. .ToList(),
  5631. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5632. })
  5633. .OrderByDescending(x => x.BookingRoomNum)
  5634. .Take(10)
  5635. .ToList();
  5636. var hotelPlatformGroupByData = data.GroupBy(x => x.BookinSite)
  5637. .Select(g => new
  5638. {
  5639. Platform = g.Key,
  5640. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5641. hotelData = g.GroupBy(x => x.HotelName)
  5642. .Select(g1 => new
  5643. {
  5644. hotelName = g1.Key,
  5645. roomNights = g1.Sum(x => x.RoomNights),
  5646. roomTotal = g1.Sum(x => x.RoomTotal),
  5647. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5648. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5649. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5650. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5651. })
  5652. .ToList(),
  5653. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5654. })
  5655. .OrderByDescending(x => x.BookingRoomNum)
  5656. .ToList();
  5657. return Ok(JsonView(true, "操作成功!", new { hotelCountryGroupByData = hotelCountryGroupByData, hotelCityData = hotelCityGroupByData, hotelPlatformData = hotelPlatformGroupByData }));
  5658. }
  5659. /// <summary>
  5660. /// 国交数据统计
  5661. /// 商邀邀请国家数量TOP10
  5662. /// </summary>
  5663. /// <param name="_dto"></param>
  5664. /// <returns></returns>
  5665. [HttpPost("StatisticsInvitation")]
  5666. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5667. public async Task<IActionResult> StatisticsInvitation(YOYDto _dto)
  5668. {
  5669. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5670. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5671. endDt = $"{_dto.Year}-12-31 23:59:59";
  5672. string sql = string.Format(@"
  5673. SELECT
  5674. oa.DiId,
  5675. di.TeamName AS GroupName,
  5676. oa.Country,
  5677. oa.Area AS City,
  5678. oa.Client,
  5679. oa.Date
  5680. FROM
  5681. Res_OfficialActivities oa
  5682. LEFT JOIN Grp_DelegationInfo di ON oa.DiId = di.Id
  5683. WHERE
  5684. oa.IsDel = 0
  5685. AND oa.Date BETWEEN '{0}' AND '{1}'
  5686. ", beginDt, endDt);
  5687. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation_HW>(sql).ToListAsync();
  5688. var groupByCountry = data.GroupBy(x => x.Country)
  5689. .Select(g => new
  5690. {
  5691. Country = g.Key,
  5692. TimeNum = g.Count(),
  5693. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  5694. })
  5695. .OrderByDescending(x => x.TimeNum)
  5696. .Take(10)
  5697. .ToList();
  5698. var groupByClient = data.GroupBy(x => x.Client)
  5699. .Select(g => new
  5700. {
  5701. Country = g.Key,
  5702. TimeNum = g.Count(),
  5703. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  5704. })
  5705. .OrderByDescending(x => x.TimeNum)
  5706. .Take(10)
  5707. .ToList();
  5708. return Ok(JsonView(true, "操作成功!", new { groupByCountry = groupByCountry, groupByClient = groupByClient }));
  5709. }
  5710. /// <summary>
  5711. /// 会务数据统计
  5712. /// 会务城市TOP10排序
  5713. /// </summary>
  5714. /// <param name="_dto"></param>
  5715. /// <returns></returns>
  5716. [HttpPost("StatisticsConferenceCity")]
  5717. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5718. public async Task<IActionResult> StatisticsConferenceCity(YOYDto _dto)
  5719. {
  5720. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5721. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5722. endDt = $"{_dto.Year}-12-31 23:59:59";
  5723. string sql = string.Format(@"
  5724. SELECT
  5725. ioa.DiId,
  5726. ioa.InviterArea AS Country
  5727. FROM
  5728. Grp_InvitationOfficialActivities ioa
  5729. INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
  5730. AND ccp.IsDel = 0
  5731. AND ccp.CTable = 81
  5732. INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
  5733. WHERE
  5734. ioa.IsDel = 0
  5735. AND di.TeamDid IN (102,248,302,691,762,1047)
  5736. AND ccp.IsPay = 1
  5737. AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
  5738. ", beginDt, endDt);
  5739. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
  5740. var groupByData = data.GroupBy(x => x.Country)
  5741. .Select(g => new
  5742. {
  5743. Country = g.Key,
  5744. TimeNum = g.Count(),
  5745. LinkGroupIds = g.Select(x => x.DIId).ToList()
  5746. })
  5747. .OrderByDescending(x => x.TimeNum)
  5748. .Take(10)
  5749. .ToList();
  5750. return Ok(JsonView(true, "操作成功!", groupByData));
  5751. }
  5752. /// <summary>
  5753. /// 团组数据统计
  5754. /// 团组合作前十的客户TOP10排序
  5755. /// </summary>
  5756. /// <param name="_dto"></param>
  5757. /// <returns></returns>
  5758. [HttpPost("StatisticsCooperativeCustomer")]
  5759. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5760. public async Task<IActionResult> StatisticsCooperativeCustomer(YOYDto _dto)
  5761. {
  5762. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5763. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5764. endDt = $"{_dto.Year}-12-31 23:59:59";
  5765. DateTime _beginDt = Convert.ToDateTime(beginDt),
  5766. _endDt = Convert.ToDateTime(endDt);
  5767. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  5768. .Where(x => x.IsDel == 0)
  5769. //.Where(x => x.IsSure == 1)
  5770. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  5771. .ToListAsync();
  5772. var groupInfos1 = groupInfos.GroupBy(x => x.ClientName);
  5773. var view = groupInfos1.Select(x =>
  5774. new
  5775. {
  5776. clienName = x.Key,
  5777. clientUnit = x.FirstOrDefault()?.ClientUnit ?? "",
  5778. visitsNum = x.Count()
  5779. }
  5780. )
  5781. .OrderByDescending(x => x.visitsNum)
  5782. .Take(10)
  5783. .ToList();
  5784. return Ok(JsonView(true, "操作成功!", view));
  5785. }
  5786. /// <summary>
  5787. /// 团组数据统计
  5788. /// 已出团客户单位的类型比例图(饼状图-政府团、企业团等)
  5789. /// </summary>
  5790. /// <param name="_dto"></param>
  5791. /// <returns></returns>
  5792. [HttpPost("StatisticsCooperativeCustomerType")]
  5793. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5794. public async Task<IActionResult> StatisticsCooperativeCustomerType(YOYDto _dto)
  5795. {
  5796. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5797. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5798. endDt = $"{_dto.Year}-12-31 23:59:59";
  5799. DateTime _beginDt = Convert.ToDateTime(beginDt),
  5800. _endDt = Convert.ToDateTime(endDt);
  5801. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  5802. .LeftJoin<Sys_SetData>((di, sd) => di.TeamDid == sd.Id)
  5803. .Where((di, sd) => di.IsDel == 0)
  5804. .Where((di, sd) => di.VisitDate >= _beginDt && di.VisitDate <= _endDt)
  5805. .Select((di, sd) => new
  5806. {
  5807. Id = di.Id,
  5808. GroupTypeId = di.TeamDid,
  5809. GroupTypeName = sd.Name,
  5810. })
  5811. .ToListAsync();
  5812. var groupInfos1 = groupInfos.GroupBy(x => x.GroupTypeName);
  5813. var view = groupInfos1.Select(x =>
  5814. new
  5815. {
  5816. groupTypeName = x.Key,
  5817. groupNum = x.Count(),
  5818. linkGroupId = x.Select(x1 => x1.Id).ToList()
  5819. }
  5820. )
  5821. .OrderByDescending(x => x.groupNum)
  5822. .ToList();
  5823. return Ok(JsonView(true, "操作成功!", view));
  5824. }
  5825. /// <summary>
  5826. /// 团组数据统计
  5827. /// 团组数量
  5828. /// </summary>
  5829. /// <param name="_dto"></param>
  5830. /// <returns></returns>
  5831. [HttpPost("StatisticsGroupNum")]
  5832. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5833. public async Task<IActionResult> StatisticsGroupNum(YOYDto _dto)
  5834. {
  5835. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5836. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5837. endDt = $"{_dto.Year}-12-31 23:59:59";
  5838. DateTime _beginDt = Convert.ToDateTime(beginDt),
  5839. _endDt = Convert.ToDateTime(endDt);
  5840. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  5841. .Where(x => x.IsDel == 0)
  5842. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  5843. .Select(x => new StatisticsGroupInfoEntity
  5844. {
  5845. Id = x.Id,
  5846. VisitDate = x.VisitDate,
  5847. Month = x.VisitDate.Month,
  5848. //MonthName = x.VisitDate.ToString("MMM", CultureInfo.GetCultureInfo("zh-CN")),
  5849. VisitPNumber = x.VisitPNumber
  5850. })
  5851. .MergeTable()
  5852. .OrderBy(x => new { x.Month })
  5853. .ToListAsync();
  5854. string groupNumStr = $"年度出访量:{groupInfos.Count}\r\n";
  5855. var groupNumYearData = new
  5856. {
  5857. year = _dto.Year,
  5858. yearName = _dto.Year + "年",
  5859. num = groupInfos.Count,
  5860. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  5861. };
  5862. var groupNumData = groupInfos.GroupBy(x => x.Quarter)
  5863. .Select(x => new
  5864. {
  5865. Quarter = x.Key,
  5866. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  5867. Num = x.Count(),
  5868. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  5869. })
  5870. .OrderBy(x => x.Quarter)
  5871. .ToList();
  5872. groupNumData.ForEach(x =>
  5873. {
  5874. groupNumStr += $"{x.QuarterName}出访量:{x.Num};";
  5875. });
  5876. var groupNumMonthData = groupInfos.GroupBy(x => x.Month)
  5877. .Select(x => new
  5878. {
  5879. Month = x.Key,
  5880. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  5881. Num = x.Count(),
  5882. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  5883. })
  5884. .OrderBy(x => x.Month)
  5885. .ToList();
  5886. return Ok(JsonView(true, "操作成功!", new
  5887. {
  5888. yearData = groupNumYearData,
  5889. quarterData = groupNumData,
  5890. monthData = groupNumMonthData,
  5891. remark = groupNumStr
  5892. }));
  5893. }
  5894. /// <summary>
  5895. /// 团组数据统计
  5896. /// 团组人数
  5897. /// </summary>
  5898. /// <param name="_dto"></param>
  5899. /// <returns></returns>
  5900. [HttpPost("StatisticsGroupPeopleNum")]
  5901. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5902. public async Task<IActionResult> StatisticsGroupPeopleNum(YOYDto _dto)
  5903. {
  5904. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5905. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5906. endDt = $"{_dto.Year}-12-31 23:59:59";
  5907. DateTime _beginDt = Convert.ToDateTime(beginDt),
  5908. _endDt = Convert.ToDateTime(endDt);
  5909. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  5910. .Where(x => x.IsDel == 0)
  5911. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  5912. .Select(x => new StatisticsGroupInfoEntity
  5913. {
  5914. Id = x.Id,
  5915. VisitDate = x.VisitDate,
  5916. Month = x.VisitDate.Month,
  5917. VisitPNumber = x.VisitPNumber
  5918. })
  5919. .MergeTable()
  5920. .OrderBy(x => new { x.Month })
  5921. .ToListAsync();
  5922. string groupPeopleNumStr = $"年度出访人数:{groupInfos.Sum(x => x.VisitPNumber)}\r\n";
  5923. var groupPeopleNumYearData = new
  5924. {
  5925. year = _dto.Year,
  5926. yearName = _dto.Year + "年",
  5927. num = groupInfos.Sum(x => x.VisitPNumber),
  5928. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  5929. };
  5930. var groupPeopleNumData = groupInfos.GroupBy(x => x.Quarter)
  5931. .Select(x => new
  5932. {
  5933. Quarter = x.Key,
  5934. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  5935. Num = x.Sum(x1 => x1.VisitPNumber),
  5936. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  5937. })
  5938. .OrderBy(x => x.Quarter)
  5939. .ToList();
  5940. groupPeopleNumData.ForEach(x =>
  5941. {
  5942. groupPeopleNumStr += $"{x.QuarterName}出访人数:{x.Num};";
  5943. });
  5944. var groupPeopleNumMonthData = groupInfos.GroupBy(x => x.Month)
  5945. .Select(x => new
  5946. {
  5947. Month = x.Key,
  5948. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  5949. Num = x.Sum(x1 => x1.VisitPNumber),
  5950. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  5951. })
  5952. .OrderBy(x => x.Month)
  5953. .ToList();
  5954. return Ok(JsonView(true, "操作成功!", new
  5955. {
  5956. yearData = groupPeopleNumYearData,
  5957. quarterData = groupPeopleNumData,
  5958. monthData = groupPeopleNumMonthData,
  5959. remark = groupPeopleNumStr
  5960. }));
  5961. }
  5962. /// <summary>
  5963. /// 团组数据统计
  5964. /// OP 成本
  5965. /// </summary>
  5966. /// <param name="_dto"></param>
  5967. /// <returns></returns>
  5968. [HttpPost("StatisticsOP")]
  5969. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5970. public async Task<IActionResult> StatisticsOP(StatisticsOPDto _dto)
  5971. {
  5972. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  5973. if (_dto.Type < 1 || _dto.Type > 2) return Ok(JsonView(false, "Type参数错误!"));
  5974. int thisYear = _dto.Year, lastYear = _dto.Year - 1;
  5975. string beginDt = $"{lastYear}-01-01 00:00:00",
  5976. endDt = $"{thisYear}-12-31 23:59:59";
  5977. string sql = string.Format(@"
  5978. SELECT
  5979. temp.Id,
  5980. DiId,
  5981. PaymentTime,
  5982. [Year],
  5983. [Quarter],
  5984. [Month],
  5985. Area,
  5986. FeeType,
  5987. sd1.Name AS FeeTypeName,
  5988. FeeSubType,
  5989. sd2.Name AS FeeSubTypeName,
  5990. CONVERT(DECIMAL(12, 2), Price * Qauntity * ExchangeRate) AS Price
  5991. FROM
  5992. (
  5993. SELECT
  5994. ctggr.Id,
  5995. ctggr.DiId,
  5996. ctggr.Area,
  5997. CASE
  5998. WHEN ctggr.PriceType IS NULL THEN 1069
  5999. ELSE ctggr.PriceType
  6000. END AS FeeType,
  6001. ctggrc.SId AS FeeSubType,
  6002. ctggrc.Price,
  6003. CASE
  6004. WHEN ctggrc.Count IS NULL THEN 1
  6005. ELSE ctggrc.Count
  6006. END AS Qauntity,
  6007. ccp.DayRate AS ExchangeRate,
  6008. ctggrc.CreateTime AS PaymentTime,
  6009. YEAR(ctggrc.CreateTime) AS [Year],
  6010. CONVERT(INT,DATENAME(QUARTER, ctggrc.CreateTime)) AS [Quarter],
  6011. MONTH(ctggrc.CreateTime) AS [Month]
  6012. FROM
  6013. Grp_CarTouristGuideGroundReservations ctggr
  6014. INNER JOIN Grp_CarTouristGuideGroundReservationsContent ctggrc ON ctggr.Id = ctggrc.CTGGRId
  6015. AND ctggrc.IsDel = 0
  6016. INNER JOIN Grp_CreditCardPayment ccp ON ctggr.Id = ccp.CId
  6017. AND ccp.CTable = 79
  6018. AND ccp.IsDel = 0
  6019. WHERE
  6020. ctggr.IsDel = 0
  6021. AND ctggrc.SId != 1070 --费用子项筛掉尾款
  6022. AND ctggrc.Price > 0 --筛选真实存在的数据
  6023. AND ccp.IsPay = 1
  6024. ) temp
  6025. LEFT JOIN Sys_SetData sd1 ON FeeType = sd1.Id
  6026. LEFT JOIN Sys_SetData sd2 ON FeeSubType = sd2.Id
  6027. WHERE
  6028. temp.Area NOT LIKE '%尾款%' -- 筛选掉尾款相关信息
  6029. AND temp.FeeType != 1062 --费用类型筛选掉全款和首付款数据
  6030. AND temp.PaymentTime BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  6031. ORDER BY
  6032. temp.[Year],
  6033. temp.[Quarter],
  6034. temp.[Month]
  6035. ", beginDt, endDt);
  6036. var opInfos = await _sqlSugar.SqlQueryable<StatisticsOP>(sql).ToListAsync();
  6037. //处理地区相关信息
  6038. var countrys = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0).ToListAsync();
  6039. for (int i = 0; i < opInfos.Count; i++)
  6040. {
  6041. string country = string.Empty, city = string.Empty;
  6042. int dataId = 0;
  6043. bool isCountryId = int.TryParse(opInfos[i].Area, out dataId);
  6044. string[] citySelecter = new string[] { "其他城市", "所有城市" };
  6045. if (isCountryId)
  6046. {
  6047. var countryInfo = countrys.Find(x => x.Id == dataId);
  6048. country = countryInfo?.Country ?? "";
  6049. if (citySelecter.Contains(countryInfo?.City)) city = country;
  6050. else city = countryInfo?.City ?? "";
  6051. }
  6052. else
  6053. {
  6054. var countryInfo1 = countrys.Find(x => opInfos[i].Area.Contains(x.Country));
  6055. if (countryInfo1 != null)
  6056. {
  6057. country = countryInfo1?.Country ?? "";
  6058. city = countryInfo1?.City ?? country;
  6059. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  6060. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  6061. else city = countryInfo2?.City ?? country;
  6062. }
  6063. else
  6064. {
  6065. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  6066. if (countryInfo2 != null)
  6067. {
  6068. country = countryInfo2?.Country ?? "";
  6069. city = countryInfo2?.City ?? "";
  6070. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  6071. }
  6072. }
  6073. }
  6074. opInfos[i].Country = country;
  6075. opInfos[i].City = city;
  6076. }
  6077. var opParentFeeData = new StatisticsOP()._OPParentFeeInfo;
  6078. if (_dto.Type == 1)
  6079. {
  6080. //同比增长率=(本期数-同期数)/ 同期数
  6081. var yearData = opInfos.GroupBy(x => x.ParentFeeName)
  6082. .Select(x => new StatisticsOPYOY(
  6083. feeId: x.FirstOrDefault()?.ParentFeeId ?? 0,
  6084. feeName: x.Key,
  6085. currPeriodFee: x.Where(x => x.Year == thisYear).Sum(x => x.Price),
  6086. samePeriodFee: x.Where(x => x.Year == lastYear).Sum(x => x.Price),
  6087. currPeriodGroupTotal: x.Where(x => x.Year == thisYear).Select(x => x.DiId).Distinct().Count(),
  6088. samePeriodGroupTotal: x.Where(x => x.Year == lastYear).Select(x => x.DiId).Distinct().Count(),
  6089. subFeeData: x.GroupBy(x1 => x1.FeeSubType)
  6090. .Select(x1 => new StatisticsOPSubFeeYOY(
  6091. feeId: x1.Key,
  6092. feeName: x1.FirstOrDefault()?.FeeSubTypeName ?? "",
  6093. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  6094. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  6095. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  6096. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  6097. cityData: x1.GroupBy(x2 => x2.City)
  6098. .Select(x2 => new StatisticsOPCityYOY(
  6099. cityName: x2.Key,
  6100. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  6101. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  6102. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  6103. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price)
  6104. ))
  6105. .ToArray()
  6106. ))
  6107. .ToArray()
  6108. ))
  6109. .OrderBy(x => x.FeeId)
  6110. .ToList();
  6111. var opParentYearIds = yearData.Select(x => x.FeeId).ToList();
  6112. var opParentYearDataSelector = opParentFeeData.Where(x => !opParentYearIds.Contains(x.Id)).ToList();
  6113. if (opParentYearDataSelector.Count > 0)
  6114. {
  6115. foreach (var item in opParentYearDataSelector)
  6116. {
  6117. yearData.Add(
  6118. new StatisticsOPYOY(feeId: item.Id,
  6119. feeName: item.Name,
  6120. currPeriodFee: 0.00M,
  6121. samePeriodFee: 0.00M,
  6122. currPeriodGroupTotal: 0,
  6123. samePeriodGroupTotal: 0,
  6124. subFeeData: new StatisticsOPSubFeeYOY[] { }
  6125. ));
  6126. }
  6127. yearData = yearData.OrderBy(x => x.FeeId).ToList();
  6128. }
  6129. return Ok(JsonView(true, "操作成功!", yearData));
  6130. }
  6131. else if (_dto.Type == 2)
  6132. {
  6133. var monthData = opInfos.GroupBy(x => x.Month)
  6134. .Select(x => new StatisticsOPMonthYOY(
  6135. monthId: x.Key,
  6136. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)x.Key) ? ((MonthEnum)(int)x.Key).GetEnumDescription() : "",
  6137. feeDatas: x.GroupBy(x1 => x1.ParentFeeId)
  6138. .Select(x1 => new StatisticsOPYOY(
  6139. feeId: x1.Key,
  6140. feeName: x1.FirstOrDefault()?.ParentFeeName ?? "",
  6141. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  6142. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  6143. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  6144. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  6145. subFeeData: x1.GroupBy(x2 => x2.FeeSubType)
  6146. .Select(x2 => new StatisticsOPSubFeeYOY(
  6147. feeId: x2.Key,
  6148. feeName: x2.FirstOrDefault()?.FeeSubTypeName ?? "",
  6149. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  6150. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price),
  6151. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  6152. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  6153. cityData: x2.GroupBy(x3 => x3.City)
  6154. .Select(x3 => new StatisticsOPCityYOY(
  6155. cityName: x3.Key,
  6156. currPeriodFee: x3.Where(x3 => x3.Year == thisYear).Sum(x3 => x3.Price),
  6157. samePeriodFee: x3.Where(x3 => x3.Year == lastYear).Sum(x3 => x3.Price),
  6158. currPeriodGroupTotal: x3.Where(x3 => x3.Year == thisYear).Select(x3 => x3.DiId).Distinct().Count(),
  6159. samePeriodGroupTotal: x3.Where(x3 => x3.Year == lastYear).Select(x3 => x3.DiId).Distinct().Count()
  6160. ))
  6161. .ToArray()
  6162. ))
  6163. .ToArray()
  6164. ))
  6165. .ToArray()
  6166. ))
  6167. //.OrderBy(x => x.MonthId)
  6168. .ToList();
  6169. //1、月份是否足够十二月
  6170. var monthIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  6171. var monthDataIds = monthData.Select(x => x.MonthId).ToArray();
  6172. var newMonthIds = monthIds.Where(x => !monthDataIds.Contains(x)).ToList();
  6173. if (newMonthIds.Count > 0)
  6174. {
  6175. foreach (var item in newMonthIds)
  6176. {
  6177. monthData.Add(new StatisticsOPMonthYOY(
  6178. monthId: item,
  6179. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)item) ? ((MonthEnum)(int)item).GetEnumDescription() : "",
  6180. feeDatas: System.Array.Empty<StatisticsOPYOY>()
  6181. ));
  6182. }
  6183. monthData = monthData.OrderBy(x => x.MonthId).ToList();
  6184. }
  6185. //2、费用父类是否足够
  6186. for (int i = 0; i < monthData.Count; i++)
  6187. {
  6188. var month = monthData[i];
  6189. var opParentFeeIds = month.FeeDatas.Select(x => x.FeeId).ToList();
  6190. var opParentFeeDataSelector = opParentFeeData.Where(x => !opParentFeeIds.Contains(x.Id)).ToList();
  6191. if (opParentFeeDataSelector.Count > 0)
  6192. {
  6193. var feeDatas = month.FeeDatas.ToList();
  6194. foreach (var item in opParentFeeDataSelector)
  6195. {
  6196. feeDatas.Add(new StatisticsOPYOY(
  6197. feeId: item.Id,
  6198. feeName: item.Name,
  6199. currPeriodFee: 0.00M,
  6200. samePeriodFee: 0.00M,
  6201. currPeriodGroupTotal: 0,
  6202. samePeriodGroupTotal: 0,
  6203. subFeeData: System.Array.Empty<StatisticsOPSubFeeYOY>()
  6204. ));
  6205. }
  6206. feeDatas = feeDatas.OrderBy(x => x.FeeId).ToList();
  6207. monthData[i].FeeDatas = feeDatas.ToArray();
  6208. }
  6209. }
  6210. //3、费用子类是否足够
  6211. return Ok(JsonView(true, "操作成功!", monthData));
  6212. }
  6213. return Ok(JsonView(false, "操作失败!"));
  6214. }
  6215. /// <summary>
  6216. /// 团组数据统计
  6217. /// 团组预算/实际成本
  6218. /// </summary>
  6219. /// <param name="_dto"></param>
  6220. /// <returns></returns>
  6221. [HttpPost("StatisticsGroupCost")]
  6222. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6223. public async Task<IActionResult> StatisticsBRCost(StatisticsBRCostDto _dto)
  6224. {
  6225. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  6226. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6227. endDt = $"{_dto.Year}-12-31 23:59:59";
  6228. var sql = string.Format(@"
  6229. SELECT
  6230. ROW_NUMBER() OVER(
  6231. ORDER BY
  6232. di.VisitDate DESC
  6233. ) AS 'RowNumber',
  6234. di.Id,
  6235. di.TeamName AS 'GroupName',
  6236. di.ClientUnit,
  6237. di.VisitDate,
  6238. di.VisitDays,
  6239. di.VisitPNumber,
  6240. (
  6241. SELECT
  6242. TOP 1 CASE
  6243. ISNUMERIC (gcp.Currency)
  6244. WHEN 1 THEN (
  6245. SELECT
  6246. Name
  6247. FROM
  6248. Sys_SetData sd
  6249. WHERE
  6250. CAST(gcp.Currency AS INT) = sd.Id
  6251. )
  6252. ELSE gcp.Currency
  6253. END AS 'CurrencyCode'
  6254. FROM
  6255. Grp_GroupCostParameter gcp
  6256. WHERE
  6257. gcp.IsDel = 0
  6258. AND gcp.DiId = di.Id
  6259. ) Budget_CurrencyCode,
  6260. --预算币种
  6261. (
  6262. SELECT
  6263. TOP 1 CAST(COALESCE(gcp.Rate, 0.0000) AS DECIMAL(12, 4))
  6264. FROM
  6265. Grp_GroupCostParameter gcp
  6266. WHERE
  6267. gcp.IsDel = 0
  6268. AND gcp.DiId = di.Id
  6269. ) Budget_Rate,
  6270. --预算汇率
  6271. (
  6272. SELECT
  6273. CAST(
  6274. SUM(COALESCE(gcp.VisaCB, 0) * COALESCE(gcp.VisaRS, 0)) AS DECIMAL(12, 2)
  6275. )
  6276. FROM
  6277. Grp_GroupCostParameter gcp
  6278. WHERE
  6279. gcp.IsDel = 0
  6280. AND gcp.DiId = di.id
  6281. ) Budget_VisaAmount,
  6282. -- 预算签证成本
  6283. (
  6284. SELECT
  6285. CAST(
  6286. SUM(
  6287. (
  6288. (ccp.PayMoney * ccp.DayRate)
  6289. )
  6290. ) AS DECIMAL(12, 2)
  6291. )
  6292. FROM
  6293. Grp_VisaInfo vi
  6294. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6295. AND ccp.CTable = 80
  6296. AND vi.Id = ccp.CId
  6297. WHERE
  6298. vi.IsDel = 0
  6299. AND ccp.IsAuditGM = 1
  6300. AND ccp.IsPay = 1
  6301. AND di.Id = vi.DIId
  6302. ) AS Reality_VisaAmount,
  6303. -- 实际签证成本
  6304. (
  6305. SELECT
  6306. CAST(
  6307. SUM(
  6308. COALESCE(gcp.JJCCB, 0) * COALESCE(gcp.JJCRS, 0) + COALESCE(gcp.GWCCB, 0) * COALESCE(gcp.GWCRS, 0) + COALESCE(gcp.TDCCB, 0) * COALESCE(gcp.TDCRS, 0)
  6309. ) AS DECIMAL(12, 2)
  6310. )
  6311. FROM
  6312. Grp_GroupCostParameter gcp
  6313. WHERE
  6314. gcp.IsDel = 0
  6315. AND gcp.DiId = di.id
  6316. ) Budget_AirTicketAmount,
  6317. -- 预算机票成本
  6318. (
  6319. SELECT
  6320. CAST(
  6321. SUM(
  6322. (
  6323. (ccp.PayMoney * ccp.DayRate)
  6324. )
  6325. ) AS DECIMAL(12, 2)
  6326. )
  6327. FROM
  6328. Grp_AirTicketReservations atr
  6329. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6330. AND ccp.CTable = 85
  6331. AND atr.Id = ccp.CId
  6332. WHERE
  6333. atr.IsDel = 0
  6334. AND ccp.IsAuditGM = 1
  6335. AND ccp.IsPay = 1
  6336. AND di.Id = atr.DiId
  6337. ) Reality_AirTicketAmount,
  6338. --实际机票
  6339. (
  6340. SELECT
  6341. CAST(
  6342. SUM(
  6343. 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)
  6344. ) AS DECIMAL(12, 2)
  6345. )
  6346. FROM
  6347. Grp_GroupCostParameter gcp
  6348. WHERE
  6349. gcp.IsDel = 0
  6350. AND gcp.DiId = di.id
  6351. ) Budget_HotelAmount,
  6352. -- 预算酒店成本
  6353. (
  6354. SELECT
  6355. CAST(
  6356. SUM(
  6357. (ccp.PayMoney * ccp.DayRate)
  6358. ) AS DECIMAL(12, 2)
  6359. )
  6360. FROM
  6361. Grp_HotelReservations hr
  6362. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  6363. WHERE
  6364. hr.IsDel = 0
  6365. AND ccp.IsDel = 0
  6366. AND ccp.CTable = 76
  6367. AND ccp.IsAuditGM = 1
  6368. AND ccp.PayMoney <> 0
  6369. AND ccp.IsPay = 1
  6370. AND di.Id = hr.DiId
  6371. ) AS Reality_HotelAmount,
  6372. -- 实际酒店成本
  6373. (
  6374. SELECT
  6375. CAST(
  6376. SUM(COALESCE(gcp.DJCB, 0) * COALESCE(gcp.DJRS, 0)) AS DECIMAL(12, 2)
  6377. )
  6378. FROM
  6379. Grp_GroupCostParameter gcp
  6380. WHERE
  6381. gcp.IsDel = 0
  6382. AND gcp.DiId = di.id
  6383. ) Budget_OPAmount,
  6384. -- 预算 OP
  6385. (
  6386. SELECT
  6387. CAST(
  6388. SUM(
  6389. (
  6390. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  6391. )
  6392. ) AS DECIMAL(12, 2)
  6393. )
  6394. FROM
  6395. Grp_CarTouristGuideGroundReservations ctggr
  6396. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  6397. AND ccp.CTable = 79
  6398. AND ctggr.Id = ccp.CId
  6399. WHERE
  6400. ctggr.IsDel = 0
  6401. AND ccp.IsAuditGM = 1
  6402. AND ccp.IsPay = 1
  6403. AND di.Id = ctggr.DiId
  6404. ) AS Reality_OPAmount,
  6405. -- 实际 OP
  6406. (
  6407. SELECT
  6408. CAST(
  6409. SUM(COALESCE(gcp.GWCB, 0) * COALESCE(gcp.GWRS, 0)) AS DECIMAL(12, 2)
  6410. )
  6411. FROM
  6412. Grp_GroupCostParameter gcp
  6413. WHERE
  6414. gcp.IsDel = 0
  6415. AND gcp.DiId = di.id
  6416. ) Budget_OAAmount,
  6417. -- 预算 商邀
  6418. (
  6419. SELECT
  6420. CAST(
  6421. SUM(
  6422. (ccp.PayMoney * ccp.DayRate)
  6423. ) AS DECIMAL(12, 2)
  6424. )
  6425. FROM
  6426. Grp_InvitationOfficialActivities ioa
  6427. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6428. AND ccp.CTable = 81
  6429. AND ioa.Id = ccp.CId
  6430. WHERE
  6431. ioa.IsDel = 0
  6432. AND ccp.IsAuditGM = 1
  6433. AND ccp.IsPay = 1
  6434. AND di.Id = ioa.Diid
  6435. ) AS Reality_OAAmount,
  6436. -- 实际 商邀
  6437. (
  6438. SELECT
  6439. CAST(
  6440. SUM(
  6441. 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)
  6442. ) AS DECIMAL(12, 2)
  6443. )
  6444. FROM
  6445. Grp_GroupCostParameter gcp
  6446. WHERE
  6447. gcp.IsDel = 0
  6448. AND gcp.DiId = di.id
  6449. ) Budget_OtherAmount,
  6450. -- 预算其他成本
  6451. (
  6452. SELECT
  6453. CAST(
  6454. SUM(
  6455. (ccp.PayMoney * ccp.DayRate)
  6456. ) AS DECIMAL(12, 2)
  6457. )
  6458. FROM
  6459. Grp_Customers ic
  6460. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6461. AND ccp.CTable = 82
  6462. AND ic.Id = ccp.CId
  6463. WHERE
  6464. ic.IsDel = 0
  6465. AND ccp.IsAuditGM = 1And ccp.IsPay = 1
  6466. AND di.Id = ic.DiId
  6467. ) AS Reality_InsureAmount,
  6468. -- 实际保险成本
  6469. (
  6470. SELECT
  6471. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  6472. FROM
  6473. Grp_DecreasePayments dp
  6474. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6475. AND ccp.CTable = 98
  6476. AND dp.Id = ccp.CId
  6477. WHERE
  6478. dp.IsDel = 0
  6479. AND ccp.Ctable = 98
  6480. AND ccp.IsAuditGM = 1
  6481. AND ccp.IsPay = 1
  6482. AND di.Id = dp.Diid
  6483. ) AS Reality_OtherCostAmount -- 实际其他款项
  6484. FROM
  6485. Grp_DelegationInfo di
  6486. WHERE
  6487. di.IsDel = 0
  6488. AND di.IsBid = 0
  6489. --AND di.TeamDid IN (38, 39, 40, 1048)
  6490. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  6491. ", beginDt, endDt);
  6492. if (!string.IsNullOrEmpty(_dto.Search))
  6493. {
  6494. sql += $"AND di.TeamName Like '%{_dto.Search}%'";
  6495. }
  6496. var view = await _sqlSugar.SqlQueryable<StatisticsBRCostView>(sql).ToListAsync();
  6497. view = view.Where(x => !x.GroupName.Contains("投标") && x.RealityAmount > 0).OrderByDescending(x => x.Id).ToList();
  6498. var total = view.Count;
  6499. var toSkip = (_dto.PageIndex - 1) * _dto.PageSize;
  6500. var data = view.Skip(toSkip).Take(_dto.PageSize).ToList();
  6501. if (data.Count > 0)
  6502. {
  6503. var diIds = data.Select(x => x.Id).ToList();
  6504. var currencyData = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToListAsync();
  6505. var ccpData = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
  6506. .Where(x => x.IsDel == 0 &&
  6507. diIds.Contains(x.DIId) &&
  6508. x.IsPay == 1 &&
  6509. x.IsAuditGM == 1
  6510. )
  6511. .ToListAsync();
  6512. for (int i = 0; i < data.Count; i++)
  6513. {
  6514. var info = data[i];
  6515. info.RowNumber = i + 1;
  6516. #region 1:签证 80
  6517. var visaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 80).ToList();
  6518. var visaDesc = "-";
  6519. if (visaDatas.Count > 0)
  6520. {
  6521. visaDesc = $"实际币种金额:";
  6522. foreach (var visa in visaDatas)
  6523. {
  6524. var currencyCode = currencyData.Find(x => x.Id == visa.PaymentCurrency)?.Name;
  6525. visaDesc += $"{visa.PayMoney} {currencyCode} 汇率:{visa.DayRate.ToString("#0.0000")};";
  6526. }
  6527. }
  6528. info.Reality_VisaAmountDesc = visaDesc;
  6529. #endregion
  6530. #region 2:机票 85
  6531. var airDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 85).ToList();
  6532. var airDesc = "-";
  6533. if (airDatas.Count > 0)
  6534. {
  6535. airDesc = $"实际币种金额:";
  6536. foreach (var air in airDatas)
  6537. {
  6538. var currencyCode = currencyData.Find(x => x.Id == air.PaymentCurrency)?.Name;
  6539. airDesc += $"{air.PayMoney} {currencyCode} 汇率:{air.DayRate.ToString("#0.0000")};";
  6540. }
  6541. }
  6542. info.Reality_AirTicketAmountDesc = airDesc;
  6543. #endregion
  6544. #region 3:酒店 76
  6545. var hotelDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 76 && x.PayMoney != 0).ToList();
  6546. var hotelDesc = "-";
  6547. if (hotelDatas.Count > 0)
  6548. {
  6549. hotelDesc = $"实际币种金额:";
  6550. foreach (var hotel in hotelDatas)
  6551. {
  6552. var currencyCode = currencyData.Find(x => x.Id == hotel.PaymentCurrency)?.Name;
  6553. hotelDesc += $"{hotel.PayMoney} {currencyCode} 汇率:{hotel.DayRate.ToString("#0.0000")};";
  6554. }
  6555. }
  6556. info.Reality_HotelAmountDesc = hotelDesc;
  6557. #endregion
  6558. #region 4:OP 79
  6559. var opDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 79 && x.PayMoney != 0).ToList();
  6560. var opDesc = "-";
  6561. if (opDatas.Count > 0)
  6562. {
  6563. opDesc = $"实际币种金额;";
  6564. foreach (var op in opDatas)
  6565. {
  6566. var currencyCode = currencyData.Find(x => x.Id == op.PaymentCurrency)?.Name;
  6567. opDesc += $"{op.PayMoney} {currencyCode} 汇率:{op.DayRate.ToString("#0.0000")};";
  6568. }
  6569. }
  6570. info.Reality_OPAmountDesc = opDesc;
  6571. #endregion
  6572. #region 5:商邀 81
  6573. var oaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 81 && x.PayMoney != 0).ToList();
  6574. var oaDesc = "-";
  6575. if (oaDatas.Count > 0)
  6576. {
  6577. oaDesc = $"实际币种金额:";
  6578. foreach (var oa in oaDatas)
  6579. {
  6580. var currencyCode = currencyData.Find(x => x.Id == oa.PaymentCurrency)?.Name;
  6581. oaDesc += $"{oa.PayMoney} {currencyCode} 汇率:{oa.DayRate.ToString("#0.0000")};";
  6582. }
  6583. }
  6584. info.Reality_OAAmountDesc = oaDesc;
  6585. #endregion
  6586. #region 6:其他款项(保险 82、其他款项 98)
  6587. var cTables = new List<int>() { 82, 98 };
  6588. var otherDatas = ccpData.Where(x => x.DIId == info.Id && cTables.Contains(x.CTable) && x.PayMoney != 0).ToList();
  6589. var otherDesc = "-";
  6590. if (otherDatas.Count > 0)
  6591. {
  6592. otherDesc = $"实际币种金额:";
  6593. foreach (var other in otherDatas)
  6594. {
  6595. var currencyCode = currencyData.Find(x => x.Id == other.PaymentCurrency)?.Name;
  6596. otherDesc += $"{other.PayMoney} {currencyCode} 汇率:{other.DayRate.ToString("#0.0000")};";
  6597. }
  6598. }
  6599. info.Reality_OtherCostAmountDesc = otherDesc;
  6600. #endregion
  6601. }
  6602. }
  6603. var briefData = _mapper.Map<List<StatisticsBRCostBriefView>>(data);
  6604. return Ok(JsonView(briefData, total));
  6605. }
  6606. /// <summary>
  6607. /// 团组数据统计
  6608. /// 当前时间团组所在城市
  6609. /// </summary>
  6610. /// <param name="dto"></param>
  6611. /// <returns></returns>
  6612. [HttpPost("StatisticsNowCityOfGroup")]
  6613. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6614. public async Task<IActionResult> StatisticsNowCityOfGroup(StatisticsNowCityOfGroupDto dto)
  6615. {
  6616. if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
  6617. var nowLable = DateTime.Now.ToString("yyyy-MM-dd");
  6618. var sql = string.Format(@"SELECT * FROM Grp_DelegationInfo WHERE ISdel = 0 AND '{0}' BETWEEN VisitStartDate AND VisitEndDate", nowLable);
  6619. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql)
  6620. .Select(x => new { x.Id, x.VisitCountry, x.TeamName, x.ClientUnit, x.VisitStartDate, x.VisitEndDate }).
  6621. ToListAsync();
  6622. if (!groupInfos.Any()) return Ok(JsonView(false, "今日暂无团组出行!"));
  6623. var groupIds = groupInfos.Select(x => x.Id).ToList();
  6624. //三字码
  6625. var threeDatas = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  6626. //国家
  6627. var countryDatas = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.City)).ToListAsync();
  6628. //公务
  6629. var OADatas = await _sqlSugar
  6630. .Queryable<Res_OfficialActivities>().Where(x => x.IsDel == 0 && groupIds.Contains(x.DiId) && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.Area))
  6631. .ToListAsync();
  6632. //酒店
  6633. var hotelDatas = await _sqlSugar.Queryable<Grp_HotelReservations>()
  6634. .LeftJoin<Grp_NationalTravelFee>((hr, ntf) => hr.AreaId == ntf.Id)
  6635. .Where((hr, ntf) => hr.IsDel == 0 && groupIds.Contains(hr.DiId))
  6636. .Select((hr, ntf) => new
  6637. {
  6638. hr.DiId,
  6639. hr.AreaId,
  6640. hr.HotelName,
  6641. hr.CheckInDate,
  6642. hr.CheckOutDate,
  6643. hr.HotelAddress,
  6644. ntf.Country,
  6645. ntf.City
  6646. })
  6647. .ToListAsync();
  6648. //机票
  6649. /*
  6650. *舱位类型
  6651. *457 头等舱
  6652. *458 公务舱
  6653. *459 超经舱
  6654. *460 经济舱
  6655. *461 退票
  6656. *565 其他
  6657. *574 长段公务舱
  6658. *575 短途经济舱
  6659. *1023 行程单打印费
  6660. *1024 选座费
  6661. */
  6662. var classTypes = new int[] { 457, 458, 459, 460, 574, 575 };
  6663. var airDatas = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  6664. .Where(atr => atr.IsDel == 0 && groupIds.Contains(atr.DIId) && classTypes.Contains(atr.CType))
  6665. .ToListAsync();
  6666. string[] characters = { "|", "、" };
  6667. var result = new List<StatisticsNowCityOfGroupResultView>();
  6668. foreach (var item in groupInfos)
  6669. {
  6670. string statusText = string.Empty,
  6671. address = string.Empty;
  6672. var countrys = item.VisitCountry;
  6673. if (string.IsNullOrEmpty(countrys)) continue;
  6674. var currCountrys = item.VisitCountry.Split(characters, StringSplitOptions.RemoveEmptyEntries);
  6675. var stutus = true;
  6676. #region 公务
  6677. var currOADatas = OADatas.Where(x => x.DiId == item.Id && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  6678. if (currOADatas.Any())
  6679. {
  6680. foreach (var curr_oa in currOADatas)
  6681. {
  6682. var localTime = GetCountryOrCityCurrentDateTime(curr_oa.Country, curr_oa.Area);
  6683. if (localTime == null) continue;
  6684. var currOaDtStart = Convert.ToDateTime($"{Convert.ToDateTime(curr_oa.Date).ToString("yyyy-MM-dd")} {curr_oa.Time}");
  6685. var currOaDtEnd = currOaDtStart.AddHours(2);
  6686. var currTimeZoneStatus = localTime >= currOaDtStart && localTime <= currOaDtEnd;
  6687. if (!currTimeZoneStatus) continue;
  6688. stutus = false;
  6689. statusText = "公务活动中";
  6690. address = curr_oa.Address;
  6691. break;
  6692. }
  6693. }
  6694. #endregion
  6695. #region 酒店
  6696. var currHotelDatas = hotelDatas.Where(x => x.DiId == item.Id && !string.IsNullOrEmpty(x.Country) && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  6697. if (stutus && hotelDatas.Any())
  6698. {
  6699. foreach (var curr_hotel in currHotelDatas)
  6700. {
  6701. var checkInDt = Convert.ToDateTime(curr_hotel.CheckInDate);
  6702. List<(DateTime start, DateTime end)> timeRanges = new List<(DateTime, DateTime)>();
  6703. while (checkInDt <= Convert.ToDateTime(curr_hotel.CheckOutDate))
  6704. {
  6705. int year = checkInDt.Year,
  6706. month = checkInDt.Month,
  6707. day = checkInDt.Day;
  6708. timeRanges.Add((new DateTime(year, month, day, 0, 0, 0), new DateTime(year, month, day, 9, 0, 0)));
  6709. timeRanges.Add((new DateTime(year, month, day, 18, 0, 0), new DateTime(year, month, day, 23, 59, 59)));
  6710. checkInDt = checkInDt.AddDays(1);
  6711. }
  6712. if (!timeRanges.Any()) continue;
  6713. if (string.IsNullOrEmpty(curr_hotel.Country) && string.IsNullOrEmpty(curr_hotel.City)) continue;
  6714. var countryInfo = countryDatas.Where(x => x.Id == curr_hotel.AreaId).FirstOrDefault();
  6715. if (countryInfo == null) continue;
  6716. var localTime = GetCountryOrCityCurrentDateTime(countryInfo.Country, countryInfo.City);
  6717. var currTimeZoneStatus = timeRanges.Any(range => localTime >= range.start && localTime <= range.end);
  6718. if (!currTimeZoneStatus) continue;
  6719. stutus = false;
  6720. statusText = "入住酒店中";
  6721. address = curr_hotel.HotelAddress;
  6722. break;
  6723. }
  6724. }
  6725. #endregion
  6726. #region 机票--通过三字码解析处理
  6727. var airTicketDatas = GetTableByBlackCode(item.Id);
  6728. if (stutus && airTicketDatas != null)
  6729. {
  6730. foreach (DataRow curr_airTicket in airTicketDatas.Rows)
  6731. {
  6732. string departDate = curr_airTicket["Date"].ToString(), //出发日期
  6733. departThree = curr_airTicket["Three"].ToString(), //城市三字码
  6734. departTime = curr_airTicket["StartTime"].ToString(), //出发时刻
  6735. departTerminal = curr_airTicket["StartBuilding"].ToString(), //出发航站楼
  6736. arriveTerminal = curr_airTicket["EndBuilding"].ToString(), //抵达航站楼
  6737. arrivedDate = curr_airTicket["ArrivedDate"].ToString(), //抵达日期
  6738. arrivedTime = curr_airTicket["EndTime"].ToString(), //抵达日期
  6739. flightTime = curr_airTicket["FlightTime"].ToString(); //飞行时间
  6740. if (string.IsNullOrEmpty(departThree)) continue;
  6741. string departAirThree = departThree.Substring(0, 3),
  6742. arriveAirThree = departThree.Substring(3, 3);
  6743. string departCountry = string.Empty,
  6744. departCity = string.Empty,
  6745. departAirport = string.Empty,
  6746. arriveCountry = string.Empty,
  6747. arriveCity = string.Empty,
  6748. arriveAirport = string.Empty;
  6749. var departCountryInfo = threeDatas.Find(x => x.Three.Equals(departAirThree));
  6750. var arriveCountryInfo = threeDatas.Find(x => x.Three.Equals(arriveAirThree));
  6751. if (departCountryInfo == null || arriveCountryInfo == null) continue;
  6752. departCountry = departCountryInfo.Country;
  6753. departCity = departCountryInfo.City;
  6754. departAirport = departCountryInfo.AirPort;
  6755. arriveCountry = arriveCountryInfo.Country;
  6756. arriveCity = arriveCountryInfo.City;
  6757. arriveAirport = arriveCountryInfo.AirPort;
  6758. var arriveDateTimeBool = DateTime.TryParse(arrivedDate + " " + arrivedTime.Insert(2, ":"), out DateTime arriveDateTime);
  6759. if (!arriveDateTimeBool) continue;
  6760. var filghtHoursBool = int.TryParse(flightTime.Split("H")[0].ToString(), out int filghtHours);
  6761. var filghtMinutesBool = int.TryParse(flightTime.Split("H")[1].Remove(2).ToString(), out int filghtMinutes);
  6762. if (!filghtHoursBool || !filghtHoursBool) continue;
  6763. var departDateTime = arriveDateTime.AddHours(-filghtHours).AddMinutes(-filghtMinutes);
  6764. var localTime = GetCountryOrCityCurrentDateTime(arriveCountry, arriveCity);
  6765. var currTimeZoneStatus = localTime >= departDateTime && localTime <= arriveDateTime;
  6766. if (!currTimeZoneStatus) continue;
  6767. stutus = false;
  6768. statusText = $"正飞往{arriveCity}城市中";
  6769. address = $"{arriveCountry}{arriveAirport}{arriveTerminal}";
  6770. break;
  6771. }
  6772. }
  6773. if (stutus) statusText = $"其他";
  6774. #endregion
  6775. result.Add(new StatisticsNowCityOfGroupResultView()
  6776. {
  6777. GroupName = item.TeamName,
  6778. Client = item.ClientUnit,
  6779. StatusText = statusText,
  6780. Address = address
  6781. });
  6782. }
  6783. result.AddRange(new List<StatisticsNowCityOfGroupResultView>() {
  6784. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组1",Client = "模拟数据单位1",StatusText = "正在公务中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  6785. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组2",Client = "模拟数据单位2",StatusText = "入住酒店中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  6786. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组3",Client = "模拟数据单位3",StatusText = "其他",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  6787. });
  6788. var result1 = result.GroupBy(x => x.Address).Select(g => new
  6789. {
  6790. address = g.Key,
  6791. Items = g.ToList().Select(gg => new { gg.GroupName, gg.Client, gg.StatusText }).ToList()
  6792. });
  6793. if (!result1.Any()) return Ok(JsonView(false, "今天暂无出行的的团!"));
  6794. return Ok(JsonView(result1));
  6795. }
  6796. private StatisticsNowCityOfGroupView CitySplit(string cityLable, List<Res_ThreeCode> cities)
  6797. {
  6798. var info = new StatisticsNowCityOfGroupView();
  6799. if (string.IsNullOrEmpty(cityLable)) return info;
  6800. var cityArray = cityLable.Split("-");
  6801. var departCityCode = cityArray[0];
  6802. var arriveCityCode = cityArray[1];
  6803. var departAirportInfo = cities.Find(x => x.Three.Equals(departCityCode.ToUpper()));
  6804. info.DepartAirportCode = departCityCode;
  6805. info.DepartCountryName = departAirportInfo?.Country ?? "-";
  6806. info.DepartCityName = departAirportInfo?.City ?? "-";
  6807. var arriveAirportInfo = cities.Find(x => x.Three.Equals(arriveCityCode.ToUpper()));
  6808. info.ArriveAirportCode = arriveCityCode;
  6809. info.ArriveCountryName = arriveAirportInfo?.Country ?? "-";
  6810. info.ArriveCityName = arriveAirportInfo?.City ?? "-";
  6811. return info;
  6812. }
  6813. #endregion
  6814. #region 企业利润
  6815. /// <summary>
  6816. /// 企业利润 infos
  6817. /// </summary>
  6818. /// <param name="beginDt"></param>
  6819. /// <param name="endDt"></param>
  6820. /// <returns></returns>
  6821. private async Task<CorporateProfitInfosView> CorporateProfitInfos(string beginDt, string endDt)
  6822. {
  6823. var view = new CorporateProfitInfosView();
  6824. //已审核SQL
  6825. // string sql = string.Format(@"SELECT
  6826. // ROW_NUMBER() OVER(ORDER BY di.VisitDate Asc) AS 'RowIndex',
  6827. // di.Id,
  6828. // di.ClientName,
  6829. // di.TeamName,
  6830. // di.TeamDid,
  6831. // ss.Name AS 'GroupTypeName',
  6832. // di.VisitDate,
  6833. // di.VisitPNumber,
  6834. // (
  6835. // SELECT
  6836. // SUM(ffr.ItemSumPrice)
  6837. // FROM
  6838. // OA2023DB.dbo.Fin_ForeignReceivables ffr
  6839. // WHERE
  6840. // ffr.IsDel = 0
  6841. // AND ffr.Diid = di.Id
  6842. // ) 'ReceivableAmount',
  6843. // (
  6844. // SELECT
  6845. // SUM(fpr.Price)
  6846. // FROM
  6847. // OA2023DB.dbo.Fin_ProceedsReceived fpr
  6848. // WHERE
  6849. // fpr.IsDel = 0
  6850. // AND fpr.DIId = di.Id
  6851. // ) 'ReceivedAmount',
  6852. // (
  6853. // SELECT
  6854. // SUM(ccp.PayMoney * ccp.DayRate)
  6855. // FROM
  6856. // Fin_PaymentRefundAndOtherMoney prom
  6857. // INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
  6858. // AND prom.DiId = ccp.DIId
  6859. // WHERE
  6860. // prom.IsDel = 0
  6861. // AND prom.PayType = 1
  6862. // AND ccp.CTable = 285
  6863. // AND ccp.IsAuditGM = 1
  6864. // AND prom.DiId = di.Id
  6865. // ) AS 'RefundedAmount',
  6866. // (
  6867. // SELECT
  6868. // SUM(ccp.PayMoney * ccp.DayRate)
  6869. // FROM
  6870. // Grp_HotelReservations hr
  6871. // INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  6872. // WHERE
  6873. // hr.IsDel = 0
  6874. // AND ccp.IsDel = 0
  6875. // AND ccp.CTable = 76
  6876. // AND (
  6877. // ccp.IsAuditGM = 1
  6878. // OR ccp.IsAuditGM = 3
  6879. // )
  6880. // AND hr.DiId = di.Id
  6881. // ) AS 'HotelAmount',
  6882. // (
  6883. // SELECT
  6884. // SUM(
  6885. // (ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate)
  6886. // )
  6887. // FROM
  6888. // Grp_CarTouristGuideGroundReservations ctggr
  6889. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  6890. // AND ccp.CTable = 79
  6891. // AND ctggr.Id = ccp.CId
  6892. // WHERE
  6893. // ctggr.IsDel = 0
  6894. // AND (
  6895. // ccp.IsAuditGM = 1
  6896. // OR ccp.IsAuditGM = 3
  6897. // )
  6898. // AND ctggr.DiId = di.Id
  6899. // ) AS 'LocalGuideAmount',
  6900. // (
  6901. // SELECT
  6902. // SUM(ccp.PayMoney * ccp.DayRate)
  6903. // FROM
  6904. // Grp_AirTicketReservations atr
  6905. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6906. // AND ccp.CTable = 85
  6907. // AND atr.Id = ccp.CId
  6908. // WHERE
  6909. // atr.IsDel = 0
  6910. // AND ccp.IsAuditGM = 1
  6911. // AND atr.DIId = di.Id
  6912. // ) AS 'AirTicketAmount',
  6913. // (
  6914. // SELECT
  6915. // SUM(ccp.PayMoney * ccp.DayRate)
  6916. // FROM
  6917. // Grp_VisaInfo vi
  6918. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6919. // AND ccp.CTable = 80
  6920. // AND vi.Id = ccp.CId
  6921. // WHERE
  6922. // vi.IsDel = 0
  6923. // AND ccp.IsAuditGM = 1
  6924. // AND vi.DIId = di.Id
  6925. // ) AS 'VisaAmount',
  6926. // (
  6927. // SELECT
  6928. // SUM(ccp.PayMoney * ccp.DayRate)
  6929. // FROM
  6930. // Grp_InvitationOfficialActivities ioa
  6931. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6932. // AND ccp.CTable = 81
  6933. // AND ioa.Id = ccp.CId
  6934. // WHERE
  6935. // ioa.IsDel = 0
  6936. // AND ccp.IsAuditGM = 1
  6937. // AND ioa.DiId = di.Id
  6938. // ) AS 'OAAmount',
  6939. // (
  6940. // SELECT
  6941. // SUM(ccp.PayMoney * ccp.DayRate)
  6942. // FROM
  6943. // Grp_Customers ic
  6944. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6945. // AND ccp.CTable = 82
  6946. // AND ic.Id = ccp.CId
  6947. // WHERE
  6948. // ic.IsDel = 0
  6949. // AND ccp.IsAuditGM = 1
  6950. // AND ic.DiId = di.Id
  6951. // ) AS 'InsureAmount',
  6952. // (
  6953. // SELECT
  6954. // SUM(ccp.PayMoney * ccp.DayRate)
  6955. // FROM
  6956. // Grp_DecreasePayments dp
  6957. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6958. // AND ccp.CTable = 98
  6959. // AND dp.Id = ccp.CId
  6960. // WHERE
  6961. // dp.IsDel = 0
  6962. // AND ccp.IsAuditGM = 1
  6963. // AND dp.Diid = di.Id
  6964. // ) AS 'OtherAmount'
  6965. //FROM
  6966. // OA2023DB.dbo.Grp_DelegationInfo di
  6967. // LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
  6968. //WHERE
  6969. // di.IsDel = 0
  6970. // AND di.IsBid = 0
  6971. // AND di.VisitDate BETWEEN '{0}' AND '{1}'", beginDt, endDt);
  6972. //含未审核SQL
  6973. string sql = string.Format(@"SELECT
  6974. ROW_NUMBER() OVER(
  6975. ORDER BY
  6976. di.VisitDate Asc
  6977. ) AS 'RowIndex',
  6978. di.Id,
  6979. di.ClientName,
  6980. di.TeamName,
  6981. di.TeamDid,
  6982. ss.Name AS 'GroupTypeName',
  6983. di.VisitDate,
  6984. di.VisitPNumber,
  6985. (
  6986. SELECT
  6987. SUM(ffr.ItemSumPrice)
  6988. FROM
  6989. OA2023DB.dbo.Fin_ForeignReceivables ffr
  6990. WHERE
  6991. ffr.IsDel = 0
  6992. AND ffr.Diid = di.Id
  6993. ) 'ReceivableAmount',
  6994. (
  6995. SELECT
  6996. SUM(fpr.Price)
  6997. FROM
  6998. OA2023DB.dbo.Fin_ProceedsReceived fpr
  6999. WHERE
  7000. fpr.IsDel = 0
  7001. AND fpr.DIId = di.Id
  7002. ) 'ReceivedAmount',
  7003. (
  7004. SELECT
  7005. SUM(ccp.PayMoney * ccp.DayRate)
  7006. FROM
  7007. Fin_PaymentRefundAndOtherMoney prom
  7008. INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
  7009. AND prom.DiId = ccp.DIId
  7010. WHERE
  7011. prom.IsDel = 0
  7012. AND prom.PayType = 1
  7013. AND ccp.CTable = 285 --AND ccp.IsAuditGM = 1
  7014. AND ccp.IsAuditGM != 2
  7015. AND prom.DiId = di.Id
  7016. ) AS 'RefundedAmount',
  7017. (
  7018. SELECT
  7019. SUM(ccp.PayMoney * ccp.DayRate)
  7020. FROM
  7021. Grp_HotelReservations hr
  7022. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  7023. WHERE
  7024. hr.IsDel = 0
  7025. AND ccp.IsDel = 0
  7026. AND ccp.CTable = 76 -- AND (
  7027. -- ccp.IsAuditGM = 1
  7028. -- OR ccp.IsAuditGM = 3
  7029. -- )
  7030. AND ccp.IsAuditGM != 2
  7031. AND hr.DiId = di.Id
  7032. ) AS 'HotelAmount',
  7033. (
  7034. SELECT
  7035. SUM(
  7036. (ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate)
  7037. )
  7038. FROM
  7039. Grp_CarTouristGuideGroundReservations ctggr
  7040. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  7041. AND ccp.CTable = 79
  7042. AND ctggr.Id = ccp.CId
  7043. WHERE
  7044. ctggr.IsDel = 0 -- AND (
  7045. -- ccp.IsAuditGM = 1
  7046. -- OR ccp.IsAuditGM = 3
  7047. -- )
  7048. AND ccp.IsAuditGM != 2
  7049. AND ctggr.DiId = di.Id
  7050. ) AS 'LocalGuideAmount',
  7051. (
  7052. SELECT
  7053. SUM(ccp.PayMoney * ccp.DayRate)
  7054. FROM
  7055. Grp_AirTicketReservations atr
  7056. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7057. AND ccp.CTable = 85
  7058. AND atr.Id = ccp.CId
  7059. WHERE
  7060. atr.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7061. AND ccp.IsAuditGM != 2
  7062. AND atr.DIId = di.Id
  7063. ) AS 'AirTicketAmount',
  7064. (
  7065. SELECT
  7066. SUM(ccp.PayMoney * ccp.DayRate)
  7067. FROM
  7068. Grp_VisaInfo vi
  7069. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7070. AND ccp.CTable = 80
  7071. AND vi.Id = ccp.CId
  7072. WHERE
  7073. vi.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7074. AND ccp.IsAuditGM != 2
  7075. AND vi.DIId = di.Id
  7076. ) AS 'VisaAmount',
  7077. (
  7078. SELECT
  7079. SUM(ccp.PayMoney * ccp.DayRate)
  7080. FROM
  7081. Grp_InvitationOfficialActivities ioa
  7082. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7083. AND ccp.CTable = 81
  7084. AND ioa.Id = ccp.CId
  7085. WHERE
  7086. ioa.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7087. AND ccp.IsAuditGM != 2
  7088. AND ioa.DiId = di.Id
  7089. ) AS 'OAAmount',
  7090. (
  7091. SELECT
  7092. SUM(ccp.PayMoney * ccp.DayRate)
  7093. FROM
  7094. Grp_Customers ic
  7095. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7096. AND ccp.CTable = 82
  7097. AND ic.Id = ccp.CId
  7098. WHERE
  7099. ic.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7100. AND ccp.IsAuditGM != 2
  7101. AND ic.DiId = di.Id
  7102. ) AS 'InsureAmount',
  7103. (
  7104. SELECT
  7105. SUM(ccp.PayMoney * ccp.DayRate)
  7106. FROM
  7107. Grp_DecreasePayments dp
  7108. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7109. AND ccp.CTable = 98
  7110. AND dp.Id = ccp.CId
  7111. WHERE
  7112. dp.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7113. AND ccp.IsAuditGM != 2
  7114. AND dp.Diid = di.Id
  7115. ) AS 'OtherAmount'
  7116. FROM
  7117. OA2023DB.dbo.Grp_DelegationInfo di
  7118. LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
  7119. WHERE
  7120. di.IsDel = 0
  7121. AND di.IsBid = 0
  7122. AND di.VisitDate BETWEEN '{0}' AND '{1}'", beginDt, endDt);
  7123. var groupItems = await _sqlSugar.SqlQueryable<CorporateProfitInfo>(sql).ToArrayAsync();
  7124. if (groupItems.Any())
  7125. {
  7126. var groupIds = groupItems.Select(x => x.Id).ToArray();
  7127. var feeCountInfos = await CorporateProfitFeeCount(groupIds);
  7128. if (feeCountInfos.Any())
  7129. {
  7130. foreach (var item in groupItems)
  7131. {
  7132. var tips = feeCountInfos.FirstOrDefault(x => x.Id == item.Id)?.FeeCountTipsLabel ?? "";
  7133. if (!string.IsNullOrEmpty(tips)) item.FeeCountTipsLabel = tips;
  7134. }
  7135. }
  7136. }
  7137. var dailySql = string.Format(@"SELECT
  7138. dfp.Id,
  7139. dfp.CompanyId,
  7140. sc.CompanyName,
  7141. sd.DepName AS 'Branch',
  7142. su.CnName AS 'Applicant',
  7143. dfp.PriceTypeId,
  7144. sst.Id AS 'PriceParentTypeId',
  7145. sst.Name AS 'PriceParentTypeName',
  7146. ss.Id AS 'PriceTypeId',
  7147. ss.Name AS 'PriceypeName',
  7148. dfp.Instructions,
  7149. dfp.SumPrice AS 'CNYTotal',
  7150. dfpc.PriceName,
  7151. dfpc.Quantity,
  7152. dfpc.Price,
  7153. dfpc.ItemTotal,
  7154. dfpc.Remark,
  7155. dfp.CreateTime
  7156. From
  7157. Fin_DailyFeePayment dfp
  7158. INNER JOIN Fin_DailyFeePaymentContent dfpc on dfp.Id = dfpc.DFPId
  7159. LEFT JOIN Sys_Company sc on dfp.CompanyId = sc.Id
  7160. LEFT JOIN Sys_Users su on dfp.CreateUserId = su.Id
  7161. LEFT JOIN Sys_Department sd on su.DepId = sd.Id
  7162. LEFT JOIN Sys_SetData ss on dfp.PriceTypeId = ss.Id
  7163. LEFT JOIN Sys_SetDataType sst on ss.STid = sst.Id
  7164. WHERE
  7165. dfp.IsDel = 0
  7166. AND dfpc.IsDel = 0
  7167. AND dfp.CreateTime BETWEEN '{0}' AND '{1}'
  7168. AND dfp.IsPay = 1
  7169. ORDER BY
  7170. dfp.CompanyId,
  7171. su.DepId,
  7172. dfp.CreateUserId,
  7173. dfp.PriceTypeId,
  7174. dfp.CreateTime ASC", beginDt, endDt);
  7175. var dailyItems = await _sqlSugar.SqlQueryable<DailyInfo>(dailySql).ToArrayAsync();
  7176. view.GroupItems = groupItems.OrderBy(x => x.RowIndex).ToArray();
  7177. view.DailyItems = dailyItems;
  7178. return view;
  7179. }
  7180. /// <summary>
  7181. /// 企业利润
  7182. /// 团组费用条数统计
  7183. /// </summary>
  7184. /// <param name="groupIds"></param>
  7185. /// <returns></returns>
  7186. private async Task<CorporateProfitFeeCount[]> CorporateProfitFeeCount(int[] groupIds)
  7187. {
  7188. if (!groupIds.Any()) return Array.Empty<CorporateProfitFeeCount>();
  7189. //含未审核SQL
  7190. string sql = string.Format(@"SELECT
  7191. ROW_NUMBER() OVER(
  7192. ORDER BY
  7193. di.VisitDate Asc
  7194. ) AS 'RowIndex',
  7195. di.Id,
  7196. di.TeamName,
  7197. di.VisitDate,
  7198. (
  7199. SELECT
  7200. Count(1)
  7201. FROM
  7202. OA2023DB.dbo.Fin_ForeignReceivables ffr
  7203. WHERE
  7204. ffr.IsDel = 0
  7205. AND ffr.Diid = di.Id
  7206. ) 'ReceivableTotal',
  7207. (
  7208. SELECT
  7209. Count(1)
  7210. FROM
  7211. OA2023DB.dbo.Fin_ProceedsReceived fpr
  7212. WHERE
  7213. fpr.IsDel = 0
  7214. AND fpr.DIId = di.Id
  7215. ) 'ReceivedTotal',
  7216. (
  7217. SELECT
  7218. Count(1)
  7219. FROM
  7220. Fin_PaymentRefundAndOtherMoney prom
  7221. INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
  7222. AND prom.DiId = ccp.DIId
  7223. WHERE
  7224. prom.IsDel = 0
  7225. AND prom.PayType = 1
  7226. AND ccp.CTable = 285
  7227. --AND ccp.IsAuditGM = 1
  7228. AND ccp.IsAuditGM != 2
  7229. AND prom.DiId = di.Id
  7230. ) AS 'RefundedTotal',
  7231. (
  7232. SELECT
  7233. Count(1)
  7234. FROM
  7235. Grp_HotelReservations hr
  7236. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  7237. WHERE
  7238. hr.IsDel = 0
  7239. AND ccp.IsDel = 0
  7240. AND ccp.CTable = 76 -- AND (
  7241. -- ccp.IsAuditGM = 1
  7242. -- OR ccp.IsAuditGM = 3
  7243. -- )
  7244. AND ccp.IsAuditGM != 2
  7245. AND hr.DiId = di.Id
  7246. ) AS 'HotelTotal',
  7247. (
  7248. SELECT
  7249. Count(1)
  7250. FROM
  7251. Grp_CarTouristGuideGroundReservations ctggr
  7252. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  7253. AND ccp.CTable = 79
  7254. AND ctggr.Id = ccp.CId
  7255. WHERE
  7256. ctggr.IsDel = 0 -- AND (
  7257. -- ccp.IsAuditGM = 1
  7258. -- OR ccp.IsAuditGM = 3
  7259. -- )
  7260. AND ccp.IsAuditGM != 2
  7261. AND ctggr.DiId = di.Id
  7262. ) AS 'LocalGuideTotal',
  7263. (
  7264. SELECT
  7265. Count(1)
  7266. FROM
  7267. Grp_AirTicketReservations atr
  7268. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7269. AND ccp.CTable = 85
  7270. AND atr.Id = ccp.CId
  7271. WHERE
  7272. atr.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7273. AND ccp.IsAuditGM != 2
  7274. AND atr.DIId = di.Id
  7275. ) AS 'AirTicketToal',
  7276. (
  7277. SELECT
  7278. Count(1)
  7279. FROM
  7280. Grp_VisaInfo vi
  7281. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7282. AND ccp.CTable = 80
  7283. AND vi.Id = ccp.CId
  7284. WHERE
  7285. vi.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7286. AND ccp.IsAuditGM != 2
  7287. AND vi.DIId = di.Id
  7288. ) AS 'VisaTotal',
  7289. (
  7290. SELECT
  7291. Count(1)
  7292. FROM
  7293. Grp_InvitationOfficialActivities ioa
  7294. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7295. AND ccp.CTable = 81
  7296. AND ioa.Id = ccp.CId
  7297. WHERE
  7298. ioa.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7299. AND ccp.IsAuditGM != 2
  7300. AND ioa.DiId = di.Id
  7301. ) AS 'OATotal',
  7302. (
  7303. SELECT
  7304. Count(1)
  7305. FROM
  7306. Grp_Customers ic
  7307. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7308. AND ccp.CTable = 82
  7309. AND ic.Id = ccp.CId
  7310. WHERE
  7311. ic.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7312. AND ccp.IsAuditGM != 2
  7313. AND ic.DiId = di.Id
  7314. ) AS 'InsureTotal',
  7315. (
  7316. SELECT
  7317. Count(1)
  7318. FROM
  7319. Grp_DecreasePayments dp
  7320. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7321. AND ccp.CTable = 98
  7322. AND dp.Id = ccp.CId
  7323. WHERE
  7324. dp.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7325. AND ccp.IsAuditGM != 2
  7326. AND dp.Diid = di.Id
  7327. ) AS 'OtherTotal'
  7328. FROM
  7329. OA2023DB.dbo.Grp_DelegationInfo di
  7330. LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
  7331. WHERE
  7332. di.IsDel = 0
  7333. AND di.IsBid = 0
  7334. AND di.Id IN({0})", string.Join(",", groupIds));
  7335. return await _sqlSugar.SqlQueryable<CorporateProfitFeeCount>(sql).ToArrayAsync();
  7336. }
  7337. /// <summary>
  7338. /// 团组利润item详情
  7339. /// </summary>
  7340. /// <param name="type">
  7341. /// 1:详情
  7342. /// 2:excel 生成
  7343. /// </param>
  7344. /// <param name="begin"></param>
  7345. /// <param name="end"></param>
  7346. /// <returns></returns>
  7347. private async Task<CorporateProfitItemView> CorporateProfitItems(int type, string begin, string end)
  7348. {
  7349. var data = await CorporateProfitInfos(begin, end);
  7350. var groupItems = data.GroupItems;
  7351. var dailyItems = data.DailyItems;
  7352. var priceTypeIds = new List<int>() {
  7353. 686, //686 信用卡还款
  7354. 687, //687 张总私人费用
  7355. 688, //688 代报销社保生育补贴
  7356. 688, //688 代报销社保生育补贴
  7357. 306, //306 人事行政费用-张总家用类
  7358. 325, //325 会展部备用金
  7359. 689, //689 团组签证保险
  7360. };
  7361. var companyDailyItems = dailyItems
  7362. .Where(x => !priceTypeIds.Contains(x.PriceTypeId))
  7363. .GroupBy(x => x.CompanyName)
  7364. .Select(g => new { CompanyName = g.Key, CNYTotal = g.Sum(x => x.CNYTotal) })
  7365. .OrderBy(x => x.CNYTotal)
  7366. .ToArray();
  7367. //业务类型
  7368. var groupTypeIds = new List<int>() {
  7369. 38, // 政府团
  7370. 39, // 企业团
  7371. 40, // 散客团
  7372. 1048 // 高校团
  7373. };
  7374. var inforTypeIds = new List<int>() {
  7375. 302, // 成都-会务活动
  7376. 691, // 四川-会务活动
  7377. };
  7378. //团组 收款、成本、利润 合计
  7379. var groupCollectionTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CollectionTotal);
  7380. var groupReceivableTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableProfitTotal);
  7381. var groupCostTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal);
  7382. var groupProfitTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ProfitTotal);
  7383. //非团组 收款、成本、利润 合计
  7384. var notGroupCollectionTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CollectionTotal);
  7385. var notGroupReceivableTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableProfitTotal);
  7386. var notGroupCostTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal);
  7387. var notGroupProfitTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ProfitTotal);
  7388. //会务数量
  7389. int inforCount = groupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Count();
  7390. //服务人数
  7391. int serviceCount = groupItems.Sum(x => x.VisitPNumber);
  7392. //总利润
  7393. decimal totalProfit = groupProfitTotal + notGroupProfitTotal;
  7394. var dailyLabel = $"*不含日付费用类型(信用卡还款、张总私人费用、代报销社保生育补贴、人事行政费用 - 张总家用类、会展部备用金、团组签证保险)\r\n";
  7395. var dailyExcelLabel = dailyLabel;
  7396. if (companyDailyItems.Any())
  7397. {
  7398. foreach (var dailyFee in companyDailyItems)
  7399. {
  7400. dailyLabel += $"<p>[{dailyFee.CompanyName}]日常产生费用:{dailyFee.CNYTotal.ToString("#0.00")} CNY </p>";
  7401. dailyExcelLabel += $"[{dailyFee.CompanyName}]日常产生费用:{dailyFee.CNYTotal.ToString("#0.00")} CNY \r\n";
  7402. }
  7403. }
  7404. string label = string.Format(@$"<div style='color:black'><p>团组收款合计:{groupCollectionTotal.ToString("#0.00")} CNY&nbsp;团组产生费用合计:{groupCostTotal.ToString("#0.00")} CNY&nbsp;团组利润合计:{groupProfitTotal.ToString("#0.00")} CNY</p><p>非团组收款合计:{notGroupCollectionTotal.ToString("#0.00")} CNY&nbsp;非团组产生费用合计:{notGroupCostTotal.ToString("#0.00")} CNY&nbsp;非团组利润合计:{notGroupProfitTotal.ToString("#0.00")} CNY</p>{dailyLabel}<p>其中会务:{inforCount}个</p><p>服务人数:{serviceCount}人</p>总利润:{totalProfit.ToString("#0.00")} CNY</div>");
  7405. var datas = _mapper.Map<CorporateProfitItem[]>(groupItems);
  7406. if (type == 2) //excel 下载
  7407. {
  7408. var designer = new WorkbookDesigner();
  7409. var tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/团组利润模板.xls";
  7410. designer.Workbook = new Workbook(tempPath);
  7411. designer.SetDataSource("ReceivablesTemp", datas);
  7412. //
  7413. designer.SetDataSource("ReceivableProfitTotal", groupReceivableTotal.ToString("#0.00"));
  7414. designer.SetDataSource("NotReceivableProfitTotal", notGroupReceivableTotal.ToString("#0.00"));
  7415. designer.SetDataSource("SumAccounts", groupCollectionTotal.ToString("#0.00"));
  7416. designer.SetDataSource("SumReceived", groupCostTotal.ToString("#0.00"));
  7417. designer.SetDataSource("SumBalance", groupProfitTotal.ToString("#0.00"));
  7418. designer.SetDataSource("notSumAccounts", notGroupCollectionTotal.ToString("#0.00"));
  7419. designer.SetDataSource("notSumReceived", notGroupCostTotal.ToString("#0.00"));
  7420. designer.SetDataSource("SumOfNotTeamBalance", notGroupProfitTotal.ToString("#0.00"));
  7421. designer.SetDataSource("DailyLabel", dailyExcelLabel);
  7422. designer.SetDataSource("MeetingNumber", inforCount + "个");
  7423. designer.SetDataSource("ServiceNumber", serviceCount + "人");
  7424. designer.SetDataSource("SumAllBalance", totalProfit.ToString("#0.00"));
  7425. //根据数据源处理生成报表内容
  7426. designer.Process();
  7427. string fileName = $"团组利润({Convert.ToDateTime(begin).ToString("yyyy年MM月dd日")}~{Convert.ToDateTime(end).ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls";
  7428. designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
  7429. string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
  7430. label = url;
  7431. }
  7432. return new CorporateProfitItemView()
  7433. {
  7434. Items = datas,
  7435. Label = label
  7436. };
  7437. }
  7438. /// <summary>
  7439. /// 企业利润
  7440. /// Item
  7441. /// </summary>
  7442. /// <param name="dto"></param>
  7443. /// <returns></returns>
  7444. [HttpPost("CorporateProfitItem")]
  7445. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  7446. public async Task<IActionResult> CorporateProfitItem(CorporateProfitItemDto dto)
  7447. {
  7448. int portType = dto.PortType,
  7449. userId = dto.UserId,
  7450. pageId = dto.PageId;
  7451. #region 参数验证
  7452. //var validationRules = new CorporateProfitItemDtoFoalidator();
  7453. //var validResult = await validationRules.ValidateAsync(dto);
  7454. //if (!validResult.IsValid)
  7455. //{
  7456. // var errors = new StringBuilder();
  7457. // foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  7458. // return Ok(JsonView(false, errors.ToString()));
  7459. //}
  7460. //#region 页面操作权限验证
  7461. //var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId, pageId);
  7462. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  7463. //#endregion
  7464. #endregion
  7465. string beginDt = $"{dto.BeginDt} 00:00:00",
  7466. endDt = $"{dto.EndDt} 23:59:59";
  7467. return Ok(JsonView(true, "操作成功!", await CorporateProfitItems(1, beginDt, endDt)));
  7468. }
  7469. /// <summary>
  7470. /// 企业利润 Excel导出
  7471. /// </summary>
  7472. /// <param name="dto"></param>
  7473. /// <returns></returns>
  7474. [HttpPost("CorporateProfitExcelDownload")]
  7475. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  7476. public async Task<IActionResult> CorporateProfitExcelDownload(CorporateProfitExcelDownloadDto dto)
  7477. {
  7478. int portType = dto.PortType,
  7479. userId = dto.UserId,
  7480. pageId = dto.PageId,
  7481. excelType = dto.ExcelType;
  7482. #region 参数验证
  7483. var validationRules = new CorporateProfitExcelDownloadDtoFoalidator();
  7484. var validResult = await validationRules.ValidateAsync(dto);
  7485. if (!validResult.IsValid)
  7486. {
  7487. var errors = new StringBuilder();
  7488. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  7489. return Ok(JsonView(false, errors.ToString()));
  7490. }
  7491. #region 页面操作权限验证
  7492. //var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId,pageId);
  7493. //if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权限!"));
  7494. #endregion
  7495. #endregion
  7496. string beginDt = $"{dto.BeginDt} 00:00:00",
  7497. endDt = $"{dto.EndDt} 23:59:59";
  7498. DateTime beginDate = DateTime.Parse(beginDt),
  7499. endDate = DateTime.Parse(endDt);
  7500. string yearBeginDt = $"{beginDate.Year}-01-01 00:00:00",
  7501. yearEndDt = $"{beginDate.Year}-12-31 23:59:59";
  7502. //业务类型
  7503. var priceTypeIds = new List<int>() {
  7504. 686, //686 信用卡还款
  7505. 687, //687 张总私人费用
  7506. 688, //688 代报销社保生育补贴
  7507. 688, //688 代报销社保生育补贴
  7508. 306, //306 人事行政费用-张总家用类
  7509. 325, //325 会展部备用金
  7510. 689, //689 团组签证保险
  7511. };
  7512. var data = await CorporateProfitInfos(beginDt, endDt);
  7513. var groupItems = data.GroupItems;
  7514. var dailyItems = data.DailyItems;
  7515. //筛选不统计的费用类型
  7516. //if (dailyItems.Any()) dailyItems = dailyItems.Where(x => !priceTypeIds.Contains(x.PriceTypeId)).ToArray();
  7517. var yearData = await CorporateProfitInfos(yearBeginDt, yearEndDt);
  7518. var yearGroupItems = yearData.GroupItems;
  7519. var yearDailyItems = yearData.DailyItems;
  7520. //筛选不统计的费用类型
  7521. //if (yearDailyItems.Any()) yearDailyItems = yearDailyItems.Where(x => !priceTypeIds.Contains(x.PriceTypeId)).ToArray();
  7522. #region 公共参数
  7523. //团组收款、成本、利润 合计
  7524. decimal monthGroupCollectionTotal = groupItems.Sum(x => x.CollectionTotal),
  7525. monthGroupCostTotal = groupItems.Sum(x => x.CostTotal),
  7526. yearGroupCollectionTotal = yearGroupItems.Sum(x => x.CollectionTotal),
  7527. yearGroupCostTotal = yearGroupItems.Sum(x => x.CostTotal);
  7528. //日付申请 48 人员费用、 49 办公费用、50 销售费用、51 其他费用、55 大运会、90 各部门基础固定费用明细
  7529. decimal monthStaffCosts = dailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.CNYTotal),
  7530. monthOfficeExpenses = dailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.CNYTotal),
  7531. monthCostSales = dailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.CNYTotal),
  7532. monthOtherFees = dailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.CNYTotal),
  7533. monthDyhFees = dailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.CNYTotal),
  7534. monthDepartFixedExpenses = dailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.CNYTotal),
  7535. yearStaffCosts = yearDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.CNYTotal),
  7536. yearOfficeExpenses = yearDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.CNYTotal),
  7537. yearCostSales = yearDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.CNYTotal),
  7538. yearOtherFees = yearDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.CNYTotal),
  7539. yearDyhFees = yearDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.CNYTotal),
  7540. yearDepartFixedExpenses = yearDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.CNYTotal);
  7541. #endregion
  7542. //月度报表、季度报表、年度报表
  7543. if (excelType == 1 || excelType == 2 || excelType == 3)
  7544. {
  7545. var designer = new WorkbookDesigner();
  7546. string fileName = $"({beginDate.ToString("yyyy年MM月dd日")}~{endDate.ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls",
  7547. fileNamePrefix = string.Empty,
  7548. tempPath = string.Empty,
  7549. workSheetName = string.Empty;
  7550. if (excelType == 1)
  7551. {
  7552. tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/月度报表模板.xls";
  7553. workSheetName = "月度报表";
  7554. fileNamePrefix = "月度报表";
  7555. }
  7556. else if (excelType == 2)
  7557. {
  7558. tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/季度报表模板.xls";
  7559. workSheetName = "季度报表";
  7560. fileNamePrefix = "季度报表";
  7561. }
  7562. else if (excelType == 3)
  7563. {
  7564. tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/年度报表模板.xls";
  7565. workSheetName = "年度报表";
  7566. fileNamePrefix = "年度报表";
  7567. }
  7568. else return Ok(JsonView(false));
  7569. designer.Workbook = new Workbook(tempPath);
  7570. designer.Workbook.Worksheets[0].Name = workSheetName;
  7571. #region 填充值
  7572. string time = $"所属期间: {beginDate.ToString("yyyy 年 MM 月 dd 日")} 至 {endDate.ToString("yyyy 年 MM 月 dd 日")}";
  7573. designer.SetDataSource("Time", time);
  7574. designer.SetDataSource("MonthReceivedPrice", monthGroupCollectionTotal.ToString("#0.00"));//本月已收
  7575. designer.SetDataSource("YearReceivedPrice", yearGroupCollectionTotal.ToString("#0.00")); //本年已收
  7576. designer.SetDataSource("MonthSumReceives", monthGroupCollectionTotal.ToString("#0.00"));//本月团组收款
  7577. designer.SetDataSource("MonthTeamCost", monthGroupCostTotal.ToString("#0.00")); //本月团组成本
  7578. designer.SetDataSource("YearSumReceives", yearGroupCollectionTotal.ToString("#0.00"));//本年团组收款
  7579. designer.SetDataSource("YearTeamCost", yearGroupCostTotal.ToString("#0.00")); //本年团组成本
  7580. designer.SetDataSource("MonthStaffCosts", monthStaffCosts.ToString("#0.00"));//本月人员费用
  7581. designer.SetDataSource("YearStaffCosts", yearStaffCosts.ToString("#0.00")); //本年人员费用
  7582. designer.SetDataSource("MonthOfficeExpenses", monthOfficeExpenses.ToString("#0.00"));//本月办公费用
  7583. designer.SetDataSource("YearOfficeExpenses", yearOfficeExpenses.ToString("#0.00")); //本年办公费用
  7584. designer.SetDataSource("MonthCostSales", monthCostSales.ToString("#0.00"));//本月销售费用
  7585. designer.SetDataSource("YearCostSales", yearCostSales.ToString("#0.00")); //本年销售费用
  7586. designer.SetDataSource("MonthOtherFees", monthOtherFees.ToString("#0.00"));//本月其他费用
  7587. designer.SetDataSource("YearOtherFees", yearOtherFees.ToString("#0.00")); //本年其他费用
  7588. designer.SetDataSource("MonthDYHFees", monthDyhFees.ToString("#0.00"));//本月大运会费用
  7589. designer.SetDataSource("YearDYHFees", yearDyhFees.ToString("#0.00")); //本年大运会费用
  7590. designer.SetDataSource("MonthDepartFixedFees", monthDepartFixedExpenses.ToString("#0.00"));//本月各部门基础固定费用明细费用
  7591. designer.SetDataSource("YearDepartFixedFees", yearDepartFixedExpenses.ToString("#0.00")); //本年各部门基础固定费用明细费用
  7592. // 填表时间
  7593. string fillingTime = $"填报时间:{DateTime.Now.ToString("yyyy.MM.dd")}";
  7594. designer.SetDataSource("FillingTime", fillingTime);
  7595. #endregion
  7596. //根据数据源处理生成报表内容
  7597. designer.Process();
  7598. fileName = fileNamePrefix + fileName;
  7599. designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
  7600. string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
  7601. return Ok(JsonView(true, "操作成功!", url));
  7602. }
  7603. //利润报表
  7604. else if (excelType == 4)
  7605. {
  7606. var designer = new WorkbookDesigner();
  7607. var tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/利润报表New.xlsx";
  7608. designer.Workbook = new Workbook(tempPath);
  7609. #region 填充值
  7610. string time = $"所属期间: {beginDate.ToString("yyyy 年 MM 月 dd 日")} 至 {endDate.ToString("yyyy 年 MM 月 dd 日")}";
  7611. designer.SetDataSource("Time", time);
  7612. //办公费用
  7613. decimal officePirce = yearStaffCosts + yearOfficeExpenses;
  7614. designer.SetDataSource("officePirce", officePirce.ToString("#0.00"));
  7615. //业务类型
  7616. var groupTypeIds = new List<int>() {
  7617. 38, // 政府团
  7618. 39, // 企业团
  7619. 40, // 散客团
  7620. 1048 // 高校团
  7621. };
  7622. var inforTypeIds = new List<int>() {
  7623. 302, // 成都-会务活动
  7624. 691, // 四川-会务活动
  7625. };
  7626. var competitionTypeIds = new List<int>() {
  7627. 762, //四川-赛事项目收入
  7628. 1047, // 成都-赛事项目收入
  7629. };
  7630. var otherTypeIds = new List<int>();
  7631. otherTypeIds.AddRange(groupTypeIds);
  7632. otherTypeIds.AddRange(inforTypeIds);
  7633. otherTypeIds.AddRange(competitionTypeIds);
  7634. decimal monthAllIncomes = groupItems.Sum(x => x.ReceivableAmount), //月-收入
  7635. monthTzIncomes = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7636. monthHwIncomes = groupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7637. monthSsIncomes = groupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7638. monthQtIncomes = groupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7639. monthAllCost = groupItems.Sum(x => x.CostTotal), //月-成本
  7640. monthTzCost = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7641. monthHwCost = groupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7642. monthSsCost = groupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7643. monthQtCost = groupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7644. monthAllGross = monthAllIncomes - monthAllCost, //月-毛利金额
  7645. monthTzGross = monthTzIncomes - monthTzCost,
  7646. monthHwGross = monthHwIncomes - monthHwCost,
  7647. monthSsGross = monthSsIncomes - monthSsCost,
  7648. monthQtGross = monthQtIncomes - monthQtCost,
  7649. yearAllIncomes = yearGroupItems.Sum(x => x.ReceivableAmount), //年-收入
  7650. yearTzIncomes = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7651. yearHwIncomes = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7652. yearSsIncomes = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7653. yearQtIncomes = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7654. yearAllCost = yearGroupItems.Sum(x => x.CostTotal), //年-成本
  7655. yearTzCost = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7656. yearHwCost = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7657. yearSsCost = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7658. yearQtCost = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7659. yearAllGross = yearAllIncomes - yearAllCost, //年-毛利金额
  7660. yearTzGross = yearTzIncomes - yearTzCost,
  7661. yearHwGross = yearHwIncomes - yearHwCost,
  7662. yearSsGross = yearSsIncomes - yearSsCost,
  7663. yearQtGross = yearQtIncomes - yearQtCost;
  7664. //年-团数量
  7665. int yearAllCount = yearGroupItems.Count(),
  7666. yearTzCount = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Count(),
  7667. yearHwCount = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Count(),
  7668. yearSsCount = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Count(),
  7669. yearQtCount = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Count();
  7670. //年-利率
  7671. string yearAllRate = "0.00 %",
  7672. yearTzRate = "0.00 %",
  7673. yearHwRate = "0.00 %",
  7674. yearSsRate = "0.00 %",
  7675. yearQtRate = "0.00 %";
  7676. if (yearAllIncomes != 0) yearAllRate = (yearAllGross / yearAllIncomes * 100).ToString("#0.00") + "%";
  7677. if (yearTzIncomes != 0) yearTzRate = (yearTzGross / yearTzIncomes * 100).ToString("#0.00") + "%";
  7678. if (yearHwIncomes != 0) yearHwRate = (yearHwGross / yearHwIncomes * 100).ToString("#0.00") + "%";
  7679. if (yearSsIncomes != 0) yearSsRate = (yearSsGross / yearSsIncomes * 100).ToString("#0.00") + "%";
  7680. if (yearQtIncomes != 0) yearQtRate = (yearQtGross / yearQtIncomes * 100).ToString("#0.00") + "%";
  7681. #region 月
  7682. //收入
  7683. designer.SetDataSource("MonthAllIncomes", monthAllIncomes.ToString("#0.00"));
  7684. designer.SetDataSource("MonthtzIncomes", monthTzIncomes.ToString("#0.00"));
  7685. designer.SetDataSource("MonthhwIncomes", monthHwIncomes.ToString("#0.00"));
  7686. designer.SetDataSource("MonthssIncomes", monthSsIncomes.ToString("#0.00"));
  7687. designer.SetDataSource("MonthqtIncomes", monthQtIncomes.ToString("#0.00"));
  7688. //成本
  7689. designer.SetDataSource("MonthAllCost", monthAllCost.ToString("#0.00"));
  7690. designer.SetDataSource("MonthtzCost", monthTzCost.ToString("#0.00"));
  7691. designer.SetDataSource("MonthhwCost", monthHwCost.ToString("#0.00"));
  7692. designer.SetDataSource("MonthssCost", monthSsCost.ToString("#0.00"));
  7693. designer.SetDataSource("MonthqtCost", monthQtCost.ToString("#0.00"));
  7694. //毛利金额
  7695. designer.SetDataSource("MonthAllGross", monthAllGross.ToString("#0.00"));
  7696. designer.SetDataSource("MonthtzGross", monthTzGross.ToString("#0.00"));
  7697. designer.SetDataSource("MonthhwGross", monthHwGross.ToString("#0.00"));
  7698. designer.SetDataSource("MonthssGross", monthSsGross.ToString("#0.00"));
  7699. designer.SetDataSource("MonthqtGross", monthQtGross.ToString("#0.00"));
  7700. #endregion
  7701. #region 年
  7702. //收入
  7703. designer.SetDataSource("YearAllIncomes", yearAllIncomes.ToString("#0.00"));
  7704. designer.SetDataSource("YeartzIncomes", yearTzIncomes.ToString("#0.00"));
  7705. designer.SetDataSource("YearhwIncomes", yearHwIncomes.ToString("#0.00"));
  7706. designer.SetDataSource("YearssIncomes", yearSsIncomes.ToString("#0.00"));
  7707. designer.SetDataSource("YearqtIncomes", yearQtIncomes.ToString("#0.00"));
  7708. //成本
  7709. designer.SetDataSource("YearAllCost", yearAllCost.ToString("#0.00"));
  7710. designer.SetDataSource("YeartzCost", yearTzCost.ToString("#0.00"));
  7711. designer.SetDataSource("YearhwCost", yearHwCost.ToString("#0.00"));
  7712. designer.SetDataSource("YearssCost", yearSsCost.ToString("#0.00"));
  7713. designer.SetDataSource("YearqtCost", yearQtCost.ToString("#0.00"));
  7714. //毛利金额
  7715. designer.SetDataSource("YearAllGross", yearAllGross.ToString("#0.00"));
  7716. designer.SetDataSource("YeartzGross", yearTzGross.ToString("#0.00"));
  7717. designer.SetDataSource("YearhwGross", yearHwGross.ToString("#0.00"));
  7718. designer.SetDataSource("YearssGross", yearSsGross.ToString("#0.00"));
  7719. designer.SetDataSource("YearqtGross", yearQtGross.ToString("#0.00"));
  7720. //毛利率
  7721. designer.SetDataSource("YearAllRate", yearAllRate);
  7722. designer.SetDataSource("YeartzRate", yearTzRate);
  7723. designer.SetDataSource("YearhwRate", yearHwRate);
  7724. designer.SetDataSource("YearssRate", yearSsRate);
  7725. designer.SetDataSource("YearqtRate", yearQtRate);
  7726. //数量
  7727. designer.SetDataSource("AllCount", yearAllCount.ToString());
  7728. designer.SetDataSource("tzCount", yearTzCount.ToString());
  7729. designer.SetDataSource("hwCount", yearHwCount.ToString());
  7730. designer.SetDataSource("ssCount", yearSsCount.ToString());
  7731. designer.SetDataSource("qtCount", yearQtCount.ToString());
  7732. #endregion
  7733. #region 日付相关
  7734. var dailyViewItems = new List<CorporateProfitDailyView>();
  7735. var dailyTypes = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0).ToListAsync();
  7736. var conmmentTexts = new List<CorporateProfitDailyCommentView>();
  7737. #region 员工费用 48
  7738. decimal monthStaffCostTotal = dailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.ItemTotal),
  7739. yearStaffCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.ItemTotal);
  7740. dailyViewItems.Add(new CorporateProfitDailyView() { No = "一", PriceName = "人员费用", ThisMonthAmount = monthStaffCostTotal, ThisYearAmount = yearStaffCostTotal });
  7741. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7742. {
  7743. MonthComment = DailyListToString(dailyItems.Where(x => x.PriceParentTypeId == 48).ToArray()),
  7744. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 48).ToArray())
  7745. });
  7746. var dailyStaffTypes = dailyTypes.Where(x => x.STid == 48).OrderBy(x => x.Id).ToList();
  7747. foreach (var item in dailyStaffTypes)
  7748. {
  7749. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  7750. decimal monthAmount = dailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  7751. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  7752. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  7753. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7754. {
  7755. MonthComment = DailyListToString(dailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  7756. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  7757. });
  7758. }
  7759. #endregion
  7760. #region 办公费用
  7761. decimal monthWorkCostTotal = dailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.ItemTotal), //总费用
  7762. yearWorkCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.ItemTotal);
  7763. dailyViewItems.Add(new CorporateProfitDailyView() { No = "二", PriceName = "办公费用", ThisMonthAmount = monthWorkCostTotal, ThisYearAmount = yearWorkCostTotal });
  7764. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7765. {
  7766. MonthComment = DailyListToString(dailyItems.Where(x => x.PriceParentTypeId == 49).ToArray()),
  7767. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 49).ToArray())
  7768. });
  7769. var dailyWorkTypes = dailyTypes.Where(x => x.STid == 49).OrderBy(x => x.Id).ToList();
  7770. foreach (var item in dailyWorkTypes)
  7771. {
  7772. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  7773. decimal monthAmount = dailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  7774. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  7775. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  7776. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7777. {
  7778. MonthComment = DailyListToString(dailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  7779. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  7780. });
  7781. }
  7782. #endregion
  7783. #region 销售费用
  7784. decimal monthSalesCostTotal = dailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.ItemTotal), //总费用
  7785. yearSalesCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.ItemTotal);
  7786. dailyViewItems.Add(new CorporateProfitDailyView() { No = "三", PriceName = "销售费用", ThisMonthAmount = monthSalesCostTotal, ThisYearAmount = yearSalesCostTotal });
  7787. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7788. {
  7789. MonthComment = DailyListToString(dailyItems.Where(x => x.PriceParentTypeId == 50).ToArray()),
  7790. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 50).ToArray())
  7791. });
  7792. var dailySalesTypes = dailyTypes.Where(x => x.STid == 50).OrderBy(x => x.Id).ToList();
  7793. foreach (var item in dailySalesTypes)
  7794. {
  7795. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  7796. decimal monthAmount = dailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  7797. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  7798. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  7799. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7800. {
  7801. MonthComment = DailyListToString(dailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  7802. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  7803. });
  7804. }
  7805. #endregion
  7806. #region 51 其他费用
  7807. decimal monthOtherCostTotal = dailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.ItemTotal), //总费用
  7808. yearOtherCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.ItemTotal);
  7809. dailyViewItems.Add(new CorporateProfitDailyView() { No = "四", PriceName = "其他费用", ThisMonthAmount = monthOtherCostTotal, ThisYearAmount = yearOtherCostTotal });
  7810. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7811. {
  7812. MonthComment = DailyListToString(dailyItems.Where(x => x.PriceParentTypeId == 51).ToArray()),
  7813. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 51).ToArray())
  7814. });
  7815. var dailyOtherTypes = dailyTypes.Where(x => x.STid == 51).OrderBy(x => x.Id).ToList();
  7816. foreach (var item in dailyOtherTypes)
  7817. {
  7818. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  7819. decimal monthAmount = dailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  7820. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  7821. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  7822. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7823. {
  7824. MonthComment = DailyListToString(dailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  7825. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  7826. });
  7827. }
  7828. #endregion
  7829. #region 55 大运会
  7830. decimal monthDyhCostTotal = dailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.ItemTotal), //总费用
  7831. yearDyhCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.ItemTotal);
  7832. dailyViewItems.Add(new CorporateProfitDailyView() { No = "五", PriceName = "大运会", ThisMonthAmount = monthDyhCostTotal, ThisYearAmount = yearDyhCostTotal });
  7833. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7834. {
  7835. MonthComment = DailyListToString(dailyItems.Where(x => x.PriceParentTypeId == 55).ToArray()),
  7836. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 55).ToArray())
  7837. });
  7838. var dailyDyhTypes = dailyTypes.Where(x => x.STid == 55).OrderBy(x => x.Id).ToList();
  7839. foreach (var item in dailyDyhTypes)
  7840. {
  7841. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  7842. decimal monthAmount = dailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  7843. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  7844. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  7845. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7846. {
  7847. MonthComment = DailyListToString(dailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  7848. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  7849. });
  7850. }
  7851. #endregion
  7852. #region 90 各部门基础固定费用明细
  7853. decimal monthBasicCostTotal = dailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.ItemTotal), //总费用
  7854. yearBasicCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.ItemTotal);
  7855. dailyViewItems.Add(new CorporateProfitDailyView() { No = "六", PriceName = "各部门基础固定费用明细", ThisMonthAmount = monthBasicCostTotal, ThisYearAmount = yearBasicCostTotal });
  7856. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7857. {
  7858. MonthComment = DailyListToString(dailyItems.Where(x => x.PriceParentTypeId == 90).ToArray()),
  7859. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 90).ToArray())
  7860. });
  7861. var dailyBasicTypes = dailyTypes.Where(x => x.STid == 90).OrderBy(x => x.Id).ToList();
  7862. foreach (var item in dailyBasicTypes)
  7863. {
  7864. string priceName = item.Name;
  7865. decimal monthAmount = dailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  7866. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  7867. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  7868. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  7869. {
  7870. MonthComment = DailyListToString(dailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  7871. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  7872. });
  7873. }
  7874. #endregion
  7875. //designer.SetDataSource("DailyView", dailyViewItems);
  7876. var dt = CommonFun.ToDataTableArray(dailyViewItems);
  7877. dt.TableName = "DailyView";
  7878. designer.SetDataSource(dt);
  7879. #endregion
  7880. #endregion
  7881. //根据数据源处理生成报表内容
  7882. designer.Process();
  7883. var dailySheet = designer.Workbook.Worksheets[1];
  7884. //渲染批注
  7885. for (int i = 0; i < dailyViewItems.Count; i++)
  7886. {
  7887. string monthComment = $"C{i + 3}",
  7888. yearComment = $"D{i + 3}";
  7889. int monthCommentIndex = dailySheet.Comments.Add(monthComment),
  7890. yearCommentIndex = dailySheet.Comments.Add(yearComment);
  7891. if (dailyViewItems[i].ThisMonthAmount != 0.00M)
  7892. {
  7893. string commentText1 = conmmentTexts[i].MonthComment;
  7894. Aspose.Cells.Comment comment = dailySheet.Comments[monthCommentIndex];
  7895. comment.Note = commentText1;
  7896. comment.Width = 400;
  7897. comment.Height = 400;
  7898. comment.Font.Color = Color.Red;
  7899. }
  7900. if (dailyViewItems[i].ThisYearAmount != 0.00M)
  7901. {
  7902. string commentText2 = conmmentTexts[i].YearComment;
  7903. Aspose.Cells.Comment comment = dailySheet.Comments[yearCommentIndex];
  7904. comment.Note = commentText2;
  7905. comment.Width = 400;
  7906. comment.Height = 400;
  7907. comment.Font.Color = Color.Red;
  7908. }
  7909. }
  7910. string fileName = $"利润报表({beginDate.ToString("yyyy年MM月dd日")}~{endDate.ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls";
  7911. designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
  7912. string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
  7913. return Ok(JsonView(true, "操作成功!", url));
  7914. }
  7915. else if (excelType == 5)
  7916. {
  7917. var view = await CorporateProfitItems(2, beginDt, endDt);
  7918. return Ok(JsonView(true, "操作成功!", view.Label));
  7919. }
  7920. return Ok(JsonView(false));
  7921. }
  7922. private static string DailyListToString(DailyInfo[] infos)
  7923. {
  7924. StringBuilder sb = new StringBuilder();
  7925. int index = 1;
  7926. foreach (var info in infos)
  7927. {
  7928. sb.Append(index + "、");
  7929. sb.Append($"[{info.ItemTotal.ToString("#0.00")}]:{info.PriceName};");
  7930. sb.Append(Environment.NewLine);
  7931. index++;
  7932. }
  7933. return sb.ToString();
  7934. }
  7935. #endregion
  7936. }
  7937. }