StatisticsController.cs 428 KB

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