StatisticsController.cs 410 KB

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