StatisticsController.cs 328 KB

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