FinancialController.cs 353 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585
  1. using Aspose.Cells;
  2. using Aspose.Words;
  3. using EyeSoft.Extensions;
  4. using EyeSoft.IO;
  5. using FluentValidation;
  6. using Humanizer;
  7. using NPOI.SS.UserModel;
  8. using NPOI.XSSF.UserModel;
  9. using OASystem.API.OAMethodLib;
  10. using OASystem.API.OAMethodLib.APNs;
  11. using OASystem.API.OAMethodLib.File;
  12. using OASystem.API.OAMethodLib.QiYeWeChatAPI.AppNotice;
  13. using OASystem.Domain.AesEncryption;
  14. using OASystem.Domain.Dtos.Financial;
  15. using OASystem.Domain.Dtos.Groups;
  16. using OASystem.Domain.Entities.Customer;
  17. using OASystem.Domain.Entities.Financial;
  18. using OASystem.Domain.Entities.Groups;
  19. using OASystem.Domain.ViewModels.Financial;
  20. using OASystem.Domain.ViewModels.Groups;
  21. using OASystem.Infrastructure.Repositories.Financial;
  22. using OASystem.Infrastructure.Repositories.Groups;
  23. using OfficeOpenXml;
  24. using SqlSugar.Extensions;
  25. using System.Collections;
  26. using System.Data;
  27. using System.Data.OleDb;
  28. using System.Diagnostics;
  29. using System.Globalization;
  30. using System.IO.Compression;
  31. using static OASystem.API.OAMethodLib.JWTHelper;
  32. namespace OASystem.API.Controllers
  33. {
  34. /// <summary>
  35. /// 财务模块
  36. /// </summary>
  37. [Route("api/[controller]/[action]")]
  38. [ApiController]
  39. public class FinancialController : ControllerBase
  40. {
  41. private readonly IMapper _mapper;
  42. private readonly IConfiguration _config;
  43. private readonly ILogger<FinancialController> _logger;
  44. private readonly SqlSugarClient _sqlSugar;
  45. private readonly HttpClient _httpClient;
  46. private readonly SetDataTypeRepository _setDataTypeRep;
  47. private readonly SetDataRepository _setDataRep;
  48. private readonly DailyFeePaymentRepository _daiRep; //日付申请仓库
  49. private readonly TeamRateRepository _teamRateRep; //团组汇率仓库
  50. private readonly ForeignReceivablesRepository _ForForeignReceivablesRep; //对外收款账单仓库
  51. private readonly ProceedsReceivedRepository _proceedsReceivedRep; //已收款项仓库
  52. private readonly PaymentRefundAndOtherMoneyRepository _paymentRefundAndOtherMoneyRep; //收款退还与其他款项 仓库
  53. private readonly DelegationInfoRepository _delegationInfoRep; //团组信息 仓库
  54. private readonly ForeignReceivablesRepository _foreignReceivablesRepository;
  55. private readonly CheckBoxsRepository _groupCheckBox; //团组成本选中项 仓库
  56. /// <summary>
  57. /// 初始化
  58. /// </summary>
  59. public FinancialController(
  60. IMapper mapper,
  61. IConfiguration configuration,
  62. ILogger<FinancialController> logger,
  63. DailyFeePaymentRepository daiRep,
  64. SqlSugarClient sqlSugar,
  65. SetDataTypeRepository setDataTypeRep,
  66. TeamRateRepository teamRateRep,
  67. ForeignReceivablesRepository ForForeignReceivablesRep,
  68. ProceedsReceivedRepository proceedsReceivedRep,
  69. PaymentRefundAndOtherMoneyRepository paymentRefundAndOtherMoneyRep,
  70. HttpClient httpClient,
  71. DelegationInfoRepository delegationInfoRep,
  72. SetDataRepository setDataRep,
  73. ForeignReceivablesRepository foreignReceivablesRepository,
  74. CheckBoxsRepository groupCheckBox
  75. )
  76. {
  77. _mapper = mapper;
  78. _config = configuration;
  79. _logger = logger;
  80. _daiRep = daiRep;
  81. _sqlSugar = sqlSugar;
  82. _setDataTypeRep = setDataTypeRep;
  83. _teamRateRep = teamRateRep;
  84. _ForForeignReceivablesRep = ForForeignReceivablesRep;
  85. _proceedsReceivedRep = proceedsReceivedRep;
  86. _paymentRefundAndOtherMoneyRep = paymentRefundAndOtherMoneyRep;
  87. _httpClient = httpClient;
  88. _delegationInfoRep = delegationInfoRep;
  89. _setDataRep = setDataRep;
  90. _foreignReceivablesRepository = foreignReceivablesRepository;
  91. _groupCheckBox = groupCheckBox;
  92. }
  93. #region 日付申请
  94. /// <summary>
  95. /// 获取日付申请 基础数据源
  96. /// </summary>
  97. /// <param name="dto"> 日付申请 分页 dto</param>
  98. /// <returns></returns>
  99. [HttpPost]
  100. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  101. public async Task<IActionResult> PostPageSearchDailyPaymentPriceTypeData(PortDtoBase dto)
  102. {
  103. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  104. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  105. var result = await _daiRep.GetPagePriceTypeData(dto, currUserInfo.UserId);
  106. if (result == null || result.Code != 0)
  107. {
  108. return Ok(JsonView(false, result.Msg));
  109. }
  110. var data = result.Data;
  111. return Ok(JsonView(data));
  112. }
  113. /// <summary>
  114. /// 获取日付申请 基础数据源 - 转账表识
  115. /// </summary>
  116. /// <param name="dto"> 日付申请 分页 dto</param>
  117. /// <returns></returns>
  118. [HttpPost]
  119. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  120. public async Task<IActionResult> GetSearchDailyPaymentPriceTypeAddData(PortDtoBase dto)
  121. {
  122. var result = await _daiRep.GetPriceTypeAddData(dto);
  123. if (result == null || result.Code != 0)
  124. {
  125. return Ok(JsonView(false, result.Msg));
  126. }
  127. var data = result.Data;
  128. return Ok(JsonView(data));
  129. }
  130. /// <summary>
  131. /// 日付申请 Page Search
  132. /// </summary>
  133. /// <param name="dto"> 日付申请 分页 dto</param>
  134. /// <returns></returns>
  135. [HttpPost]
  136. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  137. public async Task<IActionResult> PostPageSearchDailyPaymentList(PageDailyFeePaymentDto dto)
  138. {
  139. var result = await _daiRep.GetPageSearchAll(dto);
  140. if (result == null || result.Code != 0)
  141. {
  142. return Ok(JsonView(false, result.Msg));
  143. }
  144. var data = result.Data;
  145. if (data == null)
  146. {
  147. return Ok(JsonView(false, result.Msg));
  148. }
  149. return Ok(JsonView(data));
  150. }
  151. /// <summary>
  152. /// 日付申请 Single Search By Id
  153. /// </summary>
  154. /// <param name="dto"></param>
  155. /// <returns></returns>
  156. [HttpPost]
  157. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  158. public async Task<IActionResult> PostSearchDailyPaymentInfo(SearchDailyFeePaymentDto dto)
  159. {
  160. var result = await _daiRep.GetSearchById(dto);
  161. if (result == null || result.Code != 0)
  162. {
  163. return Ok(JsonView(false, result.Msg));
  164. }
  165. return Ok(JsonView(result.Data));
  166. }
  167. /// <summary>
  168. /// 日付申请 添加
  169. /// </summary>
  170. /// <param name="dto"> 日付申请 添加 dto</param>
  171. /// <returns></returns>
  172. [HttpPost]
  173. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  174. public async Task<IActionResult> PostAddDailyPayment(AddDailyFeePaymentDto dto)
  175. {
  176. var result = await _daiRep.Add(dto);
  177. if (result == null || result.Code != 0)
  178. {
  179. return Ok(JsonView(false, result.Msg));
  180. }
  181. #region 应用推送
  182. try
  183. {
  184. int dailyId = result.Data.GetType().GetProperty("dailyId").GetValue(result.Data, null);
  185. int sign = result.Data.GetType().GetProperty("sign").GetValue(result.Data, null);
  186. await AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dailyId, sign, QiyeWeChatEnum.CaiWuChat);
  187. //2024-10-21 新增LZ UID
  188. var userIds = new List<int>() { 21 };
  189. string title = $"系统通知";
  190. var dailyInfo = await _sqlSugar.Queryable<Fin_DailyFeePayment>().Where(x => x.Id == dailyId).FirstAsync();
  191. string content = $"[新增-日付申请]一项费用:[费用说明:{dailyInfo.Instructions}]{dailyInfo.SumPrice:#0.00} CNY;";
  192. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.DailyPayment, title, content, userIds, 0);
  193. var h5 = new PageParam_PriceAuditH5() { diid = "", uid = "21" };
  194. await APNsTools.iOS_PushNotifications1("051", "日付费用审核", "", content, true, "ExpenseAuditWebView", h5);
  195. //罗颖申请的费用发送通知
  196. if (dto.UserId == 374)
  197. {
  198. var qw_userIds = new List<string>() {
  199. //"374", //罗颖
  200. "208", //雷怡
  201. "309", //赖红燕
  202. };
  203. //Todo:企微消息通知
  204. await AppNoticeLibrary.SendUserMsg_CompanyShare_ToDailtPay(dailyId, 374, qw_userIds);
  205. }
  206. }
  207. catch (Exception ex)
  208. {
  209. }
  210. #endregion
  211. return Ok(JsonView(true));
  212. }
  213. /// <summary>
  214. /// 日付申请 Update
  215. /// </summary>
  216. /// <param name="dto"> 日付申请 修改 dto</param>
  217. /// <returns></returns>
  218. [HttpPost]
  219. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  220. public async Task<IActionResult> PostEditDailyPayment(EditDailyFeePaymentDto dto)
  221. {
  222. var result = await _daiRep.Edit(dto);
  223. if (result == null || result.Code != 0)
  224. {
  225. return Ok(JsonView(false, result.Msg));
  226. }
  227. #region 应用推送
  228. try
  229. {
  230. int dailyId = result.Data.GetType().GetProperty("dailyId").GetValue(result.Data, null);
  231. int sign = result.Data.GetType().GetProperty("sign").GetValue(result.Data, null);
  232. await AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dailyId, sign, QiyeWeChatEnum.CaiWuChat);
  233. //2024-10-21 新增LZ UID
  234. var userIds = new List<int>() { 21 };
  235. string title = $"系统通知";
  236. var dailyInfo = await _sqlSugar.Queryable<Fin_DailyFeePayment>().Where(x => x.Id == dailyId).FirstAsync();
  237. string content = $"[更新-日付申请]一项费用:[费用说明:{dailyInfo.Instructions}]{dailyInfo.SumPrice:#0.00} CNY;";
  238. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.DailyPayment, title, content, userIds, 0);
  239. var h5 = new PageParam_PriceAuditH5() { diid = "", uid = "21" };
  240. await APNsTools.iOS_PushNotifications1("051", "日付费用审核", "", content, true, "ExpenseAuditWebView", h5);
  241. }
  242. catch (Exception ex)
  243. {
  244. }
  245. #endregion
  246. return Ok(JsonView(true));
  247. }
  248. /// <summary>
  249. /// 日付申请 Del
  250. /// </summary>
  251. /// <param name="dto"> 日付申请 删除 dto</param>
  252. /// <returns></returns>
  253. [HttpPost]
  254. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  255. public async Task<IActionResult> PostDelDailyPayment(DelDailyFeePaymentDto dto)
  256. {
  257. _sqlSugar.BeginTran();
  258. var result = await _daiRep.Del(dto);
  259. //删除日付关联表
  260. var delCount = _sqlSugar.Updateable<Fin_RoyaltyForm>()
  261. .Where(x => x.IsDel == 0 && x.DayOverhead == dto.Id)
  262. .SetColumns(x => new Fin_RoyaltyForm
  263. {
  264. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  265. DeleteUserId = dto.UserId,
  266. IsDel = 1
  267. }).ExecuteCommand();
  268. _sqlSugar.CommitTran();
  269. if (result == null || result.Code != 0)
  270. {
  271. return Ok(JsonView(false, result.Msg));
  272. }
  273. return Ok(JsonView(true));
  274. }
  275. /// <summary>
  276. /// 日付申请 财务审核
  277. /// </summary>
  278. /// <param name="dto"> dto </param>
  279. /// <returns></returns>
  280. [HttpPost]
  281. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  282. public async Task<IActionResult> PostDelDailyPaymentAudit(DP_AuditStatusDto dto)
  283. {
  284. var result = await _daiRep.DailyPaymentAudit(dto);
  285. if (result == null || result.Code != 0)
  286. {
  287. return Ok(JsonView(false, result.Msg));
  288. }
  289. return Ok(JsonView(true));
  290. }
  291. /// <summary>
  292. /// 日付申请 Single Excel Download
  293. /// </summary>
  294. /// <param name="dto"> dto </param>
  295. /// <returns></returns>
  296. [HttpPost]
  297. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  298. public async Task<IActionResult> PostExcelDailyPaymentDownload(SearchDailyFeePaymentDto dto)
  299. {
  300. if (dto.PortType == 1 || dto.PortType == 2)
  301. {
  302. string feeSql = string.Format(@"Select * From Fin_DailyFeePayment
  303. Where IsDel=0 And Id = {0} ", dto.Id);
  304. var feeData = await _sqlSugar.SqlQueryable<Fin_DailyFeePaymentInfolView>(feeSql).FirstAsync();
  305. if (feeData == null)
  306. {
  307. return Ok(JsonView(false, "暂无数据!"));
  308. }
  309. string feeContentSql = string.Format(@"Select * From Fin_DailyFeePaymentContent
  310. Where IsDel=0 And DFPId = {0} ", dto.Id);
  311. feeData.FeeContents = await _sqlSugar.SqlQueryable<Fin_DailyFeePaymentContentInfolView>(feeContentSql).ToListAsync();
  312. if (feeData != null)
  313. {
  314. string userName = string.Empty;
  315. string userSql = string.Format("Select * From Sys_Users Where Id={0} And Isdel = {1}", feeData.CreateUserId, 0);
  316. Sys_Users user = await _sqlSugar.SqlQueryable<Sys_Users>(userSql).FirstAsync();
  317. if (user != null) { userName = user.CnName; }
  318. var setData = _setDataTypeRep.QueryDto<Sys_SetData, Fin_DailyFeePaymentPagePriceSubTypeView>().ToList();
  319. //48人员费用 49办公费用 50 销售费用 51 其他费用 55 大运会
  320. var priceSubTypeData = setData.Where(s => s.STid == 55).ToList();
  321. var pairs = new Dictionary<string, object>();
  322. var datas = new List<DataTable>();
  323. //if (priceSubTypeData.Where(s => s.Id == feeData.PriceTypeId).ToList().Count() > 0)//大运会专属模板
  324. //{
  325. // //AsposeHelper.ExpertExcelToModel("日常费用付款申请模板-大运会数据.xls", "DailyPayment", "大运会所有日常费用付款申请.xls",
  326. // // pairs, datas);
  327. //}
  328. //else //日付常规模板
  329. //{
  330. pairs.Clear();
  331. pairs.Add("Opertor", userName);
  332. pairs.Add("DateTime", feeData.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
  333. pairs.Add("FAuditStatus", feeData.FAuditDesc);
  334. pairs.Add("MAuditStatus", feeData.MAuditDesc);
  335. pairs.Add("SumPrice", feeData.SumPrice);
  336. DataTable data = AsposeHelper.ListToDataTable("DailyFeePayment", feeData.FeeContents);
  337. datas.Clear();
  338. datas.Add(data);
  339. string fileName = string.Format("{0}-日常费用付款申请.xlsx", feeData.Instructions);
  340. string msg = AsposeHelper.ExpertExcelToModel("日常费用付款申请模板.xlsx", "DailyPayment", fileName, pairs, datas);
  341. return Ok(JsonView(true, msg));
  342. //}
  343. }
  344. else
  345. {
  346. return Ok(JsonView(false, "暂无数据!"));
  347. }
  348. }
  349. return Ok(JsonView(true));
  350. }
  351. /// <summary>
  352. /// 日付申请
  353. /// 总经理未审核 日付信息
  354. /// </summary>
  355. /// <returns></returns>
  356. [HttpGet]
  357. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  358. public async Task<IActionResult> DailyPaymentGMUnAudited()
  359. {
  360. var dailyInfos = await _sqlSugar.Queryable<Fin_DailyFeePayment>()
  361. .LeftJoin<Sys_Users>((dfp, u) => dfp.CreateUserId == u.Id)
  362. .Where(dfp => dfp.IsDel == 0 &&
  363. //dfp.FAudit == 1 &&
  364. //dfp.IsPay == 0 &&
  365. dfp.MAudit == 0
  366. )
  367. .OrderBy(dfp => dfp.CreateTime, OrderByType.Desc)
  368. //.OrderBy(dfp => dfp.FAudit, OrderByType.Desc)
  369. .Select((dfp, u) => new
  370. {
  371. id = dfp.Id,
  372. amountName = dfp.Instructions,
  373. amount = dfp.SumPrice,
  374. fAuditStatus = dfp.FAudit == 1 ? "审核通过" :
  375. dfp.FAudit == 2 ? "审核未通过" : "未审核",
  376. fAuditDate = dfp.FAuditDate,
  377. applicant = u.CnName,
  378. applicantDate = dfp.CreateTime
  379. })
  380. //.ToListAsync();
  381. .CountAsync();
  382. //int count = dailyInfos.Count;
  383. return Ok(JsonView(true, "查询成功", dailyInfos));
  384. }
  385. #endregion
  386. #region 团组提成
  387. /// <summary>
  388. /// 提成 Page Search
  389. /// </summary>
  390. /// <param name="dto"> 提成 分页 dto</param>
  391. /// <returns></returns>
  392. [HttpPost]
  393. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  394. public async Task<IActionResult> PostPageSearchCommissionList(GroupCommissionDto dto)
  395. {
  396. var data = await GroupCommission.GetCommissionPageList(dto);
  397. return Ok(JsonView(data.Data));
  398. }
  399. #endregion
  400. #region 团组汇率
  401. /// <summary>
  402. /// 团组汇率 Select数据源(团组列,汇率列)
  403. /// </summary>
  404. /// <param name="dto"></param>
  405. /// <returns></returns>
  406. [HttpPost]
  407. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  408. public async Task<IActionResult> GetGroupRateDataSources(TeamRateDto dto)
  409. {
  410. try
  411. {
  412. //迁移数据更新团组汇率
  413. //Result teamRateData1 = await _teamRateRep.GetGroupRateChangeData();
  414. //var data = await _teamRateRep.PostGroupTeamRateHot();
  415. Stopwatch stopwatch = Stopwatch.StartNew();
  416. var groupNameDto = new GroupNameDto() { PortType = dto.PortType };
  417. var groups = await _delegationInfoRep.GetGroupNameList(groupNameDto);
  418. var _currData = new List<CurrencyHot>();
  419. string currData = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>("GroupTeamCurrencyData");//string 取
  420. if (!string.IsNullOrEmpty(currData))
  421. {
  422. _currData = JsonConvert.DeserializeObject<List<CurrencyHot>>(currData);
  423. }
  424. else
  425. {
  426. _currData = await _teamRateRep.PostGroupTeamRateHot();
  427. //过期时间 25 Hours
  428. TimeSpan ts = DateTime.Now.AddHours(25).TimeOfDay;
  429. await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync("GroupTeamCurrencyData", JsonConvert.SerializeObject(_currData), ts);
  430. }
  431. var _data = new { GroupData = groups.Data, TeamRateData = _currData };
  432. stopwatch.Stop();
  433. return Ok(JsonView(true, $"查询成功!耗时:{stopwatch.ElapsedMilliseconds / 1000}s", _data));
  434. }
  435. catch (Exception ex)
  436. {
  437. return Ok(JsonView(false, ex.Message));
  438. }
  439. }
  440. ///// <summary>
  441. ///// 团组汇率 changge
  442. ///// </summary>
  443. ///// <returns></returns>
  444. //[HttpPost]
  445. //[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  446. //public async Task<IActionResult> ChangeGroupRateInfo()
  447. //{
  448. // try
  449. // {
  450. // Result teamRateData = await _teamRateRep.GetGroupRateChangeData();
  451. // if (teamRateData.Code != 0)
  452. // {
  453. // return Ok(JsonView(false, teamRateData.Msg));
  454. // }
  455. // return Ok(JsonView(true, teamRateData.Msg, teamRateData.Data));
  456. // }
  457. // catch (Exception ex)
  458. // {
  459. // return Ok(JsonView(false, ex.Message));
  460. // throw;
  461. // }
  462. //}
  463. /// <summary>
  464. /// 团组汇率 Select汇率详情
  465. /// </summary>
  466. /// <param name="dto"></param>
  467. /// <returns></returns>
  468. [HttpPost]
  469. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  470. public async Task<IActionResult> GetGroupRateInfo(TeamRateInfoDto dto)
  471. {
  472. try
  473. {
  474. Result teamRateData = await _teamRateRep.GetGroupRateInfoByDiid(dto);
  475. if (teamRateData.Code != 0)
  476. {
  477. return Ok(JsonView(false, teamRateData.Msg));
  478. }
  479. return Ok(JsonView(true, teamRateData.Msg, teamRateData.Data));
  480. }
  481. catch (Exception ex)
  482. {
  483. return Ok(JsonView(false, ex.Message));
  484. throw;
  485. }
  486. }
  487. /// <summary>
  488. /// 团组汇率 添加 or 更新
  489. /// </summary>
  490. /// <param name="dto"></param>
  491. /// <returns></returns>
  492. [HttpPost]
  493. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  494. public async Task<IActionResult> PostGroupRateUpdate(TeamRateUpdateDto dto)
  495. {
  496. try
  497. {
  498. Result teamRateData = await _teamRateRep.PostGroupRateUpdate(dto);
  499. if (teamRateData.Code != 0)
  500. {
  501. return Ok(JsonView(false, teamRateData.Msg));
  502. }
  503. return Ok(JsonView(true, teamRateData.Msg, teamRateData.Data));
  504. }
  505. catch (Exception ex)
  506. {
  507. return Ok(JsonView(false, ex.Message));
  508. throw;
  509. }
  510. }
  511. #endregion
  512. #region 对外收款账单 关联已收款项
  513. /// <summary>
  514. /// 对外收款账单 Select数据源(团组名,币种,汇款方式)
  515. /// 关联已收款项
  516. /// </summary>
  517. /// <param name="dto"></param>
  518. /// <returns></returns>
  519. [HttpPost]
  520. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  521. public async Task<IActionResult> GetForeignReceivablesDataSources(ForeignReceivablesDataSourcesDto dto)
  522. {
  523. return Ok(await _ForForeignReceivablesRep.GetDataSource(dto));
  524. }
  525. /// <summary>
  526. /// 对外收款账单
  527. /// 账单详情
  528. /// 关联已收款项
  529. /// </summary>
  530. /// <param name="dto"></param>
  531. /// <returns></returns>
  532. [HttpPost]
  533. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  534. public async Task<IActionResult> GetGroupReceivablesInfoByDiId(ForForeignReceivablesInfoDto dto)
  535. {
  536. try
  537. {
  538. Result ffrData = await _ForForeignReceivablesRep.GetGroupReceivablesInfoByDiId(dto);
  539. if (ffrData.Code != 0)
  540. {
  541. return Ok(JsonView(false, ffrData.Msg));
  542. }
  543. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  544. }
  545. catch (Exception ex)
  546. {
  547. return Ok(JsonView(false, ex.Message));
  548. throw;
  549. }
  550. }
  551. /// <summary>
  552. /// 对外收款账单
  553. /// 账单 删除
  554. /// 关联已收款项
  555. /// </summary>
  556. /// <param name="dto"></param>
  557. /// <returns></returns>
  558. [HttpPost]
  559. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  560. public async Task<IActionResult> PostGroupReceivablesDel(DelForForeignReceivablesInfoDto dto)
  561. {
  562. try
  563. {
  564. Result ffrData = await _ForForeignReceivablesRep._Del(dto);
  565. if (ffrData.Code != 0)
  566. {
  567. return Ok(JsonView(false, ffrData.Msg));
  568. }
  569. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  570. }
  571. catch (Exception ex)
  572. {
  573. return Ok(JsonView(false, ex.Message));
  574. throw;
  575. }
  576. }
  577. /// <summary>
  578. /// 对外收款账单
  579. /// 添加 And 更新
  580. /// 关联已收款项
  581. /// </summary>
  582. /// <param name="dto"></param>
  583. /// <returns></returns>
  584. [HttpPost]
  585. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  586. public async Task<IActionResult> PostReceivablesOperate(ForeignReceivablesAddAndUpdateDto dto)
  587. {
  588. try
  589. {
  590. Result ffrData = await _ForForeignReceivablesRep.PostReceivablesOperate(dto);
  591. if (ffrData.Code != 0)
  592. {
  593. return Ok(JsonView(false, ffrData.Msg));
  594. }
  595. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  596. }
  597. catch (Exception ex)
  598. {
  599. return Ok(JsonView(false, ex.Message));
  600. throw;
  601. }
  602. }
  603. /// <summary>
  604. /// 已收款项
  605. /// 账单 删除
  606. /// 关联已收款项
  607. /// </summary>
  608. /// <param name="dto"></param>
  609. /// <returns></returns>
  610. [HttpPost]
  611. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  612. public async Task<IActionResult> PostAmountReceivedDel(ProceedsReceivedDelDto dto)
  613. {
  614. try
  615. {
  616. Result ffrData = await _proceedsReceivedRep._Del(dto);
  617. if (ffrData.Code != 0)
  618. {
  619. return Ok(JsonView(false, ffrData.Msg));
  620. }
  621. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  622. }
  623. catch (Exception ex)
  624. {
  625. return Ok(JsonView(false, ex.Message));
  626. throw;
  627. }
  628. }
  629. /// <summary>
  630. /// 已收款项
  631. /// 添加 And 更新
  632. /// 关联已收款项
  633. /// </summary>
  634. /// <param name="dto"></param>
  635. /// <returns></returns>
  636. [HttpPost]
  637. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  638. public async Task<IActionResult> PostAmountReceivedOperate(ProceedsReceivedDto dto)
  639. {
  640. try
  641. {
  642. Result ffrData = await _proceedsReceivedRep.PostAmountReceivedOperate(dto);
  643. if (ffrData.Code != 0)
  644. {
  645. return Ok(JsonView(false, ffrData.Msg));
  646. }
  647. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  648. }
  649. catch (Exception ex)
  650. {
  651. return Ok(JsonView(false, ex.Message));
  652. throw;
  653. }
  654. }
  655. /// <summary>
  656. /// 财务 已收款项
  657. /// 分配已收款项至 应收项下
  658. /// 关联已收款项
  659. /// </summary>
  660. /// <param name="dto"></param>
  661. /// <returns></returns>
  662. [HttpPost]
  663. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  664. public async Task<IActionResult> PostAllocateAmountReceived(AllocateAmountReceivedDto dto)
  665. {
  666. try
  667. {
  668. Result ffrData = await _proceedsReceivedRep.PostAllocateAmountReceived(dto);
  669. if (ffrData.Code != 0)
  670. {
  671. return Ok(JsonView(false, ffrData.Msg));
  672. }
  673. return Ok(JsonView(true));
  674. }
  675. catch (Exception ex)
  676. {
  677. return Ok(JsonView(false, ex.Message));
  678. throw;
  679. }
  680. }
  681. ///// <summary>
  682. ///// 财务 收款账单
  683. ///// 导出Word(北京,四川)
  684. ///// </summary>
  685. ///// <param name="dto"></param>
  686. ///// <returns></returns>
  687. //[HttpPost]
  688. //[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  689. //public async Task<IActionResult> PostAccountReceivableWordExport(AccountReceivableWordExportDto dto)
  690. //{
  691. // try
  692. // {
  693. // //模板处理
  694. // string typeName = string.Empty;
  695. // if (dto.TemplateType == 1) //四川
  696. // {
  697. // typeName = "四川";
  698. // }
  699. // else if (dto.TemplateType == 2) //北京
  700. // {
  701. // typeName = "北京";
  702. // }
  703. // else return Ok(JsonView(false,"请选择正确的模板类型!"));
  704. // string wordTempName = string.Format("收款账单({0})模板.doc", typeName);
  705. // }
  706. // catch (Exception ex)
  707. // {
  708. // return Ok(JsonView(false, ex.Message));
  709. // }
  710. //}
  711. #endregion
  712. #region 对外收款账单
  713. /// <summary>
  714. /// 对外收款账单
  715. /// 数据源
  716. /// </summary>
  717. /// <param name="dto"></param>
  718. /// <returns></returns>
  719. [HttpPost]
  720. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  721. public async Task<IActionResult> PostGroupReceivablesDataSource(ForeignReceivablesDataSourcesDto dto)
  722. {
  723. return Ok(await _ForForeignReceivablesRep.PostDataSource(dto));
  724. }
  725. /// <summary>
  726. /// 对外收款账单,团组列表分页
  727. /// 数据源
  728. /// </summary>
  729. /// <param name="dto"></param>
  730. /// <returns></returns>
  731. [HttpPost]
  732. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  733. public async Task<IActionResult> ForeignReceivablesDataSourcesOffSet(ForeignReceivablesDataSourcesOffSetDto dto)
  734. {
  735. return Ok(await _ForForeignReceivablesRep.PostDataSourceOffSet(dto));
  736. }
  737. /// <summary>
  738. /// 对外收款账单
  739. /// 账单详情
  740. /// </summary>
  741. /// <param name="dto"></param>
  742. /// <returns></returns>
  743. [HttpPost]
  744. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  745. public async Task<IActionResult> PostGroupReceivablesInfoByDiId(ForForeignReceivablesNewDto dto)
  746. {
  747. return Ok(await _ForForeignReceivablesRep.PostGroupReceivablesInfoByDiId(dto));
  748. }
  749. /// <summary>
  750. /// 对外收款账单
  751. /// 添加 And 更新
  752. /// </summary>
  753. /// <param name="dto"></param>
  754. /// <returns></returns>
  755. [HttpPost]
  756. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  757. public async Task<IActionResult> PostReceivablesSave(ForeignReceivablesSaveDto dto)
  758. {
  759. return Ok(await _ForForeignReceivablesRep.PostReceivablesSave(dto));
  760. }
  761. /// <summary>
  762. /// 对外收款账单
  763. /// (单条数据)添加 And 更新
  764. /// </summary>
  765. /// <param name="dto"></param>
  766. /// <returns></returns>
  767. [HttpPost]
  768. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  769. public async Task<IActionResult> PostReceivablesSingleSave(PostReceivablesSingleSaveDto dto)
  770. {
  771. return Ok(await _ForForeignReceivablesRep.PostReceivablesSingleSave(dto));
  772. }
  773. /// <summary>
  774. /// 对外收款账单
  775. /// 审核
  776. /// </summary>
  777. /// <param name="dto"></param>
  778. /// <returns></returns>
  779. [HttpPost]
  780. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  781. public async Task<IActionResult> PostReceivablesAudit(FeeAuditDto dto)
  782. {
  783. return Ok(await _ForForeignReceivablesRep.FeeAudit(dto));
  784. }
  785. /// <summary>
  786. /// 已收账单
  787. /// 删除
  788. /// </summary>
  789. /// <param name="dto"></param>
  790. /// <returns></returns>
  791. [HttpPost]
  792. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  793. public async Task<IActionResult> PostReceivablesDel(ForeignReceivablesDelDto dto)
  794. {
  795. Result ffrData = await _ForForeignReceivablesRep.PostReceivablesDel(dto);
  796. if (ffrData.Code != 0)
  797. {
  798. return Ok(JsonView(false, ffrData.Msg));
  799. }
  800. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  801. }
  802. /// <summary>
  803. /// 已收账单
  804. /// File Download
  805. /// Init
  806. /// </summary>
  807. /// <returns></returns>
  808. [HttpPost]
  809. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  810. public async Task<IActionResult> PostReceivablesFeilDownloadInit()
  811. {
  812. return Ok(JsonView(true, "操作成功!", new List<dynamic> {
  813. new { Id = 1, Name = "生成收款单(四川)" },
  814. new { Id = 2, Name = "生成收款单(北京)" },
  815. new { Id = 3, Name = "汇款账单" }
  816. }
  817. ));
  818. }
  819. private class EnterExitCostCurrency
  820. {
  821. public string Name { get; set; }
  822. public string Code { get; set; }
  823. public decimal Rate { get; set; }
  824. }
  825. /// <summary>
  826. /// 已收账单
  827. /// File Downloasd
  828. /// </summary>
  829. /// <param name="dto"></param>
  830. /// <returns></returns>
  831. [HttpPost]
  832. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  833. public async Task<IActionResult> PostReceivablesFeilDownload(ForeignReceivablesFeilDownloadDto dto)
  834. {
  835. try
  836. {
  837. if (dto.DiId < 1)
  838. {
  839. return Ok(JsonView(false, "请传入有效DiId参数!"));
  840. }
  841. if (dto.FileType < 1 || dto.FileType > 3)
  842. {
  843. return Ok(JsonView(false, "请传入有效FileType参数! 1 生成收款单(四川) 2 生成收款单(北京) 3 汇款账单"));
  844. }
  845. var _currencyDatas = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToList();
  846. var _DelegationInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0 && it.Id == dto.DiId).First();
  847. if (_DelegationInfo == null)
  848. {
  849. return Ok(JsonView(false, "暂无团组信息!!"));
  850. }
  851. if (dto.FileType == 1 || dto.FileType == 2)
  852. {
  853. var _ForeignReceivables = _sqlSugar.Queryable<Fin_ForeignReceivables>().Where(it => it.IsDel == 0 && it.Diid == dto.DiId).ToList();
  854. if (_ForeignReceivables.Count < 1)
  855. {
  856. return Ok(JsonView(false, "暂无收款信息!!"));
  857. }
  858. string tempName = "";
  859. if (dto.FileType == 1) tempName = $"收款账单(四川)模板.docx";
  860. else if (dto.FileType == 2) tempName = $"收款账单(北京)模板.docx";
  861. string tempPath = AppSettingsHelper.Get("WordBasePath") + $"ForeignReceivables/Temp/{tempName}";
  862. //载入模板
  863. var doc = new Document(tempPath);
  864. var builder = new DocumentBuilder(doc);
  865. #region 替换Word模板书签内容
  866. //这里可以创建个DataTable循环添加书签的值,这里提示一下就不多做修改了
  867. //付款方
  868. if (doc.Range.Bookmarks["To"] != null)
  869. {
  870. Bookmark mark = doc.Range.Bookmarks["To"];
  871. mark.Text = _ForeignReceivables[0].To == null ? "" : _ForeignReceivables[0].To.ToString();
  872. }
  873. //付款方电话
  874. if (doc.Range.Bookmarks["ToTel"] != null)
  875. {
  876. Bookmark mark = doc.Range.Bookmarks["ToTel"];
  877. mark.Text = _ForeignReceivables[0].ToTel == null ? "" : _ForeignReceivables[0].ToTel.ToString();
  878. }
  879. //导出时间
  880. if (doc.Range.Bookmarks["Date"] != null)
  881. {
  882. Bookmark mark = doc.Range.Bookmarks["Date"];
  883. mark.Text = DateTime.Now.ToString("yyyy-MM-dd");
  884. }
  885. //注
  886. if (doc.Range.Bookmarks["Attention"] != null)
  887. {
  888. Bookmark mark = doc.Range.Bookmarks["Attention"];
  889. mark.Text = _ForeignReceivables[0].Attention == null ? "" : _ForeignReceivables[0].Attention.ToString();
  890. }
  891. //团队名称
  892. if (doc.Range.Bookmarks["Team"] != null)
  893. {
  894. Bookmark mark = doc.Range.Bookmarks["Team"];
  895. mark.Text = _DelegationInfo.VisitCountry == null ? "" : _DelegationInfo.VisitCountry.Replace("|", "、").ToString();
  896. }
  897. //付款日期
  898. if (doc.Range.Bookmarks["PayDate"] != null)
  899. {
  900. Bookmark mark = doc.Range.Bookmarks["PayDate"];
  901. mark.Text = _ForeignReceivables[0].PayDate == null ? "" : Convert.ToDateTime(_ForeignReceivables[0].PayDate).ToString("yyyy年MM月dd日");
  902. }
  903. decimal sumPrice = 0;
  904. //各项费用
  905. if (doc.Range.Bookmarks["PayItemContent"] != null)
  906. {
  907. string items = "";
  908. foreach (var fr in _ForeignReceivables)
  909. {
  910. var currInfo = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == fr.Currency).First();
  911. items += $"{fr.PriceName} {currInfo?.Name} {fr.Price:#0.00} * {fr.Count} {fr.Unit} * {fr.Rate}.................. RMB {fr.ItemSumPrice:#0.00}\n";
  912. sumPrice += fr.ItemSumPrice;
  913. }
  914. Bookmark mark = doc.Range.Bookmarks["PayItemContent"];
  915. mark.Text = items;
  916. }
  917. //合计
  918. if (doc.Range.Bookmarks["Total"] != null)
  919. {
  920. Bookmark mark = doc.Range.Bookmarks["Total"];
  921. mark.Text = sumPrice.ToString("#0.00");
  922. }
  923. #endregion
  924. //文件名
  925. string strFileName = _DelegationInfo.TeamName + "-收款账单.docx";
  926. //去水印
  927. new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String(AsposeHelper.asposeKey)));
  928. doc.Save(AppSettingsHelper.Get("WordBasePath") + "ForeignReceivables/File/" + strFileName);
  929. string url = AppSettingsHelper.Get("WordBaseUrl") + "Office/Word/ForeignReceivables/File/" + strFileName;
  930. return Ok(JsonView(true, "成功", new { Url = url }));
  931. }
  932. else if (dto.FileType == 3) //汇款通知
  933. {
  934. var _EnterExitCosts = _sqlSugar.Queryable<Grp_EnterExitCost>().Where(it => it.IsDel == 0 && it.DiId == dto.DiId).First();
  935. var _DayAndCosts = _sqlSugar.Queryable<Grp_DayAndCost>().Where(it => it.IsDel == 0 && it.DiId == dto.DiId && it.NationalTravelFeeId > 0).ToList();
  936. if (_EnterExitCosts == null)
  937. {
  938. return Ok(JsonView(false, "该团组未填写出入境费用;"));
  939. }
  940. var _EnterExitCostCurrencys = new List<EnterExitCostCurrency>();
  941. if (!string.IsNullOrEmpty(_EnterExitCosts.CurrencyRemark))
  942. {
  943. var currency1 = _EnterExitCosts.CurrencyRemark.Split("|");
  944. foreach (var item in currency1)
  945. {
  946. var currency2 = item.Split(":");
  947. var currency3 = currency2[0].Split("(");
  948. var currencyName = currency3[0].ToString();
  949. var currencyCode = currency3[1].Split(")")[0].ToString();
  950. _EnterExitCostCurrencys.Add(new EnterExitCostCurrency
  951. {
  952. Name = currencyName,
  953. Code = currencyCode,
  954. Rate = Convert.ToDecimal(currency2[1] ?? "0")
  955. });
  956. }
  957. }
  958. var _cityFee = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(it => it.IsDel == 0).ToList();
  959. foreach (var item in _DayAndCosts)
  960. {
  961. var cityInfo = _cityFee.Where(it => it.Id == item.NationalTravelFeeId).FirstOrDefault();
  962. if (cityInfo != null)
  963. {
  964. if (cityInfo.City.Contains("全部城市") || cityInfo.City.Contains("其他城市") || cityInfo.City.Contains("所有城市"))
  965. {
  966. item.Place = cityInfo.Country;
  967. }
  968. else item.Place = cityInfo.City;
  969. }
  970. }
  971. //数据源
  972. //住宿费 伙食费 公杂费 培训费 选中才计算出费用
  973. //住宿费 选中赋值
  974. List<Grp_DayAndCost> dac1 = new List<Grp_DayAndCost>();
  975. if (_EnterExitCosts.ChoiceThree == 1) dac1 = _DayAndCosts.Where(it => it.Type == 1).ToList(); //住宿费
  976. //伙食费 选中赋值
  977. List<Grp_DayAndCost> dac2 = new List<Grp_DayAndCost>();
  978. if (_EnterExitCosts.ChoiceFour == 1) dac2 = _DayAndCosts.Where(it => it.Type == 2).ToList(); //伙食费
  979. //公杂费 选中赋值
  980. List<Grp_DayAndCost> dac3 = new List<Grp_DayAndCost>();
  981. if (_EnterExitCosts.ChoiceFour == 1) dac3 = _DayAndCosts.Where(it => it.Type == 3).ToList(); //公杂费
  982. //培训费 选中赋值
  983. List<Grp_DayAndCost> dac4 = new List<Grp_DayAndCost>();
  984. if (_EnterExitCosts.ChoiceFour == 1) dac4 = _DayAndCosts.Where(it => it.Type == 4).ToList(); //培训费
  985. //币种Data
  986. var currData = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0 && it.STid == 66).ToList();
  987. var DeleClientList = _sqlSugar.Queryable<Grp_TourClientList>()
  988. .LeftJoin<Crm_DeleClient>((tcl, dc) => tcl.ClientId == dc.Id && dc.IsDel == 0)
  989. .LeftJoin<Crm_CustomerCompany>((tcl, dc, cc) => dc.CrmCompanyId == cc.Id && dc.IsDel == 0)
  990. .Where((tcl, dc, cc) => tcl.IsDel == 0 && tcl.DiId == dto.DiId)
  991. .Select((tcl, dc, cc) => new ClientAirInfo
  992. {
  993. LastName = dc.LastName,
  994. FirstName = dc.FirstName,
  995. Sex = dc.Sex,
  996. Birthday = dc.BirthDay,
  997. Company = cc.CompanyFullName,
  998. Job = dc.Job,
  999. AirType = tcl.ShippingSpaceTypeId
  1000. })
  1001. .ToList();
  1002. if (DeleClientList.Count < 1)
  1003. {
  1004. return Ok(JsonView(false, "暂无团组成员,请先填写团组成员!!!"));
  1005. }
  1006. foreach (var item in DeleClientList)
  1007. {
  1008. EncryptionProcessor.DecryptProperties(item);
  1009. item.Company = item.Company.Replace("\n", "");
  1010. }
  1011. var _ClientNames = DeleClientList.Select(x => x.Name).ToList();
  1012. var _GroupClient = DeleClientList.GroupBy(x => x.Company).ToList();
  1013. Dictionary<string, string> bookmarkArr = null;
  1014. string tempPath = AppSettingsHelper.Get("WordBasePath") + $"ForeignReceivables/Temp/汇款通知.docx";
  1015. //载入模板
  1016. var doc = new Document(tempPath);
  1017. DocumentBuilder builder = null;
  1018. var filesToZip = new List<string>();
  1019. foreach (var ClientItem in _GroupClient) //遍历单位
  1020. {
  1021. doc = new Document(tempPath);
  1022. builder = new DocumentBuilder(doc);
  1023. var paragraph = new Paragraph(doc);
  1024. bookmarkArr = new Dictionary<string, string>
  1025. {
  1026. { "titleClientUnit", ClientItem.Key }, //title单位
  1027. { "ClientUnit", ClientItem.Key }, //单位
  1028. { "VisitStartDate", _DelegationInfo.VisitStartDate.ToString("yyyy年MM月dd日") },//出发日期
  1029. { "name", string.Join(",", ClientItem.Select(x => x.Name).ToArray()).TrimEnd(',') },//全部人员信息
  1030. { "VisitCountry", _DelegationInfo.VisitCountry.Replace("|", "、") },//出访国家
  1031. { "dayTime", DateTime.Now.ToString("yyyy年MM月dd日") }//今天日期
  1032. };
  1033. var ClientItemList = ClientItem.ToList();
  1034. string UsersTop = string.Empty;//word中人员以及金额
  1035. decimal WordAllPrice = 0.00M;
  1036. //int[] infoColumn = new int[5] {dac1.Select(x=>x.Place.Length).ToList().Max(),2, dac1.Select(x => x.Cost.Length).Max() + dac1.Select(x => x.Currency.Length).Max(),
  1037. // 6, 3 + dac1.Where(x=>!string.IsNullOrWhiteSpace(x.Place)).Select(x=>(Convert.ToDecimal(x.SubTotal) / Convert.ToDecimal(x.Cost)).ToString().Length).Max() };
  1038. //遍历人员
  1039. for (int i = 0; i < ClientItemList.Count; i++)
  1040. {
  1041. var TeableBookmarkArr = new Dictionary<string, string>();
  1042. var client = ClientItemList[i]; //每个人员
  1043. var firstName = ClientItemList[i].Name;
  1044. /*
  1045. * 457 头等舱
  1046. * 458 公务舱
  1047. * 460 经济舱
  1048. */
  1049. decimal airPrice = 0.00M,
  1050. cityTranffic = 0.00M;
  1051. string airName = string.Empty;
  1052. if (client.AirType == 457)
  1053. {
  1054. airName = $"头等舱";
  1055. airPrice = _EnterExitCosts.AirTD;
  1056. cityTranffic = _EnterExitCosts.CityTranffic2;
  1057. }
  1058. else if (client.AirType == 458)
  1059. {
  1060. airName = $"公务舱";
  1061. airPrice = _EnterExitCosts.AirGW;
  1062. cityTranffic = _EnterExitCosts.CityTranffic1;
  1063. }
  1064. else if (client.AirType == 460)
  1065. {
  1066. airName = $"经济舱";
  1067. airPrice = _EnterExitCosts.AirJJ;
  1068. cityTranffic = _EnterExitCosts.CityTranffic;
  1069. }
  1070. //计算费用总和
  1071. decimal AllPrice = airPrice + cityTranffic + dac1.Sum(x => x.SubTotal) + dac2.Sum(x => x.SubTotal) +
  1072. dac3.Sum(x => x.SubTotal) + dac4.Sum(x => x.SubTotal) + _EnterExitCosts.Visa + _EnterExitCosts.Safe +
  1073. +_EnterExitCosts.YiMiao + _EnterExitCosts.YiMiao + _EnterExitCosts.Ticket + _EnterExitCosts.Service;
  1074. WordAllPrice += AllPrice;
  1075. UsersTop += firstName + "出访费用为¥" + AllPrice.ToString("#0.00") + "元、";
  1076. TeableBookmarkArr.Add("jp", airPrice.ToString("#0.00") + " 元"); //机票金额
  1077. TeableBookmarkArr.Add("cs", $"{cityTranffic:#0.00} 元"); //城市交通费用
  1078. TeableBookmarkArr.Add("zs", dac1.Sum(x => Convert.ToDecimal(x.SubTotal)).ToString("#0.00") + " 元"); //住宿费
  1079. string zsinfo = string.Empty;
  1080. string hsinfo = string.Empty;
  1081. string gzinfo = string.Empty;
  1082. var placeArr = new List<string>();
  1083. Aspose.Words.Tables.Table FirstTable = (Aspose.Words.Tables.Table)doc.GetChild(NodeType.Table, 0, true);
  1084. Aspose.Words.Tables.Table ChildTable = (Aspose.Words.Tables.Table)FirstTable.GetChild(NodeType.Table, 0, true);
  1085. Aspose.Words.Tables.Table ChildTable1 = (Aspose.Words.Tables.Table)FirstTable.GetChild(NodeType.Table, 1, true);
  1086. Aspose.Words.Tables.Table ChildTable2 = (Aspose.Words.Tables.Table)FirstTable.GetChild(NodeType.Table, 2, true);
  1087. int rowIndex = 0;
  1088. if (dac1.Count <= 0 && ChildTable != null) ChildTable.Remove(); //删除表格
  1089. foreach (var item in dac1)
  1090. {
  1091. if (string.IsNullOrWhiteSpace(item.Place))
  1092. {
  1093. continue;
  1094. }
  1095. if (placeArr.Contains(item.Place))
  1096. {
  1097. continue;
  1098. }
  1099. else
  1100. {
  1101. placeArr.Add(item.Place);
  1102. }
  1103. if (!string.IsNullOrWhiteSpace(item.Place))
  1104. {
  1105. if (rowIndex > ChildTable.Rows.Count - 1)
  1106. {
  1107. var chitableRow = ChildTable.LastRow.Clone(true);
  1108. ChildTable.AppendChild(chitableRow);
  1109. }
  1110. int days = dac1.FindAll(x => x.Place == item.Place).Count;
  1111. SetCells(ChildTable, doc, rowIndex, 0, item.Place);
  1112. SetCells(ChildTable, doc, rowIndex, 1, days + "晚");
  1113. string currencyCode = currData.Find(it => it.Id == item.Currency)?.Remark ?? "Unknown";
  1114. SetCells(ChildTable, doc, rowIndex, 2, item.Cost.ToString("#0.00") + currencyCode + "/晚");
  1115. var currencyRate = DecimalToString((item.SubTotal / item.Cost), 4);
  1116. var sys_currencyInfo = _currencyDatas.Find(x => item.Currency == x.Id);
  1117. if (sys_currencyInfo != null)
  1118. {
  1119. var sys_currencyCode = sys_currencyInfo.Name;
  1120. var eec_currencyInfo = _EnterExitCostCurrencys.Find(x => x.Code.Equals(sys_currencyCode));
  1121. if (eec_currencyInfo != null)
  1122. {
  1123. currencyRate = DecimalToString(eec_currencyInfo.Rate, 4);
  1124. }
  1125. }
  1126. SetCells(ChildTable, doc, rowIndex, 3, "汇率" + currencyRate);
  1127. SetCells(ChildTable, doc, rowIndex, 4, "CNY " + item.SubTotal + "\r\n");
  1128. rowIndex++;
  1129. zsinfo += item.Place + " " + days + "晚 " + item.Cost.ToString("#0.00") + currencyCode + "/晚" + " 汇率" + (item.SubTotal / item.Cost).ToString("#0.0000") + " CNY " + item.SubTotal * days + "\r\n";
  1130. }
  1131. }
  1132. placeArr.Clear();
  1133. rowIndex = 0;
  1134. if (dac2.Count <= 0 && ChildTable1 != null) ChildTable1.Remove(); //删除表格
  1135. foreach (var item in dac2)
  1136. {
  1137. if (string.IsNullOrWhiteSpace(item.Place))
  1138. {
  1139. continue;
  1140. }
  1141. if (placeArr.Contains(item.Place))
  1142. {
  1143. continue;
  1144. }
  1145. else
  1146. {
  1147. placeArr.Add(item.Place);
  1148. }
  1149. if (!string.IsNullOrWhiteSpace(item.Place))
  1150. {
  1151. if (rowIndex > ChildTable1.Rows.Count - 1)
  1152. {
  1153. var chitableRow = ChildTable1.LastRow.Clone(true);
  1154. ChildTable1.AppendChild(chitableRow);
  1155. }
  1156. int days = dac2.FindAll(x => x.Place == item.Place).Count;
  1157. SetCells(ChildTable1, doc, rowIndex, 0, item.Place);
  1158. SetCells(ChildTable1, doc, rowIndex, 1, days + "天");
  1159. string currencyCode = currData.Find(it => it.Id == item.Currency)?.Remark ?? "Unknown";
  1160. SetCells(ChildTable1, doc, rowIndex, 2, item.Cost.ToString("#0.00") + currencyCode + "/天");
  1161. var currencyRate = DecimalToString((item.SubTotal / item.Cost), 4);
  1162. var sys_currencyInfo = _currencyDatas.Find(x => item.Currency == x.Id);
  1163. if (sys_currencyInfo != null)
  1164. {
  1165. var sys_currencyCode = sys_currencyInfo.Name;
  1166. var eec_currencyInfo = _EnterExitCostCurrencys.Find(x => x.Code.Equals(sys_currencyCode));
  1167. if (eec_currencyInfo != null)
  1168. {
  1169. currencyRate = DecimalToString(eec_currencyInfo.Rate, 4);
  1170. }
  1171. }
  1172. SetCells(ChildTable1, doc, rowIndex, 3, "汇率" + currencyRate);
  1173. SetCells(ChildTable1, doc, rowIndex, 4, "CNY " + item.SubTotal);
  1174. rowIndex++;
  1175. hsinfo += item.Place + " " + days + "天 " + item.Cost.ToString("#0.00") + currencyCode + "/天" + " 汇率" + (item.SubTotal / item.Cost).ToString("#0.0000") + " CNY " + item.SubTotal * days + "\r\n";
  1176. }
  1177. }
  1178. placeArr.Clear();
  1179. rowIndex = 0;
  1180. if (dac2.Count <= 0 && ChildTable2 != null) ChildTable2.Remove(); //删除表格
  1181. foreach (var item in dac3)
  1182. {
  1183. if (string.IsNullOrWhiteSpace(item.Place))
  1184. {
  1185. continue;
  1186. }
  1187. if (placeArr.Contains(item.Place))
  1188. {
  1189. continue;
  1190. }
  1191. else
  1192. {
  1193. placeArr.Add(item.Place);
  1194. }
  1195. if (!string.IsNullOrWhiteSpace(item.Place))
  1196. {
  1197. if (rowIndex > ChildTable2.Rows.Count - 1)
  1198. {
  1199. var chitableRow = ChildTable2.LastRow.Clone(true);
  1200. ChildTable2.AppendChild(chitableRow);
  1201. }
  1202. int days = dac3.FindAll(x => x.Place == item.Place).Count;
  1203. SetCells(ChildTable2, doc, rowIndex, 0, item.Place);
  1204. SetCells(ChildTable2, doc, rowIndex, 1, days + "天");
  1205. string currencyCode = currData.Find(it => it.Id == item.Currency)?.Remark ?? "Unknown";
  1206. SetCells(ChildTable2, doc, rowIndex, 2, item.Cost.ToString("#0.00") + currencyCode + "/天");
  1207. var currencyRate = DecimalToString((item.SubTotal / item.Cost), 4);
  1208. var sys_currencyInfo = _currencyDatas.Find(x => item.Currency == x.Id);
  1209. if (sys_currencyInfo != null)
  1210. {
  1211. var sys_currencyCode = sys_currencyInfo.Name;
  1212. var eec_currencyInfo = _EnterExitCostCurrencys.Find(x => x.Code.Equals(sys_currencyCode));
  1213. if (eec_currencyInfo != null)
  1214. {
  1215. currencyRate = DecimalToString(eec_currencyInfo.Rate, 4);
  1216. }
  1217. }
  1218. SetCells(ChildTable2, doc, rowIndex, 3, "汇率" + currencyRate);
  1219. SetCells(ChildTable2, doc, rowIndex, 4, "CNY " + item.SubTotal + "\r\n");
  1220. rowIndex++;
  1221. gzinfo += item.Place + " " + days + "天 " + item.Cost.ToString("#0.00") + currencyCode + "/天" + " 汇率" + (item.SubTotal / item.Cost).ToString("#0.00") + " CNY " + item.SubTotal * days + "\r\n";
  1222. }
  1223. }
  1224. placeArr.Clear();
  1225. TeableBookmarkArr.Add("zsinfo", zsinfo); //住宿费详情
  1226. TeableBookmarkArr.Add("hs", dac2.Sum(x => Convert.ToDecimal(x.SubTotal)).ToString("#0.00") + " 元"); //伙食费
  1227. TeableBookmarkArr.Add("hsinfo", hsinfo); //伙食费详情
  1228. TeableBookmarkArr.Add("gz", dac3.Sum(x => Convert.ToDecimal(x.SubTotal)).ToString("#0.00") + " 元"); //公杂费
  1229. TeableBookmarkArr.Add("gzinfo", gzinfo); //公杂费详情
  1230. string otherFeestr = "";
  1231. decimal otherFee = 0.00M;
  1232. if (_EnterExitCosts.Visa > 0.00M)
  1233. {
  1234. otherFee += _EnterExitCosts.Visa;
  1235. otherFeestr += $"签证费{_EnterExitCosts.Visa:#0.00}元、";
  1236. }
  1237. if (_EnterExitCosts.YiMiao > 0.00M)
  1238. {
  1239. otherFee += _EnterExitCosts.YiMiao;
  1240. otherFeestr += $"疫苗费{_EnterExitCosts.YiMiao:#0.00}元、";
  1241. }
  1242. if (_EnterExitCosts.HeSuan > 0.00M)
  1243. {
  1244. otherFee += _EnterExitCosts.HeSuan;
  1245. otherFeestr += $"核酸检测费{_EnterExitCosts.HeSuan:#0.00}元、";
  1246. }
  1247. if (_EnterExitCosts.Safe > 0.00M)
  1248. {
  1249. otherFee += _EnterExitCosts.Safe;
  1250. otherFeestr += $"保险费{_EnterExitCosts.Safe:#0.00}元、";
  1251. }
  1252. if (_EnterExitCosts.Ticket > 0.00M)
  1253. {
  1254. otherFee += _EnterExitCosts.Ticket;
  1255. otherFeestr += $"参展门票费{_EnterExitCosts.Ticket:#0.00}元、";
  1256. }
  1257. if (otherFeestr.Length > 0)
  1258. {
  1259. otherFeestr = otherFeestr.Substring(0, otherFeestr.Length - 1);
  1260. otherFeestr += "等费用";
  1261. }
  1262. TeableBookmarkArr.Add("qt", otherFee.ToString("#0.00") + " 元");//其他费用
  1263. TeableBookmarkArr.Add("qtinfo", otherFeestr);//其他费用第二列
  1264. TeableBookmarkArr.Add("fw", _EnterExitCosts.Service.ToString("#0.00") + "元/人");//服务费
  1265. TeableBookmarkArr.Add("AllPrice", AllPrice.ToString("#0.00") + "元/人");//表格合计费用
  1266. TeableBookmarkArr.Add("title", $"费用清单-{airName}({firstName})");
  1267. foreach (var book in TeableBookmarkArr.Keys)
  1268. {
  1269. if (doc.Range.Bookmarks[book] != null)
  1270. {
  1271. Bookmark mark = doc.Range.Bookmarks[book];
  1272. mark.Text = TeableBookmarkArr[book];
  1273. }
  1274. }
  1275. if (i != ClientItemList.Count - 1)
  1276. {
  1277. builder.PageSetup.Orientation = Aspose.Words.Orientation.Portrait;
  1278. Aspose.Words.Tables.Table table = (Aspose.Words.Tables.Table)doc.GetChild(NodeType.Table, 0, true);
  1279. table.ParentNode.InsertAfter(paragraph, table);
  1280. var CloneTable = (Aspose.Words.Tables.Table)table.Clone(true);
  1281. table.ParentNode.InsertAfter(CloneTable, paragraph);
  1282. }
  1283. TeableBookmarkArr.Clear();
  1284. }
  1285. bookmarkArr.Add("VisitPrice", WordAllPrice.ToString());//出访费用总额
  1286. bookmarkArr.Add("CnAllPrice", WordAllPrice.ConvertCNYUpper());//出访费用总额中文
  1287. bookmarkArr.Add("namesPrice", UsersTop.TrimEnd('、'));//各人员出访费用 付辰同志出访费用为¥73,604.8元
  1288. foreach (var book in bookmarkArr.Keys)
  1289. {
  1290. if (doc.Range.Bookmarks[book] != null)
  1291. {
  1292. Bookmark mark = doc.Range.Bookmarks[book];
  1293. mark.Text = bookmarkArr[book];
  1294. }
  1295. }
  1296. //MemoryStream outSteam = new MemoryStream();
  1297. string filsPath = AppSettingsHelper.Get("WordBasePath") + $"ForeignReceivables/File/{ClientItem.Key.Replace("\n", "")}_{_DelegationInfo.VisitCountry.Replace("|", "、")}.docx";
  1298. //去水印
  1299. new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String(AsposeHelper.asposeKey)));
  1300. doc.Save(filsPath);
  1301. filesToZip.Add(filsPath);
  1302. //streams.Add(ClientItem.Key + ".docx", outSteam.ToArray());
  1303. }
  1304. //文件名
  1305. string zipFileName = _DelegationInfo.TeamName + "-收款账单.zip";
  1306. string zipPath = $"ForeignReceivables/File/{_DelegationInfo.TeamName}-收款账单{DateTime.Now:yyyyMMddHHmmss}.zip";
  1307. try
  1308. {
  1309. using (var zip = ZipFile.Open(AppSettingsHelper.Get("WordBasePath") + zipPath, ZipArchiveMode.Create))
  1310. {
  1311. foreach (var file in filesToZip)
  1312. {
  1313. zip.CreateEntryFromFile(file, Path.GetFileName(file));
  1314. }
  1315. }
  1316. }
  1317. catch (Exception ex)
  1318. {
  1319. return Ok(JsonView(false, ex.Message));
  1320. }
  1321. string url = AppSettingsHelper.Get("WordBaseUrl") + $"Office/Word/{zipPath}";
  1322. return Ok(JsonView(true, "成功", new { Url = url }));
  1323. }
  1324. return Ok(JsonView(false, "操作失败!"));
  1325. }
  1326. catch (Exception ex)
  1327. {
  1328. return Ok(JsonView(false, ex.Message));
  1329. }
  1330. }
  1331. /// <summary>
  1332. /// decimal保留指定位数小数
  1333. /// </summary>
  1334. /// <param name="num">原始数量</param>
  1335. /// <param name="scale">保留小数位数</param>
  1336. /// <returns>截取指定小数位数后的数量字符串</returns>
  1337. private static string DecimalToString(decimal num, int scale)
  1338. {
  1339. string numToString = num.ToString();
  1340. int index = numToString.IndexOf(".");
  1341. int length = numToString.Length;
  1342. if (index != -1)
  1343. {
  1344. return string.Format("{0}.{1}",
  1345. numToString.Substring(0, index),
  1346. numToString.Substring(index + 1, Math.Min(length - index - 1, scale)));
  1347. }
  1348. else
  1349. {
  1350. return num.ToString();
  1351. }
  1352. }
  1353. /// <summary>
  1354. /// 保留小数位数
  1355. /// </summary>
  1356. /// <param name="n">待处理的值</param>
  1357. /// <param name="d">保留位数</param>
  1358. /// <param name="isEnter">是否四舍五入</param>
  1359. /// <returns></returns>
  1360. private static decimal Round(decimal n, int d, bool isEnter = false)
  1361. {
  1362. if (isEnter)
  1363. return decimal.Round(n, d, MidpointRounding.AwayFromZero);
  1364. return Math.Truncate(n * (decimal)Math.Pow(10, d)) / (decimal)Math.Pow(10, d);
  1365. }
  1366. private void SetCells(Aspose.Words.Tables.Table table, Document doc, int rows, int cells, string val)
  1367. {
  1368. //获取table中的某个单元格,从0开始
  1369. Aspose.Words.Tables.Cell lshCell = table.Rows[rows].Cells[cells];
  1370. //将单元格中的第一个段落移除
  1371. lshCell.FirstParagraph.Remove();
  1372. //if (cells == 0) lshCell.CellFormat.Width = 120;
  1373. //else if (cells == 1) lshCell.CellFormat.Width = 50;
  1374. //else if (cells == 2) lshCell.CellFormat.Width = 120;
  1375. //else if (cells == 3) lshCell.CellFormat.Width = 100;
  1376. //else if (cells == 4) lshCell.CellFormat.Width = 120;
  1377. //新建一个段落
  1378. var p = new Paragraph(doc);
  1379. var r = new Run(doc, val);
  1380. r.Font.Size = 8;
  1381. //把设置的值赋给之前新建的段落
  1382. p.AppendChild(r);
  1383. //将此段落加到单元格内
  1384. lshCell.AppendChild(p);
  1385. }
  1386. /// <summary>
  1387. /// 已收账单
  1388. /// 提示导入出入境报价费用
  1389. /// </summary>
  1390. /// <param name="groupId"></param>
  1391. /// <returns></returns>
  1392. [HttpPost]
  1393. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1394. public async Task<IActionResult> PostReceivablesImportFee(int groupId)
  1395. {
  1396. if (groupId < 1) return Ok(JsonView(false, "请传入有效的GroupId参数!"));
  1397. var data = await GeneralMethod.ReceivablesImportFeeAsync(groupId);
  1398. var view = _mapper.Map<List<ProceedsReceivedNewView>>(data);
  1399. return Ok(JsonView(true, "操作成功", view));
  1400. }
  1401. #endregion
  1402. #region 已收款项
  1403. /// <summary>
  1404. /// 已收款项
  1405. /// 查询
  1406. /// </summary>
  1407. /// <param name="dto"></param>
  1408. /// <returns></returns>
  1409. [HttpPost]
  1410. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1411. public async Task<IActionResult> PostAmountReceived(AmountReceivedDto dto)
  1412. {
  1413. try
  1414. {
  1415. if (dto == null)
  1416. {
  1417. return Ok(JsonView(false, "参数不能为空!"));
  1418. }
  1419. Result ffrData = await _proceedsReceivedRep.PostAmountReceived(dto.DiId);
  1420. dynamic data = null;
  1421. if (dto.PortType == 1)
  1422. {
  1423. if (ffrData.Code != 0)
  1424. {
  1425. return Ok(JsonView(false, ffrData.Msg));
  1426. }
  1427. data = ffrData.Data;
  1428. }
  1429. else if (dto.PortType == 2)
  1430. {
  1431. if (ffrData.Code != 0)
  1432. {
  1433. return Ok(JsonView(false, ffrData.Msg));
  1434. }
  1435. data = ffrData.Data;
  1436. }
  1437. else if (dto.PortType == 2)
  1438. {
  1439. if (ffrData.Code != 0)
  1440. {
  1441. return Ok(JsonView(false, ffrData.Msg));
  1442. }
  1443. data = ffrData.Data;
  1444. }
  1445. else return Ok(JsonView(false, "请选择正确的端口号!"));
  1446. return Ok(JsonView(true, "操作成功!", data));
  1447. }
  1448. catch (Exception ex)
  1449. {
  1450. return Ok(JsonView(false, ex.Message));
  1451. }
  1452. }
  1453. /// <summary>
  1454. /// 已收款项
  1455. /// Add Or Edit
  1456. /// </summary>
  1457. /// <param name="dto"></param>
  1458. /// <returns></returns>
  1459. [HttpPost]
  1460. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1461. public async Task<IActionResult> PostAmountReceivedAddOrEdit(AmountReceivedAddOrEditDto dto)
  1462. {
  1463. try
  1464. {
  1465. if (dto == null)
  1466. {
  1467. return Ok(JsonView(false, "参数不能为空!"));
  1468. }
  1469. Result ffrData = await _proceedsReceivedRep.PostAmountReceivedAddOrEditDto(dto);
  1470. #region 判断金额是否收完
  1471. //已收
  1472. var Fin_ProceedsReceived_SumPrice = _sqlSugar
  1473. .Queryable<Fin_ProceedsReceived>()
  1474. .Where(x => x.Diid == dto.DiId && x.IsDel == 0)
  1475. .Sum(x => x.Price);
  1476. //收款账单金额 (应收)
  1477. var Fin_ForeignReceivables_SumPrice = _sqlSugar
  1478. .Queryable<Fin_ForeignReceivables>()
  1479. .Where(x => x.Diid == dto.DiId && x.IsDel == 0)
  1480. .Sum(x => x.ItemSumPrice);
  1481. if ((Fin_ProceedsReceived_SumPrice - Fin_ForeignReceivables_SumPrice) >= 0)
  1482. {
  1483. _sqlSugar.Updateable<Grp_DelegationInfo>()
  1484. .Where(x => x.Id == dto.DiId && x.IsDel == 0)
  1485. .SetColumns(x => new Grp_DelegationInfo { IsSure = 1 })
  1486. .ExecuteCommand();
  1487. }
  1488. #endregion
  1489. if (dto.PortType == 1)
  1490. {
  1491. if (ffrData.Code != 0)
  1492. {
  1493. return Ok(JsonView(false, ffrData.Msg));
  1494. }
  1495. }
  1496. else if (dto.PortType == 2)
  1497. {
  1498. if (ffrData.Code != 0)
  1499. {
  1500. return Ok(JsonView(false, ffrData.Msg));
  1501. }
  1502. }
  1503. else if (dto.PortType == 2)
  1504. {
  1505. if (ffrData.Code != 0)
  1506. {
  1507. return Ok(JsonView(false, ffrData.Msg));
  1508. }
  1509. }
  1510. else
  1511. {
  1512. return Ok(JsonView(false, "请选择正确的端口号!"));
  1513. }
  1514. return Ok(JsonView(true, "操作成功!"));
  1515. }
  1516. catch (Exception ex)
  1517. {
  1518. return Ok(JsonView(false, ex.Message));
  1519. }
  1520. }
  1521. /// <summary>
  1522. /// 已收款项
  1523. /// Del
  1524. /// </summary>
  1525. /// <param name="dto"></param>
  1526. /// <returns></returns>
  1527. [HttpPost]
  1528. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1529. public async Task<IActionResult> PostAmountReceived_Del(AmountReceivedDelDto dto)
  1530. {
  1531. try
  1532. {
  1533. if (dto == null)
  1534. {
  1535. return Ok(JsonView(false, "参数不能为空!"));
  1536. }
  1537. Result ffrData = await _proceedsReceivedRep.PostAmountReceivedDel(dto);
  1538. if (ffrData.Code != 0)
  1539. {
  1540. return Ok(JsonView(false, ffrData.Msg));
  1541. }
  1542. return Ok(JsonView(true, "操作成功!"));
  1543. }
  1544. catch (Exception ex)
  1545. {
  1546. return Ok(JsonView(false, ex.Message));
  1547. }
  1548. }
  1549. /// <summary>
  1550. /// 已收款项
  1551. /// 会计团组费用excel下载
  1552. /// </summary>
  1553. /// <param name="dto"></param>
  1554. /// <returns></returns>
  1555. [HttpPost]
  1556. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1557. public async Task<IActionResult> GroupAccFee‌ExcelDownload(GroupAccFee‌ExcelDto dto)
  1558. {
  1559. //用户权限验证:只有财务部门的同事才能下载
  1560. var userInfo = await _sqlSugar.Queryable<Sys_Users>()
  1561. .LeftJoin<Sys_Department>((x, y) => x.DepId == y.Id)
  1562. .Where((x, y) => x.Id == dto.UserId && x.IsDel == 0 && y.DepName.Contains("财务"))
  1563. .FirstAsync();
  1564. if (userInfo == null) return Ok(JsonView(false, "只有财务部同事可下载!"));
  1565. //团组信息验证
  1566. var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  1567. .FirstAsync(x => x.Id == dto.GroupId && x.IsDel == 0);
  1568. if (groupInfo == null) return Ok(JsonView(false, "团组信息不存在或已删除,不可下载!"));
  1569. //已收款项信息验证
  1570. var proceedInfos = await _sqlSugar.Queryable<Fin_ProceedsReceived>()
  1571. .Where(x => x.Diid == dto.GroupId && x.IsDel == 0)
  1572. .Select(x => new GroupAccFee‌ExcelView()
  1573. {
  1574. OrgName‌ = x.Client,
  1575. VisitorNum‌ = 1, //假设每条记录代表一个访客
  1576. ActualAR = 0.00M,
  1577. PaidDate‌ = x.SectionTime,
  1578. PaidAmount‌ = x.Price,
  1579. Remark = x.Remark,
  1580. })
  1581. .ToListAsync();
  1582. if (!proceedInfos.Any()) return Ok(JsonView(false, "已收款项信息不存在或已删除,不可下载!"));
  1583. var costInfo = await _sqlSugar.Queryable<Grp_EnterExitCost>()
  1584. .Where(x => x.DiId == dto.GroupId && x.IsDel == 0)
  1585. .FirstAsync();
  1586. var rateInfos = CommonFun.GetCurrencyChinaToList(costInfo.CurrencyRemark);
  1587. var hotelCostInfos = await _sqlSugar.Queryable<Grp_DayAndCost>()
  1588. .LeftJoin<Sys_SetData>((x, y) => x.Currency == y.Id)
  1589. .Where((x, y) => x.DiId == dto.GroupId && x.Type == 1 && x.IsDel == 0)
  1590. .Select((x, y) => new { x.Place, x.Cost, x.Currency, y.Name, CurrencyName = y.Remark, Rate = x.SubTotal / x.Cost, x.SubTotal })
  1591. .ToListAsync();
  1592. decimal visaFee = costInfo?.Visa ?? 0.00M, //签证费
  1593. //intercityFare = costInfo?.CityTranffic ?? 0.00M, //城市区间交通费
  1594. hotelFee = hotelCostInfos.Sum(x => x.Cost), //住宿费
  1595. hotelCNYEquivalent = hotelCostInfos.Sum(x => x.SubTotal), //住宿费CNY折算价
  1596. hotelRate = rateInfos.FirstOrDefault(x => x.CurrencyCode.Equals(hotelCostInfos.FirstOrDefault().Name))?.Rate ?? 0.00M; //住宿费汇率
  1597. string hotelCurrency = hotelCostInfos.FirstOrDefault()?.CurrencyName ?? "-"; //住宿费币种
  1598. var costInfosNew = new List<GroupAccFee‌ExcelView>() {
  1599. new (){ CostName = "酒店",CostAmt = hotelFee,CostCurrency = hotelCurrency, CostRate = hotelRate, CNYEquivalent = hotelCNYEquivalent},
  1600. new (){ CostName = "市区间交通-经济舱",CostAmt = costInfo?.CityTranffic ?? 0.00M,CostCurrency = "人民币" },
  1601. new (){ CostName = "市区间交通-公务舱",CostAmt = costInfo?.CityTranffic1 ?? 0.00M,CostCurrency = "人民币" },
  1602. new (){ CostName = "市区间交通-头等舱",CostAmt = costInfo?.CityTranffic2 ?? 0.00M,CostCurrency = "人民币" },
  1603. new (){ CostName = "签证",CostAmt = visaFee,CostCurrency = "人民币" },
  1604. };
  1605. if (proceedInfos == null || proceedInfos.Count < 1) proceedInfos = costInfosNew;
  1606. int replaceCount = Math.Min(proceedInfos.Count, costInfosNew.Count);
  1607. // 替换元素
  1608. for (int i = 0; i < replaceCount; i++)
  1609. {
  1610. var newInfo = costInfosNew[i];
  1611. proceedInfos[i].CostName = newInfo.CostName;
  1612. if (newInfo.CostAmt != null && newInfo.CostAmt > 0.00M) proceedInfos[i].CostAmt = newInfo.CostAmt;
  1613. if (newInfo.CostRate != null && newInfo.CostRate > 0.00M) proceedInfos[i].CostRate = newInfo.CostRate;
  1614. if (newInfo.CNYEquivalent != null && newInfo.CNYEquivalent > 0.00M) proceedInfos[i].CNYEquivalent = newInfo.CNYEquivalent;
  1615. proceedInfos[i].CostCurrency = newInfo.CostCurrency;
  1616. }
  1617. // 添加剩余元素
  1618. if (costInfosNew.Count > proceedInfos.Count) proceedInfos.AddRange(costInfosNew.Skip(proceedInfos.Count));
  1619. int index = 1;
  1620. proceedInfos.ForEach(x =>
  1621. {
  1622. x.Index = index;
  1623. index++;
  1624. });
  1625. string url = string.Empty;
  1626. #region 生成Excel文件
  1627. var designer = new WorkbookDesigner
  1628. {
  1629. Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/‌GroupAccFee‌Temp.xlsx")
  1630. };
  1631. designer.SetDataSource("DataView", proceedInfos);
  1632. //根据数据源处理生成报表内容
  1633. designer.Process();
  1634. //设置sum函数
  1635. int cellIndex = proceedInfos.Count + 3;
  1636. int cellFormulaIndex = cellIndex - 1;
  1637. var calcFormula‌ = $"=SUM(F3:F{cellFormulaIndex})";
  1638. designer.Workbook.Worksheets[0].Cells[$"F{cellIndex}"].Formula = calcFormula‌;
  1639. //计算sum函数
  1640. designer.Workbook.Worksheets[0].CalculateFormula(new CalculationOptions() { IgnoreError = true }, true);
  1641. string fileName = $"AmountReceived/{groupInfo.TeamName}_会计团组费用{Guid.NewGuid()}.xlsx";
  1642. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  1643. url = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  1644. #endregion
  1645. return Ok(JsonView(true, "操作成功!", url));
  1646. }
  1647. #endregion
  1648. #region 收款退还与其他款项 --> 收款退还
  1649. /// <summary>
  1650. /// 收款退还与其他款项
  1651. /// 查询 根据团组Id
  1652. /// </summary>
  1653. /// <param name="dto"></param>
  1654. /// <returns></returns>
  1655. [HttpPost]
  1656. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1657. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyItemByDiId(PaymentRefundAndOtherMoneyItemByDiIdDto dto)
  1658. {
  1659. if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
  1660. if (dto.PageId <= 0) return Ok(JsonView(false, "请传入正确的的页面Id!"));
  1661. if (dto.UserId <= 0) return Ok(JsonView(false, "请传入正确的的员工Id!"));
  1662. #region 页面功能权限处理
  1663. var pageFunAuth = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1664. if (pageFunAuth.CheckAuth == 0)
  1665. {
  1666. return Ok(JsonView(false, "您没有当前页面查询权限!"));
  1667. }
  1668. #endregion
  1669. Result _result = await _paymentRefundAndOtherMoneyRep.ItemByDiId(dto.DiId);
  1670. if (dto.PortType == 1 || dto.PortType == 2 || dto.PortType == 3) //1 Web 2 Android 3 Ios
  1671. {
  1672. if (_result.Code != 0)
  1673. {
  1674. return Ok(JsonView(false, _result.Msg));
  1675. }
  1676. var data = new
  1677. {
  1678. PageFuncAuth = pageFunAuth,
  1679. _result.Data
  1680. };
  1681. return Ok(JsonView(true, "操作成功!", data));
  1682. }
  1683. else
  1684. {
  1685. return Ok(JsonView(false, "请输入正确的端口号! 1 Web 2 Android 3 Ios;"));
  1686. }
  1687. }
  1688. /// <summary>
  1689. /// 收款退还与其他款项
  1690. /// 删除
  1691. /// </summary>
  1692. /// <param name="dto"></param>
  1693. /// <returns></returns>
  1694. [HttpPost]
  1695. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1696. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyDel(PaymentRefundAndOtherMoneyDelDto dto)
  1697. {
  1698. if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
  1699. if (dto.PageId <= 0) return Ok(JsonView(false, "请传入正确的的页面Id!"));
  1700. if (dto.UserId <= 0) return Ok(JsonView(false, "请传入正确的的员工Id!"));
  1701. #region 页面功能权限处理
  1702. var pageFunAuth = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1703. #endregion
  1704. if (pageFunAuth.DeleteAuth == 0)
  1705. {
  1706. return Ok(JsonView(false, "您没有当前页面删除权限!"));
  1707. }
  1708. Result _result = await _paymentRefundAndOtherMoneyRep.Del(dto);
  1709. if (_result.Code != 0)
  1710. {
  1711. return Ok(JsonView(false, _result.Msg));
  1712. }
  1713. return Ok(JsonView(true, "操作成功!"));
  1714. }
  1715. /// <summary>
  1716. /// 收款退还与其他款项
  1717. /// Info Data Source
  1718. /// </summary>
  1719. /// <param name="dto"></param>
  1720. /// <returns></returns>
  1721. [HttpPost]
  1722. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1723. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyInfoDataSource(PortDtoBase dto)
  1724. {
  1725. Result _result = await _paymentRefundAndOtherMoneyRep.InfoDataSource(dto);
  1726. if (_result.Code != 0)
  1727. {
  1728. return Ok(JsonView(false, _result.Msg));
  1729. }
  1730. return Ok(JsonView(true, "查询成功!", _result.Data));
  1731. }
  1732. /// <summary>
  1733. /// 收款退还与其他款项
  1734. /// Info
  1735. /// </summary>
  1736. /// <param name="dto"></param>
  1737. /// <returns></returns>
  1738. [HttpPost]
  1739. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1740. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyInfo(PaymentRefundAndOtherMoneyInfoDto dto)
  1741. {
  1742. if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
  1743. var view = await _paymentRefundAndOtherMoneyRep.Info(dto);
  1744. return Ok(view);
  1745. }
  1746. /// <summary>
  1747. /// 收款退还与其他款项 --> 收款退还(只保留人名币)
  1748. /// 操作(Add Or Edit)
  1749. /// </summary>
  1750. /// <param name="dto"></param>
  1751. /// <returns></returns>
  1752. [HttpPost]
  1753. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1754. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyAddOrEdit(PaymentRefundAndOtherMoneyAddOrEditDto dto)
  1755. {
  1756. if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
  1757. if (dto.PageId <= 0) return Ok(JsonView(false, "请传入正确的的页面Id!"));
  1758. if (dto.UserId <= 0) return Ok(JsonView(false, "请传入正确的的员工Id!"));
  1759. #region 页面功能权限处理
  1760. var pageFunAuth = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1761. #endregion
  1762. if (dto.Status == 1) //add
  1763. {
  1764. if (pageFunAuth.AddAuth == 0) return Ok(JsonView(false, "您没有当前页面添加权限!"));
  1765. }
  1766. else if (dto.Status == 2) //edit
  1767. {
  1768. if (pageFunAuth.EditAuth == 0) return Ok(JsonView(false, "您没有当前页面编辑权限!"));
  1769. }
  1770. else return Ok(JsonView(false, "请输入正确的操作状态! 1 添加 2 修改!"));
  1771. return Ok(await _paymentRefundAndOtherMoneyRep.AddOrEdit(dto));
  1772. }
  1773. #endregion
  1774. #region 应收报表
  1775. /// <summary>
  1776. /// 查询单个团组的应收报表 费用明细
  1777. /// </summary>
  1778. /// <param name="groupId"></param>
  1779. /// <returns></returns>
  1780. [HttpGet]
  1781. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1782. public async Task<IActionResult> GetSyntheticalReceivableFeeDetails(int groupId)
  1783. {
  1784. // 参数验证
  1785. if (groupId <= 0)
  1786. {
  1787. return Ok(JsonView(false, "团组ID无效。"));
  1788. }
  1789. // 验证团组是否存在
  1790. var groupValid = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  1791. .Where(x => x.Id == groupId && x.IsDel == 0)
  1792. .AnyAsync();
  1793. if (!groupValid)
  1794. {
  1795. return Ok(JsonView(false, "团组ID无效或已被删除。"));
  1796. }
  1797. // 使用参数化查询避免SQL注入
  1798. string sql = @"
  1799. Select
  1800. Id,
  1801. TeamName,
  1802. CTable,
  1803. ModuleName,
  1804. CNYMoney
  1805. from
  1806. (
  1807. SELECT
  1808. di.Id,
  1809. di.TeamName,
  1810. sd.Name AS ModuleName,
  1811. ccp.CTable,
  1812. CASE
  1813. WHEN ccp.CTable = 76 THEN (
  1814. SELECT
  1815. hotelname
  1816. FROM
  1817. Grp_HotelReservations hr
  1818. WHERE
  1819. hr.Id = ccp.CId
  1820. and hr.IsDel = 0
  1821. )
  1822. WHEN ccp.CTable = 79 THEN (
  1823. SELECT
  1824. PriceName
  1825. FROM
  1826. Grp_CarTouristGuideGroundReservations ctgr
  1827. WHERE
  1828. ctgr.Id = ccp.CId
  1829. and ctgr.IsDel = 0
  1830. )
  1831. WHEN ccp.CTable = 80 THEN (
  1832. SELECT
  1833. Area
  1834. FROM
  1835. Grp_VisaInfo vi
  1836. WHERE
  1837. vi.Id = ccp.CId
  1838. and vi.IsDel = 0
  1839. )
  1840. WHEN ccp.CTable = 81 THEN (
  1841. SELECT
  1842. InviterArea
  1843. FROM
  1844. Grp_InvitationOfficialActivities ioa
  1845. WHERE
  1846. ioa.Id = ccp.CId
  1847. and ioa.IsDel = 0
  1848. )
  1849. WHEN ccp.CTable = 82 THEN (
  1850. SELECT
  1851. (
  1852. SELECT
  1853. GName
  1854. FROM
  1855. Grp_InsuranceCost ic
  1856. WHERE
  1857. ic.Id = c.Iid
  1858. )
  1859. FROM
  1860. Grp_Customers c
  1861. WHERE
  1862. c.Id = ccp.CId
  1863. and c.IsDel = 0
  1864. )
  1865. WHEN ccp.CTable = 85 THEN (
  1866. SELECT
  1867. FlightsCode
  1868. FROM
  1869. Grp_AirTicketReservations atr
  1870. WHERE
  1871. atr.Id = ccp.CId
  1872. and atr.IsDel = 0
  1873. )
  1874. WHEN ccp.CTable = 98 THEN (
  1875. SELECT
  1876. PriceName
  1877. FROM
  1878. Grp_DecreasePayments dp
  1879. WHERE
  1880. dp.Id = ccp.CId
  1881. and dp.IsDel = 0
  1882. )
  1883. WHEN ccp.CTable = 1015 THEN (
  1884. SELECT
  1885. PriceName
  1886. FROM
  1887. Fin_GroupExtraCost gec
  1888. WHERE
  1889. gec.Id = ccp.CId
  1890. and gec.IsDel = 0
  1891. )
  1892. ELSE '-'
  1893. END AS PriceName,
  1894. CASE
  1895. WHEN ccp.CTable = 76 THEN (
  1896. SELECT
  1897. IsDel
  1898. FROM
  1899. Grp_HotelReservations hr
  1900. WHERE
  1901. hr.Id = ccp.CId
  1902. and hr.IsDel = 0
  1903. )
  1904. WHEN ccp.CTable = 79 THEN (
  1905. SELECT
  1906. IsDel
  1907. FROM
  1908. Grp_CarTouristGuideGroundReservations ctgr
  1909. WHERE
  1910. ctgr.Id = ccp.CId
  1911. and ctgr.IsDel = 0
  1912. )
  1913. WHEN ccp.CTable = 80 THEN (
  1914. SELECT
  1915. IsDel
  1916. FROM
  1917. Grp_VisaInfo vi
  1918. WHERE
  1919. vi.Id = ccp.CId
  1920. and vi.IsDel = 0
  1921. )
  1922. WHEN ccp.CTable = 81 THEN (
  1923. SELECT
  1924. IsDel
  1925. FROM
  1926. Grp_InvitationOfficialActivities ioa
  1927. WHERE
  1928. ioa.Id = ccp.CId
  1929. and ioa.IsDel = 0
  1930. )
  1931. WHEN ccp.CTable = 82 THEN (
  1932. SELECT
  1933. IsDel
  1934. FROM
  1935. Grp_Customers c
  1936. WHERE
  1937. c.Id = ccp.CId
  1938. and c.IsDel = 0
  1939. )
  1940. WHEN ccp.CTable = 85 THEN (
  1941. SELECT
  1942. IsDel
  1943. FROM
  1944. Grp_AirTicketReservations atr
  1945. WHERE
  1946. atr.Id = ccp.CId
  1947. and atr.IsDel = 0
  1948. )
  1949. WHEN ccp.CTable = 98 THEN (
  1950. SELECT
  1951. IsDel
  1952. FROM
  1953. Grp_DecreasePayments dp
  1954. WHERE
  1955. dp.Id = ccp.CId
  1956. and dp.IsDel = 0
  1957. )
  1958. WHEN ccp.CTable = 1015 THEN (
  1959. SELECT
  1960. IsDel
  1961. FROM
  1962. Fin_GroupExtraCost gec
  1963. WHERE
  1964. gec.Id = ccp.CId
  1965. and gec.IsDel = 0
  1966. )
  1967. ELSE '1'
  1968. END AS ChildIsDel,
  1969. (ccp.PayMoney * ccp.DayRate) AS CNYMoney,
  1970. ccp.IsDel AS CcpIsDel,
  1971. di.IsDel AS DiIsDel
  1972. FROM
  1973. Grp_CreditCardPayment ccp
  1974. INNER JOIN Grp_DelegationInfo di ON ccp.DIId = di.Id
  1975. LEFT JOIN sys_setdata sd ON ccp.CTable = sd.Id
  1976. ) as view1
  1977. WHERE
  1978. DiIsDel = 0
  1979. AND ChildIsDel = 0
  1980. AND DiIsDel = 0
  1981. AND Id = @GroupId";
  1982. try
  1983. {
  1984. var datas = await _sqlSugar.SqlQueryable<SyntheticalReceivableFeeDetailsView>(sql)
  1985. .AddParameters(new { GroupId = groupId })
  1986. .ToListAsync();
  1987. // 分组统计并排序
  1988. var feeDatas = datas
  1989. .GroupBy(g => new { g.CTable, g.ModuleName })
  1990. .Select(s => new SyntheticalReceivableFeeDetailsView
  1991. {
  1992. ModuleName = s.Key.ModuleName ?? "未知模块",
  1993. CTable = s.Key.CTable,
  1994. CNYMoney = s.Sum(ss => ss.CNYMoney)
  1995. })
  1996. .OrderBy(x => x.CTable)
  1997. .ToList();
  1998. // 构建结果字符串
  1999. var feeLabel = new StringBuilder();
  2000. foreach (var item in feeDatas)
  2001. {
  2002. feeLabel.AppendLine($"{item.ModuleName} :{item.CNYMoney:#,##0.00} CNY");
  2003. feeLabel.AppendLine(); // 空行
  2004. }
  2005. // 如果没有数据,返回提示信息
  2006. if (feeDatas.Count == 0)
  2007. {
  2008. return Ok(JsonView(true, "查询成功,但未找到相关费用明细。", "暂无费用明细"));
  2009. }
  2010. return Ok(JsonView(true, "操作成功", feeLabel.ToString()));
  2011. }
  2012. catch (Exception ex)
  2013. {
  2014. // 记录日志
  2015. _logger.LogError(ex, "查询团组费用明细时发生错误,团组ID:{GroupId}", groupId);
  2016. return Ok(JsonView(false, "查询过程中发生错误,请稍后重试。"));
  2017. }
  2018. }
  2019. /// <summary>
  2020. /// 应收报表
  2021. /// 查询 根据日期范围
  2022. /// </summary>
  2023. /// <param name="dto"></param>
  2024. /// <returns></returns>
  2025. [HttpPost]
  2026. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2027. public async Task<IActionResult> PostSyntheticalReceivableByDateRange(PostSyntheticalReceivableByDateRangeDto dto)
  2028. {
  2029. #region 老版查询
  2030. //string sqlWhere = " Where di.IsDel=0 ";
  2031. //#region 验证
  2032. //if (string.IsNullOrEmpty(dto.beginDt) && string.IsNullOrEmpty(dto.endDt))
  2033. //{
  2034. // return Ok(JsonView(false, "日期参数至少填写一个!"));
  2035. //}
  2036. //if (!string.IsNullOrEmpty(dto.beginDt))
  2037. //{
  2038. // if (Regex.Match(dto.beginDt, @"^\d{4}-\d{2}-\d{2}$").Value.Length < 1)
  2039. // {
  2040. // return Ok(JsonView(false, "日期参数格式错误,应为yyyy-MM-dd!"));
  2041. // }
  2042. // else
  2043. // {
  2044. // sqlWhere += string.Format(@" And di.VisitDate >= '{0} 00:00:00' ", dto.beginDt);
  2045. // }
  2046. //}
  2047. //if (!string.IsNullOrEmpty(dto.endDt))
  2048. //{
  2049. // if (Regex.Match(dto.endDt, @"^\d{4}-\d{2}-\d{2}$").Value.Length < 1)
  2050. // {
  2051. // return Ok(JsonView(false, "日期参数格式错误,应为yyyy-MM-dd!"));
  2052. // }
  2053. // else
  2054. // {
  2055. // sqlWhere += string.Format(@" And di.VisitDate <= '{0} 23:59:59' ", dto.endDt);
  2056. // }
  2057. //}
  2058. //if (!string.IsNullOrEmpty(dto.groupName))
  2059. //{
  2060. // sqlWhere += string.Format(@" And di.TeamName Like '%{0}%' ", dto.groupName);
  2061. //}
  2062. //#endregion
  2063. ////已收款项 判断如果是市场部的人员进来的话 只显示自己的 其他的都显示全部的
  2064. //string userSqlWhere = "";
  2065. //var userInfos = await _sqlSugar.Queryable<Sys_Users>()
  2066. // .InnerJoin<Sys_Department>((u, d) => u.DepId == d.Id)
  2067. // .Where((u, d) => u.IsDel == 0 && d.DepName.Contains("市场部") && u.Id == dto.CurrUserId)
  2068. // .ToListAsync();
  2069. //if (userInfos.Count > 0) userSqlWhere = string.Format(@$" And JietuanOperator={dto.CurrUserId} ");
  2070. ////排序倒序
  2071. //string sql = string.Format(@$"select distinct fr.diid,di.TeamName,di.ClientUnit,di.VisitDate,di.CreateTime from Fin_ForeignReceivables fr join Grp_DelegationInfo di on fr.DIID = di.id {sqlWhere} {userSqlWhere} Order By di.VisitDate Desc");
  2072. //var list_rst = _sqlSugar.SqlQueryable<PostSyntheticalReceivableByDateRangeView>(sql).ToList();
  2073. #endregion
  2074. //日期验证
  2075. var startTimeFlag = DateTime.TryParse(dto.beginDt, out DateTime begintime);
  2076. var endTimeFlag = DateTime.TryParse(dto.endDt, out DateTime endtime);
  2077. if (!startTimeFlag || !endTimeFlag) return Ok(JsonView(false, "请输入正确的开始、结束时间!"));
  2078. string groupName = dto.groupName;
  2079. int currUserId = dto.CurrUserId;
  2080. //已收款项 判断如果是市场部的人员进来的话 只显示自己的 其他的都显示全部的
  2081. var marketStaffFlag = await _sqlSugar.Queryable<Sys_Users>()
  2082. .InnerJoin<Sys_Department>((u, d) => u.DepId == d.Id)
  2083. .Where((u, d) => u.IsDel == 0 && d.DepName.Contains("市场部") && u.Id == dto.CurrUserId)
  2084. .AnyAsync();
  2085. var list_rst = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  2086. .Where(x => x.IsDel == 0)
  2087. .WhereIF(startTimeFlag && endTimeFlag, x => x.VisitDate >= begintime && x.VisitDate <= endtime)
  2088. .WhereIF(!string.IsNullOrEmpty(groupName), x => x.TeamName.Contains(groupName))
  2089. .WhereIF(marketStaffFlag, x => x.JietuanOperator == currUserId)
  2090. .OrderBy(x => x.VisitDate)
  2091. .Select(x => new PostSyntheticalReceivableByDateRangeView()
  2092. {
  2093. diid = x.Id,
  2094. teamName = x.TeamName,
  2095. clientUnit = x.ClientUnit,
  2096. visitDate = x.VisitDate.ToString("yyyy-MM-dd")
  2097. })
  2098. .ToListAsync();
  2099. var setData = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  2100. decimal sumAll_fr = 0M; //应收
  2101. decimal sumAll_pr = 0M; //已收
  2102. decimal sumAll_balance = 0M; //尾款
  2103. var result = new PostSyntheticalReceivableByDateRangeResultView();
  2104. if (list_rst.Any())
  2105. {
  2106. //查询团组各模块费用信息
  2107. string sql = @"
  2108. Select
  2109. Id,
  2110. TeamName,
  2111. CTable,
  2112. ModuleName,
  2113. CNYMoney
  2114. from
  2115. (
  2116. SELECT
  2117. di.Id,
  2118. di.TeamName,
  2119. sd.Name AS ModuleName,
  2120. ccp.CTable,
  2121. CASE
  2122. WHEN ccp.CTable = 76 THEN (
  2123. SELECT
  2124. hotelname
  2125. FROM
  2126. Grp_HotelReservations hr
  2127. WHERE
  2128. hr.Id = ccp.CId
  2129. and hr.IsDel = 0
  2130. )
  2131. WHEN ccp.CTable = 79 THEN (
  2132. SELECT
  2133. PriceName
  2134. FROM
  2135. Grp_CarTouristGuideGroundReservations ctgr
  2136. WHERE
  2137. ctgr.Id = ccp.CId
  2138. and ctgr.IsDel = 0
  2139. )
  2140. WHEN ccp.CTable = 80 THEN (
  2141. SELECT
  2142. Area
  2143. FROM
  2144. Grp_VisaInfo vi
  2145. WHERE
  2146. vi.Id = ccp.CId
  2147. and vi.IsDel = 0
  2148. )
  2149. WHEN ccp.CTable = 81 THEN (
  2150. SELECT
  2151. InviterArea
  2152. FROM
  2153. Grp_InvitationOfficialActivities ioa
  2154. WHERE
  2155. ioa.Id = ccp.CId
  2156. and ioa.IsDel = 0
  2157. )
  2158. WHEN ccp.CTable = 82 THEN (
  2159. SELECT
  2160. (
  2161. SELECT
  2162. GName
  2163. FROM
  2164. Grp_InsuranceCost ic
  2165. WHERE
  2166. ic.Id = c.Iid
  2167. )
  2168. FROM
  2169. Grp_Customers c
  2170. WHERE
  2171. c.Id = ccp.CId
  2172. and c.IsDel = 0
  2173. )
  2174. WHEN ccp.CTable = 85 THEN (
  2175. SELECT
  2176. FlightsCode
  2177. FROM
  2178. Grp_AirTicketReservations atr
  2179. WHERE
  2180. atr.Id = ccp.CId
  2181. and atr.IsDel = 0
  2182. )
  2183. WHEN ccp.CTable = 98 THEN (
  2184. SELECT
  2185. PriceName
  2186. FROM
  2187. Grp_DecreasePayments dp
  2188. WHERE
  2189. dp.Id = ccp.CId
  2190. and dp.IsDel = 0
  2191. )
  2192. WHEN ccp.CTable = 1015 THEN (
  2193. SELECT
  2194. PriceName
  2195. FROM
  2196. Fin_GroupExtraCost gec
  2197. WHERE
  2198. gec.Id = ccp.CId
  2199. and gec.IsDel = 0
  2200. )
  2201. ELSE '-'
  2202. END AS PriceName,
  2203. CASE
  2204. WHEN ccp.CTable = 76 THEN (
  2205. SELECT
  2206. IsDel
  2207. FROM
  2208. Grp_HotelReservations hr
  2209. WHERE
  2210. hr.Id = ccp.CId
  2211. and hr.IsDel = 0
  2212. )
  2213. WHEN ccp.CTable = 79 THEN (
  2214. SELECT
  2215. IsDel
  2216. FROM
  2217. Grp_CarTouristGuideGroundReservations ctgr
  2218. WHERE
  2219. ctgr.Id = ccp.CId
  2220. and ctgr.IsDel = 0
  2221. )
  2222. WHEN ccp.CTable = 80 THEN (
  2223. SELECT
  2224. IsDel
  2225. FROM
  2226. Grp_VisaInfo vi
  2227. WHERE
  2228. vi.Id = ccp.CId
  2229. and vi.IsDel = 0
  2230. )
  2231. WHEN ccp.CTable = 81 THEN (
  2232. SELECT
  2233. IsDel
  2234. FROM
  2235. Grp_InvitationOfficialActivities ioa
  2236. WHERE
  2237. ioa.Id = ccp.CId
  2238. and ioa.IsDel = 0
  2239. )
  2240. WHEN ccp.CTable = 82 THEN (
  2241. SELECT
  2242. IsDel
  2243. FROM
  2244. Grp_Customers c
  2245. WHERE
  2246. c.Id = ccp.CId
  2247. and c.IsDel = 0
  2248. )
  2249. WHEN ccp.CTable = 85 THEN (
  2250. SELECT
  2251. IsDel
  2252. FROM
  2253. Grp_AirTicketReservations atr
  2254. WHERE
  2255. atr.Id = ccp.CId
  2256. and atr.IsDel = 0
  2257. )
  2258. WHEN ccp.CTable = 98 THEN (
  2259. SELECT
  2260. IsDel
  2261. FROM
  2262. Grp_DecreasePayments dp
  2263. WHERE
  2264. dp.Id = ccp.CId
  2265. and dp.IsDel = 0
  2266. )
  2267. WHEN ccp.CTable = 1015 THEN (
  2268. SELECT
  2269. IsDel
  2270. FROM
  2271. Fin_GroupExtraCost gec
  2272. WHERE
  2273. gec.Id = ccp.CId
  2274. and gec.IsDel = 0
  2275. )
  2276. ELSE '1'
  2277. END AS ChildIsDel,
  2278. (ccp.PayMoney * ccp.DayRate) AS CNYMoney,
  2279. ccp.IsDel AS CcpIsDel,
  2280. di.IsDel AS DiIsDel
  2281. FROM
  2282. Grp_CreditCardPayment ccp
  2283. INNER JOIN Grp_DelegationInfo di ON ccp.DIId = di.Id
  2284. LEFT JOIN sys_setdata sd ON ccp.CTable = sd.Id
  2285. ) as view1
  2286. WHERE
  2287. DiIsDel = 0
  2288. AND ChildIsDel = 0
  2289. AND DiIsDel = 0
  2290. AND Id IN (@GroupIds)";
  2291. var groupIds = list_rst.Select(x => x.diid).ToList();
  2292. var datas = _sqlSugar.SqlQueryable<SyntheticalReceivableFeeDetailsView>(sql)
  2293. .AddParameters(new { GroupIds = groupIds })
  2294. .ToList();
  2295. #region 2025-12-01 新增团组成本报价
  2296. string groupCostSql = @"select * from Grp_GroupCostParameter where IsDel = 0 and CostType = 'A' And diid IN (@GroupIds)";
  2297. var groupCostDatas = _sqlSugar.SqlQueryable<GroupCostCalculate>(groupCostSql)
  2298. .AddParameters(new { GroupIds = groupIds })
  2299. .ToList();
  2300. #endregion
  2301. int rowNumber = 1;
  2302. foreach (var item_rst in list_rst)
  2303. {
  2304. item_rst.No = rowNumber;
  2305. rowNumber++;
  2306. int diId = item_rst.diid;
  2307. decimal sum_fr = 0M;
  2308. decimal sum_pr = 0M;
  2309. string str_client = string.Empty;
  2310. decimal sum_refund = 0M; //收款退还
  2311. decimal sum_extra = 0M; //超支费用
  2312. //decimal balance = 0M;
  2313. string str_schedule = string.Empty;
  2314. //1.应收
  2315. string sql_fr = string.Format(@" Select * From Fin_ForeignReceivables Where IsDel=0 And Diid={0} ", diId);
  2316. List<Fin_ForeignReceivables> list_fr = _sqlSugar.SqlQueryable<Fin_ForeignReceivables>(sql_fr).ToList();
  2317. sum_fr = list_fr.Sum(s => s.ItemSumPrice);
  2318. //2.已收
  2319. string sql_pr = string.Format(@" Select * From Fin_ProceedsReceived Where IsDel=0 And Diid={0} ", diId);
  2320. List<Fin_ProceedsReceived> list_pr = _sqlSugar.SqlQueryable<Fin_ProceedsReceived>(sql_pr).ToList();
  2321. foreach (var item_pr in list_pr)
  2322. {
  2323. sum_pr += item_pr.Price;
  2324. str_client += string.Format(@"{0};", item_pr.Client);
  2325. str_schedule += string.Format(@"{0};", item_pr.Remark);
  2326. }
  2327. if (str_schedule.Length > 0)
  2328. {
  2329. str_schedule = str_schedule.TrimEnd(';');
  2330. }
  2331. if (str_client.Length > 0)
  2332. {
  2333. str_client = str_client.TrimEnd(';');
  2334. }
  2335. //3.收款退还
  2336. string sql_other = string.Format(@"Select * From Fin_PaymentRefundAndOtherMoney prao
  2337. Inner Join Grp_CreditCardPayment ccp On prao.Id = ccp.CId
  2338. Where ccp.CTable = 285 And ccp.IsPay = 1 And prao.IsDel = 0 And ccp.IsDel = 0 And prao.DiId = {0}", diId);
  2339. List<Grp_CreditCardPayment> list_other = _sqlSugar.SqlQueryable<Grp_CreditCardPayment>(sql_other).ToList();
  2340. sum_refund = list_other.Sum(s => s.PayMoney * s.DayRate);
  2341. //4.超支
  2342. //string sql_extra = string.Format(@" Select c.* From Fin_GroupExtraCost f
  2343. //Inner join Grp_CreditCardPayment c On f.Id = c.CId
  2344. //Where c.CTable = 1015 And c.IsPay = 1 And f.IsDel = 0 And c.IsDel = 0 And f.DiId = {0} ", diId);
  2345. //List<Grp_CreditCardPayment> list_extra = _sqlSugar.SqlQueryable<Grp_CreditCardPayment>(sql_extra).ToList();
  2346. //sum_extra = list_extra.Sum(s => s.PayMoney * s.DayRate);
  2347. item_rst.frPrice = sum_fr.ToString("#0.00");
  2348. item_rst.extraPrice = sum_extra.ToString("#0.00");
  2349. item_rst.receivableTotal = (sum_fr + sum_extra).ToString("#0.00");
  2350. item_rst.prPrice = sum_pr.ToString("#0.00");
  2351. item_rst.refundAmount = sum_refund.ToString("#0.00");
  2352. item_rst.receivedTotal = (sum_pr - sum_refund).ToString("#0.00");
  2353. item_rst.balPrice = ((sum_fr + sum_extra) - (sum_pr - sum_refund)).ToString("#0.00");
  2354. item_rst.prClient = str_client;
  2355. item_rst.schedule = str_schedule;
  2356. string tempVisitDate = Convert.ToDateTime(item_rst.visitDate).ToString("yyyy-MM-dd");
  2357. sumAll_fr += (sum_fr + sum_extra);
  2358. sumAll_pr += (sum_pr - sum_refund);
  2359. sumAll_balance += ((sum_fr + sum_extra) - (sum_pr - sum_refund));
  2360. //应收、已收、收款退还、余款 都为零 且 团组费用有值时 变色
  2361. if (sum_fr <= 0m && (sum_fr + sum_extra) <= 0m && sum_refund <= 0m && ((sum_fr + sum_extra) - (sum_pr - sum_refund)) <= 0m)
  2362. {
  2363. item_rst.isChangeColorRed = true;
  2364. var currDatas = datas.Where(w => w.Id == diId).ToList();
  2365. decimal totalCost = currDatas.Sum(s => s.CNYMoney);
  2366. if (totalCost > 0m)
  2367. {
  2368. // 分组统计并排序
  2369. var feeDatas1 = currDatas
  2370. .GroupBy(g => new { g.CTable, g.ModuleName })
  2371. .Select(s => new SyntheticalReceivableFeeDetailsView
  2372. {
  2373. ModuleName = s.Key.ModuleName ?? "未知模块",
  2374. CTable = s.Key.CTable,
  2375. CNYMoney = s.Sum(ss => ss.CNYMoney)
  2376. })
  2377. .OrderBy(x => x.CTable)
  2378. .ToList();
  2379. // 构建结果字符串
  2380. var feeLabel = new StringBuilder();
  2381. foreach (var item in feeDatas1)
  2382. {
  2383. feeLabel.AppendLine(); // 空行
  2384. feeLabel.AppendLine($"{item.ModuleName} :{item.CNYMoney:#,##0.00} CNY");
  2385. }
  2386. //item_rst.isChangeColorRed = false; //红色/橙色只显示一个
  2387. item_rst.isChangeColor = true;
  2388. item_rst.ChangeColorLabel = feeLabel.ToString();
  2389. }
  2390. }
  2391. #region 单位应收已收细项(以应收费用名称为主去(已收费用)匹配) 新增 雷怡 2024-5-08 16:35:28
  2392. var feeDatas = new List<ClientFeeInfoView>();
  2393. //匹配上的数据
  2394. foreach (var item in list_fr)
  2395. {
  2396. var prInfo = list_pr.Find(it => item.PriceName.Contains(it.Client) || item.PriceName.Equals(it.Client));
  2397. decimal _balancePayment = 0.00M;
  2398. if (item.Currency == prInfo?.Currency)
  2399. {
  2400. _balancePayment = item.ItemSumPrice - prInfo?.Price ?? 0.00M;
  2401. }
  2402. feeDatas.Add(new ClientFeeInfoView
  2403. {
  2404. client = item.PriceName,
  2405. frMoney = item.ItemSumPrice.ToString("#0.00"),
  2406. frCurrency = setData.Find(it => it.Id == item.Currency)?.Name ?? "-",
  2407. frRate = item.Rate.ToString("#0.0000"),
  2408. prReceivablesType = setData.Find(it => it.Id == prInfo?.ReceivablesType)?.Name ?? "",
  2409. prTime = prInfo?.SectionTime ?? "-",
  2410. prMoney = prInfo?.Price.ToString("#0.00") ?? "-",
  2411. prCurrency = setData.Find(it => it.Id == prInfo?.Currency)?.Name ?? "",
  2412. balPayment = _balancePayment.ToString("#0.00")
  2413. });
  2414. }
  2415. //未匹配上的数据
  2416. foreach (var item in list_pr)
  2417. {
  2418. var frInfo = list_fr.Find(it => it.PriceName.Contains(item.Client) || it.PriceName.Equals(item.Client));
  2419. if (frInfo == null)
  2420. {
  2421. feeDatas.Add(new ClientFeeInfoView
  2422. {
  2423. client = item.Client + "[未匹配上的已收数据(应收已收公司名称不一致)]",
  2424. frMoney = "0.00",
  2425. frCurrency = "-",
  2426. frRate = "0.0000",
  2427. prReceivablesType = setData.Find(it => it.Id == item?.ReceivablesType)?.Name ?? "",
  2428. prTime = item?.SectionTime ?? "-",
  2429. prMoney = item?.Price.ToString("#0.00") ?? "0.00",
  2430. prCurrency = setData.Find(it => it.Id == item?.Currency)?.Name ?? "",
  2431. balPayment = "0.00"
  2432. });
  2433. }
  2434. }
  2435. if (feeDatas.Count < 1)
  2436. {
  2437. feeDatas.Add(new ClientFeeInfoView() { });
  2438. }
  2439. item_rst.feeItem = feeDatas;
  2440. #endregion
  2441. #region 团组成本报价信息 2025-12-01 13:56:55
  2442. var groupCostInfo = groupCostDatas.FirstOrDefault(f => f.DiId == diId);
  2443. item_rst.groupCost = groupCostInfo?.GroupTotalPrice ?? 0.00m;
  2444. item_rst.groupCostItem = groupCostInfo?.ChildFeeInfos ?? new List<ChildFeeInfo>();
  2445. #endregion
  2446. }
  2447. result.total_fr = sumAll_fr.ToString("#0.00");
  2448. result.total_pr = sumAll_pr.ToString("#0.00");
  2449. result.total_balance = sumAll_balance.ToString("#0.00");
  2450. result.dataList = new List<PostSyntheticalReceivableByDateRangeView>(list_rst);
  2451. if (dto.requestType == 1)
  2452. {
  2453. return Ok(JsonView(true, "请求成功", result, list_rst.Count));
  2454. }
  2455. else if (dto.requestType == 2)
  2456. {
  2457. //----------------------------
  2458. var list_Ex = new List<Excel_SyntheticalReceivableByDateRange>();
  2459. var designer = new WorkbookDesigner()
  2460. {
  2461. Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/应收款项模板 - 副本.xls")
  2462. };
  2463. int excNo = 1;
  2464. foreach (var item in list_rst)
  2465. {
  2466. var exc = new Excel_SyntheticalReceivableByDateRange
  2467. {
  2468. No = excNo.ToString(),
  2469. TeamName = item.teamName,
  2470. ClientUnit = item.clientUnit,
  2471. VisitDate = item.visitDate,
  2472. Accounts = item.frPrice,
  2473. Extra = item.extraPrice,
  2474. ReceivableTotal = item.receivableTotal,
  2475. Received = item.prPrice,
  2476. RefundAmount = item.refundAmount,
  2477. ReceivedTotal = item.receivedTotal,
  2478. Balance = item.balPrice,
  2479. Collection = item.schedule,
  2480. GroupCost = item.groupCost.ToString("#0.00"),
  2481. };
  2482. excNo++;
  2483. DateTime time = Convert.ToDateTime(item.visitDate);
  2484. TimeSpan ts = DateTime.Now - time;
  2485. float sy = float.Parse(item.balPrice);
  2486. if (ts.Days >= 365 && sy > 0)
  2487. {
  2488. exc.Sign = "需收款";
  2489. }
  2490. else
  2491. {
  2492. exc.Sign = "";
  2493. }
  2494. list_Ex.Add(exc);
  2495. }
  2496. var dt = CommonFun.GetDataTableFromIList(list_Ex);
  2497. dt.TableName = "Excel_SyntheticalReceivableByDateRange";
  2498. if (dt != null)
  2499. {
  2500. designer.SetDataSource("SumPrice", "应收合计:" + result.total_fr + "RMB 已收合计:" + result.total_pr + "RMB 余款合计:" + result.total_balance + "RMB");
  2501. //数据源
  2502. designer.SetDataSource(dt);
  2503. //根据数据源处理生成报表内容
  2504. designer.Process();
  2505. string fileName = ("Receivable/应收款项(" + dto.beginDt + "~" + dto.endDt + ").xlsx");
  2506. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  2507. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  2508. return Ok(JsonView(true, "成功", new { url = rst }));
  2509. }
  2510. }
  2511. else if (dto.requestType == 3)
  2512. {
  2513. //----------------------------
  2514. var list_Ex_Orange = new List<Excel_SyntheticalReceivableByDateRange>();
  2515. var list_Ex_Red = new List<Excel_SyntheticalReceivableByDateRange>();
  2516. var designer = new WorkbookDesigner()
  2517. {
  2518. Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/应收款项模板1.xls")
  2519. };
  2520. //只查询标注颜色的数据
  2521. var list_rst_orange = list_rst.Where(x => x.isChangeColor).ToList();
  2522. var orangeGroupIds = list_rst.Where(x => x.isChangeColor).Select(x => x.diid).ToList();
  2523. var list_rst_red = list_rst.Where(x => x.isChangeColorRed && !orangeGroupIds.Contains(x.diid)).ToList();
  2524. int excNo1 = 1, excNo2 = 1;
  2525. foreach (var item in list_rst_orange)
  2526. {
  2527. var exc = new Excel_SyntheticalReceivableByDateRange
  2528. {
  2529. No = excNo1.ToString(),
  2530. TeamName = item.teamName,
  2531. ClientUnit = item.clientUnit,
  2532. VisitDate = item.visitDate,
  2533. ChangeColorLabel = item.ChangeColorLabel,
  2534. GroupCost = item.groupCost.ToString("#0.00")
  2535. };
  2536. excNo1++;
  2537. list_Ex_Orange.Add(exc);
  2538. }
  2539. foreach (var item in list_rst_red)
  2540. {
  2541. var exc = new Excel_SyntheticalReceivableByDateRange
  2542. {
  2543. No = excNo2.ToString(),
  2544. TeamName = item.teamName,
  2545. ClientUnit = item.clientUnit,
  2546. VisitDate = item.visitDate,
  2547. ChangeColorLabel = item.ChangeColorLabel,
  2548. GroupCost = item.groupCost.ToString("#0.00")
  2549. };
  2550. excNo2++;
  2551. list_Ex_Red.Add(exc);
  2552. }
  2553. var dt_orange = CommonFun.GetDataTableFromIList(list_Ex_Orange);
  2554. dt_orange.TableName = "DataSource1";
  2555. var dt_red = CommonFun.GetDataTableFromIList(list_Ex_Red);
  2556. dt_red.TableName = "DataSource2";
  2557. if (dt_orange != null || dt_red != null)
  2558. {
  2559. //数据源
  2560. designer.SetDataSource(dt_orange);
  2561. designer.SetDataSource(dt_red);
  2562. //根据数据源处理生成报表内容
  2563. designer.Process();
  2564. string fileName = $"Receivable/应收款项{dto.beginDt}~{dto.endDt})_标注团组{Guid.NewGuid():N}.xlsx";
  2565. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  2566. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  2567. return Ok(JsonView(true, "成功", new { url = rst }));
  2568. }
  2569. }
  2570. }
  2571. return Ok(JsonView(true, "暂无数据", result, list_rst.Count));
  2572. }
  2573. #endregion
  2574. #region 付款申请
  2575. /// <summary>
  2576. /// 付款申请
  2577. /// 基础数据
  2578. /// </summary>
  2579. /// <returns></returns>
  2580. [HttpPost]
  2581. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2582. public async Task<IActionResult> PostPayRequestInit()
  2583. {
  2584. var conpanyDatas = _sqlSugar.Queryable<Sys_Company>()
  2585. .Where(it => it.IsDel == 0)
  2586. .Select(it => new
  2587. {
  2588. it.Id,
  2589. it.CompanyName
  2590. }).ToList();
  2591. return Ok(JsonView(true, "操作成功!", new { ConpanyData = conpanyDatas }));
  2592. }
  2593. /// <summary>
  2594. /// 付款申请 (PageId=51)
  2595. /// 查询 根据日期范围
  2596. /// </summary>
  2597. /// <param name="dto"></param>
  2598. /// <returns></returns>
  2599. [HttpPost]
  2600. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2601. public async Task<IActionResult> PostPayRequest_Center(PostPayRequestByDateRangeDto dto)
  2602. {
  2603. Stopwatch stopwatch = Stopwatch.StartNew();
  2604. #region 验证
  2605. string format = "yyyy-MM-dd";
  2606. if (!DateTime.TryParseExact(dto.beginDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime beginDt))
  2607. {
  2608. return Ok(JsonView(false, "开始日期格式不正确!正确格式:yyyy-MM-dd"));
  2609. }
  2610. if (!DateTime.TryParseExact(dto.endDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime endDt))
  2611. {
  2612. return Ok(JsonView(false, "结束日期格式不正确!正确格式:yyyy-MM-dd"));
  2613. }
  2614. #region 页面操作权限验证
  2615. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2616. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  2617. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  2618. #endregion
  2619. #endregion
  2620. try
  2621. {
  2622. PaymentRequestCheckedView checkedView = new PaymentRequestCheckedView();
  2623. var checkedStr = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>("paymentRequestCheckedData");
  2624. if (checkedStr != null)
  2625. {
  2626. checkedView = JsonConvert.DeserializeObject<PaymentRequestCheckedView>(checkedStr.ToString());
  2627. if (checkedView.GroupIds.Count > 0)
  2628. {
  2629. checkedView.GroupIds = checkedView.GroupIds.OrderBy(x => x).ToList();
  2630. }
  2631. }
  2632. tree_Fin_DailyFeePaymentResult dailyResult = PayRequest_DailyByDateRange(dto.Status, checkedView.DailyPaymentIds, dto.beginDt, dto.endDt);
  2633. tree_Group_DailyFeePaymentResult groupResult = PayRequest_GroupPaymentByDateRange(dto.Status, checkedView.GroupIds, checkedView.HotelSubIds, dto.beginDt, dto.endDt);
  2634. stopwatch.Stop();
  2635. return Ok(JsonView(true, $"查询成功!耗时{stopwatch.ElapsedMilliseconds / 1000}s", new { daily = dailyResult, group = groupResult }));
  2636. }
  2637. catch (Exception ex)
  2638. {
  2639. return Ok(JsonView(false, ex.Message));
  2640. }
  2641. }
  2642. /// <summary>
  2643. /// 根据团组类型类型处理团组费用所属公司
  2644. /// </summary>
  2645. /// <param name="teamId"></param>
  2646. /// <returns></returns>
  2647. private CompanyInfo ExpenseCompanyByTeamId(int teamId)
  2648. {
  2649. var _companyInfo = new CompanyInfo()
  2650. {
  2651. Id = 2,
  2652. ConpanyName = "四川泛美交流有限公司"
  2653. };
  2654. var _SiChuan = new List<int>() {
  2655. 38, // 政府团
  2656. 39, // 企业团
  2657. 40, // 散客团
  2658. 102, // 未知
  2659. 248, // 非团组
  2660. 691, // 四川-会务活动
  2661. 762, // 四川-赛事项目收入
  2662. 1048,//高校团
  2663. };
  2664. var _ChengDu = new List<int>() {
  2665. 302, // 成都-会务活动
  2666. 1047, // 成都-赛事项目收入
  2667. };
  2668. if (_SiChuan.Contains(teamId))
  2669. {
  2670. _companyInfo.Id = 2;
  2671. _companyInfo.ConpanyName = "四川泛美交流有限公司";
  2672. }
  2673. if (_ChengDu.Contains(teamId))
  2674. {
  2675. _companyInfo.Id = 1;
  2676. _companyInfo.ConpanyName = "成都泛美商务有限公司";
  2677. }
  2678. return _companyInfo;
  2679. }
  2680. /// <summary>
  2681. /// 付款申请(团组费用申请相关)
  2682. /// 查询 根据日期范围
  2683. /// </summary>
  2684. /// <param name="status"></param>
  2685. /// <param name="_groupIds"></param>
  2686. /// <param name="_hotelSubIds"></param>
  2687. /// <param name="beginDt"></param>
  2688. /// <param name="endDt"></param>
  2689. /// <returns></returns>
  2690. private tree_Group_DailyFeePaymentResult PayRequest_GroupPaymentByDateRange(int status, List<int> _groupIds, List<int> _hotelSubIds, string beginDt, string endDt)
  2691. {
  2692. var _DailyFeePaymentResult = new tree_Group_DailyFeePaymentResult();
  2693. var dataList = new List<tree_Group_DailyFeePaymentPageListView>();
  2694. #region sql条件处理
  2695. string sqlWhere = string.Format(@" And (AuditGMDate Between '{0} 00:00:00' And '{1} 23:59:59') ", beginDt, endDt);
  2696. if (status == 2)
  2697. {
  2698. if (_hotelSubIds.Count > 1)
  2699. {
  2700. var hrIds = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => _hotelSubIds.Contains(it.Id) && it.Price != 0).Select(it => it.HrId).Distinct().ToList();
  2701. var hrIds1 = _sqlSugar.Queryable<Grp_CreditCardPayment>().Where(it => it.CTable == 76 && hrIds.Contains(it.CId)).Select(it => it.Id).ToList();
  2702. if (hrIds1.Count > 1)
  2703. {
  2704. _groupIds.AddRange(hrIds1);
  2705. }
  2706. }
  2707. if (_groupIds.Count < 1)
  2708. {
  2709. _DailyFeePaymentResult.dataList = new List<tree_Group_DailyFeePaymentPageListView>();
  2710. return _DailyFeePaymentResult;
  2711. }
  2712. sqlWhere += string.Format(@" And Id In ({0})", string.Join(",", _groupIds));
  2713. }
  2714. string sql_1 = string.Format(@"Select * From Grp_CreditCardPayment Where IsDel = 0 And IsPay = 0 And (IsAuditGM = 1 Or IsAuditGM = 3 ){0}", sqlWhere);
  2715. #endregion
  2716. var _paymentDatas = _sqlSugar.SqlQueryable<Grp_CreditCardPayment>(sql_1).ToList();//付款信息
  2717. _DailyFeePaymentResult.gz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 0).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); //公转
  2718. _DailyFeePaymentResult.sz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 1).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); ; //私转
  2719. List<int> groupIds = _paymentDatas.Select(it => it.DIId).Distinct().ToList();
  2720. var _groupDatas = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0 && groupIds.Contains(it.Id)).ToList();
  2721. //_groupDatas = (List<Grp_DelegationInfo>)_groupDatas.GroupBy(it => it.TeamDid);
  2722. #region 相关基础数据源
  2723. var userDatas = _sqlSugar.Queryable<Sys_Users>().ToList();
  2724. var setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  2725. var countryFeeDatas = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(it => it.IsDel == 0).ToList();
  2726. var hotelDatas = _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  2727. var hotelContentDatas = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => it.IsDel == 0 && it.IsPay == 0 && it.Price != 0 && groupIds.Contains(it.DiId)).ToList();
  2728. var opDatas = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  2729. var visaDatas = _sqlSugar.Queryable<Grp_VisaInfo>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DIId)).ToList();
  2730. var ioaDatas = _sqlSugar.Queryable<Grp_InvitationOfficialActivities>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  2731. var insureDatas = _sqlSugar.Queryable<Grp_Customers>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  2732. var airDatas = _sqlSugar.Queryable<Grp_AirTicketReservations>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DIId)).ToList();
  2733. //var otherMoneyDatas = _sqlSugar.Queryable<Fin_OtherPrice>().Where(it => it.IsDel == 0 && groupIds.Contains(it.Diid)).ToList();
  2734. var otherMoneyDatas = _sqlSugar.Queryable<Grp_DecreasePayments>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  2735. var refundPaymentDatas = _sqlSugar.Queryable<Fin_PaymentRefundAndOtherMoney>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  2736. var ExtraCostDatas = _sqlSugar.Queryable<Fin_GroupExtraCost>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  2737. #endregion
  2738. //Expense company
  2739. foreach (var groupInfo in _groupDatas)
  2740. {
  2741. var childList = new List<Group_DailyFeePaymentContentInfolView>();
  2742. var groupPaymentDatas = _paymentDatas.Where(it => groupInfo.Id == it.DIId).ToList();
  2743. int rouNumber = 1;
  2744. foreach (var payInfo in groupPaymentDatas)
  2745. {
  2746. string priName = "-";
  2747. string orbitalPrivateTransfer = payInfo.OrbitalPrivateTransfer == 0 ? "公转" : payInfo.OrbitalPrivateTransfer == 1 ? "私转" : "-";
  2748. switch (payInfo.CTable)
  2749. {
  2750. case 76: //76 酒店预订
  2751. priName = $"[费用名称:{hotelDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.HotelName ?? ""}]";
  2752. break;
  2753. case 79: //79 车/导游地接
  2754. var opData = opDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id);
  2755. if (opData != null)
  2756. {
  2757. string area = "";
  2758. bool b = int.TryParse(opData.Area, out int areaId);
  2759. if (b)
  2760. {
  2761. string area1 = countryFeeDatas.Find(it => it.Id == areaId)?.Country ?? "-";
  2762. area = $"{area1}({setDatas.Find(it => it.Id == opData.PriceType)?.Name ?? "-"})";
  2763. }
  2764. else area = opData.Area;
  2765. string opPriName = "-";
  2766. if (!string.IsNullOrEmpty(opData.PriceName)) opPriName = opData.PriceName;
  2767. area += $"({opPriName})";
  2768. if (payInfo.OrbitalPrivateTransfer == 0) //公转
  2769. {
  2770. priName = $"【{orbitalPrivateTransfer}】【导游: {opData.ServiceGuide} 】[费用名称:{area}]";
  2771. }
  2772. else if (payInfo.OrbitalPrivateTransfer == 1) //私转
  2773. {
  2774. priName = $"【{orbitalPrivateTransfer}】【导游:{opData.ServiceGuide}】[费用名称:{area}]";
  2775. }
  2776. }
  2777. break;
  2778. case 80: // 80 签证
  2779. string sql = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", groupInfo.Id);
  2780. var arr = _sqlSugar.SqlQueryable<SimplClientInfo>(sql).ToList();
  2781. string visaClientName = visaDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.VisaClient ?? "";
  2782. string clientName = "-";
  2783. if (Regex.Match(visaClientName, @"\d+,?").Value.Length > 0)
  2784. {
  2785. string[] temparr = visaClientName.Split(',');
  2786. string fistrStr = temparr[0];
  2787. int count = temparr.Length;
  2788. int tempId;
  2789. bool success = int.TryParse(fistrStr, out tempId);
  2790. if (success)
  2791. {
  2792. SimplClientInfo tempInfo = arr.FirstOrDefault(s => s.Id == tempId);
  2793. if (tempInfo != null)
  2794. {
  2795. EncryptionProcessor.DecryptProperties(tempInfo);
  2796. if (count > 1)
  2797. {
  2798. clientName = string.Format(@"{0}{1}等{2}人", tempInfo.LastName, tempInfo.FirstName, count);
  2799. }
  2800. else
  2801. {
  2802. clientName = string.Format(@"{0}{1}", tempInfo.LastName, tempInfo.FirstName);
  2803. }
  2804. }
  2805. }
  2806. else
  2807. {
  2808. clientName = fistrStr;
  2809. }
  2810. }
  2811. priName = $"[费用名称:{clientName}]";
  2812. break;
  2813. case 81: // 81 邀请/公务活动
  2814. priName = $"[费用名称:{ioaDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.Inviter ?? " -"}]";
  2815. break;
  2816. case 82: // 82 团组客户保险
  2817. string bx_sql = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", groupInfo.Id);
  2818. var bx_arr = _sqlSugar.SqlQueryable<SimplClientInfo>(bx_sql).ToList();
  2819. foreach (var bx in bx_arr) EncryptionProcessor.DecryptProperties(bx);
  2820. string bx_ClientName = insureDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.ClientName ?? "";
  2821. string bx_clientName = "-";
  2822. if (Regex.Match(bx_ClientName, @"\d+,?").Value.Length > 0)
  2823. {
  2824. string[] temparr = bx_ClientName.Split(',');
  2825. string fistrStr = temparr[0];
  2826. int count = temparr.Length;
  2827. int tempId;
  2828. bool success = int.TryParse(fistrStr, out tempId);
  2829. if (success)
  2830. {
  2831. SimplClientInfo tempInfo = bx_arr.FirstOrDefault(s => s.Id == tempId);
  2832. if (tempInfo != null)
  2833. {
  2834. if (count > 1)
  2835. {
  2836. bx_clientName = string.Format(@"{0}{1}等{2}人", tempInfo.LastName, tempInfo.FirstName, count);
  2837. }
  2838. else
  2839. {
  2840. bx_clientName = string.Format(@"{0}{1}", tempInfo.LastName, tempInfo.FirstName);
  2841. }
  2842. }
  2843. }
  2844. else
  2845. {
  2846. bx_clientName = fistrStr;
  2847. }
  2848. }
  2849. //priName = $"[费用名称:{insureDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.ClientName ?? " -"}]";
  2850. priName = $"[费用名称:{bx_clientName}]";
  2851. break;
  2852. case 85: // 85 机票预订
  2853. string flightsCode = airDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.FlightsCode ?? "-";
  2854. string airPayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "-";
  2855. priName = $"{flightsCode}【{airPayType}】";
  2856. break;
  2857. case 98: // 98 其他款项
  2858. priName = $"[费用名称:{otherMoneyDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  2859. break;
  2860. case 285: // 285 收款退还
  2861. priName = $"[费用名称:{refundPaymentDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  2862. break;
  2863. case 1015: // 1015 超支费用
  2864. priName = $"[费用名称:{ExtraCostDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  2865. break;
  2866. default:
  2867. priName = "";
  2868. break;
  2869. }
  2870. bool status1 = false;
  2871. if (_groupIds != null)
  2872. {
  2873. status1 = _groupIds.Contains(payInfo.Id);
  2874. }
  2875. if (payInfo.CTable == 76) //酒店单独处理
  2876. {
  2877. var hotelContents = hotelContentDatas.Where(it => it.HrId == payInfo.CId);
  2878. var childInfos = new List<Group_DailyFeePaymentContentInfolView>();
  2879. foreach (var hotelContent in hotelContents)
  2880. {
  2881. string subPriceName = "";
  2882. if (hotelContent.PriceType == 1) subPriceName = "房费";
  2883. else if (hotelContent.PriceType == 2) subPriceName = "早餐";
  2884. else if (hotelContent.PriceType == 3) subPriceName = "地税";
  2885. else if (hotelContent.PriceType == 4) subPriceName = "城市税";
  2886. if (string.IsNullOrEmpty(subPriceName)) subPriceName = priName;
  2887. else subPriceName = $"{priName.Replace("]", "")}-{subPriceName}]";
  2888. string payeeStr1 = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
  2889. string.IsNullOrEmpty(hotelContent.Payee) ? "-" : hotelContent.Payee,
  2890. string.IsNullOrEmpty(hotelContent.OtherBankName) ? "-" : hotelContent.OtherBankName,
  2891. string.IsNullOrEmpty(hotelContent.OtherSideNo) ? "-" : hotelContent.OtherSideNo);
  2892. decimal _PaymentAmount1 = hotelContent.Price;//此次付款金额
  2893. decimal _CNYSubTotalAmount1 = _PaymentAmount1 * hotelContent.Rate;//此次付款金额
  2894. _CNYSubTotalAmount1 = Convert.ToDecimal(_CNYSubTotalAmount1.ToString("#0.00"));
  2895. //酒店子项Id选中状态更改
  2896. if (_hotelSubIds != null) status1 = _hotelSubIds.Contains(hotelContent.Id);
  2897. var childInfo1 = new Group_DailyFeePaymentContentInfolView()
  2898. {
  2899. IsChecked = status1,
  2900. Id = payInfo.Id,
  2901. HotelSubId = hotelContent.Id,
  2902. Payee = payeeStr1,
  2903. RowNumber = rouNumber,
  2904. Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
  2905. ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  2906. PayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "",
  2907. TransferMark = orbitalPrivateTransfer,
  2908. PriceName = subPriceName,
  2909. ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
  2910. PayCurrCode = setDatas.Find(it => it.Id == hotelContent.Currency)?.Name ?? "",
  2911. PaymentAmount = _PaymentAmount1,
  2912. PayRate = hotelContent.Rate,
  2913. CNYSubTotalAmount = _CNYSubTotalAmount1,
  2914. AuditStatus = payInfo.IsAuditGM
  2915. };
  2916. string remaksDescription1 = $"【{childInfo1.PayType}】【{childInfo1.ModuleName}】{rouNumber}、[申请人:{childInfo1.Applicant}]{subPriceName}[收款方:{childInfo1.Payee}] {childInfo1.PayCurrCode} {_PaymentAmount1:#0.00}、CNY:{childInfo1.CNYSubTotalAmount:#0.00}(团组:{groupInfo.TeamName})";
  2917. childInfo1.RemaksDescription = remaksDescription1;
  2918. if (status == 2)
  2919. {
  2920. if (status1)
  2921. {
  2922. childInfos.Add(childInfo1);
  2923. }
  2924. }
  2925. else childInfos.Add(childInfo1);
  2926. rouNumber++;
  2927. }
  2928. childList.AddRange(childInfos);
  2929. }
  2930. else
  2931. {
  2932. string payeeStr = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
  2933. string.IsNullOrEmpty(payInfo.Payee) ? "-" : payInfo.Payee,
  2934. string.IsNullOrEmpty(payInfo.OtherBankName) ? "-" : payInfo.OtherBankName,
  2935. string.IsNullOrEmpty(payInfo.OtherSideNo) ? "-" : payInfo.OtherSideNo);
  2936. decimal _PaymentAmount = (payInfo.PayMoney / 100) * payInfo.PayPercentage;//此次付款金额
  2937. decimal _CNYSubTotalAmount = _PaymentAmount * payInfo.DayRate;//此次付款金额
  2938. _CNYSubTotalAmount = Convert.ToDecimal(_CNYSubTotalAmount.ToString("#0.00"));
  2939. var childInfo = new Group_DailyFeePaymentContentInfolView()
  2940. {
  2941. IsChecked = status1,
  2942. Id = payInfo.Id,
  2943. Payee = payeeStr,
  2944. RowNumber = rouNumber,
  2945. Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
  2946. ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  2947. PayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "",
  2948. TransferMark = orbitalPrivateTransfer,
  2949. PriceName = priName,
  2950. ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
  2951. PayCurrCode = setDatas.Find(it => it.Id == payInfo.PaymentCurrency)?.Name ?? "",
  2952. PaymentAmount = _PaymentAmount,
  2953. PayRate = payInfo.DayRate,
  2954. CNYSubTotalAmount = _CNYSubTotalAmount,
  2955. AuditStatus = payInfo.IsAuditGM
  2956. };
  2957. string remaksDescription = $"【{childInfo.PayType}】【{childInfo.ModuleName}】{rouNumber}、[申请人:{childInfo.Applicant}]{priName}[收款方:{childInfo.Payee}] {childInfo.PayCurrCode} {_PaymentAmount:#0.00}、CNY:{childInfo.CNYSubTotalAmount:#0.00}(团组:{groupInfo.TeamName})";
  2958. childInfo.RemaksDescription = remaksDescription;
  2959. childList.Add(childInfo);
  2960. rouNumber++;
  2961. }
  2962. }
  2963. var companyInfo = ExpenseCompanyByTeamId(groupInfo.TeamDid);
  2964. dataList.Add(new tree_Group_DailyFeePaymentPageListView()
  2965. {
  2966. Id = Guid.NewGuid().ToString("N"),
  2967. GroupName = groupInfo.TeamName,
  2968. CompanyId = companyInfo.Id,
  2969. ConpanyName = companyInfo.ConpanyName,
  2970. CNYTotalAmount = childList.Sum(it => it.CNYSubTotalAmount),
  2971. ChildList = childList,
  2972. });
  2973. }
  2974. _DailyFeePaymentResult.dataList = dataList;
  2975. return _DailyFeePaymentResult;
  2976. }
  2977. /// <summary>
  2978. /// 付款申请(日付申请相关)
  2979. /// 查询 根据日期范围
  2980. /// </summary>
  2981. /// <param name="status"></param>
  2982. /// <param name="_dailyIds"></param>
  2983. /// <param name="beginDt"></param>
  2984. /// <param name="endDt"></param>
  2985. /// <returns></returns>
  2986. private tree_Fin_DailyFeePaymentResult PayRequest_DailyByDateRange(int status, List<int> _dailyIds, string beginDt, string endDt)
  2987. {
  2988. #region sql条件处理
  2989. string sqlWhere = string.Format(@" And dfp.CreateTime between '{0} 00:00:00' And '{1} 23:59:59' ", beginDt, endDt);
  2990. if (status == 2)
  2991. {
  2992. if (_dailyIds.Count < 1)
  2993. {
  2994. return new tree_Fin_DailyFeePaymentResult() { childList = new List<Fin_DailyFeePaymentContentInfolView>() };
  2995. }
  2996. sqlWhere += string.Format(@" And dfp.Id In({0}) ", string.Join(",", _dailyIds));
  2997. }
  2998. string sql_1 = string.Format(@"Select * From (
  2999. Select row_number() over (order by dfp.Id Desc) as RowNumber,
  3000. dfp.Id,dfp.CompanyId,c.CompanyName,dfp.Instructions,dfp.SumPrice,
  3001. dfp.CreateUserId,u.CnName CreateUser,dfp.CreateTime,dfp.FAudit,dfp.MAudit,
  3002. dfp.PriceTypeId,dfp.TransferTypeId
  3003. From Fin_DailyFeePayment dfp
  3004. Inner Join Sys_Company c On dfp.CompanyId = c.Id
  3005. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  3006. Where dfp.IsDel=0 {0}
  3007. AND (dfp.FAudit = 1 OR dfp.FAudit = 3)
  3008. AND (dfp.MAudit = 1 OR dfp.MAudit = 3)
  3009. AND dfp.IsPay = 0
  3010. ) temp ", sqlWhere);
  3011. #endregion
  3012. List<tree_Fin_DailyFeePaymentPageListView> DailyFeePaymentData = _sqlSugar.SqlQueryable<tree_Fin_DailyFeePaymentPageListView>(sql_1).ToList();
  3013. var dic_setData = new Dictionary<int, string>();
  3014. Sys_SetDataType stGZ = _daiRep.Query<Sys_SetDataType>(s => s.Name == "公转").First();
  3015. Sys_SetDataType stSZ = _daiRep.Query<Sys_SetDataType>(s => s.Name == "私转").First();
  3016. foreach (var item in DailyFeePaymentData)
  3017. {
  3018. if (_dailyIds != null)
  3019. {
  3020. item.IsChecked = _dailyIds.Contains(item.Id);
  3021. }
  3022. if (dic_setData.ContainsKey(item.PriceTypeId))
  3023. {
  3024. item.priceTypeStr = dic_setData[item.PriceTypeId];
  3025. }
  3026. else
  3027. {
  3028. Sys_SetData sd_priceType = _daiRep.Query<Sys_SetData>(s => s.Id == item.PriceTypeId).First();
  3029. if (sd_priceType != null)
  3030. {
  3031. item.priceTypeStr = sd_priceType.Name;
  3032. dic_setData.Add(item.PriceTypeId, sd_priceType.Name);
  3033. }
  3034. }
  3035. if (dic_setData.ContainsKey(item.transferTypeId))
  3036. {
  3037. item.transferTypeIdStr = dic_setData[item.transferTypeId];
  3038. Sys_SetData sd_transfer = _daiRep.Query<Sys_SetData>(s => s.Id == item.transferTypeId).First();
  3039. if (sd_transfer != null)
  3040. {
  3041. item.transferParentId = sd_transfer.STid;
  3042. item.transferParentIdStr = sd_transfer.STid == stGZ.Id ? "公转" : sd_transfer.STid == stSZ.Id ? "私转" : "";
  3043. }
  3044. }
  3045. else
  3046. {
  3047. Sys_SetData sd_transfer = _daiRep.Query<Sys_SetData>(s => s.Id == item.transferTypeId).First();
  3048. if (sd_transfer != null)
  3049. {
  3050. item.transferTypeIdStr = sd_transfer.Name;
  3051. item.transferParentId = sd_transfer.STid;
  3052. item.transferParentIdStr = sd_transfer.STid == stGZ.Id ? "公转" : sd_transfer.STid == stSZ.Id ? "私转" : "";
  3053. dic_setData.Add(item.transferTypeId, sd_transfer.Name);
  3054. }
  3055. }
  3056. string feeContentSql = string.Format(@"Select * From Fin_DailyFeePaymentContent
  3057. Where IsDel=0 And DFPId = {0} ", item.Id);
  3058. item.childList = _sqlSugar.SqlQueryable<Fin_DailyFeePaymentContentInfolView>(feeContentSql).ToList();
  3059. int rowNumber = 1;
  3060. foreach (var subItem in item.childList)
  3061. {
  3062. string remaksDescription = $"{rowNumber}、【{item.priceTypeStr}】{item.Instructions}({subItem.PriceName}) CNY:{subItem.ItemTotal.ToString("#0.0000")}(单价:{subItem.Price.ToString("#0.0000")} * {subItem.Quantity.ToString("#0.0000")})";
  3063. subItem.RemaksDescription = remaksDescription;
  3064. string excelRemaksDescription = $"【{item.priceTypeStr}】{item.Instructions}({subItem.PriceName}) CNY:{subItem.ItemTotal.ToString("#0.0000")}(单价:{subItem.Price.ToString("#0.0000")} * {subItem.Quantity.ToString("#0.0000")})【申请人:{item.CreateUser} 申请时间:{item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")}】";
  3065. subItem.ExcelRemaksDescription = excelRemaksDescription;
  3066. rowNumber++;
  3067. }
  3068. }
  3069. decimal total_gz = DailyFeePaymentData.Where(s => s.transferParentId == stGZ.Id).Sum(d => d.SumPrice ?? 0M);
  3070. decimal total_sz = DailyFeePaymentData.Where(s => s.transferParentId == stSZ.Id).Sum(d => d.SumPrice ?? 0M);
  3071. var result = new tree_Fin_DailyFeePaymentResult() { gz = total_gz, sz = total_sz, dataList = DailyFeePaymentData };
  3072. return result;
  3073. }
  3074. /// <summary>
  3075. /// 付款申请 (PageId=51)
  3076. /// 团组,日付相关费用 选中状态变更
  3077. /// </summary>
  3078. /// <param name="dto"></param>
  3079. /// <returns></returns>
  3080. [HttpPost]
  3081. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3082. public async Task<IActionResult> PostPayRequestCheckedChange(PayRequestCheckedChangeDto dto)
  3083. {
  3084. #region 验证
  3085. if (dto.Type < 1 || dto.Type > 2)
  3086. {
  3087. return Ok(JsonView(false, "请传入有效的Type参数! 1 checked 2 清除上次勾选"));
  3088. }
  3089. #endregion
  3090. var requestCheckedView = new PaymentRequestCheckedView();
  3091. var groupIds = new List<int>();
  3092. var dailyPaymentIds = new List<int>();
  3093. var hotelIds = new List<int>();
  3094. #region 参数处理
  3095. if (!string.IsNullOrEmpty(dto.GroupIds))
  3096. {
  3097. if (dto.GroupIds.Contains(","))
  3098. {
  3099. groupIds = dto.GroupIds.Split(',').Select(int.Parse).ToList();
  3100. }
  3101. else
  3102. {
  3103. groupIds.Add(int.Parse(dto.GroupIds));
  3104. }
  3105. }
  3106. if (!string.IsNullOrEmpty(dto.HotelSubIds))
  3107. {
  3108. if (dto.HotelSubIds.Contains(","))
  3109. {
  3110. hotelIds = dto.HotelSubIds.Split(',').Select(int.Parse).ToList();
  3111. }
  3112. else
  3113. {
  3114. hotelIds.Add(int.Parse(dto.HotelSubIds));
  3115. }
  3116. }
  3117. if (!string.IsNullOrEmpty(dto.DailyPaymentIds))
  3118. {
  3119. if (dto.DailyPaymentIds.Contains(","))
  3120. {
  3121. dailyPaymentIds = dto.DailyPaymentIds.Split(',').Select(int.Parse).ToList();
  3122. }
  3123. else
  3124. {
  3125. dailyPaymentIds.Add(int.Parse(dto.DailyPaymentIds));
  3126. }
  3127. }
  3128. #endregion
  3129. requestCheckedView.GroupIds = groupIds;
  3130. requestCheckedView.HotelSubIds = hotelIds;
  3131. requestCheckedView.DailyPaymentIds = dailyPaymentIds;
  3132. if (dto.Type == 1)
  3133. {
  3134. TimeSpan ts = DateTime.Now.AddDays(180) - DateTime.Now; //设置redis 过期时间 半年(180)
  3135. var status = await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync<string>("paymentRequestCheckedData", JsonConvert.SerializeObject(requestCheckedView), ts);
  3136. if (status)
  3137. {
  3138. return Ok(JsonView(true, "操作成功!"));
  3139. }
  3140. }
  3141. else if (dto.Type == 2)
  3142. {
  3143. var status = await RedisRepository.RedisFactory.CreateRedisRepository().KeyDeleteAsync("paymentRequestCheckedData");
  3144. if (status)
  3145. {
  3146. return Ok(JsonView(true, "操作成功!"));
  3147. }
  3148. }
  3149. return Ok(JsonView(false, "操作失败!"));
  3150. }
  3151. /// <summary>
  3152. /// 付款申请 (PageId=51)
  3153. /// 团组,日付相关费用 汇率变更
  3154. /// </summary>
  3155. /// <param name="dto"></param>
  3156. /// <returns></returns>
  3157. [HttpPost]
  3158. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3159. public async Task<IActionResult> PostPayRequestRateChange(PayRequestRateChangeDto dto)
  3160. {
  3161. #region 验证
  3162. DateTime beginDt, endDt;
  3163. string format = "yyyy-MM-dd";
  3164. if (!DateTime.TryParseExact(dto.beginDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out beginDt))
  3165. {
  3166. return Ok(JsonView(false, "开始日期格式不正确!正确格式:yyyy-MM-dd"));
  3167. }
  3168. if (!DateTime.TryParseExact(dto.endDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt))
  3169. {
  3170. return Ok(JsonView(false, "结束日期格式不正确!正确格式:yyyy-MM-dd"));
  3171. }
  3172. if (dto.UserId < 1) return Ok(JsonView(false, "请传入有效的UserId参数!"));
  3173. if (dto.Id < 1) return Ok(JsonView(false, "请传入有效的Id参数!"));
  3174. if (dto.Rate <= 0) return Ok(JsonView(false, "请传入有效的Rate参数!"));
  3175. #endregion
  3176. int hotelSubStatus = 0, status = 0;
  3177. int diid = 0, cTable = 0, currId = 0;
  3178. if (dto.HotelSubId > 0)
  3179. {
  3180. //更改酒店子表汇率
  3181. hotelSubStatus = _sqlSugar.Updateable<Grp_HotelReservationsContent>()
  3182. .SetColumns(it => it.Rate == dto.Rate)
  3183. .Where(it => it.Id == dto.HotelSubId)
  3184. .ExecuteCommand();
  3185. if (hotelSubStatus > 0)
  3186. {
  3187. var hotelSubInfo = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => it.Id == dto.HotelSubId).First();
  3188. if (hotelSubInfo != null)
  3189. {
  3190. diid = hotelSubInfo.DiId;
  3191. currId = hotelSubInfo.Currency;
  3192. }
  3193. //付款申请汇率更改成功;更改团组汇率对应币种
  3194. string currCode = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == currId).First()?.Name ?? "";
  3195. await _teamRateRep.UpdateGroupRateByDiIdAndCTableId(diid, 76, currCode, dto.Rate);
  3196. }
  3197. }
  3198. if (dto.Id > 0)
  3199. {
  3200. var ccpInfo = _sqlSugar.Queryable<Grp_CreditCardPayment>().Where(it => it.Id == dto.Id).First();
  3201. decimal cnyMoney = 0.00M;
  3202. if (ccpInfo != null)
  3203. {
  3204. cnyMoney = ccpInfo.PayMoney * dto.Rate;
  3205. diid = ccpInfo.DIId;
  3206. cTable = ccpInfo.CTable;
  3207. currId = ccpInfo.PaymentCurrency;
  3208. }
  3209. status = _sqlSugar.Updateable<Grp_CreditCardPayment>()
  3210. .SetColumns(it => it.DayRate == dto.Rate)
  3211. .SetColumns(it => it.RMBPrice == cnyMoney)
  3212. .Where(it => it.Id == dto.Id)
  3213. .ExecuteCommand();
  3214. if (status > 0)
  3215. {
  3216. //付款申请汇率更改成功;更改团组汇率对应币种
  3217. if (cTable != 76)
  3218. {
  3219. string currCode = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == currId).First()?.Name ?? "";
  3220. await _teamRateRep.UpdateGroupRateByDiIdAndCTableId(diid, cTable, currCode, dto.Rate);
  3221. }
  3222. }
  3223. }
  3224. if (hotelSubStatus > 0 || status > 0)
  3225. {
  3226. PaymentRequestCheckedView checkedView = new PaymentRequestCheckedView();
  3227. var checkedStr = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>("paymentRequestCheckedData");
  3228. if (checkedStr != null)
  3229. {
  3230. checkedView = JsonConvert.DeserializeObject<PaymentRequestCheckedView>(checkedStr.ToString());
  3231. }
  3232. tree_Fin_DailyFeePaymentResult dailyResult = PayRequest_DailyByDateRange(1, checkedView.DailyPaymentIds, dto.beginDt, dto.endDt);
  3233. tree_Group_DailyFeePaymentResult groupResult = PayRequest_GroupPaymentByDateRange(1, checkedView.GroupIds, checkedView.HotelSubIds, dto.beginDt, dto.endDt);
  3234. decimal _gz = dailyResult.gz + groupResult.gz;
  3235. decimal _sz = dailyResult.sz + groupResult.sz;
  3236. return Ok(JsonView(true, "操作成功!", new { gz = dailyResult, sz = groupResult }));
  3237. }
  3238. return Ok(JsonView(false, "该项汇率修改失败!"));
  3239. }
  3240. /// <summary>
  3241. /// 付款申请 (PageId=51)
  3242. /// 团组,日付相关费用 付款状态变更
  3243. /// </summary>
  3244. /// <param name="dto"></param>
  3245. /// <returns></returns>
  3246. [HttpPost]
  3247. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3248. public async Task<IActionResult> PostPayRequestPayChange(PayRequestPayChangeDto dto)
  3249. {
  3250. if (dto.UserId < 1) return Ok(JsonView(false, "请传入有效的UserId参数!"));
  3251. //if (string.IsNullOrEmpty(dto.GroupIds))
  3252. //{
  3253. // return Ok(JsonView(false, "请传入有效的GroupIds参数!"));
  3254. //}
  3255. //if (string.IsNullOrEmpty(dto.DailyPaymentIds))
  3256. //{
  3257. // return Ok(JsonView(false, "请传入有效的DailyPaymentIds参数!"));
  3258. //}
  3259. List<int> groupIds = new List<int>();
  3260. List<int> dailyPaymentIds = new List<int>();
  3261. List<int> hotelSubIds = new List<int>();
  3262. #region 参数处理
  3263. if (!string.IsNullOrEmpty(dto.GroupIds))
  3264. {
  3265. if (dto.GroupIds.Contains(",")) groupIds = dto.GroupIds.Split(',').Select(int.Parse).ToList();
  3266. else groupIds.Add(int.Parse(dto.GroupIds));
  3267. }
  3268. if (!string.IsNullOrEmpty(dto.HotelSubIds))
  3269. {
  3270. if (dto.HotelSubIds.Contains(",")) hotelSubIds = dto.HotelSubIds.Split(',').Select(int.Parse).ToList();
  3271. else hotelSubIds.Add(int.Parse(dto.HotelSubIds));
  3272. if (hotelSubIds.Count > 0)
  3273. {
  3274. foreach (var item in hotelSubIds)
  3275. {
  3276. if (item < 1)
  3277. {
  3278. hotelSubIds.Remove(item);
  3279. }
  3280. }
  3281. }
  3282. }
  3283. if (!string.IsNullOrEmpty(dto.DailyPaymentIds))
  3284. {
  3285. if (dto.DailyPaymentIds.Contains(",")) dailyPaymentIds = dto.DailyPaymentIds.Split(',').Select(int.Parse).ToList();
  3286. else dailyPaymentIds.Add(int.Parse(dto.DailyPaymentIds));
  3287. }
  3288. #endregion
  3289. bool changeStatus = false;
  3290. _sqlSugar.BeginTran();
  3291. if (groupIds.Count > 0)
  3292. {
  3293. var ccpInfos = _sqlSugar.Queryable<Grp_CreditCardPayment>().Where(it => it.IsDel == 0 && groupIds.Contains(it.Id)).ToList();
  3294. var otherTypeCcpIds = ccpInfos.Where(it => it.CTable != 76).Select(it => it.Id).ToList();
  3295. var hotelTyprCcpIds = ccpInfos.Where(it => it.CTable == 76).Select(it => it.Id).ToList();
  3296. int groupStatus = 0;
  3297. if (otherTypeCcpIds.Count > 0) //其他费用类型 正常付款
  3298. {
  3299. groupStatus = _sqlSugar.Updateable<Grp_CreditCardPayment>()
  3300. .SetColumns(it => it.IsPay == 1)
  3301. .Where(it => otherTypeCcpIds.Contains(it.Id))
  3302. .ExecuteCommand();
  3303. changeStatus = true;
  3304. }
  3305. if (hotelTyprCcpIds.Count > 0) //酒店费用子项逻辑付款,酒店子项费用全部付完款,c表ispay=1
  3306. {
  3307. if (hotelSubIds.Count > 0)
  3308. {
  3309. List<int> hrPayIds = new List<int>();
  3310. var hrIspayStatus = _sqlSugar.Updateable<Grp_HotelReservationsContent>()
  3311. .SetColumns(it => it.IsPay == 1)
  3312. .Where(it => hotelSubIds.Contains(it.Id))
  3313. .ExecuteCommand();
  3314. changeStatus = true;
  3315. //酒店子项是否全部付完款
  3316. List<int> hrIds = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => it.IsDel == 0 && hotelSubIds.Contains(it.Id)).Select(it => it.HrId).Distinct().ToList();
  3317. if (hrIds.Count > 0)
  3318. {
  3319. var hotelSubFeeData = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => it.IsDel == 0 && hrIds.Contains(it.HrId)).ToList();
  3320. var hotelSubFeeGroupData = hotelSubFeeData.GroupBy(it => it.HrId).ToList();
  3321. foreach (var item in hotelSubFeeGroupData)
  3322. {
  3323. var allTotal = item.Where(it => it.Price > 0).ToList().Count;
  3324. var paymentTotal = item.Where(it => it.Price > 0 && it.IsPay == 1).ToList().Count;
  3325. if (allTotal == paymentTotal)
  3326. {
  3327. hrPayIds.Add(item.Key);
  3328. }
  3329. }
  3330. }
  3331. if (hrPayIds.Count > 0)
  3332. {
  3333. //c表更改全部付款的酒店费用
  3334. groupStatus = _sqlSugar.Updateable<Grp_CreditCardPayment>()
  3335. .SetColumns(it => it.IsPay == 1)
  3336. .Where(it => it.CTable == 76 && hrPayIds.Contains(it.CId))
  3337. .ExecuteCommand();
  3338. }
  3339. }
  3340. }
  3341. }
  3342. //if (hotelSubIds.Count > 0)
  3343. //{
  3344. // var groupStatus = _sqlSugar.Updateable<Grp_HotelReservationsContent>()
  3345. // .SetColumns(it => it.IsPay == 1)
  3346. // .Where(it => hotelSubIds.Contains(it.Id))
  3347. // .ExecuteCommand();
  3348. // if (groupStatus > 0)
  3349. // {
  3350. // changeStatus = true;
  3351. // }
  3352. //}
  3353. if (dailyPaymentIds.Count > 0)
  3354. {
  3355. var dailyPaymentStatus = _sqlSugar.Updateable<Fin_DailyFeePayment>()
  3356. .SetColumns(it => it.IsPay == 1)
  3357. .Where(it => dailyPaymentIds.Contains(it.Id))
  3358. .ExecuteCommand();
  3359. //修改提成关联表
  3360. var ids = _sqlSugar.Queryable<Fin_DailyFeePayment>()
  3361. .LeftJoin<Fin_RoyaltyForm>((dfp, rf) => dfp.Id == rf.DayOverhead && rf.IsDel == 0)
  3362. .Where(dfp => dailyPaymentIds.Contains(dfp.Id) && dfp.IsDel == 0)
  3363. .Select((dfp, rf) => rf.ConfirmIdArr).ToList();
  3364. var idsList = string.Join(',', ids).Split(',')
  3365. .Select(x =>
  3366. {
  3367. if (!string.IsNullOrWhiteSpace(x) && int.TryParse(x, out int intx))
  3368. {
  3369. return intx;
  3370. }
  3371. return 0;
  3372. })
  3373. .Where(x => x != 0)
  3374. .Distinct()
  3375. .ToList();
  3376. _sqlSugar.Updateable<Fin_RoyaltyConfirm>()
  3377. .SetColumns(it => it.IsSeed == 1)
  3378. .Where(it => idsList.Contains(it.Id) && it.IsSeed == 0)
  3379. .ExecuteCommand();
  3380. if (dailyPaymentStatus > 0)
  3381. {
  3382. changeStatus = true;
  3383. }
  3384. }
  3385. if (changeStatus)
  3386. {
  3387. _sqlSugar.CommitTran();
  3388. //todo:日志记录
  3389. _logger.LogInformation("【付款申请】【状态:操作成功!】请求参数: OpUserId: {UserId}, GroupIds: {GroupIds}, DailyPaymentIds: {DailyPaymentIds}, HotelSubIds: {HotelSubIds}",
  3390. dto.UserId, string.Join(",", groupIds), string.Join(",", dailyPaymentIds), string.Join(",", hotelSubIds));
  3391. #region 应用推送
  3392. try
  3393. {
  3394. foreach (int ccpId in groupIds)
  3395. {
  3396. List<string> tempList = new List<string>() { ccpId.ToString() };
  3397. await AppNoticeLibrary.SendUserMsg_GroupStatus_PayResult(ccpId, tempList);
  3398. }
  3399. foreach (int dailyId in dailyPaymentIds)
  3400. {
  3401. List<string> tempList = new List<string>() { dailyId.ToString() };
  3402. await AppNoticeLibrary.DailyPayReminder_Pay_ToUser(dailyId, tempList);
  3403. }
  3404. }
  3405. catch (Exception ex)
  3406. {
  3407. }
  3408. #endregion
  3409. return Ok(JsonView(true, "操作成功!"));
  3410. }
  3411. _sqlSugar.RollbackTran();
  3412. //todo:日志记录
  3413. _logger.LogWarning("【付款申请】【状态:操作失败!】 请求参数:OpUserId: {UserId}, GroupIds: {GroupIds}, DailyPaymentIds: {DailyPaymentIds}, HotelSubIds: {HotelSubIds}",
  3414. dto.UserId, string.Join(",", groupIds), string.Join(",", dailyPaymentIds), string.Join(",", hotelSubIds));
  3415. return Ok(JsonView(false, "付款状态修改失败!"));
  3416. }
  3417. /// <summary>
  3418. /// 付款申请 (PageId=51)
  3419. /// File Download
  3420. /// </summary>
  3421. /// <param name="dto"></param>
  3422. /// <returns></returns>
  3423. [HttpPost]
  3424. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3425. public async Task<IActionResult> PostPayRequestFileDownload(PayRequestFileDownloadDto dto)
  3426. {
  3427. Stopwatch stopwatch = Stopwatch.StartNew();
  3428. #region 参数,权限 验证
  3429. if (dto.PortType < 1)
  3430. {
  3431. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  3432. }
  3433. if (dto.UserId < 1)
  3434. {
  3435. return Ok(JsonView(false, "请传入有效的UserId参数!"));
  3436. }
  3437. if (dto.PageId < 1)
  3438. {
  3439. dto.PageId = 51;
  3440. return Ok(JsonView(false, "请传入有效的PageId参数!"));
  3441. }
  3442. var conpanyDatas = _sqlSugar.Queryable<Sys_Company>()
  3443. .Where(it => it.IsDel == 0)
  3444. .Select(it => new
  3445. {
  3446. Id = it.Id,
  3447. ConpamyName = it.CompanyName
  3448. }).ToList();
  3449. var conpanyIds = conpanyDatas.Select(x => x.Id).ToList();
  3450. if (!conpanyIds.Contains(dto.ConpanyId))
  3451. {
  3452. return Ok(JsonView(false, "请传入有效的ConpanyId参数!"));
  3453. }
  3454. #region 页面操作权限验证
  3455. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  3456. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权限!"));
  3457. #endregion
  3458. #endregion
  3459. try
  3460. {
  3461. var checkedView = new PaymentRequestCheckedView();
  3462. var checkedStr = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>("paymentRequestCheckedData");
  3463. if (checkedStr != null)
  3464. {
  3465. checkedView = JsonConvert.DeserializeObject<PaymentRequestCheckedView>(checkedStr.ToString());
  3466. }
  3467. if (checkedView == null)
  3468. {
  3469. return Ok(JsonView(false, "没有选中的数据!"));
  3470. }
  3471. if (checkedView.GroupIds == null && checkedView.DailyPaymentIds == null)
  3472. {
  3473. return Ok(JsonView(false, "没有选中的数据!"));
  3474. }
  3475. tree_Fin_DailyFeePaymentResult dailyResult = PayRequest_DailyByDateRange(2, checkedView.DailyPaymentIds, dto.beginDt, dto.endDt);
  3476. tree_Group_DailyFeePaymentResult groupResult = PayRequest_GroupPaymentByDateRange(2, checkedView.GroupIds, checkedView.HotelSubIds, dto.beginDt, dto.endDt);
  3477. if (dailyResult.childList == null)
  3478. {
  3479. dailyResult.childList = new List<Fin_DailyFeePaymentContentInfolView>();
  3480. }
  3481. var _GroupData = new List<tree_Group_DailyFeePaymentPageListView>();
  3482. var _DailyData = new List<tree_Fin_DailyFeePaymentPageListView>();
  3483. if (groupResult.dataList != null && groupResult.dataList.Any()) _GroupData = groupResult.dataList.Where(it => it.CompanyId == dto.ConpanyId).ToList();
  3484. if (dailyResult.dataList != null && dailyResult.dataList.Any()) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == dto.ConpanyId).ToList();
  3485. ////1 成都泛美商务有限公司
  3486. //if (dto.ConpanyId == 1)
  3487. //{
  3488. // if (groupResult.dataList != null && groupResult.dataList.Count > 0) _GroupData = groupResult.dataList.Where(it => it.CompanyId == 1).ToList();
  3489. // if (dailyResult.dataList != null && dailyResult.dataList.Count > 0) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == 1).ToList();
  3490. //}
  3491. ////2 四川泛美交流有限公司
  3492. //else if (dto.ConpanyId == 2)
  3493. //{
  3494. // if (groupResult.dataList != null && groupResult.dataList.Count > 0) _GroupData = groupResult.dataList.Where(it => it.CompanyId == 2).ToList();
  3495. // if (dailyResult.dataList != null && dailyResult.dataList.Count > 0) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == 2).ToList();
  3496. //}
  3497. ////3 成都纽茵教育科技有限公司
  3498. //else if (dto.ConpanyId == 3)
  3499. //{
  3500. // if (groupResult.dataList != null && groupResult.dataList.Count > 0) _GroupData = groupResult.dataList.Where(it => it.CompanyId == 3).ToList();
  3501. // if (dailyResult.dataList != null && dailyResult.dataList.Count > 0) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == 3).ToList();
  3502. //}
  3503. ////4 成都鸿企中元科技有限公司
  3504. //else if (dto.ConpanyId == 4)
  3505. //{
  3506. // return Ok(JsonView(false, "暂未开放该类型!"));
  3507. //}
  3508. //else
  3509. //{
  3510. // return Ok(JsonView(false, "参数ConpanyId不可使用!"));
  3511. //}
  3512. string _requestPaymentDt = DateTime.Now.ToString("yyyy-MM-dd"),//申请付款日期
  3513. _appliedAmount = "", //申请付款金额
  3514. _GZStr = "", //公转价格描述
  3515. _SZStr = ""; //私转价格描述
  3516. decimal groupGZAmout = 0.00M, groupSZAmout = 0.00M;
  3517. decimal dailyGZAmout = 0.00M, dailySZAmout = 0.00M;
  3518. string dailyGZStr = "", dailySZStr = "", groupGZStr = "", groupSZStr = "";
  3519. #region 数据处理
  3520. //团组费用相关
  3521. foreach (var item in _GroupData)
  3522. {
  3523. string groupGZSubStr = "";
  3524. string groupSZSubStr = "";
  3525. foreach (var subItem in item.ChildList)
  3526. {
  3527. if (subItem.TransferMark.Equals("公转"))
  3528. {
  3529. groupGZAmout += subItem.CNYSubTotalAmount;
  3530. groupGZSubStr += $"{subItem.RemaksDescription}\r\n";
  3531. }
  3532. else if (subItem.TransferMark.Equals("私转"))
  3533. {
  3534. groupSZAmout += subItem.CNYSubTotalAmount;
  3535. groupSZSubStr += $"{subItem.RemaksDescription}\r\n";
  3536. }
  3537. //groupGZSubStr += $"\t";
  3538. }
  3539. //if (!string.IsNullOrEmpty(groupGZSubStr)) groupGZStr += $"团组:{item.GroupName}\r\n{groupGZSubStr}\r\n";
  3540. //if (!string.IsNullOrEmpty(groupSZSubStr)) groupSZStr += $"团组:{item.GroupName}\r\n{groupSZSubStr}\r\n";
  3541. if (!string.IsNullOrEmpty(groupGZSubStr)) groupGZStr += $"{groupGZSubStr}\r\n";
  3542. if (!string.IsNullOrEmpty(groupSZSubStr)) groupSZStr += $"{groupSZSubStr}\r\n";
  3543. }
  3544. //日常费用相关
  3545. foreach (var item in _DailyData)
  3546. {
  3547. foreach (var subItem in item.childList)
  3548. {
  3549. if (item.transferParentId == 62) //公转
  3550. {
  3551. dailyGZAmout += item.SumPrice ?? 0.00M;
  3552. dailyGZStr += $"{item.RowNumber}、【{item.CompanyName}】{subItem.ExcelRemaksDescription}\r\n";
  3553. }
  3554. else if (item.transferParentId == 63) //私转
  3555. {
  3556. dailySZAmout += item.SumPrice ?? 0.00M;
  3557. dailySZStr += $"{item.RowNumber}、【{item.CompanyName}】{subItem.ExcelRemaksDescription}\r\n";
  3558. }
  3559. }
  3560. }
  3561. _GZStr = $"【公转】团组相关费用(合计:CNY {groupGZAmout:#0.00}):\r\n{groupGZStr}【公转】日常付款费用(合计:CNY {dailyGZAmout:#0.00}):\r\n{dailyGZStr}";
  3562. _SZStr = $"【私转】团组相关费用(合计:CNY {groupSZAmout:#0.00}):\r\n{groupSZStr}【私转】日常付款费用(合计:CNY {dailySZAmout:#0.00}):\r\n{dailySZStr}";
  3563. _appliedAmount = $"公转:CNY {(groupGZAmout + dailyGZAmout).ToString("#0.00")}\r\n私转:CNY {(groupSZAmout + dailySZAmout).ToString("#0.00")}";
  3564. #endregion
  3565. var designer = new WorkbookDesigner
  3566. {
  3567. Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/付款申请书.xls")
  3568. };
  3569. designer.SetDataSource("Date", _requestPaymentDt);
  3570. designer.SetDataSource("Price", _appliedAmount);
  3571. designer.SetDataSource("Content", _GZStr);
  3572. designer.SetDataSource("Content1", _SZStr);
  3573. //根据数据源处理生成报表内容
  3574. designer.Process();
  3575. string fileName = ("PayRequest/付款申请(" + dto.beginDt + "~" + dto.endDt + ").xlsx");
  3576. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  3577. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  3578. stopwatch.Stop();
  3579. return Ok(JsonView(true, $"操作成功!{stopwatch.ElapsedMilliseconds / 1000}s", new { url = rst }));
  3580. }
  3581. catch (Exception ex)
  3582. {
  3583. return Ok(JsonView(false, ex.Message));
  3584. }
  3585. }
  3586. #endregion
  3587. #region 超支费用
  3588. /// <summary>
  3589. /// 超支费用
  3590. /// 1增、2改、3删
  3591. /// </summary>
  3592. /// <param name="dto"></param>
  3593. /// <returns></returns>
  3594. [HttpPost]
  3595. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3596. public async Task<IActionResult> PostGroupExtraCost_Operator(Fin_GroupExtraCostDto_OP dto)
  3597. {
  3598. #region 验证
  3599. #endregion
  3600. var _entity = new Fin_GroupExtraCost
  3601. {
  3602. DiId = dto.diId,
  3603. PriceName = dto.priceName,
  3604. Price = dto.price,
  3605. PriceCurrency = dto.currency,
  3606. PriceType = dto.priceType,
  3607. Coefficient = dto.coefficient,
  3608. PriceDetailType = dto.priceDetailType,
  3609. FilePath = dto.filePath,
  3610. Remark = dto.remark,
  3611. PriceCount = dto.PriceCount,
  3612. Area = dto.Area,
  3613. SupervisorConfirm = dto.SupervisorConfirm,
  3614. ManagerConfirm = dto.ManagerConfirm,
  3615. SYsupervisorConfirm = dto.SYsupervisorConfirm
  3616. };
  3617. bool b_PriceDt = DateTime.TryParse(dto.PriceDt, out DateTime dt_PriceDt);
  3618. if (b_PriceDt)
  3619. {
  3620. _entity.PriceDt = dt_PriceDt;
  3621. }
  3622. else
  3623. {
  3624. _entity.PriceDt = DateTime.MinValue;
  3625. }
  3626. _entity.PriceSum = dto.price * dto.PriceCount;
  3627. _daiRep.BeginTran();
  3628. if (dto.editType == 1)
  3629. {
  3630. _entity.CreateUserId = dto.createUser;
  3631. _entity.CreateTime = DateTime.Now;
  3632. _entity.IsDel = 0;
  3633. int returnId = await _daiRep.AddAsyncReturnId<Fin_GroupExtraCost>(_entity);
  3634. if (returnId > 0)
  3635. {
  3636. dto.Id = returnId;
  3637. }
  3638. }
  3639. else if (dto.editType == 2)
  3640. {
  3641. bool res = await _daiRep.UpdateAsync<Fin_GroupExtraCost>(s => s.Id == dto.Id, s => new Fin_GroupExtraCost
  3642. {
  3643. PriceName = dto.priceName,
  3644. Price = dto.price,
  3645. PriceCurrency = dto.currency,
  3646. PriceType = dto.priceType,
  3647. PriceDetailType = dto.priceDetailType,
  3648. Coefficient = dto.coefficient,
  3649. FilePath = dto.filePath,
  3650. Remark = dto.remark,
  3651. PriceCount = dto.PriceCount,
  3652. PriceDt = _entity.PriceDt,
  3653. PriceSum = _entity.PriceSum,
  3654. Area = _entity.Area,
  3655. });
  3656. if (!res)
  3657. {
  3658. _daiRep.RollbackTran();
  3659. return Ok(JsonView(false, "2操作失败!"));
  3660. }
  3661. }
  3662. else if (dto.editType == 3)
  3663. {
  3664. string delTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
  3665. bool res = await _daiRep.UpdateAsync<Fin_GroupExtraCost>(s => s.Id == dto.Id, s => new Fin_GroupExtraCost
  3666. {
  3667. IsDel = 1,
  3668. DeleteTime = delTime,
  3669. DeleteUserId = dto.createUser
  3670. });
  3671. if (!res)
  3672. {
  3673. _daiRep.RollbackTran();
  3674. return Ok(JsonView(false, "3操作失败!"));
  3675. }
  3676. }
  3677. else
  3678. {
  3679. _daiRep.RollbackTran();
  3680. return Ok(JsonView(false, "未知的editType"));
  3681. }
  3682. if (!ExtraCost_editCreditCardPayment(dto))
  3683. {
  3684. return Ok(JsonView(false, "ccp操作失败"));
  3685. }
  3686. //同步修改收款账单
  3687. _foreignReceivablesRepository.OverSpSeteceivables(new OverSpSeteceivablesDto
  3688. {
  3689. CreateUserId = dto.createUser,
  3690. DiId = dto.diId,
  3691. });
  3692. _daiRep.CommitTran();
  3693. return Ok(JsonView(true, "操作成功"));
  3694. }
  3695. private Result PostCurrencyByDiid_Sync(int diId, int CId, int currencyId)
  3696. {
  3697. if (diId == 0)
  3698. {
  3699. return new Result() { Code = -1, Msg = "请传入团组Id!" };
  3700. }
  3701. if (CId == 0)
  3702. {
  3703. return new Result() { Code = -1, Msg = "请传入类型Id!" };
  3704. }
  3705. if (currencyId == 0)
  3706. {
  3707. return new Result() { Code = -1, Msg = "请传入币种Id!" };
  3708. }
  3709. Grp_TeamRate _TeamRate = _sqlSugar.Queryable<Grp_TeamRate>().First(a => a.DiId == diId && a.IsDel == 0 && a.CTable == CId);
  3710. var currencyInfos = new List<CurrencyInfo>();
  3711. var CurrencyRate = new CurrencyInfo();
  3712. try
  3713. {
  3714. if (_TeamRate != null)
  3715. {
  3716. Sys_SetData _SetData = _sqlSugar.Queryable<Sys_SetData>().First(a => a.IsDel == 0 && a.Id == currencyId);
  3717. if (_SetData != null)
  3718. {
  3719. currencyInfos = CommonFun.GetCurrencyChinaToList(_TeamRate.Remark);
  3720. CurrencyRate = currencyInfos.FirstOrDefault(a => a.CurrencyCode == _SetData.Name);
  3721. if (CurrencyRate != null)
  3722. {
  3723. return new Result() { Code = 0, Msg = "查询成功!", Data = CurrencyRate };
  3724. }
  3725. else
  3726. {
  3727. return new Result() { Code = -1, Msg = "暂无团组汇率,请前往设置!", Data = CurrencyRate };
  3728. }
  3729. }
  3730. else
  3731. {
  3732. return new Result() { Code = -1, Msg = "暂无团组汇率,请前往设置!", Data = CurrencyRate };
  3733. }
  3734. }
  3735. else
  3736. {
  3737. return new Result() { Code = -1, Msg = "暂无团组汇率,请前往设置!", Data = CurrencyRate };
  3738. }
  3739. }
  3740. catch (Exception)
  3741. {
  3742. return new Result() { Code = -1, Msg = "查询异常!", Data = CurrencyRate };
  3743. }
  3744. }
  3745. private bool ExtraCost_editCreditCardPayment(Fin_GroupExtraCostDto_OP costDto)
  3746. {
  3747. //设置团组汇率
  3748. decimal dcm_dayrate = 1M;
  3749. decimal dcm_rmbPrice = costDto.price;
  3750. int ispay = costDto.payType == 72 ? 1 : 0;
  3751. if (costDto.costSign != 3)
  3752. {
  3753. //获取新汇率 int diId,int CId, int currencyId
  3754. Result rate = this.PostCurrencyByDiid_Sync(costDto.diId, 1015, costDto.currency);
  3755. if (rate.Code == 0)
  3756. {
  3757. var rateInfo = (rate.Data as CurrencyInfo);
  3758. if (rateInfo is not null)
  3759. {
  3760. dcm_dayrate = rateInfo.Rate;
  3761. dcm_rmbPrice = rateInfo.Rate * dcm_rmbPrice;
  3762. }
  3763. else
  3764. {
  3765. dcm_dayrate = 1;
  3766. }
  3767. }
  3768. }
  3769. Grp_CreditCardPayment ccp = _daiRep.Query<Grp_CreditCardPayment>(s => s.CId == costDto.Id && s.CTable == 1015).First();
  3770. if (ccp == null)
  3771. {
  3772. ccp = new Grp_CreditCardPayment();
  3773. ccp.PayDId = costDto.payType;// dto
  3774. ccp.ConsumptionPatterns = "";
  3775. ccp.ConsumptionDate = "";
  3776. ccp.CTDId = costDto.payCardId;// dto
  3777. ccp.BankNo = "";
  3778. ccp.CardholderName = "";
  3779. ccp.PayMoney = costDto.price;// dto
  3780. ccp.PaymentCurrency = costDto.currency;// dto
  3781. ccp.CompanyBankNo = "";
  3782. ccp.OtherBankName = "";
  3783. ccp.OtherSideNo = "";
  3784. ccp.OtherSideName = "";
  3785. ccp.Remark = "";
  3786. ccp.CreateUserId = costDto.createUser;
  3787. ccp.CreateTime = DateTime.Now;
  3788. ccp.MFOperator = 0;
  3789. ccp.MFOperatorDate = "";
  3790. ccp.IsAuditDM = 0;
  3791. ccp.AuditDMOperate = 0;
  3792. ccp.AuditDMDate = "";
  3793. ccp.IsAuditMF = 0;
  3794. ccp.AuditMFOperate = 0;
  3795. ccp.AuditMFDate = "";
  3796. ccp.IsAuditGM = 0;
  3797. ccp.AuditGMOperate = 0;
  3798. ccp.AuditGMDate = "";
  3799. ccp.IsPay = ispay; // upd
  3800. ccp.DIId = costDto.diId;// dto
  3801. ccp.CId = costDto.Id;// dto
  3802. ccp.CTable = 1015; //超支费用指向id
  3803. ccp.IsDel = 0;
  3804. ccp.PayPercentage = 100M;
  3805. ccp.PayThenMoney = 0M;
  3806. ccp.PayPercentageOld = 100M;
  3807. ccp.PayThenMoneyOld = 0M;
  3808. ccp.UpdateDate = "";
  3809. ccp.Payee = costDto.payee;// dto
  3810. ccp.OrbitalPrivateTransfer = costDto.costSign;// dto
  3811. ccp.ExceedBudget = 0;
  3812. ccp.DayRate = dcm_dayrate; //upd
  3813. ccp.RMBPrice = dcm_rmbPrice; //upd
  3814. int ccpInsertId = _daiRep.AddReturnId<Grp_CreditCardPayment>(ccp);
  3815. if (ccpInsertId > 0)
  3816. {
  3817. return true;
  3818. }
  3819. }
  3820. else
  3821. {
  3822. if (costDto.editType == 2)
  3823. {
  3824. bool res = _daiRep.Update<Grp_CreditCardPayment>(s => s.Id == ccp.Id, s => new Grp_CreditCardPayment
  3825. {
  3826. PayDId = costDto.payType,
  3827. CTDId = costDto.payCardId,
  3828. PayMoney = costDto.price,
  3829. PaymentCurrency = costDto.currency,
  3830. IsPay = ispay,
  3831. Payee = costDto.payee,
  3832. OrbitalPrivateTransfer = costDto.costSign,
  3833. DayRate = dcm_dayrate,
  3834. RMBPrice = dcm_rmbPrice
  3835. });
  3836. return res;
  3837. }
  3838. else if (costDto.editType == 3)
  3839. {
  3840. string delTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
  3841. bool res2 = _daiRep.Update<Grp_CreditCardPayment>(s => s.Id == ccp.Id, s => new Grp_CreditCardPayment
  3842. {
  3843. IsDel = 1,
  3844. DeleteTime = delTime,
  3845. DeleteUserId = costDto.createUser
  3846. });
  3847. return res2;
  3848. }
  3849. }
  3850. return false;
  3851. }
  3852. /// <summary>
  3853. /// 超支费用
  3854. /// 详情查询
  3855. /// </summary>
  3856. /// <param name="dto"></param>
  3857. /// <returns></returns>
  3858. [HttpPost]
  3859. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3860. public async Task<IActionResult> PostGroupExtraCost_Detail(Fin_GroupExtraCostDto_Detail dto)
  3861. {
  3862. if (dto.Id < 1)
  3863. {
  3864. return Ok(JsonView(false, "查询失败"));
  3865. }
  3866. string sql = string.Format(@" Select
  3867. f.Id,f.DiId,
  3868. f.PriceName,f.Price,f.PriceCurrency,c.Payee,c.OrbitalPrivateTransfer,c.PayDId,f.area,
  3869. c.CTDId,f.PriceType,f.PriceDetailType,f.Coefficient,f.Remark,f.PriceCount,f.PriceDt
  3870. From Fin_GroupExtraCost f
  3871. Inner Join Grp_CreditCardPayment c On f.Id = c.CId
  3872. Left Join Sys_Users u On f.CreateUserId = u.Id
  3873. Where f.IsDel=0 And c.CTable = 1015
  3874. And f.Id = {0} ", dto.Id);
  3875. Fin_GroupExtraCostDetailView detailView = await _sqlSugar.SqlQueryable<Fin_GroupExtraCostDetailView>(sql).FirstAsync();
  3876. if (detailView == null)
  3877. {
  3878. return Ok(JsonView(false, "查询失败"));
  3879. }
  3880. if (!string.IsNullOrEmpty(detailView.Remark))
  3881. {
  3882. detailView.Remark = detailView.Remark.Replace("[TuT]", string.Empty);
  3883. }
  3884. return Ok(JsonView(true, "查询成功", detailView));
  3885. }
  3886. /// <summary>
  3887. /// 超支费用
  3888. /// 列表查询
  3889. /// </summary>
  3890. /// <param name="dto"></param>
  3891. /// <returns></returns>
  3892. [HttpPost]
  3893. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3894. public async Task<IActionResult> PostGroupExtraCost_Search(Fin_GroupExtraCostDto_Search dto)
  3895. {
  3896. string sqlWhere = string.Format(@" And f.DiId = {0} ", dto.diId);
  3897. int startIndex = (dto.PageIndex - 1) * dto.PageSize + 1;
  3898. int endIndex = startIndex + dto.PageSize - 1;
  3899. string sql_data = string.Format(@"Select * From (
  3900. Select row_number() over (order by f.Id Desc) as RowNumber,f.Id,f.DiId,
  3901. f.PriceName,f.PriceType,f.PriceDetailType,CAST(f.Price as varchar)+' '+s.[Name] as PriceStr,f.PriceCount,CAST(f.PriceSum as varchar)+' '+s.[Name] as PriceSumStr,
  3902. f.CreateUserId,f.PriceDt,c.IsAuditGM,f.ManagerConfirm,f.SupervisorConfirm,f.Remark,
  3903. CASE ManagerConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'ManagerConfirmStr' , CASE SupervisorConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'SupervisorConfirmStr',
  3904. CASE SYsupervisorConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'SYsupervisorConfirmStr'
  3905. From Fin_GroupExtraCost f
  3906. Inner Join Grp_CreditCardPayment c On f.Id = c.CId
  3907. Inner Join Sys_SetData s On f.PriceCurrency = s.Id
  3908. Left Join Sys_Users u On f.CreateUserId = u.Id
  3909. Where f.IsDel=0 And c.CTable = 1015 {0}
  3910. ) temp Where RowNumber Between {1} and {2}", sqlWhere, startIndex, endIndex);
  3911. string sql_count = string.Format(@"Select Count(1) as DataCount From (
  3912. Select row_number() over (order by f.Id Desc) as RowNumber,f.Id,f.DiId,
  3913. f.PriceName,f.PriceType,f.Price,f.FilePath,f.CreateUserId,f.CreateTime,c.IsAuditGM,f.ManagerConfirm,f.SupervisorConfirm,f.Remark,
  3914. CASE ManagerConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'ManagerConfirmStr' , CASE SupervisorConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'SupervisorConfirmStr',
  3915. CASE SYsupervisorConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'SYsupervisorConfirmStr'
  3916. From Fin_GroupExtraCost f
  3917. Inner Join Grp_CreditCardPayment c On f.Id = c.CId
  3918. Inner Join Sys_SetData s On f.PriceCurrency = s.Id
  3919. Left Join Sys_Users u On f.CreateUserId = u.Id
  3920. Where f.IsDel=0 And c.CTable = 1015 {0}
  3921. ) temp ", sqlWhere);
  3922. if (dto.PortType == 1 || dto.PortType == 2 || dto.PortType == 3) //web
  3923. {
  3924. //Fin_DailyFeePaymentPageCount
  3925. var count = await _sqlSugar.SqlQueryable<Fin_GroupExtraCostViewDataCount>(sql_count).FirstAsync();
  3926. List<Fin_GroupExtraCostView> dataList = await _sqlSugar.SqlQueryable<Fin_GroupExtraCostView>(sql_data).ToListAsync();
  3927. Dictionary<int, string> dic_setData = new Dictionary<int, string>();
  3928. Dictionary<int, string> dic_user = new Dictionary<int, string>();
  3929. foreach (var item in dataList)
  3930. {
  3931. bool b_ct = DateTime.TryParse(item.PriceDt, out DateTime dtTemp_PriceDt);
  3932. if (b_ct)
  3933. {
  3934. item.PriceDt = dtTemp_PriceDt.ToString("yyyy-MM-dd");
  3935. }
  3936. //费用类型
  3937. if (dic_setData.ContainsKey(item.PriceType))
  3938. {
  3939. item.PriceTypeStr = dic_setData[item.PriceType];
  3940. }
  3941. else
  3942. {
  3943. Sys_SetData sd_priceTypeDetail = _daiRep.Query<Sys_SetData>(s => s.Id == item.PriceType).First();
  3944. if (sd_priceTypeDetail != null)
  3945. {
  3946. string tempName = sd_priceTypeDetail.Name.Replace("n", "");
  3947. item.PriceTypeStr = tempName;
  3948. dic_setData.Add(item.PriceType, tempName);
  3949. }
  3950. }
  3951. if (item.PriceDetailType > 0)
  3952. {
  3953. if (dic_setData.ContainsKey(item.PriceDetailType))
  3954. {
  3955. item.PriceTypeStr = item.PriceTypeStr + " - " + dic_setData[item.PriceDetailType];
  3956. }
  3957. else
  3958. {
  3959. Sys_SetData sd_priceTypeDetail = _daiRep.Query<Sys_SetData>(s => s.Id == item.PriceDetailType).First();
  3960. if (sd_priceTypeDetail != null)
  3961. {
  3962. string tempName = sd_priceTypeDetail.Name.Replace("n", "");
  3963. item.PriceTypeStr = item.PriceTypeStr + " - " + tempName;
  3964. dic_setData.Add(item.PriceDetailType, tempName);
  3965. }
  3966. }
  3967. }
  3968. //系统用户
  3969. if (dic_user.ContainsKey(item.CreateUserId))
  3970. {
  3971. item.CreateUserIdStr = dic_user[item.CreateUserId];
  3972. }
  3973. else
  3974. {
  3975. Sys_Users users = _daiRep.Query<Sys_Users>(s => s.Id == item.CreateUserId).First();
  3976. if (users != null)
  3977. {
  3978. item.CreateUserIdStr = users.CnName;
  3979. dic_user.Add(item.CreateUserId, users.CnName);
  3980. }
  3981. }
  3982. switch (item.IsAuditGM)
  3983. {
  3984. case 0: item.IsAuditGMStr = "未审核"; break;
  3985. case 1: item.IsAuditGMStr = "已通过"; break;
  3986. case 2: item.IsAuditGMStr = "未通过"; break;
  3987. default: item.IsAuditGMStr = "未知状态"; break;
  3988. }
  3989. }
  3990. var overspendAuditUser = AppSettingsHelper.Get<OverspendAuditUserView>("OverspendAuditUser");
  3991. var result = new
  3992. {
  3993. CurrPageIndex = dto.PageIndex,
  3994. CurrPageSize = dto.PageSize,
  3995. DataCount = count.DataCount,
  3996. DataList = dataList,
  3997. overspendAuditUser = new
  3998. {
  3999. jinliExpand = overspendAuditUser.Find(x => x.Job == "opJinLi").Users.Select(x => x.Id),
  4000. zhuguanExpand = overspendAuditUser.Find(x => x.Job == "opZhuGuan").Users.Select(x => x.Id),
  4001. syzhuguanExpand = overspendAuditUser.Find(x => x.Job == "syZhuGuan").Users.Select(x => x.Id),
  4002. }
  4003. };
  4004. return Ok(JsonView(true, "查询成功", result));
  4005. }
  4006. return Ok(JsonView(false, "查询失败"));
  4007. }
  4008. /// <summary>
  4009. /// 超支费用
  4010. /// 数据集合配置
  4011. /// </summary>
  4012. /// <param name="dto"></param>
  4013. /// <returns></returns>
  4014. [HttpPost]
  4015. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4016. public async Task<IActionResult> PostGroupExtraCost_ListDataInit(Fin_GroupExtraCostDto_DataListInit dto)
  4017. {
  4018. //支付方式
  4019. List<Sys_SetData> Payment = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 14 && a.IsDel == 0).ToList();
  4020. List<SetDataInfoView> _Payment = _mapper.Map<List<SetDataInfoView>>(Payment);
  4021. //信用卡类型
  4022. List<Sys_SetData> Card = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 15 && a.IsDel == 0).ToList();
  4023. List<SetDataInfoView> _Card = _mapper.Map<List<SetDataInfoView>>(Card);
  4024. //超支费用类型
  4025. List<Sys_SetData> PriceType = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 79 && a.IsDel == 0).ToList();
  4026. List<SetDataInfoView> _PriceType = _mapper.Map<List<SetDataInfoView>>(PriceType);
  4027. //超支费用详细类型
  4028. List<Sys_SetData> PriceDetailType = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 80 && a.IsDel == 0).ToList();
  4029. PriceDetailType.ForEach(a => { a.Name = a.Name.Replace("n", ""); });
  4030. List<SetDataInfoView> _PriceDetailType = _mapper.Map<List<SetDataInfoView>>(PriceDetailType);
  4031. var data = new
  4032. {
  4033. Payment = _Payment,
  4034. Card = _Card,
  4035. PriceType = _PriceType,
  4036. PriceDetailType = _PriceDetailType
  4037. };
  4038. return Ok(JsonView(true, "", data));
  4039. }
  4040. /// <summary>
  4041. /// 超支费用
  4042. /// 导出团组超支费用Excel
  4043. /// </summary>
  4044. /// <param name="dto"></param>
  4045. /// <returns></returns>
  4046. [HttpPost]
  4047. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4048. public async Task<IActionResult> PostGroupExtraCost_OutputExcel(Fin_GroupExtraCostExcelDto dto)
  4049. {
  4050. string sqlGroup = string.Format(@" Select * From Grp_DelegationInfo WIth(Nolock) where Id = {0} ", dto.diId);
  4051. Grp_DelegationInfo grp_DelegationInfo = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sqlGroup).FirstAsync();
  4052. if (grp_DelegationInfo == null)
  4053. {
  4054. return Ok(JsonView(false, "导出失败,未查询到团组"));
  4055. }
  4056. Workbook workbook = new Workbook();
  4057. Worksheet sheet = workbook.Worksheets[0];
  4058. Cells cells = sheet.Cells;
  4059. //sheet.Protect(Aspose.Cells.ProtectionType.All, "123123", "");//保护工作表
  4060. //sheet.Protection.IsSelectingLockedCellsAllowed = true;//设置只能选择解锁单元格
  4061. //sheet.Protection.IsFormattingColumnsAllowed = true;//设置可以调整列
  4062. //sheet.Protection.IsFormattingRowsAllowed = true;//设置可以调整行
  4063. #region 数据源
  4064. string sqlData = string.Format(@" Select f.PriceType,REPLACE(s2.[Name],'超支费用','') as PriceTypeStr,'('+REPLACE(s3.[Name],'n','')+')' as PriceDetailTypeStr, PriceDt,PriceName,
  4065. Price,PriceCount,s.[Name] as Currency,PriceSum,f.Remark
  4066. From Fin_GroupExtraCost as f With(Nolock)
  4067. Inner Join Grp_CreditCardPayment as c With(Nolock) On f.Id = c.CId
  4068. Inner Join Sys_SetData as s With(Nolock) On f.PriceCurrency = s.Id
  4069. Inner Join Sys_SetData as s2 With(Nolock) On f.PriceType = s2.Id
  4070. Inner Join Sys_SetData as s3 With(Nolock) On f.PriceDetailType = s3.Id
  4071. Where f.DiId = {0} And f.IsDel=0 And c.CTable=1015
  4072. Order by PriceType ASC,PriceDt ASC ", dto.diId);
  4073. string sqlDataCount = string.Format(@" Select f.PriceType,COUNT(f.PriceType) as DataCount
  4074. From Fin_GroupExtraCost as f With(Nolock)
  4075. Inner Join Grp_CreditCardPayment as c With(Nolock) On f.Id = c.CId
  4076. Where f.DiId = {0} And f.IsDel=0 And c.CTable=1015
  4077. Group by PriceType ", dto.diId);
  4078. List<Fin_GroupExtraCost_ExcelView> dataList = await _sqlSugar.SqlQueryable<Fin_GroupExtraCost_ExcelView>(sqlData).ToListAsync();
  4079. List<Fin_GroupExtraCost_ExcelCountView> countList = await _sqlSugar.SqlQueryable<Fin_GroupExtraCost_ExcelCountView>(sqlDataCount).ToListAsync();
  4080. if (dataList.Count < 1 || countList.Count < 1)
  4081. {
  4082. return Ok(JsonView(false, "导出失败,未查询到数据"));
  4083. }
  4084. #endregion
  4085. #region 标题
  4086. string cellValue_Header = grp_DelegationInfo.TeamName;
  4087. //Aspose.Cells.Style style1 = workbook.Styles[workbook.Styles.Add()];//新增样式
  4088. Aspose.Cells.Style style_Header = workbook.CreateStyle();
  4089. style_Header.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  4090. style_Header.VerticalAlignment = TextAlignmentType.Center;
  4091. style_Header.Font.Name = "微软雅黑";//文字字体
  4092. style_Header.Font.Size = 18;//文字大小
  4093. style_Header.IsLocked = false;//单元格解锁
  4094. style_Header.Font.IsBold = false;//粗体
  4095. style_Header.Font.Color = Color.FromArgb(255, 0, 0);
  4096. //style1.ForegroundColor = Color.FromArgb(0x99, 0xcc, 0xff);//设置背景色
  4097. //style1.Pattern = BackgroundType.Solid; //设置背景样式
  4098. //style1.IsTextWrapped = true;//单元格内容自动换行
  4099. style_Header.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  4100. style_Header.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  4101. style_Header.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  4102. style_Header.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  4103. cells.Merge(1, 1, 1, 10);
  4104. Aspose.Cells.Range range_header = cells.CreateRange(1, 1, 1, 10);
  4105. range_header.PutValue(cellValue_Header, false, false);
  4106. range_header.SetStyle(style_Header);
  4107. cells.SetRowHeight(1, 35);
  4108. #endregion
  4109. #region 列名
  4110. Aspose.Cells.Style style_colName = workbook.CreateStyle();
  4111. style_colName.Name = "colName";
  4112. style_colName.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  4113. style_colName.VerticalAlignment = TextAlignmentType.Center;
  4114. style_colName.Font.Name = "微软雅黑";//文字字体
  4115. style_colName.Font.Size = 12;//文字大小
  4116. style_colName.IsLocked = false;//单元格解锁
  4117. style_colName.Font.IsBold = true;//粗体
  4118. style_colName.Font.Color = Color.FromArgb(0, 0, 0);
  4119. style_colName.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  4120. style_colName.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  4121. style_colName.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  4122. style_colName.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  4123. List<Fin_GroupExtraCostExcelColumnSetting> colNameSettingList = new List<Fin_GroupExtraCostExcelColumnSetting>()
  4124. {
  4125. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 1, columnName="类型", columnWidth= 25},
  4126. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 2, columnName="时间", columnWidth= 16},
  4127. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 3, columnName="内容", columnWidth= 35},
  4128. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 4, columnName="单价", columnWidth= 12},
  4129. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 5, columnName="数量", columnWidth= 12},
  4130. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 6, columnName="货币", columnWidth= 12},
  4131. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 7, columnName="费用", columnWidth= 12},
  4132. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 8, columnName="汇率", columnWidth= 12},
  4133. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 9, columnName="人民币", columnWidth= 12},
  4134. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 10, columnName="备注信息", columnWidth= 24}
  4135. };
  4136. foreach (var col in colNameSettingList)
  4137. {
  4138. cells[2, col.columnIndex].PutValue(col.columnName);
  4139. cells[2, col.columnIndex].SetStyle(style_colName);
  4140. cells.SetColumnWidth(col.columnIndex, col.columnWidth);
  4141. }
  4142. cells.SetRowHeight(2, 25);
  4143. #endregion
  4144. #region 数据填充
  4145. Aspose.Cells.Style style_dataCol = workbook.GetNamedStyle("colName");
  4146. style_dataCol.Font.IsBold = false;
  4147. style_dataCol.Name = "dataCol";
  4148. Aspose.Cells.Style style_dataBlue = workbook.CreateStyle();
  4149. style_dataBlue.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  4150. style_dataBlue.VerticalAlignment = TextAlignmentType.Center;
  4151. style_dataBlue.Font.Name = "微软雅黑";//文字字体
  4152. style_dataBlue.Font.Size = 12;//文字大小
  4153. style_dataBlue.IsLocked = false;//单元格解锁
  4154. style_dataBlue.Font.IsBold = false;//粗体
  4155. style_dataBlue.ForegroundColor = Color.FromArgb(189, 215, 238);
  4156. style_dataBlue.Pattern = BackgroundType.Solid;
  4157. style_dataBlue.Font.Color = Color.FromArgb(0, 0, 0);
  4158. style_dataBlue.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  4159. style_dataBlue.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  4160. style_dataBlue.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  4161. style_dataBlue.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  4162. Aspose.Cells.Style style_dataYellow = workbook.CreateStyle();
  4163. style_dataYellow.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  4164. style_dataYellow.VerticalAlignment = TextAlignmentType.Center;
  4165. style_dataYellow.Font.Name = "微软雅黑";//文字字体
  4166. style_dataYellow.Font.Size = 12;//文字大小
  4167. style_dataYellow.IsLocked = false;//单元格解锁
  4168. style_dataYellow.Font.IsBold = false;//粗体
  4169. style_dataYellow.ForegroundColor = Color.FromArgb(255, 242, 204);
  4170. style_dataYellow.Pattern = BackgroundType.Solid;
  4171. style_dataYellow.Font.Color = Color.FromArgb(0, 0, 0);
  4172. style_dataYellow.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  4173. style_dataYellow.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  4174. style_dataYellow.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  4175. style_dataYellow.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  4176. int rowIndex = 4;
  4177. foreach (var d in dataList)
  4178. {
  4179. //内容
  4180. string typeStr = d.PriceDetailTypeStr + d.PriceName;
  4181. cells["B" + rowIndex.ToString()].PutValue(d.PriceTypeStr);
  4182. cells["C" + rowIndex.ToString()].PutValue(d.PriceDtStr);
  4183. cells["D" + rowIndex.ToString()].PutValue(typeStr);
  4184. cells["E" + rowIndex.ToString()].PutValue(d.Price.ToString("#0.00"));
  4185. cells["F" + rowIndex.ToString()].PutValue(d.PriceCount);
  4186. cells["G" + rowIndex.ToString()].PutValue(d.Currency);
  4187. cells["H" + rowIndex.ToString()].PutValue(d.PriceSum.ToString("#0.00"));
  4188. cells["K" + rowIndex.ToString()].PutValue(d.Remark);
  4189. //样式
  4190. cells["B" + rowIndex.ToString()].SetStyle(style_dataCol);
  4191. cells["C" + rowIndex.ToString()].SetStyle(style_dataCol);
  4192. cells["D" + rowIndex.ToString()].SetStyle(style_dataCol);
  4193. cells["E" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4194. cells["F" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4195. cells["G" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4196. cells["H" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4197. cells["I" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4198. cells["J" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4199. cells["K" + rowIndex.ToString()].SetStyle(style_dataYellow);
  4200. //公式
  4201. cells["H" + rowIndex.ToString()].Formula = string.Format(@"E{0}*F{0}", rowIndex);
  4202. cells["J" + rowIndex.ToString()].Formula = string.Format(@"H{0}*I{0}", rowIndex);
  4203. cells.SetRowHeight(rowIndex - 1, 25);
  4204. rowIndex++;
  4205. }
  4206. cells["B" + rowIndex.ToString()].SetStyle(style_dataCol);
  4207. cells["C" + rowIndex.ToString()].SetStyle(style_dataCol);
  4208. cells["D" + rowIndex.ToString()].SetStyle(style_dataCol);
  4209. cells["E" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4210. cells["F" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4211. cells["G" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4212. cells["H" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4213. cells["I" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4214. cells["J" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4215. cells["K" + rowIndex.ToString()].SetStyle(style_dataYellow);
  4216. rowIndex++;
  4217. cells["B" + rowIndex.ToString()].SetStyle(style_dataCol);
  4218. cells["C" + rowIndex.ToString()].SetStyle(style_dataCol);
  4219. cells["D" + rowIndex.ToString()].SetStyle(style_dataCol);
  4220. cells["E" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4221. cells["F" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4222. cells["G" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4223. cells["H" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4224. cells["I" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4225. cells["J" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4226. cells["K" + rowIndex.ToString()].SetStyle(style_dataYellow);
  4227. rowIndex = 3;
  4228. int tempPriceType = 0;
  4229. foreach (var c in dataList)
  4230. {
  4231. if (tempPriceType == c.PriceType)
  4232. {
  4233. continue;
  4234. }
  4235. tempPriceType = c.PriceType;
  4236. int _rowCount = countList.First(s => s.PriceType == tempPriceType).DataCount;
  4237. cells.Merge(rowIndex, 1, _rowCount, 1);
  4238. Aspose.Cells.Range tempRange = cells.CreateRange(rowIndex, 1, _rowCount, 1);
  4239. rowIndex += _rowCount;
  4240. }
  4241. rowIndex = 4 + dataList.Count;
  4242. cells["D" + rowIndex.ToString()].PutValue("合计");
  4243. cells["J" + rowIndex.ToString()].Formula = string.Format(@"SUM(J4,J{0})", rowIndex - 1);
  4244. cells.SetRowHeight(rowIndex - 1, 25);
  4245. rowIndex++;
  4246. cells["D" + rowIndex.ToString()].PutValue("服务费10%开票税金8%");
  4247. cells["J" + rowIndex.ToString()].Formula = string.Format(@"J{0}*1.1*1.08", rowIndex - 1);
  4248. cells.SetRowHeight(rowIndex - 1, 25);
  4249. #endregion
  4250. #region IO
  4251. System.IO.MemoryStream ms = workbook.SaveToStream();//生成数据流
  4252. string fileName = ("GroupExtraCost/超支费用(" + cellValue_Header + ").xlsx");
  4253. byte[] bt = ms.ToArray();
  4254. workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  4255. #endregion
  4256. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  4257. return Ok(JsonView(true, "成功", new { url = rst }));
  4258. }
  4259. /// <summary>
  4260. /// 超支费用Excel导出
  4261. /// </summary>
  4262. /// <param name="dto"></param>
  4263. /// <returns></returns>
  4264. [HttpPost]
  4265. public IActionResult ExportOverspendExcel(Fin_GroupExtraCostExcelDto dto)
  4266. {
  4267. var jw = JsonView(false);
  4268. var grp_DelegationInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().First(x => x.Id == dto.diId && x.IsDel == 0);
  4269. if (grp_DelegationInfo == null)
  4270. {
  4271. return Ok(JsonView(false, "团组信息有误!"));
  4272. }
  4273. Dictionary<int, int> dicSoure = new Dictionary<int, int>()
  4274. {
  4275. {1077,1074 },
  4276. {1078,1075 },
  4277. {1079,1076 }
  4278. };
  4279. Dictionary<int, int> mealsDic = new Dictionary<int, int>()
  4280. {
  4281. {988,1074},
  4282. {93,1075},
  4283. {989,1076},
  4284. };
  4285. var checkBoxDataArr = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 17).ToList();
  4286. var CurrDataArr = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToList();
  4287. var joinTable = _sqlSugar.Queryable<Fin_GroupExtraCost, Grp_CreditCardPayment, Sys_SetData, Grp_NationalTravelFee,
  4288. Fin_LocalGuideRelevancyOverspend, Grp_CarTouristGuideGroundReservations, Sys_SetData, Grp_DelegationInfo>(
  4289. (f, c, s, g, r, l, s1, i) => new JoinQueryInfos(
  4290. JoinType.Left, f.Id == c.CId && c.CTable == 1015 && c.IsDel == 0,
  4291. JoinType.Left, c.PaymentCurrency == s.Id && s.IsDel == 0,
  4292. JoinType.Left, g.IsDel == 0 && g.Id == f.Area,
  4293. JoinType.Left, f.Id == r.OverspendId && r.IsDel == 0,
  4294. JoinType.Left, l.Id == r.LocalGuideId && l.IsDel == 0,
  4295. JoinType.Left, s1.Id == l.toCurr && s1.IsDel == 0,
  4296. JoinType.Left, i.Id == l.DiId && i.IsDel == 0
  4297. ))
  4298. .Where((f, c, s, g) => f.IsDel == 0 && f.DiId == dto.diId)
  4299. .Select((f, c, s, g, r, l, s1, i) => new
  4300. {
  4301. c.PaymentCurrency,
  4302. c.DayRate,
  4303. PaymentCurrencyStr = s.Name,
  4304. f.PriceName,
  4305. f.Remark,
  4306. f.PriceCount,
  4307. Price = f.Price * f.Coefficient,
  4308. c.PayMoney,
  4309. RMBPrice = c.RMBPrice * f.Coefficient,
  4310. Offer = c.RMBPrice * f.PriceCount * f.Coefficient,
  4311. c.CTable,
  4312. f.PriceDetailType,
  4313. Area = g.Country ?? "未选择地区!",
  4314. l.toCurr,
  4315. l.Rate,
  4316. toCurrStr = s1.Name,
  4317. g.FoodCost,
  4318. CarParentId = l.Id,
  4319. f.PriceDt,
  4320. i.VisitPNumber,
  4321. f.DiId,
  4322. f.PriceCurrency,
  4323. f.SupervisorConfirm,
  4324. f.ManagerConfirm,
  4325. f.SYsupervisorConfirm,
  4326. })
  4327. .ToList()
  4328. .Where(x =>
  4329. {
  4330. var count = 0;
  4331. var stringArr = new string[] { "SYsupervisorConfirm", "SupervisorConfirm", "ManagerConfirm" };
  4332. var max = 0;
  4333. foreach (var item in stringArr)
  4334. {
  4335. var number = x.GetType()?.GetProperty(item)?.GetValue(x).ObjToInt();
  4336. if (number > 0)
  4337. {
  4338. count++;
  4339. }
  4340. }
  4341. if (x.PriceDetailType == 1044)
  4342. {
  4343. max = 0;
  4344. }
  4345. return count > max;
  4346. })
  4347. .Select(x =>
  4348. {
  4349. var costPirce = x.Price;
  4350. decimal costRMBPrice = x.RMBPrice;
  4351. decimal costDayRate = x.DayRate;
  4352. string remake = x.Remark;
  4353. if (x.VisitPNumber > 0 && x.PriceDetailType != 1088)
  4354. {
  4355. decimal cost = x.FoodCost;
  4356. //decimal.TryParse(x.FoodCost, out decimal cost);
  4357. cost /= 2;
  4358. decimal oldPrice = costPirce;
  4359. costPirce *= x.Rate; //转换币种
  4360. if (x.toCurr != x.PaymentCurrency)
  4361. {
  4362. var rate = _setDataRep.PostCurrencyByDiid(x.DiId, 1015, x.toCurr).Result;
  4363. if (rate.Code == 0)
  4364. {
  4365. var rateData = rate.Data as CurrencyInfo;
  4366. if (rateData != null)
  4367. {
  4368. costDayRate = rateData.Rate;
  4369. }
  4370. }
  4371. }
  4372. if (dicSoure.ContainsKey(x.PriceDetailType))
  4373. {
  4374. var carCenterList = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(x1 => x1.CTGGRId == x.CarParentId && x1.IsDel == 0
  4375. && x1.SId == mealsDic.First(x2 => x2.Value == dicSoure[x.PriceDetailType]).Key).ToList();
  4376. var CarCenter = carCenterList.FirstOrDefault(x1 => (DateTime.Compare(x1.DatePrice.ObjToDate(), x.PriceDt) == 0)) ?? new
  4377. Grp_CarTouristGuideGroundReservationsContent();
  4378. costPirce += (CarCenter.Price * CarCenter.Count * x.Rate);
  4379. oldPrice += (CarCenter.Price * CarCenter.Count);
  4380. var costResultPirce = costPirce - x.VisitPNumber * cost;
  4381. costResultPirce = Convert.ToInt32(Math.Round(costResultPirce));
  4382. var findCheck = checkBoxDataArr.Find(s => s.Id == CarCenter.SId);
  4383. if (x.toCurr != x.PaymentCurrency)
  4384. {
  4385. remake += $" {x.PriceDt:M/d} {findCheck?.Name} {x.PaymentCurrencyStr} {(int)Math.Round(oldPrice)}( 折算{x.toCurrStr} {(int)Math.Round(costPirce)}) - 财政{cost} * {x.VisitPNumber} = {x.toCurrStr}{costResultPirce}";
  4386. }
  4387. else
  4388. {
  4389. remake += $" {x.PriceDt:M/d} {findCheck?.Name}{x.PaymentCurrencyStr} {(int)Math.Round(costPirce)} - 财政{cost} * {x.VisitPNumber} = {x.PaymentCurrencyStr}{costResultPirce}";
  4390. }
  4391. costPirce = costResultPirce;
  4392. }
  4393. else
  4394. {
  4395. costPirce = Convert.ToInt32(Math.Round(costPirce));
  4396. }
  4397. costRMBPrice = Convert.ToInt32(Math.Round(costPirce * costDayRate));
  4398. }
  4399. if (remake.Contains("[TuT]"))
  4400. {
  4401. remake = remake.Replace("[TuT]", "");
  4402. }
  4403. return new
  4404. {
  4405. x.PaymentCurrency,
  4406. DayRate = costDayRate,
  4407. x.PaymentCurrencyStr,
  4408. x.PriceName,
  4409. Remark = remake,
  4410. x.PriceCount,
  4411. Price = costPirce,
  4412. x.PayMoney,
  4413. RMBPrice = costRMBPrice,
  4414. Offer = costRMBPrice * x.PriceCount,
  4415. x.CTable,
  4416. x.PriceDetailType,
  4417. x.Area,
  4418. x.toCurr,
  4419. x.toCurrStr,
  4420. ItemPrice = costPirce * x.PriceCount,
  4421. };
  4422. })
  4423. .ToList();
  4424. var PriceDetailTypeArr = new int[] { 1088, 1074, 1075, 1076 };
  4425. var whereArr = joinTable.Where(x => PriceDetailTypeArr.Contains(x.PriceDetailType)).ToList();
  4426. _ = joinTable.RemoveAll(x => PriceDetailTypeArr.Contains(x.PriceDetailType));
  4427. foreach (var item in whereArr)
  4428. {
  4429. joinTable.Insert(0, item);
  4430. }
  4431. var dicClounm = new Dictionary<int, string>()
  4432. {
  4433. { 0,"Area" },
  4434. { 1,"PriceName" },
  4435. { 2,"Remark" },
  4436. { 3,"PriceCount" },
  4437. { 4,"Price" },
  4438. { 5,"ItemPrice" },
  4439. { 6,"DayRate" },
  4440. { 7,"Offer" },
  4441. };
  4442. var rowStartIndex = 2;
  4443. string filePath = AppSettingsHelper.Get("ExcelBasePath") + "\\Template\\超支费用表.xlsx";
  4444. IWorkbook workbook = new XSSFWorkbook(new FileStream(filePath, FileMode.Open, FileAccess.Read));
  4445. ISheet sheet = workbook.GetSheetAt(0);
  4446. var initStyleRow = sheet.GetRow(2);
  4447. var clounmCount = dicClounm.Count;
  4448. Action cloneRowFn = () =>
  4449. {
  4450. rowStartIndex++;
  4451. var cloneRow = sheet.CreateRow(rowStartIndex);
  4452. // 复制样式
  4453. for (int i = initStyleRow.FirstCellNum; i < initStyleRow.LastCellNum; i++)
  4454. {
  4455. ICell sourceCell = initStyleRow.GetCell(i);
  4456. ICell targetCell = cloneRow.GetCell(i) ?? cloneRow.CreateCell(i);
  4457. // 确保单元格存在样式
  4458. if (sourceCell.CellStyle != null)
  4459. {
  4460. targetCell.CellStyle = sourceCell.CellStyle;
  4461. }
  4462. }
  4463. };
  4464. sheet.GetRow(0).GetCell(0).SetCellValue($"{grp_DelegationInfo.TeamName}—超支费用");
  4465. foreach (var item in joinTable)
  4466. {
  4467. for (int i = 0; i < clounmCount; i++)
  4468. {
  4469. string property = dicClounm[i];
  4470. string value = item.GetType()!.GetProperty(property)!.GetValue(item)?.ToString() ?? "";
  4471. sheet.GetRow(rowStartIndex).GetCell(i).SetCellValue(value);
  4472. }
  4473. cloneRowFn();
  4474. }
  4475. sheet.GetRow(rowStartIndex).GetCell(2).SetCellValue($"小计:");
  4476. sheet.GetRow(rowStartIndex).GetCell(3).SetCellValue($"{joinTable.Sum(x => x.RMBPrice)}元");
  4477. var path = $"GroupExtraCost/{grp_DelegationInfo.TeamName}_超支费用.xlsx";
  4478. using (var stream = new MemoryStream())
  4479. {
  4480. workbook.Write(stream, true);
  4481. stream.Flush();
  4482. stream.Seek(0, SeekOrigin.Begin);
  4483. var pathinfo = AppSettingsHelper.Get("ExcelBasePath") + path;
  4484. if (System.IO.File.Exists(pathinfo))
  4485. {
  4486. System.IO.File.Delete(pathinfo);
  4487. }
  4488. stream.SaveToFile(AppSettingsHelper.Get("ExcelBasePath") + path);
  4489. }
  4490. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + path;
  4491. jw = JsonView(true, "成功", new { url = rst });
  4492. return Ok(jw);
  4493. }
  4494. /// <summary>
  4495. /// 获取超支系数配置
  4496. /// </summary>
  4497. /// <returns></returns>
  4498. [HttpPost]
  4499. public IActionResult QueryCoefficientConfig()
  4500. {
  4501. var arr = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.STid == 80 && x.IsDel == 0).ToList();
  4502. var carCoefficient = new int[] { 1050 }; //2.4
  4503. var menpiaoCoefficient = new int[] { 1086 }; // 1.2
  4504. var airCoefficient = new int[] { 1035, 1036 }; // 2.0
  4505. var HotelCoefficient = new int[] { 1044, 1045, 1046, 1041, 1042, 1043, 1038 }; // 1.5
  4506. var fanyiCoefficient = new int[] { 1087 }; // 1.5
  4507. var resultArr = new
  4508. ArrayList();
  4509. foreach (var item in arr)
  4510. {
  4511. var a = new { coefficient = 1M, id = 0 };
  4512. if (carCoefficient.Contains(item.Id))
  4513. {
  4514. a = a with
  4515. {
  4516. coefficient = 2.4M,
  4517. id = item.Id
  4518. };
  4519. }
  4520. else if (menpiaoCoefficient.Contains(item.Id))
  4521. {
  4522. a = a with
  4523. {
  4524. coefficient = 1.2M,
  4525. id = item.Id
  4526. };
  4527. }
  4528. else if (airCoefficient.Contains(item.Id))
  4529. {
  4530. a = a with
  4531. {
  4532. coefficient = 2.0M,
  4533. id = item.Id
  4534. };
  4535. }
  4536. else if (HotelCoefficient.Contains(item.Id))
  4537. {
  4538. a = a with
  4539. {
  4540. coefficient = 1.5M,
  4541. id = item.Id
  4542. };
  4543. }
  4544. else if (fanyiCoefficient.Contains(item.Id))
  4545. {
  4546. a = a with
  4547. {
  4548. coefficient = 1.5M,
  4549. id = item.Id
  4550. };
  4551. }
  4552. else
  4553. {
  4554. a = a with
  4555. {
  4556. coefficient = 1M,
  4557. id = item.Id
  4558. };
  4559. }
  4560. resultArr.Add(a);
  4561. }
  4562. return Ok(JsonView(true, "获取成功!", resultArr));
  4563. }
  4564. /// <summary>
  4565. /// 退费确认
  4566. /// </summary>
  4567. /// <returns></returns>
  4568. [HttpPost]
  4569. public IActionResult ReturnPremiumConfirm(ReturnPremiumConfirmDto dto)
  4570. {
  4571. var jw = JsonView(false);
  4572. var confirmStatusArr = new Dictionary<int, string>()
  4573. {
  4574. {1 ,"ManagerConfirm" },
  4575. {2 ,"SupervisorConfirm" },
  4576. {3 ,"SYsupervisorConfirm" },
  4577. };
  4578. if (dto.DataId < 1 || confirmStatusArr.Keys.Contains(dto.ConfirmId) == false)
  4579. {
  4580. jw.Msg = "参数有误!";
  4581. return Ok(jw);
  4582. }
  4583. Fin_GroupExtraCost fge = _sqlSugar.Queryable<Fin_GroupExtraCost>().First(it => it.Id == dto.DataId && it.IsDel == 0);
  4584. try
  4585. {
  4586. if (fge == null)
  4587. throw new Exception("数据不存在!");
  4588. fge.GetType().GetProperty(confirmStatusArr[dto.ConfirmId]).SetValue(fge, dto.status);
  4589. var isSaveCollectionStatement = true;
  4590. //确认后,同步修改收款账单
  4591. foreach (var item in confirmStatusArr.Keys)
  4592. {
  4593. var value = fge.GetType().GetProperty(confirmStatusArr[item]).GetValue(fge).ObjToInt();
  4594. //if (value == 0)
  4595. //{
  4596. // isSaveCollectionStatement = false;
  4597. // break;
  4598. //}
  4599. }
  4600. _sqlSugar.BeginTran();
  4601. _sqlSugar.Updateable<Fin_GroupExtraCost>(fge).ExecuteCommand();
  4602. if (isSaveCollectionStatement)
  4603. {
  4604. //同步修改收款账单
  4605. _foreignReceivablesRepository.OverSpSeteceivables(new OverSpSeteceivablesDto
  4606. {
  4607. CreateUserId = fge.CreateUserId,
  4608. DiId = fge.DiId,
  4609. });
  4610. }
  4611. }
  4612. catch (Exception ex)
  4613. {
  4614. _sqlSugar.RollbackTran();
  4615. jw.Msg = "Error! " + ex.Message;
  4616. return Ok(jw);
  4617. }
  4618. _sqlSugar.CommitTran();
  4619. jw = JsonView(true, "操作成功!");
  4620. return Ok(jw);
  4621. }
  4622. #endregion
  4623. #region 信用卡对账
  4624. /// <summary>
  4625. ///将指定的Excel的文件转换成DataTable(Excel的第一个sheet)
  4626. /// </summary>
  4627. /// <param name="fullFielPath">文件的绝对路径</param>
  4628. /// <param name="sheetName"></param>
  4629. /// <returns></returns>
  4630. private DataTable WorksheetToTable(string fullFielPath, string? sheetName = null)
  4631. {
  4632. //如果是“EPPlus”,需要指定LicenseContext。
  4633. //EPPlus.Core 不需要指定。
  4634. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  4635. var existingFile = new FileInfo(fullFielPath);
  4636. var package = new ExcelPackage(existingFile);
  4637. ExcelWorksheet worksheet;
  4638. if (string.IsNullOrEmpty(sheetName))
  4639. {
  4640. //不传入 sheetName 默认取第1个sheet。
  4641. //EPPlus 索引是0
  4642. //EPPlus.Core 索引是1
  4643. worksheet = package.Workbook.Worksheets[0];
  4644. }
  4645. else
  4646. {
  4647. worksheet = package.Workbook.Worksheets[sheetName];
  4648. }
  4649. if (worksheet == null)
  4650. throw new Exception("指定的sheetName不存在");
  4651. return WorksheetToTable(worksheet);
  4652. }
  4653. /// <summary>
  4654. /// 将worksheet转成datatable
  4655. /// </summary>
  4656. /// <param name="worksheet">待处理的worksheet</param>
  4657. /// <returns>返回处理后的datatable</returns>
  4658. private DataTable WorksheetToTable(ExcelWorksheet worksheet)
  4659. {
  4660. //获取worksheet的行数
  4661. int rows = worksheet.Dimension.End.Row;
  4662. //获取worksheet的列数
  4663. int cols = worksheet.Dimension.End.Column;
  4664. var dt = new DataTable(worksheet.Name);
  4665. DataRow dr = null;
  4666. for (int i = 1; i <= rows; i++)
  4667. {
  4668. if (i > 1)
  4669. dr = dt.Rows.Add();
  4670. for (int j = 1; j <= cols; j++)
  4671. {
  4672. //默认将第一行设置为datatable的标题
  4673. if (i == 1)
  4674. dt.Columns.Add(GetString(worksheet.Cells[i, j].Value));
  4675. //剩下的写入datatable
  4676. else
  4677. {
  4678. var cell = worksheet.Cells[i, j];
  4679. if (j == 1 || j == 2)
  4680. {
  4681. if (cell.Value is double)
  4682. {
  4683. dr[j - 1] = EPPlusConvertToDateTime((double)cell.Value).ToString("MM/dd");
  4684. }
  4685. }
  4686. else
  4687. {
  4688. dr[j - 1] = GetString(cell.Value);
  4689. }
  4690. }
  4691. }
  4692. }
  4693. return dt;
  4694. }
  4695. private string GetString(object obj)
  4696. {
  4697. if (obj == null)
  4698. return "";
  4699. return obj.ToString();
  4700. }
  4701. public static DateTime EPPlusConvertToDateTime(double numericDate)
  4702. {
  4703. // Excel起始日期
  4704. var startDate = new DateTime(1899, 12, 30);
  4705. // 将数字日期转换为时间间隔,并加上起始日期
  4706. var duration = new TimeSpan((long)(numericDate * TimeSpan.TicksPerDay));
  4707. return startDate.Add(duration);
  4708. }
  4709. private DataTable ExcelFileToDataTable(IFormFile file)
  4710. {
  4711. DataTable dtTest = null;
  4712. using (var stream = new MemoryStream())
  4713. {
  4714. file.CopyTo(stream);
  4715. using (var package = new ExcelPackage(stream))
  4716. {
  4717. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  4718. ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
  4719. dtTest = WorksheetToTable(worksheet);
  4720. }
  4721. }
  4722. return dtTest;
  4723. }
  4724. /// <summary>
  4725. /// 信用卡对账--基础数据
  4726. /// </summary>
  4727. /// <returns></returns>
  4728. [HttpPost]
  4729. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4730. public async Task<IActionResult> PostCreditCardBillInit()
  4731. {
  4732. var data = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 15).Select(x => new { x.Id, x.Name }).ToListAsync();
  4733. return Ok(JsonView(true, "操作成功!", data));
  4734. }
  4735. /// <summary>
  4736. /// 信用卡对账
  4737. /// </summary>
  4738. /// <param name="file"></param>
  4739. /// <param name="cardType"></param>
  4740. /// <param name="beginDt"></param>
  4741. /// <param name="endDt"></param>
  4742. /// <returns></returns>
  4743. [HttpPost]
  4744. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4745. public async Task<IActionResult> PostCreditCardBill(IFormFile file, int cardType, string beginDt, string endDt)
  4746. {
  4747. if (file == null || file.Length < 1)
  4748. {
  4749. return Ok(JsonView(false, "请上传文件!"));
  4750. }
  4751. string fileName = file.FileName;
  4752. if (!fileName.EndsWith(".xlsx") && !fileName.EndsWith(".xls"))
  4753. {
  4754. return Ok(JsonView(false, "请上传Excel文件!"));
  4755. }
  4756. if (cardType < 1) return Ok(JsonView(false, "请传入有效的卡类型!"));
  4757. if (string.IsNullOrEmpty(beginDt) || string.IsNullOrEmpty(endDt)) return Ok(JsonView(false, "请输入开始/结束日期!"));
  4758. var beginValid = DateTime.TryParse(beginDt, out DateTime _beginDt);
  4759. var endValid = DateTime.TryParse(endDt, out DateTime _endDt);
  4760. if (!beginValid || !endValid) return Ok(JsonView(false, "请输入正确的日期格式"));
  4761. //读取ExcelFile
  4762. DataTable dt = ExcelFileToDataTable(file);
  4763. if (dt == null)
  4764. {
  4765. return Ok(JsonView(false, $"您上传的Excel工作表没有内容,请检查!!!"));
  4766. }
  4767. dt.TableName = "TB";
  4768. //信用卡信息
  4769. string sql = string.Format($"Select * From Grp_CreditCardPayment Where Isdel = 0 And CTDId = {cardType} And ConsumptionDate between '{beginDt}' and '{endDt}' ");
  4770. var List_ccp = await _sqlSugar.SqlQueryable<Grp_CreditCardPayment>(sql).ToListAsync();
  4771. if (List_ccp.Count < 1)
  4772. {
  4773. return Ok(JsonView(false, $"未查询到 {beginDt} 至 {endDt} 信用卡账单信息!!!!"));
  4774. }
  4775. //酒店刷卡信息
  4776. var hotelData = await _sqlSugar.Queryable<Grp_HotelReservations>()
  4777. .LeftJoin<Grp_HotelReservationsContent>((hr, hrc) => hr.Id == hrc.HrId)
  4778. .Where((hr, hrc) => hr.IsDel == 0 && hrc.Price > 0 && hrc.IsPay == 1)
  4779. .Select((hr, hrc) => new
  4780. {
  4781. hrc.DiId,
  4782. hrc.HrId,
  4783. hrc.Id,
  4784. hrc.PriceType,
  4785. hrc.Price,
  4786. hrc.Currency,
  4787. hrc.Rate,
  4788. hrc.IsOppay,
  4789. hrc.PayDId,
  4790. hrc.ConsumptionPatterns,
  4791. hrc.ConsumptionDate,
  4792. ConsumptionDt = string.IsNullOrEmpty(hrc.ConsumptionDate) ? new DateTime(1990, 12, 30) : Convert.ToDateTime(hrc.ConsumptionDate),
  4793. hrc.CTDId,
  4794. hrc.BankNo,
  4795. hrc.CardholderName,
  4796. hrc.CompanyBankNo,
  4797. hrc.OtherBankName,
  4798. hrc.OtherSideNo,
  4799. hrc.IsPay,
  4800. hrc.Payee,
  4801. hrc.OrbitalPrivateTransfer
  4802. })
  4803. .ToListAsync();
  4804. if (hotelData.Count > 0)
  4805. {
  4806. hotelData = hotelData.Where(x => x.ConsumptionDt >= _beginDt && x.ConsumptionDt <= _endDt).ToList();
  4807. }
  4808. //资源信息
  4809. var delegationInfos = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).ToList();
  4810. var users = _sqlSugar.Queryable<Sys_Users>().Where(it => it.IsDel == 0).ToList();
  4811. string url = string.Empty;
  4812. try
  4813. {
  4814. /*
  4815. * 卡类型
  4816. * 74 美元卡 1
  4817. * 75 欧元卡 1
  4818. * 86 招行卡 1
  4819. * 346 中信卡 1
  4820. * 363 交行卡 1
  4821. *
  4822. */
  4823. var ids = new List<int>();
  4824. if (cardType == 74) //美元卡
  4825. {
  4826. var AirGroupReuslt = List_ccp.Where(x => x.CTable == 85).GroupBy(x => x.DIId).ToList();
  4827. if (AirGroupReuslt != null && AirGroupReuslt.Count > 0)
  4828. {
  4829. foreach (var item in AirGroupReuslt)
  4830. {
  4831. if (item.Count() > 1)
  4832. {
  4833. var obj = item.FirstOrDefault();
  4834. obj.RMBPrice = item.Sum(x => x.PayMoney);//合计币种金额
  4835. obj.Remark = "团组机票总价(虚拟)";
  4836. List_ccp.Add(obj);
  4837. }
  4838. }
  4839. }
  4840. //dt.AcceptChanges(); //提交
  4841. //修改table列名
  4842. dt.Columns[0].ColumnName = "accountType"; // 账户类型
  4843. dt.Columns[1].ColumnName = "tradeDate"; //交易日期
  4844. dt.Columns[2].ColumnName = "BillingDate"; // 记账日期
  4845. dt.Columns[3].ColumnName = "CardNo"; // 卡号
  4846. dt.Columns[4].ColumnName = "deposit"; // 存入金额
  4847. dt.Columns[5].ColumnName = "SpendingAmount"; // 支出金额
  4848. dt.Columns[6].ColumnName = "TransactionDescription"; // 交易描述
  4849. dt.Columns[7].ColumnName = "TeamRemark"; // 团组备注描述
  4850. dt.Columns[8].ColumnName = "Handlers"; // 经手人
  4851. dt.Columns[9].ColumnName = "State"; // 状态
  4852. //删除第一行数据
  4853. if (dt.Rows.Count > 0)
  4854. {
  4855. string accountType = dt.Rows[0]["accountType"].ToString();
  4856. if (dt.Rows[0]["accountType"].ToString().Equals("账户类型"))
  4857. {
  4858. dt.Rows[0].Delete();
  4859. dt.AcceptChanges(); //提交
  4860. }
  4861. }
  4862. foreach (DataRow item in dt.Rows)
  4863. {
  4864. #region 匹配的金额
  4865. decimal ExcelAmount = 0.00M;
  4866. decimal deposit = 0.00M;
  4867. if (!string.IsNullOrEmpty(item["SpendingAmount"].ToString()))
  4868. {
  4869. var isParase = decimal.TryParse(item["SpendingAmount"].ToString(), out ExcelAmount);
  4870. if (isParase)
  4871. {
  4872. var CList = List_ccp.FindAll(x => x.PayMoney == ExcelAmount);
  4873. if (CList != null && CList.Count > 0)
  4874. {
  4875. item["TeamRemark"] = delegationInfos.Find(it => it.Id == CList.First().DIId)?.TeamName;
  4876. item["Handlers"] = users.Find(it => it.Id == CList.First().CreateUserId)?.CnName;
  4877. item["State"] = 1;
  4878. }
  4879. }
  4880. }
  4881. if (!string.IsNullOrEmpty(item["deposit"].ToString()))
  4882. {
  4883. var isParse = decimal.TryParse(item["deposit"].ToString(), out deposit);
  4884. if (isParse)
  4885. {
  4886. var CList = List_ccp.FindAll(x => x.PayMoney == deposit);
  4887. if (CList != null && CList.Count > 0)
  4888. {
  4889. item["TeamRemark"] = delegationInfos.Find(it => it.Id == CList.First().DIId)?.TeamName;
  4890. item["Handlers"] = users.Find(it => it.Id == CList.First().CreateUserId)?.CnName;
  4891. item["State"] = 1;
  4892. }
  4893. }
  4894. }
  4895. #endregion
  4896. //交易描述
  4897. if (!string.IsNullOrEmpty(item["TransactionDescription"].ToString()))
  4898. {
  4899. string TransactionDescription = item["TransactionDescription"].ToString();
  4900. var startIndex = TransactionDescription.LastIndexOf("[");
  4901. var endIndex = TransactionDescription.LastIndexOf("]");
  4902. if (startIndex != -1 && endIndex != -1)
  4903. {
  4904. var moenyList = TransactionDescription.Substring(startIndex + 1, endIndex - startIndex - 1).Split(' ').
  4905. Where(x => !string.IsNullOrEmpty(x)).ToList();
  4906. decimal money = 0.00M;
  4907. foreach (var itemMoeny in moenyList)
  4908. {
  4909. if (itemMoeny.Contains('.'))
  4910. {
  4911. string itemMoenyStr = itemMoeny.Replace(",", string.Empty);
  4912. bool istrue = decimal.TryParse(itemMoenyStr, out money);
  4913. if (istrue)
  4914. {
  4915. var CList = List_ccp.FindAll(x => x.PayMoney == money);
  4916. if (CList != null && CList.Count > 0)
  4917. {
  4918. item["TeamRemark"] = delegationInfos.Find(it => it.Id == CList.First().DIId)?.TeamName;
  4919. item["Handlers"] = users.Find(it => it.Id == CList.First().CreateUserId)?.CnName;
  4920. item["State"] = 1;
  4921. }
  4922. }
  4923. }
  4924. }
  4925. }
  4926. }
  4927. }
  4928. string fileName1 = $"信用卡账单(美元卡){DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  4929. var pairs = new Dictionary<string, object>();
  4930. var datas = new List<DataTable>
  4931. {
  4932. dt
  4933. };
  4934. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-美元卡.xls", $"CreditCardBill", fileName1, pairs, datas);
  4935. }
  4936. else if (cardType == 75) //欧元卡
  4937. {
  4938. if (dt.Rows.Count > 0)
  4939. {
  4940. string accountType = dt.Rows[0][0].ToString();
  4941. if (accountType.Equals("账户类型"))
  4942. {
  4943. dt.Rows[0].Delete();
  4944. dt.AcceptChanges(); //提交
  4945. }
  4946. }
  4947. //dt.Columns[0].ColumnName = "All";
  4948. var dt1 = new DataTable
  4949. {
  4950. TableName = "TB"
  4951. };
  4952. dt1.Columns.Add("TradingDate", Type.GetType("System.String"));//交易日期
  4953. dt1.Columns.Add("TallyDate", Type.GetType("System.String")); //记账日期
  4954. dt1.Columns.Add("TradindDesc", Type.GetType("System.String"));//交易描述
  4955. dt1.Columns.Add("TradindMoney", Type.GetType("System.String"));//交易币种/金额
  4956. dt1.Columns.Add("ClearindMoney", Type.GetType("System.String"));// 清算币种/金额
  4957. dt1.Columns.Add("TeamRemark", Type.GetType("System.String")); //团组备注描述
  4958. dt1.Columns.Add("Handlers", Type.GetType("System.String")); //经手人
  4959. dt1.Columns.Add("State", Type.GetType("System.String")); //状态
  4960. for (int i = 0; i < dt.Rows.Count; i++)
  4961. {
  4962. string[] str = dt.Rows[i]["All"].ToString().Split(' ');
  4963. //string[] str = dt.Rows[i];
  4964. var dr = dt1.NewRow();
  4965. dr["TradingDate"] = str[0].ToString();
  4966. dr["TallyDate"] = str[1].ToString();
  4967. dr["TradindDesc"] = str[2].ToString() + " " + str[3].ToString();
  4968. dr["TradindMoney"] = str[4].ToString() + " " + str[5].ToString();
  4969. dr["ClearindMoney"] = str[6].ToString() + " " + str[7].ToString();
  4970. dt1.Rows.Add(dr);
  4971. }
  4972. foreach (DataRow item in dt1.Rows)
  4973. {
  4974. for (int i = 0; i < List_ccp.Count; i++)
  4975. {
  4976. DateTime dtTime1 = Convert.ToDateTime(item["TradingDate"].ToString() == "" ? DateTime.Now.ToString("MM/dd") : item["TradingDate"].ToString()); //交易日期
  4977. string USDPrice = item["TradindMoney"].ToString(); //支出金额
  4978. USDPrice = USDPrice.Split(' ')[1].Trim(); //替换掉非数字
  4979. //USDPrice = USDPrice.Split('/')[1];
  4980. // 经手人 and excel行状态
  4981. if (!string.IsNullOrEmpty(List_ccp[i].ConsumptionDate) && !string.IsNullOrEmpty(USDPrice))
  4982. {
  4983. DateTime dtTime2 = Convert.ToDateTime(List_ccp[i].ConsumptionDate.ToString() == "" ? DateTime.Now.ToString("MM/dd") : List_ccp[i].ConsumptionDate.ToString());
  4984. float price1 = float.Parse(USDPrice);
  4985. float price2 = float.Parse(List_ccp[i].PayMoney.ToString("F2"));
  4986. if (dtTime1 == dtTime2 && price1 == price2)
  4987. {
  4988. item["TeamRemark"] = delegationInfos.Find(it => it.Id == List_ccp[i].DIId)?.TeamName;
  4989. item["Handlers"] = users.Find(it => it.Id == List_ccp[i].CreateUserId)?.CnName;
  4990. item["State"] = "1";
  4991. i = List_ccp.Count - 1;
  4992. }
  4993. else item["State"] = "0";
  4994. }
  4995. else item["State"] = "0";
  4996. }
  4997. if (item["TradindDesc"].ToString().Contains("财付通"))
  4998. item["State"] = "2";
  4999. else if (item["TradindDesc"].ToString().Contains("京东"))
  5000. item["State"] = "2";
  5001. else if (item["TradindDesc"].ToString().Contains("微信支付"))
  5002. item["State"] = "2";
  5003. else if (item["TradindDesc"].ToString().Contains("淘宝"))
  5004. item["State"] = "2";
  5005. }
  5006. string fileName1 = $"信用卡账单(欧元卡){DateTime.Now:yyyy.MM.dd}.xls";
  5007. var pairs = new Dictionary<string, object>();
  5008. var datas = new List<DataTable>
  5009. {
  5010. dt
  5011. };
  5012. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-欧元卡.xls", "TB", fileName1, pairs, datas);
  5013. }
  5014. else if (cardType == 86) //招行卡
  5015. {
  5016. var AirGroupReuslt1 = List_ccp.Where(x => x.CTable == 85).GroupBy(x => x.DIId).ToList();
  5017. if (AirGroupReuslt1 != null && AirGroupReuslt1.Count > 0)
  5018. {
  5019. foreach (var item in AirGroupReuslt1)
  5020. {
  5021. if (item.Count() > 1)
  5022. {
  5023. var di = delegationInfos.Find(it => it.Id == item.Key);
  5024. var obj = item.FirstOrDefault();
  5025. obj.Remark = "团组机票总价";
  5026. if (di != null)
  5027. {
  5028. obj.Remark = "团组机票总价(" + di.TeamName + ")";
  5029. }
  5030. obj.RMBPrice = item.Sum(x => x.RMBPrice);//合计人民币
  5031. List_ccp.Add(obj);
  5032. }
  5033. }
  5034. }
  5035. //查询所有刷卡的团组
  5036. //将刷卡团组内刷卡金额的金额存入ccp_list
  5037. //将excel作比较
  5038. //机票刷卡记录
  5039. var AirListAndPayID = List_ccp.Where(x => x.CTable == 85 && x.PayDId == 72).Select(x => x.DIId).Distinct().ToList();
  5040. var AirData = _sqlSugar.Queryable<Grp_AirTicketReservations>().Where(it => AirListAndPayID.Contains(it.DIId) && it.PrePrice != it.Price).ToList();
  5041. foreach (var item in AirData)
  5042. {
  5043. var DBwhere = List_ccp.Find(x => x.PayMoney == item.PrePrice);
  5044. if (DBwhere == null)
  5045. {
  5046. List_ccp.Add(new Grp_CreditCardPayment
  5047. {
  5048. PayMoney = item.PrePrice,
  5049. DIId = item.DIId,
  5050. CreateUserId = item.CreateUserId,
  5051. Remark = "(机票单价价格)",
  5052. });
  5053. }
  5054. }
  5055. //机票刷卡记录
  5056. var hotelGroupReuslt = hotelData.Where(x => x.CTDId == 86).GroupBy(x => x.DiId).ToList();
  5057. if (hotelGroupReuslt != null && hotelGroupReuslt.Count > 0)
  5058. {
  5059. foreach (var item in hotelGroupReuslt)
  5060. {
  5061. if (item.Count() > 0)
  5062. {
  5063. var hotelInfo = new Grp_CreditCardPayment()
  5064. {
  5065. Remark = $"团组酒店总价(" + delegationInfos.Find(it => it.Id == item.Key)?.TeamName ?? "" + ")",
  5066. RMBPrice = item.Sum(x => x.Price * x.Rate),
  5067. ConsumptionDate = item.FirstOrDefault()?.ConsumptionDate ?? ""
  5068. };
  5069. List_ccp.Add(hotelInfo);
  5070. }
  5071. }
  5072. }
  5073. #region
  5074. dt.Rows[0].Delete();//删除列名行
  5075. dt.AcceptChanges();
  5076. var dt1 = new DataTable
  5077. {
  5078. TableName = "TB"
  5079. };
  5080. dt1.Columns.Add("TradingDay", Type.GetType("System.String")); // 交易日
  5081. dt1.Columns.Add("TallyDay", Type.GetType("System.String")); // 记账日
  5082. dt1.Columns.Add("TransactionDesc", Type.GetType("System.String")); // 交易描述
  5083. dt1.Columns.Add("RMBMoney", Type.GetType("System.String")); // 人名币金额
  5084. dt1.Columns.Add("CardNo", Type.GetType("System.String")); // 卡号
  5085. dt1.Columns.Add("TradingMoney", Type.GetType("System.String")); // 交易地金额
  5086. dt1.Columns.Add("Currency", Type.GetType("System.String")); // 币种
  5087. dt1.Columns.Add("TeamRemark", Type.GetType("System.String")); //团组备注描述
  5088. dt1.Columns.Add("Handlers", Type.GetType("System.String")); //经手人
  5089. dt1.Columns.Add("State", Type.GetType("System.String")); //状态
  5090. for (int j = 0; j < dt.Rows.Count; j++)//遍历行
  5091. {
  5092. DataRow dr = dt1.NewRow(); //获取每一行的数据
  5093. var tradingDay = dt.Rows[j][0].ToString();
  5094. dr["TradingDay"] = tradingDay;
  5095. var tallyDay = dt.Rows[j][1].ToString();
  5096. dr["TallyDay"] = tallyDay;
  5097. dr["TransactionDesc"] = dt.Rows[j][2].ToString();
  5098. dr["RMBMoney"] = dt.Rows[j][3].ToString();
  5099. dr["CardNo"] = dt.Rows[j][4].ToString();
  5100. string currency = "CN";
  5101. string money = dt.Rows[j][5].ToString();
  5102. if (money.Contains('('))
  5103. {
  5104. string[] strs = money.Split('(');
  5105. money = strs[0];
  5106. currency = strs[1].Replace(")", "");
  5107. }
  5108. dr["TradingMoney"] = money;
  5109. dr["Currency"] = currency;
  5110. if (string.IsNullOrEmpty(money))
  5111. {
  5112. continue;
  5113. }
  5114. dt1.Rows.Add(dr);
  5115. }
  5116. //datatable 排序
  5117. dt1.DefaultView.Sort = "TradingDay asc";
  5118. dt1 = dt1.DefaultView.ToTable();
  5119. foreach (DataRow item in dt1.Rows)
  5120. {
  5121. if (item["TradingDay"].ToString() == "" && item["RMBMoney"].ToString() == "")
  5122. {
  5123. continue;
  5124. }
  5125. //excel获取交易日期
  5126. string ExcelDt = string.Empty;
  5127. //C表交易日期
  5128. string DBDt = string.Empty;
  5129. //excel交易的金额
  5130. decimal TradingMoney = decimal.Parse(item["TradingMoney"].ToString());
  5131. if (item["TradingDay"] != null)
  5132. {
  5133. ExcelDt = item["TradingDay"].ToString();
  5134. }
  5135. //加一获取金额区间
  5136. decimal MaxTradingMoney = TradingMoney + 1;
  5137. decimal MinTradingMoney = TradingMoney - 1;
  5138. //匹配C表金额相等的值
  5139. var CList = List_ccp.FindAll(x => x.PayMoney <= MaxTradingMoney && x.PayMoney >= MinTradingMoney);
  5140. if (CList != null && CList.Count > 0)
  5141. {
  5142. #region 日期匹配
  5143. foreach (var Citem in CList)
  5144. {
  5145. if (!string.IsNullOrWhiteSpace(Citem.ConsumptionDate))
  5146. {
  5147. DBDt = DateTime.Parse(Citem.ConsumptionDate).ToString("MM/dd");
  5148. if (DBDt.Equals(ExcelDt))
  5149. {
  5150. item["TeamRemark"] = delegationInfos.Find(it => it.Id == Citem.DIId)?.TeamName;
  5151. item["Handlers"] = users.Find(it => it.Id == Citem.CreateUserId)?.CnName;
  5152. ids.Add(Citem.Id);
  5153. }
  5154. }
  5155. }
  5156. #endregion
  5157. }
  5158. var whereRange = new List<string>() { "财付通", "京东", "微信", "淘宝", "支付宝", "拼多多" };
  5159. foreach (var where in whereRange)
  5160. {
  5161. if (item["TransactionDesc"].ToString().Contains(where)) item["State"] = "2";
  5162. else item["State"] = "0";
  5163. }
  5164. if (!string.IsNullOrEmpty(item["TeamRemark"].ToString()) && !string.IsNullOrEmpty(item["Handlers"].ToString()))
  5165. item["State"] = "1";
  5166. }
  5167. //更改匹配项状态
  5168. if (ids.Count > 0)
  5169. {
  5170. var _CreditCardPayments = new List<Grp_CreditCardPayment>();
  5171. foreach (var item in ids)
  5172. {
  5173. _CreditCardPayments.Add(new Grp_CreditCardPayment() { Id = item, IsMatchCreditCard = 1.00M });
  5174. }
  5175. var updateStatus = _sqlSugar.Updateable<Grp_CreditCardPayment>(_CreditCardPayments)
  5176. .UpdateColumns(it => new { it.IsMatchCreditCard })
  5177. .Where(it => ids.Contains(it.Id))
  5178. .ExecuteCommand();
  5179. }
  5180. string fileName1 = $"信用卡账单(招行卡){DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  5181. var pairs = new Dictionary<string, object>();
  5182. var datas = new List<DataTable>
  5183. {
  5184. dt1
  5185. };
  5186. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-招行卡.xls", "CreditCardBill", fileName1, pairs, datas);
  5187. #endregion
  5188. }
  5189. else if (cardType == 346) //中信卡
  5190. {
  5191. dt.Columns.Add("TeamRemark", Type.GetType("System.String")); //团组备注描述
  5192. dt.Columns.Add("Handlers", Type.GetType("System.String")); //经手人
  5193. dt.Columns.Add("State", Type.GetType("System.String")); //状态
  5194. //修改table列名
  5195. dt.Columns[0].ColumnName = "TransactionDesc"; // 交易描述
  5196. dt.Columns[1].ColumnName = "TradingCurrencyAndMoney"; // 交易币种和金额
  5197. dt.Columns[2].ColumnName = "TransactionDate"; // 交易日期
  5198. dt.Columns[3].ColumnName = "SettlementCurrencyAndMoney";// 结算币种和金额
  5199. dt.Columns[4].ColumnName = "BookedDate"; // 入账日期
  5200. foreach (DataRow item in dt.Rows)
  5201. {
  5202. for (int i = 0; i < List_ccp.Count; i++)
  5203. {
  5204. if (string.IsNullOrEmpty(item["TransactionDate"].ToString()))
  5205. break;
  5206. DateTime dtTime1 = Convert.ToDateTime(item["TransactionDate"].ToString()); //交易日期
  5207. string USDPrice = item["TradingCurrencyAndMoney"].ToString(); //支出金额
  5208. USDPrice = USDPrice.Split('/')[1];
  5209. //string USDPrice1 = USDPrice.ToString("0.00");
  5210. // 经手人 and excel行状态
  5211. if (!string.IsNullOrEmpty(List_ccp[i].ConsumptionDate) && !string.IsNullOrEmpty(USDPrice))
  5212. {
  5213. DateTime dtTime2 = Convert.ToDateTime(List_ccp[i].ConsumptionDate);
  5214. float price1 = float.Parse(USDPrice);
  5215. float price2 = float.Parse(List_ccp[i].PayMoney.ToString("F2"));
  5216. if (dtTime1 == dtTime2 && price1 == price2)
  5217. {
  5218. item["TeamRemark"] = delegationInfos.Find(it => it.Id == List_ccp[i].DIId)?.TeamName;
  5219. item["Handlers"] = users.Find(it => it.Id == List_ccp[i].CreateUserId)?.CnName;
  5220. item["State"] = "1";
  5221. i = List_ccp.Count - 1;
  5222. }
  5223. else
  5224. item["State"] = "0";
  5225. }
  5226. else
  5227. item["State"] = "0";
  5228. }
  5229. //判断是否是数字
  5230. //if (IsNumber(item["TradingCurrencyAndMoney"].ToString().Split('/')[1]) == false)
  5231. // item["State"] = "0";
  5232. if (item["TransactionDesc"].ToString().Contains("财付通"))
  5233. item["State"] = "2";
  5234. else if (item["TransactionDesc"].ToString().Contains("京东"))
  5235. item["State"] = "2";
  5236. else if (item["TransactionDesc"].ToString().Contains("微信支付"))
  5237. item["State"] = "2";
  5238. else if (item["TransactionDesc"].ToString().Contains("淘宝"))
  5239. item["State"] = "2";
  5240. }
  5241. #region DownExcel
  5242. string fileName1 = $"信用卡账单(中信卡){DateTime.Now:yyyy.MM.dd}.xls";
  5243. var pairs = new Dictionary<string, object>();
  5244. var datas = new List<DataTable>
  5245. {
  5246. dt
  5247. };
  5248. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-中信卡.xls", "TB", fileName1, pairs, datas);
  5249. #endregion
  5250. }
  5251. else if (cardType == 363) //交行卡
  5252. {
  5253. dt.Columns[0].ColumnName = "All";
  5254. var dt1 = new DataTable();
  5255. dt1.Columns.Add("TradingDate", Type.GetType("System.String"));//交易日期
  5256. dt1.Columns.Add("TallyDate", Type.GetType("System.String")); //记账日期
  5257. dt1.Columns.Add("TradindDesc", Type.GetType("System.String"));//交易描述
  5258. dt1.Columns.Add("TradindMoney", Type.GetType("System.String"));//交易币种/金额
  5259. dt1.Columns.Add("ClearindMoney", Type.GetType("System.String"));// 清算币种/金额
  5260. dt1.Columns.Add("TeamRemark", Type.GetType("System.String")); //团组备注描述
  5261. dt1.Columns.Add("Handlers", Type.GetType("System.String")); //经手人
  5262. dt1.Columns.Add("State", Type.GetType("System.String")); //状态
  5263. for (int i = 0; i < dt.Rows.Count; i++)
  5264. {
  5265. string[] str = dt.Rows[i]["All"].ToString().Split(' ');
  5266. DataRow dr = dt1.NewRow();
  5267. dr["TradingDate"] = str[0].ToString();
  5268. dr["TallyDate"] = str[1].ToString();
  5269. dr["TradindDesc"] = str[2].ToString() + " " + str[3].ToString();
  5270. dr["TradindMoney"] = str[4].ToString() + " " + str[5].ToString();
  5271. dr["ClearindMoney"] = str[6].ToString() + " " + str[7].ToString();
  5272. dt1.Rows.Add(dr);
  5273. }
  5274. foreach (DataRow item in dt1.Rows)
  5275. {
  5276. for (int i = 0; i < List_ccp.Count; i++)
  5277. {
  5278. DateTime dtTime1 = Convert.ToDateTime(item["TradingDate"].ToString() == "" ? DateTime.Now.ToString("MM/dd") : item["TradingDate"].ToString()); //交易日期
  5279. string USDPrice = item["TradindMoney"].ToString(); //支出金额
  5280. USDPrice = USDPrice.Split(' ')[1].Trim(); //替换掉非数字
  5281. //USDPrice = USDPrice.Split('/')[1];
  5282. // 经手人 and excel行状态
  5283. if (!string.IsNullOrEmpty(List_ccp[i].ConsumptionDate) && !string.IsNullOrEmpty(USDPrice))
  5284. {
  5285. DateTime dtTime2 = Convert.ToDateTime(List_ccp[i].ConsumptionDate.ToString() == "" ? DateTime.Now.ToString("MM/dd") : List_ccp[i].ConsumptionDate.ToString());
  5286. float price1 = float.Parse(USDPrice);
  5287. float price2 = float.Parse(List_ccp[i].PayMoney.ToString("F2"));
  5288. if (dtTime1 == dtTime2 && price1 == price2)
  5289. {
  5290. item["TeamRemark"] = delegationInfos.Find(it => it.Id == List_ccp[i].DIId)?.TeamName;
  5291. item["Handlers"] = users.Find(it => it.Id == List_ccp[i].CreateUserId)?.CnName;
  5292. item["State"] = "1";
  5293. i = List_ccp.Count - 1;
  5294. }
  5295. else
  5296. item["State"] = "0";
  5297. }
  5298. else
  5299. item["State"] = "0";
  5300. }
  5301. if (item["TradindDesc"].ToString().Contains("财付通"))
  5302. item["State"] = "2";
  5303. else if (item["TradindDesc"].ToString().Contains("京东"))
  5304. item["State"] = "2";
  5305. else if (item["TradindDesc"].ToString().Contains("微信支付"))
  5306. item["State"] = "2";
  5307. else if (item["TradindDesc"].ToString().Contains("淘宝"))
  5308. item["State"] = "2";
  5309. }
  5310. string fileName1 = $"信用卡账单(交行卡){DateTime.Now:yyyy.MM.dd}.xls";
  5311. var pairs = new Dictionary<string, object>();
  5312. var datas = new List<DataTable>
  5313. {
  5314. dt
  5315. };
  5316. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-交行卡.xls", "TB", fileName1, pairs, datas);
  5317. }
  5318. }
  5319. catch (Exception ex)
  5320. {
  5321. return Ok(JsonView(false, $"匹配失败,{ex.Message}!"));
  5322. }
  5323. return Ok(JsonView(true, "操作成功", new { url }));
  5324. }
  5325. /// <summary>
  5326. /// 把数据从Excel装载到DataTable
  5327. /// </summary>
  5328. /// <param name="pathName">带路径的Excel文件名</param>
  5329. /// <param name="sheetName">工作表名</param>
  5330. /// <returns></returns>
  5331. public static DataTable ExcelToDataTable(string pathName, string sheetName = "")
  5332. {
  5333. var tbContainer = new DataTable();
  5334. string strConn = string.Empty;
  5335. if (string.IsNullOrEmpty(sheetName)) { sheetName = "Sheet1"; }
  5336. var file = new FileInfo(pathName);
  5337. if (!file.Exists) { throw new Exception("文件不存在"); }
  5338. string extension = file.Extension;
  5339. strConn = extension switch
  5340. {
  5341. ".xls" => "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'",
  5342. ".xlsx" => "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'",
  5343. _ => "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'",
  5344. };
  5345. //链接Excel
  5346. var cnnxls = new OleDbConnection(strConn);
  5347. //读取Excel里面有 表Sheet1
  5348. var oda = new System.Data.OleDb.OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
  5349. //将Excel里面有表内容装载到内存表中!
  5350. oda.Fill(tbContainer);
  5351. return tbContainer;
  5352. }
  5353. #endregion
  5354. #region 提成计算
  5355. /// <summary>
  5356. /// 提成计算
  5357. /// </summary>
  5358. /// <param name="dto"></param>
  5359. /// <returns></returns>
  5360. [HttpPost]
  5361. public IActionResult ComputeRoyalties(ComputeRoyaltiesDto dto)
  5362. {
  5363. var jw = JsonView(false);
  5364. var userId = dto.UserId;
  5365. var user = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == userId);
  5366. //jw.Data = System.Array.Empty<string>();
  5367. if (user == null)
  5368. {
  5369. jw.Msg = "暂无该用户!";
  5370. return Ok(jw);
  5371. }
  5372. if (!DateTime.TryParse(dto.StartDate, out DateTime StartDateTime))
  5373. {
  5374. jw.Msg = "开始时间格式有误!";
  5375. return Ok(jw);
  5376. }
  5377. if (!DateTime.TryParse(dto.EndDate, out DateTime EndDateTime))
  5378. {
  5379. jw.Msg = "结束时间格式有误!";
  5380. return Ok(jw);
  5381. }
  5382. if (DateTime.Compare(StartDateTime, EndDateTime) > 0)
  5383. {
  5384. jw.Msg = "开始时间大于结束时间!";
  5385. return Ok(jw);
  5386. }
  5387. int[] jobPostIds = { 24, 25, 26, 27, 28 };
  5388. var userGroups = _sqlSugar.Queryable<Sys_Users>()
  5389. .Where(x => x.IsDel == 0 && jobPostIds.Contains(x.JobPostId))
  5390. .Select(x => new { x.Id, x.JobPostId })
  5391. .ToArray()
  5392. .GroupBy(x => x.JobPostId)
  5393. .ToDictionary(g => g.Key, g => g.Select(x => x.Id).ToArray());
  5394. int[] AirTicket = userGroups.ContainsKey(24) ? userGroups[24] : Array.Empty<int>();
  5395. int[] Hotel = userGroups.ContainsKey(25) ? userGroups[25] : Array.Empty<int>();
  5396. int[] OP = userGroups.ContainsKey(28) ? userGroups[28] : Array.Empty<int>();
  5397. int[] Invitation = userGroups.ContainsKey(27) ? userGroups[27] : Array.Empty<int>();
  5398. int[] Visa = userGroups.ContainsKey(26) ? userGroups[26] : Array.Empty<int>();
  5399. //主管职位
  5400. //string[] Manager = { "149", "283" };
  5401. List<ComputeRoyaltiesView> resultArr = new List<ComputeRoyaltiesView>();
  5402. var teamLv = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.STid == 56 && x.IsDel == 0).ToList();
  5403. var auditState = new int[] { 1, 3 };
  5404. if (AirTicket.Contains(userId))
  5405. {
  5406. //提成方式:¥10/人×人数×段数(每个组团涉及的换机次数)
  5407. var listAir = _sqlSugar.Queryable<Grp_AirTicketReservations, Grp_DelegationInfo, Grp_CreditCardPayment>((x, a, b) => new
  5408. JoinQueryInfos(
  5409. JoinType.Left, a.Id == x.DIId,
  5410. JoinType.Left, b.CTable == 85 && b.CId == x.Id)
  5411. )
  5412. .Where((x, a, b) => x.IsDel == 0 && x.CreateUserId == userId && a.IsDel == 0 && a.VisitDate >= StartDateTime
  5413. && a.VisitDate <= EndDateTime && b.IsDel == 0 && auditState.Contains(b.IsAuditGM)) // 取消团组确认状态 && a.IsSure == 1
  5414. .Select((x, a, b) => new
  5415. {
  5416. x.FlightsDescription,
  5417. a.Id,
  5418. a.TeamName,
  5419. a.VisitDate,
  5420. a.TeamLevSId,
  5421. a.VisitPNumber,
  5422. x.Price,
  5423. x.ClientName,
  5424. x.ClientNum,
  5425. x.FlightsCode,
  5426. a.IsSure
  5427. })
  5428. .ToList();
  5429. var groupByid = listAir.GroupBy(x => x.Id);
  5430. foreach (var airArr in groupByid)
  5431. {
  5432. var groupAirCount = 0; //团组航段数量
  5433. var infos = new List<string>();
  5434. foreach (var air in airArr)
  5435. {
  5436. var airCount = 0; // 单条航段数量
  5437. if (air.FlightsDescription.IsNullOrWhiteSpace())
  5438. {
  5439. continue;
  5440. }
  5441. if (air.ClientName.Contains("-1") || air.ClientName.Contains("行程单") || air.FlightsCode.Contains("行程单"))
  5442. {
  5443. continue;
  5444. }
  5445. string errMsg = string.Empty;
  5446. if (air.FlightsDescription.Contains("\r\n") || Regex.Split(air.FlightsDescription, "\\d+\\.", RegexOptions.IgnoreCase).Length > 1)
  5447. {
  5448. var rowCode = Regex.Split(air.FlightsDescription, "\\d+\\.", RegexOptions.IgnoreCase).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
  5449. for (int i = 0; i < rowCode.Length; i++)
  5450. {
  5451. if (i != 0)
  5452. {
  5453. try
  5454. {
  5455. var columnValue = rowCode[i].Split(' ').Where(x => !string.IsNullOrEmpty(x)).ToList();
  5456. string day = columnValue[2].Substring(2, 2);//日
  5457. string monthAbbreviations = columnValue[2].Substring(4, 3).ToUpper();//月份
  5458. monthAbbreviations = GeneralMethod.GetLonger(monthAbbreviations);
  5459. string EndHHmm = columnValue[5].Substring(0, 2) + ":" + columnValue[5].Substring(2, 2);
  5460. DateTime EndData = DateTime.Parse($"{DateTime.Now.Year}-{monthAbbreviations}-{day} {EndHHmm}");//当前班次
  5461. var spDotandEmpty1 = rowCode[i - 1].Split(' ').Where(x => !string.IsNullOrEmpty(x)).ToList();
  5462. string day1 = spDotandEmpty1[2].Substring(2, 2);//日
  5463. string monthAbbreviations1 = spDotandEmpty1[2].Substring(4, 3).ToUpper();//月份
  5464. monthAbbreviations1 = GeneralMethod.GetLonger(monthAbbreviations1);
  5465. string HHmm = spDotandEmpty1[6].Substring(0, 2) + ":" + spDotandEmpty1[6].Substring(2, 2);
  5466. DateTime data = DateTime.Parse($"{DateTime.Now.Year}-{monthAbbreviations1}-{day1} {HHmm}");//上个班次
  5467. TimeSpan t3 = EndData - data; //两个时间相减 。默认得到的是 两个时间之间的天数 得到:365.00:00:00
  5468. double getHour = t3.TotalHours;
  5469. if (getHour >= 6)
  5470. {
  5471. if (air.Price > 0)
  5472. {
  5473. airCount += 1;
  5474. }
  5475. else
  5476. {
  5477. airCount -= 1;
  5478. }
  5479. }
  5480. }
  5481. catch (Exception ex)
  5482. {
  5483. errMsg = "机票行程代码格式有误!解析失败!" + $"({ex.Message})";
  5484. break;
  5485. }
  5486. }
  5487. else
  5488. {
  5489. if (air.Price > 0)
  5490. {
  5491. airCount += 1;
  5492. }
  5493. else
  5494. {
  5495. airCount -= 1;
  5496. }
  5497. }
  5498. }
  5499. }
  5500. else
  5501. {
  5502. if (air.Price > 0)
  5503. {
  5504. airCount++;
  5505. }
  5506. else
  5507. {
  5508. airCount--;
  5509. }
  5510. }
  5511. string info = $"航班{air.FlightsCode} {(air.Price > 0 ? "" : "此笔为退费!")} 人数为{air.ClientNum} 有效段数为{airCount} 总段数为{airCount * air.ClientNum}";
  5512. if (!string.IsNullOrWhiteSpace(errMsg))
  5513. {
  5514. info = $"航班{air.FlightsCode} " + errMsg;
  5515. }
  5516. infos.Add(info);
  5517. groupAirCount += airCount * air.ClientNum;
  5518. }
  5519. var groupinfo = listAir.First(x => x.Id == airArr.Key);
  5520. string temp = "本团人数" + Convert.ToInt32(groupinfo.VisitPNumber) + ",该人员" + user.CnName + "共订航段数" + groupAirCount.ToString() + ",每程航班提成为10元," + user.CnName + "提成共" + (groupAirCount * 10).ToString("#0.00");
  5521. resultArr.Add(new ComputeRoyaltiesView
  5522. {
  5523. TeamName = groupinfo.TeamName,
  5524. TeamId = groupinfo.Id,
  5525. ChiArr = infos,
  5526. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  5527. VisitDate = groupinfo.VisitDate,
  5528. Temp = temp,
  5529. Price = (groupAirCount * 10),
  5530. State = groupinfo.IsSure
  5531. });
  5532. }
  5533. }
  5534. else if (Hotel.Contains(userId))
  5535. {
  5536. //标准团组:¥10/间/晚 * 实际订房间数 * 实际订房晚数; setdata id 1001 客人房
  5537. var listHotel = _sqlSugar.Queryable<Grp_HotelReservations, Grp_DelegationInfo, Grp_CreditCardPayment>((x, a, b) => new JoinQueryInfos(
  5538. JoinType.Left, x.DiId == a.Id,
  5539. JoinType.Left, b.CTable == 76 && b.CId == x.Id))
  5540. .Where((x, a, b) => x.IsDel == 0 && x.CreateUserId == userId && a.VisitDate >= StartDateTime
  5541. && a.VisitDate <= EndDateTime && a.IsDel == 0 && b.IsDel == 0 && x.CardPrice != 0 && auditState.Contains(b.IsAuditGM) && x.CheckType == 1001)
  5542. .Select((x, a, b) => new // && a.IsSure == 1
  5543. {
  5544. a.Id,
  5545. a.TeamName,
  5546. a.VisitDate,
  5547. a.TeamLevSId,
  5548. a.VisitPNumber,
  5549. x.SingleRoomCount,
  5550. x.SuiteRoomCount,
  5551. x.DoubleRoomCount,
  5552. x.OtherRoomCount,
  5553. x.CheckInDate,
  5554. x.CheckOutDate,
  5555. x.HotelName,
  5556. a.IsSure
  5557. })
  5558. .ToList();
  5559. var groupByid = listHotel.GroupBy(x => x.Id);
  5560. var propertys = new string[] { "SingleRoomCount", "SuiteRoomCount", "DoubleRoomCount", "OtherRoomCount" };
  5561. foreach (var group in groupByid)
  5562. {
  5563. var infos = new List<string>();
  5564. var totalPrice = 0.00M;
  5565. foreach (var item in group)
  5566. {
  5567. var hotelCount = 0;
  5568. foreach (var property in propertys)
  5569. {
  5570. var value = item.GetType().GetProperty(property).GetValue(item).ObjToInt();
  5571. if (value > 0)
  5572. {
  5573. hotelCount += value;
  5574. }
  5575. }
  5576. if (hotelCount > 0)
  5577. {
  5578. if (DateTime.TryParse(item.CheckInDate, out DateTime checkin) && DateTime.TryParse(item.CheckOutDate, out DateTime checkout))
  5579. {
  5580. var day = checkout - checkin;
  5581. infos.Add($"{item.HotelName} 共有 {hotelCount} 间房 , 入住时间{item.CheckInDate} - {item.CheckOutDate} 共 {day.TotalDays}晚 提成数量:{hotelCount * day.TotalDays} 提成金额:{hotelCount * day.TotalDays * 10}");
  5582. totalPrice += (decimal)(hotelCount * day.TotalDays * 10);
  5583. }
  5584. else
  5585. {
  5586. infos.Add(item.HotelName + " 时间有误!请检查 。");
  5587. }
  5588. }
  5589. }
  5590. var groupinfo = listHotel.First(x => x.Id == group.Key);
  5591. var temp = "本团人数" + groupinfo.VisitPNumber + ",该人员" + user.CnName + "共操作酒店晚数" + totalPrice / 10 + ",每间每晚提成10元," + user.CnName + "提成共" + totalPrice.ToString("#0.00") + "元";
  5592. resultArr.Add(new ComputeRoyaltiesView
  5593. {
  5594. TeamName = groupinfo.TeamName,
  5595. TeamId = groupinfo.Id,
  5596. ChiArr = infos,
  5597. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  5598. VisitDate = groupinfo.VisitDate,
  5599. Temp = temp,
  5600. Price = totalPrice,
  5601. State = groupinfo.IsSure,
  5602. });
  5603. }
  5604. }
  5605. else if (OP.Contains(userId))
  5606. {
  5607. var OPList = _sqlSugar.Queryable<Grp_DelegationInfo>()
  5608. .Where((a) => a.IsDel == 0 && a.VisitDate >= StartDateTime && a.VisitDate <= EndDateTime)
  5609. .ToList(); // && a.IsSure == 1
  5610. var LvArr = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.STid == 70 && x.IsDel == 0).ToList();
  5611. foreach (var groupinfo in OPList)
  5612. {
  5613. var price = LvArr.Find(x => x.Id == groupinfo.OpRoyaltyLv)?.Name.ObjToInt() ?? 0;
  5614. string temp = $"本团等级为{teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name} 提成金额为{price} {(string.IsNullOrWhiteSpace(groupinfo.OpRoyaltyRemark) ? "" : "提成说明:" + groupinfo.OpRoyaltyRemark)}";
  5615. if (price == 0)
  5616. {
  5617. temp = $"本团等级为{teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name} op提成选项未选择!";
  5618. }
  5619. resultArr.Add(new ComputeRoyaltiesView
  5620. {
  5621. TeamName = groupinfo.TeamName,
  5622. TeamId = groupinfo.Id,
  5623. ChiArr = new List<string>() { temp },
  5624. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  5625. VisitDate = groupinfo.VisitDate,
  5626. Temp = temp,
  5627. Price = price,
  5628. State = groupinfo.IsSure,
  5629. });
  5630. }
  5631. }
  5632. else if (Invitation.Contains(userId))
  5633. {
  5634. //2)付费公务活动部分:¥50 / 团;
  5635. //4)不付费公务活动部分(自己联络)额外奖励:¥200 / 团(若公务活动方与邀请方为同一机构,奖励金额为¥100 / 团);
  5636. //5)只发邀请的团组不付费邀请额外奖励:¥100 / 团;
  5637. //邀请方已授权我司签发的邀请仍按照:¥100 / 团,无额外奖励。
  5638. const int payingOfficial = 50; // 付费单公务 50
  5639. const int notPayingOfficial = 200; // 不付费单场公务 200
  5640. const int payInvitation = 100; // 付费单邀请函 100元 / 份 一个国家只发放一份邀请函费用
  5641. const int notpayInvitation = 400; // 不付费邀请函 400 / 份 一个国家只发放一份邀请函费用,多拿的邀请函不进行叠加
  5642. //不付费邀请函 400 / 份 一个国家只发放一份邀请函费用,多拿的邀请函不进行叠加
  5643. //不付费单场公务 200 / 场 / 团 按照标准公务完成要求,确认实际场数
  5644. //付费单邀请函 100元 / 份 一个国家只发放一份邀请函费用
  5645. //付费单公务 50 / 场 / 团 按照标准公务完成要求,确认实际场数
  5646. //客户报批内容涉及的调研 / 参观性质点位 50 / 场 / 团 需提供给客户有效联系方式、点位地址等符合有效公务完成标准。每个国家原则上不超过2场(特殊增加场次以客户要求制定),超出部分,公司不发放提成。
  5647. var officialList = _sqlSugar.Queryable<Res_OfficialActivities, Grp_DelegationInfo>((x, a) => new JoinQueryInfos(JoinType.Left, a.Id == x.DiId))
  5648. .Where((x, a) => x.IsSubmitApproval == 0 && x.IsDel == 0 && a.IsDel == 0
  5649. && a.VisitDate >= StartDateTime && a.VisitDate <= EndDateTime // && a.IsSure == 1
  5650. && x.CreateUserId == userId && x.DataSource != 1335) //客人不提成
  5651. .Select((x, a) => new
  5652. {
  5653. a.Id,
  5654. a.TeamName,
  5655. a.VisitDate,
  5656. x.CreateUserId,
  5657. x.Type,
  5658. a.TeamLevSId,
  5659. x.Country,
  5660. x.Area,
  5661. x.Date,
  5662. x.Client,
  5663. a.IsSure,
  5664. x.IsPay, // 是否付费
  5665. a.VisitPNumber,
  5666. x.OfficialForm,
  5667. })
  5668. .ToList();
  5669. var groups = officialList.GroupBy(x => x.Id);
  5670. foreach (var group in groups)
  5671. {
  5672. var groupinfo = officialList.First(x => x.Id == group.Key);
  5673. string temp = string.Empty;
  5674. var money = 0;
  5675. var infos = new List<string>();
  5676. var existsCountry = new List<string>(); //邀请函国家判断
  5677. foreach (var item in group)
  5678. {
  5679. if (item.OfficialForm == 1338 || item.OfficialForm == 384) // 调研 / 参观性质点位 50 / 场 / 团
  5680. {
  5681. infos.Add($"{item.Client}为调研 / 参观性质点位,提成金额为50");
  5682. money += 50;
  5683. continue;
  5684. }
  5685. //0带公务 1不带公务 2纯公务
  5686. //1082 带公务
  5687. //1083 不带公务
  5688. //1084 纯公务
  5689. if (item.Type == 0 || item.Type == 1082)
  5690. {
  5691. if (!existsCountry.Contains(item.Country))
  5692. {
  5693. if (item.IsPay == 1) //付费邀请函
  5694. {
  5695. infos.Add($"{item.Client} 为付费邀请函,提成金额为 {payInvitation}");
  5696. money += payingOfficial;
  5697. }
  5698. else
  5699. {
  5700. infos.Add($"{item.Client} 为非付费邀请函,提成金额为 {notpayInvitation}");
  5701. money += notPayingOfficial;
  5702. }
  5703. }
  5704. }
  5705. else if (item.Type == 2 || item.Type == 1084)
  5706. {
  5707. if (item.IsPay == 1) //付费公务
  5708. {
  5709. infos.Add($"{item.Client} 为付费公务,提成金额为 {payingOfficial}");
  5710. money += payingOfficial;
  5711. }
  5712. else
  5713. {
  5714. infos.Add($"{item.Client} 为非付费公务,提成金额为 {notPayingOfficial}");
  5715. money += notPayingOfficial;
  5716. }
  5717. }
  5718. }
  5719. temp = "本团人数" + groupinfo.VisitPNumber + ",该人员" + user.CnName + "共操作公务数" + group.Count() + $",付费公务提成金额为{payingOfficial}" + $",非付费公务提成金额为{notPayingOfficial}," + user.CnName + "提成共" + money + "元"; ;
  5720. resultArr.Add(new ComputeRoyaltiesView
  5721. {
  5722. TeamName = groupinfo.TeamName,
  5723. TeamId = groupinfo.Id,
  5724. ChiArr = infos,
  5725. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  5726. VisitDate = groupinfo.VisitDate,
  5727. Temp = temp,
  5728. Price = money,
  5729. State = groupinfo.IsSure,
  5730. });
  5731. }
  5732. }
  5733. else if (Visa.Contains(userId)) //签证
  5734. {
  5735. // 1)办理英国、加拿大、美国签证¥50元 / 人 / 团;
  5736. // 申根国家及其他所有国家¥30元 / 人 / 团;
  5737. // setdata id 974 客人
  5738. var existsCountry = new string[] { "英国", "加拿大", "美国" };
  5739. var whereExpression = Expressionable.Create<Grp_VisaInfo, Grp_DelegationInfo, Grp_CreditCardPayment>()
  5740. .And(
  5741. (x, a, b) => x.IsDel == 0 && x.CreateUserId == userId && (b.IsAuditGM == 1 || b.IsAuditGM == 3)
  5742. && a.IsDel == 0 && a.VisitDate >= StartDateTime && a.VisitDate <= EndDateTime
  5743. && b.IsDel == 0 && x.IsThird == 0 && x.PassengerType == 974
  5744. && auditState.Contains(b.IsAuditGM) // && a.IsSure == 1
  5745. );
  5746. var listVisa = _sqlSugar.Queryable<Grp_VisaInfo, Grp_DelegationInfo, Grp_CreditCardPayment>((x, a, b) => new
  5747. JoinQueryInfos(
  5748. JoinType.Left, a.Id == x.DIId,
  5749. JoinType.Left, b.CTable == 80 && b.CId == x.Id)
  5750. )
  5751. .Where(whereExpression.ToExpression())
  5752. .Select((x, a, b) => new
  5753. {
  5754. a.Id,
  5755. a.TeamName,
  5756. a.VisitDate,
  5757. a.TeamLevSId,
  5758. a.VisitPNumber,
  5759. a.VisitCountry,
  5760. x.VisaDescription,
  5761. x.VisaFreeNumber,
  5762. x.VisaNumber,
  5763. x.VisaPrice,
  5764. a.IsSure,
  5765. })
  5766. .ToList();
  5767. var groupByid = listVisa.GroupBy(x => x.Id);
  5768. foreach (var visaArr in groupByid)
  5769. {
  5770. var groupinfo = listVisa.First(x => x.Id == visaArr.Key);
  5771. var singlePrice = existsCountry.Where(x => groupinfo.VisitCountry.Contains(x)).Count() > 0 ? 50 : 30;
  5772. int count = 0, money = 0;
  5773. var arr = new List<string>();
  5774. foreach (var visa in visaArr)
  5775. {
  5776. if (visa.VisaPrice > 0)
  5777. {
  5778. count += visa.VisaFreeNumber + visa.VisaNumber;
  5779. money += singlePrice * (visa.VisaFreeNumber + visa.VisaNumber);
  5780. }
  5781. else
  5782. {
  5783. count -= visa.VisaFreeNumber + visa.VisaNumber;
  5784. money -= singlePrice * (visa.VisaFreeNumber + visa.VisaNumber);
  5785. }
  5786. string info = $"签证 {visa.VisaDescription} {(visa.VisaPrice > 0 ? "" : "此笔为退费!")} 人数为{visa.VisaFreeNumber + visa.VisaNumber} 单价为{singlePrice} 金额为{singlePrice * (visa.VisaFreeNumber + visa.VisaNumber)}";
  5787. arr.Add(info);
  5788. }
  5789. string temp = "本团人数" + groupinfo.VisitPNumber + ",该人员" + user.CnName + "共办理英国、加拿大、美国签证" + (singlePrice == 50 ? count : 0).ToString() + "本护照(包含免签人员),申根国家及其他所有国家" + (singlePrice == 30 ? count : 0).ToString() + "本。" + user.CnName + "提成共" + money.ToString("#0.00") + "元";
  5790. resultArr.Add(new ComputeRoyaltiesView
  5791. {
  5792. TeamName = groupinfo.TeamName,
  5793. TeamId = groupinfo.Id,
  5794. ChiArr = arr,
  5795. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  5796. VisitDate = groupinfo.VisitDate,
  5797. Temp = temp,
  5798. Price = money,
  5799. State = groupinfo.IsSure,
  5800. });
  5801. }
  5802. }
  5803. if (resultArr.Count > 0)
  5804. {
  5805. jw.Code = 200;
  5806. jw.Msg = "success!";
  5807. decimal total = 0;
  5808. foreach (var item in resultArr)
  5809. {
  5810. //var number = item.GetType().GetProperty("price")?.GetValue(item)?.ToString();
  5811. //total += decimal.TryParse(number,out decimal numberInt) ? numberInt : 0.00M;
  5812. total += item.Price;
  5813. }
  5814. jw.Data = new
  5815. {
  5816. resultArr,
  5817. totalPrice = total,
  5818. };
  5819. }
  5820. else
  5821. {
  5822. jw.Msg = "暂无数据!";
  5823. }
  5824. return Ok(jw);
  5825. }
  5826. /// <summary>
  5827. /// 导出提成表格
  5828. /// </summary>
  5829. /// <returns></returns>
  5830. [HttpPost]
  5831. public IActionResult ExportRoyaltyExcel(ExportRoyaltyExcelDto dto)
  5832. {
  5833. var jw = JsonView(false);
  5834. var apiResult = ComputeRoyalties(new
  5835. ComputeRoyaltiesDto
  5836. {
  5837. EndDate = dto.EndDate,
  5838. StartDate = dto.StartDate,
  5839. UserId = dto.UserId,
  5840. });
  5841. var parseApiResult = ((apiResult as OkObjectResult)?.Value) as OASystem.Domain.ViewModels.JsonView;
  5842. if (parseApiResult != null && parseApiResult.Code == 200)
  5843. {
  5844. var apiArr = (parseApiResult.Data?.GetType().GetProperty("resultArr")?.GetValue(parseApiResult.Data)) as List<ComputeRoyaltiesView>;
  5845. var user = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == dto.UserId);
  5846. if (apiArr != null && apiArr.Count > 0)
  5847. {
  5848. var dic = new Dictionary<string, string>
  5849. {
  5850. //dic.Add("Name", "人员:" + user.CnName);
  5851. { "startTime", dto.StartDate },
  5852. { "endTime", dto.EndDate },
  5853. { "operName", user.CnName },
  5854. { "timeNow", DateTime.Now.ToString("yyyy年MM月dd日") },
  5855. //dic.Add("DowntimeNow", DateTime.Now.ToString("yyyy年MM月dd日"));
  5856. { "totalPrice", ("总金额:" + parseApiResult.Data?.GetType().GetProperty("totalPrice")?.GetValue(parseApiResult.Data).ObjToDecimal().ToString() ?? "0") + " 元" }
  5857. };
  5858. var ToTableArr = new ArrayList();
  5859. int No = 1;
  5860. //打开excel模板
  5861. foreach (var item in apiArr)
  5862. {
  5863. //载入数据
  5864. ToTableArr.Add(new
  5865. {
  5866. No,
  5867. item.TeamName,
  5868. item.VisitDate,
  5869. item.TeamLvStr,
  5870. item.Temp,
  5871. infos = string.Join("\r\n", item.ChiArr),
  5872. price = item.Price + "元",
  5873. });
  5874. No++;
  5875. }
  5876. DataTable TbData = CommonFun.ToDataTableArray(ToTableArr);
  5877. TbData.TableName = "TbData";
  5878. var designer = new WorkbookDesigner
  5879. {
  5880. Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/提成结算template.xlsx")
  5881. };
  5882. foreach (var key in dic.Keys)
  5883. {
  5884. designer.SetDataSource(key, dic[key]);
  5885. }
  5886. //数据源
  5887. designer.SetDataSource(TbData);
  5888. designer.Process();
  5889. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "RoyaltyExcel/" + user.CnName + "_提成结算.xlsx");
  5890. jw = JsonView(true, "success!", new
  5891. {
  5892. Url = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + "RoyaltyExcel/" + user.CnName + "_提成结算.xlsx",
  5893. });
  5894. }
  5895. }
  5896. else
  5897. {
  5898. jw.Msg = "获取提成信息error " + jw.Msg;
  5899. }
  5900. return Ok(jw);
  5901. }
  5902. /// <summary>
  5903. /// 提成财务确认通知
  5904. /// </summary>
  5905. /// <returns></returns>
  5906. [HttpPost]
  5907. public async Task<IActionResult> RoyaltyConfirmByFin(RoyaltyConfirmDto dto)
  5908. {
  5909. var jw = JsonView(false);
  5910. if (!DateTime.TryParse(dto.StartData, out DateTime StartDateTime))
  5911. {
  5912. jw.Msg = "开始时间格式有误!";
  5913. return Ok(jw);
  5914. }
  5915. if (!DateTime.TryParse(dto.EndData, out DateTime EndDateTime))
  5916. {
  5917. jw.Msg = "结束时间格式有误!";
  5918. return Ok(jw);
  5919. }
  5920. if (DateTime.Compare(StartDateTime, EndDateTime) > 0)
  5921. {
  5922. jw.Msg = "开始时间大于结束时间!";
  5923. return Ok(jw);
  5924. }
  5925. if (dto.ComputeRoyaltiesList.Count != 0)
  5926. {
  5927. var user = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == dto.UserId);
  5928. if (user == null) { return Ok(JsonView(false, "通知失败! 人员信息有误!")); }
  5929. //保存提成信息
  5930. //消息通知对应人员(公司 部门 人员 时间段 团组id 是否确定 )
  5931. List<Fin_RoyaltyConfirm> entitys = dto.ComputeRoyaltiesList.Select(x => new Fin_RoyaltyConfirm
  5932. {
  5933. UserId = dto.UserId,
  5934. ChiArr = JsonConvert.SerializeObject(x.ChiArr),
  5935. CreateTime = DateTime.Now,
  5936. CreateUserId = dto.UserId,
  5937. IsConfirm = 0,
  5938. TeamId = x.TeamId,
  5939. TeamLvStr = x.TeamLvStr,
  5940. Price = x.Price,
  5941. VisitDate = x.VisitDate,
  5942. TeamName = x.TeamName,
  5943. Temp = x.Temp,
  5944. IsSeed = 0
  5945. }).ToList();
  5946. var expressionSoftDeleteWhere = Expressionable.Create<Fin_RoyaltyConfirm>()
  5947. .And(it => it.VisitDate >= StartDateTime)
  5948. .And(it => it.VisitDate <= EndDateTime)
  5949. .And(it => it.IsDel == 0)
  5950. .And(it => it.UserId == dto.UserId)
  5951. .And(it => it.IsSeed == 0)
  5952. .ToExpression();
  5953. var expressionSelectWhere = Expressionable.Create<Fin_RoyaltyConfirm>()
  5954. .And(it => it.VisitDate >= StartDateTime)
  5955. .And(it => it.VisitDate <= EndDateTime)
  5956. .And(it => it.IsDel == 0)
  5957. .And(it => it.UserId == dto.UserId)
  5958. .And(it => it.IsSeed == 1)
  5959. .ToExpression();
  5960. _sqlSugar.BeginTran();
  5961. try
  5962. {
  5963. _ = _sqlSugar.Updateable<Fin_RoyaltyConfirm>().SetColumns(it => new Fin_RoyaltyConfirm() { IsDel = 1, DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"), DeleteUserId = dto.UserId })
  5964. .Where(expressionSoftDeleteWhere)
  5965. .ExecuteCommand();
  5966. var confirmYes = _sqlSugar.Queryable<Fin_RoyaltyConfirm>().Where(expressionSelectWhere).Select(x => x.TeamId).ToList();
  5967. entitys = entitys.Where(x => !confirmYes.Contains(x.TeamId)).ToList();
  5968. _ = _sqlSugar.Insertable<Fin_RoyaltyConfirm>(entitys).ExecuteCommand();
  5969. _sqlSugar.CommitTran();
  5970. //调用通知
  5971. var title = "提成确认";
  5972. var center = $"【{dto.StartData}】 - 【{dto.EndData}】提成财务已确认,请尽快查看!";
  5973. //【{dto.StartData}-{dto.EndData}-{dto.CompanyId}-{dto.DeparId}-{dto.UserId}】";
  5974. var ids = new List<int> { 235, 233 }; //dto.UserId
  5975. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, center, ids);
  5976. jw = JsonView(true, $"人员:{user.CnName} {dto.StartData}-{dto.EndData} 通知成功!");
  5977. }
  5978. catch (Exception ex)
  5979. {
  5980. _sqlSugar.RollbackTran();
  5981. jw = JsonView(false, "保存失败!" + ex.Message);
  5982. }
  5983. }
  5984. else
  5985. {
  5986. jw = JsonView(false, "保存失败! 无提成信息");
  5987. }
  5988. return Ok(jw);
  5989. }
  5990. /// <summary>
  5991. /// 查询提成信息
  5992. /// </summary>
  5993. /// <param name="dto"></param>
  5994. /// <returns></returns>
  5995. [HttpPost]
  5996. public IActionResult QueryRoyaltyInfo(QueryRoyaltyInfoDto dto)
  5997. {
  5998. var jw = JsonView(false);
  5999. var stateArr = new int[] { -1, 0, 1 };
  6000. if (!DateTime.TryParse(dto.StartDate, out DateTime StartDateTime))
  6001. {
  6002. jw.Msg = "开始时间格式有误!";
  6003. return Ok(jw);
  6004. }
  6005. if (!DateTime.TryParse(dto.EndDate, out DateTime EndDateTime))
  6006. {
  6007. jw.Msg = "结束时间格式有误!";
  6008. return Ok(jw);
  6009. }
  6010. if (DateTime.Compare(StartDateTime, EndDateTime) > 0)
  6011. {
  6012. jw.Msg = "开始时间大于结束时间!";
  6013. return Ok(jw);
  6014. }
  6015. if (!stateArr.Contains(dto.Send) || !stateArr.Contains(dto.Confirm))
  6016. {
  6017. jw.Msg = "状态标识有误!";
  6018. return Ok(jw);
  6019. }
  6020. var expressionSelectWhere = Expressionable.Create<Fin_RoyaltyConfirm>()
  6021. .And(it => it.VisitDate >= StartDateTime)
  6022. .And(it => it.VisitDate <= EndDateTime)
  6023. .And(it => it.IsDel == 0)
  6024. .And(it => it.UserId == dto.UserId)
  6025. .AndIF(dto.Confirm != -1, it => it.IsConfirm == dto.Confirm)
  6026. .AndIF(dto.Send != -1, it => it.IsSeed == dto.Send)
  6027. .ToExpression();
  6028. try
  6029. {
  6030. var query = _sqlSugar.Queryable<Fin_RoyaltyConfirm>().Where(expressionSelectWhere).ToList().Select(x => new
  6031. {
  6032. x.Price,
  6033. ChiArr = JsonConvert.DeserializeObject<List<string>>(x.ChiArr),
  6034. x.IsConfirm,
  6035. x.Id,
  6036. x.TeamId,
  6037. x.TeamName,
  6038. x.TeamLvStr,
  6039. x.Temp,
  6040. x.VisitDate,
  6041. x.IsSeed
  6042. });
  6043. jw = JsonView(true, "获取成功!", new
  6044. {
  6045. List = query,
  6046. CostPrice = query.Sum(x => x.Price),
  6047. ConfirmPrice = query.Where(x => x.IsConfirm == 1).Sum(x => x.Price),
  6048. NoConfirmPrice = query.Where(x => x.IsConfirm == 0).Sum(x => x.Price),
  6049. SeedPrice = query.Where(x => x.IsSeed == 1).Sum(x => x.Price),
  6050. NoSeedPrice = query.Where(x => x.IsSeed == 0).Sum(x => x.Price),
  6051. });
  6052. }
  6053. catch (Exception ex)
  6054. {
  6055. jw = JsonView(true, "获取失败!" + ex.Message);
  6056. }
  6057. return Ok(jw);
  6058. }
  6059. /// <summary>
  6060. /// 个人提成确认
  6061. /// </summary>
  6062. /// <param name="dto"></param>
  6063. /// <returns></returns>
  6064. [HttpPost]
  6065. public IActionResult RoyaltyConfirmByUser(RoyaltyConfirmByUserDto dto)
  6066. {
  6067. var jw = JsonView(false);
  6068. var stateArr = new int[] { 0, 1 };
  6069. if (!stateArr.Contains(dto.State))
  6070. {
  6071. return Ok(JsonView(false, "状态标识有误!"));
  6072. }
  6073. if (dto.Data != null && dto.Data.Count != 0)
  6074. {
  6075. var expressionUpdateWhere = Expressionable.Create<Fin_RoyaltyConfirm>()
  6076. .And(it => dto.Data.Contains(it.Id))
  6077. .And(it => it.IsDel == 0)
  6078. .ToExpression();
  6079. var count = _sqlSugar.Updateable<Fin_RoyaltyConfirm>().SetColumns(x => new Fin_RoyaltyConfirm
  6080. {
  6081. IsConfirm = dto.State,
  6082. })
  6083. .Where(expressionUpdateWhere).ExecuteCommand();
  6084. jw.Msg = $"{count}个团组确认成功!";
  6085. jw.Code = 200;
  6086. }
  6087. else
  6088. {
  6089. jw.Msg = "Data为空!";
  6090. }
  6091. return Ok(jw);
  6092. }
  6093. /// <summary>
  6094. /// 提成发放
  6095. /// </summary>
  6096. /// <param name="dto"></param>
  6097. /// <returns></returns>
  6098. [HttpPost]
  6099. public IActionResult RoyaltySeed(RoyaltySeedDto dto)
  6100. {
  6101. var jw = JsonView(false);
  6102. if (dto.Data != null && dto.Data.Count > 0)
  6103. {
  6104. var updateCount = _sqlSugar.Updateable<Fin_RoyaltyConfirm>().SetColumns(x => new Fin_RoyaltyConfirm
  6105. { IsSeed = 1 }).Where(x => dto.Data.Contains(x.Id) && x.IsDel == 0 && x.IsConfirm == 1).ExecuteCommand();
  6106. var info = $"{updateCount}个团组提成发放成功!";
  6107. if (dto.Data.Count > updateCount)
  6108. {
  6109. info += $"/r/n{dto.Data.Count - updateCount}个团组未确认!";
  6110. }
  6111. jw = JsonView(true, info);
  6112. }
  6113. else
  6114. {
  6115. jw.Msg = "发放的数据为空!";
  6116. }
  6117. return Ok(jw);
  6118. }
  6119. /// <summary>
  6120. /// 提成确认信息
  6121. /// </summary>
  6122. /// <returns></returns>
  6123. [HttpPost]
  6124. public IActionResult RoyaltyConfirmInfo()
  6125. {
  6126. var jw = JsonView(false);
  6127. var queryExpression = Expressionable.Create<Fin_RoyaltyConfirm>()
  6128. .And(r => r.IsDel == 0)
  6129. .And(r => r.IsConfirm == 1)
  6130. .And(r => r.IsSeed == 0)
  6131. .ToExpression();
  6132. var DbQueryConfirmInfo = _sqlSugar.Queryable<Fin_RoyaltyConfirm>()
  6133. .LeftJoin<Sys_Users>((r, s) => s.IsDel == 0 && s.Id == r.UserId)
  6134. .LeftJoin<Sys_JobPost>((r, s, p) => p.IsDel == 0 && p.Id == s.JobPostId)
  6135. .LeftJoin<Sys_Department>((r, s, p, d) => d.IsDel == 0 && d.Id == p.DepId)
  6136. .LeftJoin<Sys_Company>((r, s, p, d, c) => c.IsDel == 0 && c.Id == d.CompanyId)
  6137. .Where(queryExpression)
  6138. .Select((r, s, p, d, c) => new
  6139. {
  6140. r.UserId,
  6141. r.TeamId,
  6142. r.Id,
  6143. r.TeamName,
  6144. r.Price,
  6145. s.CnName,
  6146. p.JobName,
  6147. d.DepName,
  6148. c.CompanyName
  6149. })
  6150. .ToList();
  6151. var groupConfirmInfoByUser = DbQueryConfirmInfo.GroupBy(x => x.UserId);
  6152. var returnData = new ArrayList();
  6153. foreach (var item in groupConfirmInfoByUser)
  6154. {
  6155. var first = item.First();
  6156. returnData.Add(new
  6157. {
  6158. UserId = item.Key,
  6159. Count = item.Count(),
  6160. first.CompanyName,
  6161. first.DepName,
  6162. first.JobName,
  6163. first.CnName,
  6164. SumPrice = item.Sum(x => x.Price),
  6165. RoyaltyIdArr = item.Select(x => x.Id)
  6166. });
  6167. }
  6168. jw = JsonView(true, "获取成功!", returnData);
  6169. return Ok(jw);
  6170. }
  6171. /// <summary>
  6172. /// 提交到日付申请
  6173. /// </summary>
  6174. /// <returns></returns>
  6175. [HttpPost]
  6176. public async Task<IActionResult> RoyaltyFormPrice(RoyaltyFromPriceDto dto)
  6177. {
  6178. var jw = JsonView(false, "用户ID为空!");
  6179. var User = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id
  6180. == dto.CreateId && x.IsDel == 0);
  6181. if (User == null)
  6182. {
  6183. JsonView(false, "createid 不存在!");
  6184. }
  6185. if (dto.Items.Count > 0)
  6186. {
  6187. var queryExpression = Expressionable.Create<Fin_RoyaltyConfirm>()
  6188. .And(r => r.IsDel == 0)
  6189. .And(r => r.IsConfirm == 1)
  6190. .And(r => dto.Items.Select(x => x.UserId).Contains(r.UserId))
  6191. .ToExpression();
  6192. var DbQueryConfirmInfo = _sqlSugar.Queryable<Fin_RoyaltyConfirm>()
  6193. .LeftJoin<Sys_Users>((r, s) => s.IsDel == 0 && s.Id == r.UserId)
  6194. .LeftJoin<Sys_JobPost>((r, s, p) => p.IsDel == 0 && p.Id == s.JobPostId)
  6195. .LeftJoin<Sys_Department>((r, s, p, d) => d.IsDel == 0 && d.Id == p.DepId)
  6196. .LeftJoin<Sys_Company>((r, s, p, d, c) => c.IsDel == 0 && c.Id == d.CompanyId)
  6197. .Where(queryExpression)
  6198. .Select((r, s, p, d, c) => new
  6199. {
  6200. r.UserId,
  6201. r.TeamId,
  6202. r.Id,
  6203. r.TeamName,
  6204. r.Price,
  6205. s.CnName,
  6206. p.JobName,
  6207. d.DepName,
  6208. c.CompanyName,
  6209. CompanyId = c.Id,
  6210. UserName = s.CnName,
  6211. })
  6212. .ToList();
  6213. //已经提交到日付的用户提成信息
  6214. var existsDb = _sqlSugar.Queryable<Fin_RoyaltyForm>()
  6215. .Where(x => dto.Items
  6216. .Select(x => x.UserId).Contains(x.UserId) && x.IsDel == 0)
  6217. .ToList();
  6218. var GroupByConfirmInfo = DbQueryConfirmInfo.GroupBy(x => x.UserId).ToList();
  6219. //关联信息
  6220. var relevanceSoure = new List<Fin_RoyaltyForm>();
  6221. var dayPrice = new AddDailyFeePaymentDto()
  6222. {
  6223. UserId = dto.CreateId,
  6224. Instructions = DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " 提成导入日付!",
  6225. PortType = 1,
  6226. CompanyId = 2,
  6227. PriceTypeId = 668,
  6228. TransferTypeId = 798,
  6229. };
  6230. var ChiDayPrice = new List<AddDailyFeePaymentContentDto>();
  6231. _sqlSugar.BeginTran();
  6232. try
  6233. {
  6234. string message = string.Empty;
  6235. foreach (var item in GroupByConfirmInfo)
  6236. {
  6237. var first = item.First();
  6238. var reqBody = dto.Items.Find(x => x.UserId == item.Key);
  6239. var exists = item.Where(x => reqBody!.ChiArr.Contains(x.Id));
  6240. var existsDbByUser = existsDb.Where(x => x.UserId == item.Key);
  6241. var idsByUser = string.Join(',', existsDbByUser.Select(x => x.ConfirmIdArr));
  6242. var idsByUserList = idsByUser.Split(',')
  6243. .Select(x =>
  6244. {
  6245. if (!string.IsNullOrWhiteSpace(x) && int.TryParse(x, out int intx))
  6246. {
  6247. return intx;
  6248. }
  6249. return 0;
  6250. })
  6251. .Where(x => x != 0)
  6252. .ToList();
  6253. var saveArr = exists.Where(x => !idsByUserList.Contains(x.Id));
  6254. var existsYes = exists.Where(x => idsByUserList.Contains(x.Id));
  6255. var yesPrice = existsYes.Sum(x => x.Price);
  6256. var savePrice = saveArr.Sum(x => x.Price);
  6257. if (saveArr.Any())
  6258. {
  6259. ChiDayPrice.Add(new
  6260. AddDailyFeePaymentContentDto
  6261. {
  6262. ItemTotal = savePrice,
  6263. Price = savePrice,
  6264. Quantity = 1,
  6265. PriceName = first.CnName + "提成金额!",
  6266. });
  6267. relevanceSoure.Add(new
  6268. Fin_RoyaltyForm
  6269. {
  6270. CreateUserId = dto.CreateId,
  6271. ConfirmIdArr = string.Join(',', saveArr.Select(x => x.Id)),
  6272. CreateTime = DateTime.Now,
  6273. IsDel = 0,
  6274. UserId = item.Key,
  6275. });
  6276. }
  6277. if (yesPrice > 0)
  6278. {
  6279. message += $"{first.CnName} 提成 {savePrice}元已导入日付申请 , {yesPrice} 元已经存在 ! \r\n";
  6280. }
  6281. else
  6282. {
  6283. message += $"{first.CnName} 提成 {savePrice}元已导入日付申请 ! \r\n";
  6284. }
  6285. }
  6286. dayPrice.FeeContents = ChiDayPrice;
  6287. dayPrice.SumPrice = ChiDayPrice.Sum(x => x.ItemTotal);
  6288. if (dayPrice.SumPrice != 0)
  6289. {
  6290. var ApiResult = await _daiRep.Add(dayPrice);
  6291. int dailyId = Convert.ToInt32(ApiResult?.Data?.GetType().GetProperty("dailyId").GetValue(ApiResult.Data));
  6292. int sign = Convert.ToInt32(ApiResult?.Data?.GetType().GetProperty("sign").GetValue(ApiResult.Data));
  6293. relevanceSoure.ForEach(x => x.DayOverhead = dailyId);
  6294. var addCount = _sqlSugar.Insertable<Fin_RoyaltyForm>(relevanceSoure).ExecuteCommand();
  6295. }
  6296. _sqlSugar.CommitTran();
  6297. //消息通知
  6298. //await AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dailyId, sign, QiyeWeChatEnum.CaiWuChat);
  6299. jw = JsonView(true, message);
  6300. }
  6301. catch (Exception ex)
  6302. {
  6303. _sqlSugar.RollbackTran();
  6304. jw = JsonView(false, $" Api Error ({ex.Message})");
  6305. }
  6306. }
  6307. return Ok(jw);
  6308. }
  6309. #endregion
  6310. #region 团组未审核数据
  6311. /// <summary>
  6312. /// 团组未审核费用数据
  6313. /// </summary>
  6314. /// <param name="beginDt"></param>
  6315. /// <param name="endDt"></param>
  6316. /// <param name="teamName"></param>
  6317. /// <returns></returns>
  6318. [HttpGet]
  6319. public async Task<IActionResult> GroupUnAuditFeeList(string beginDt, string endDt, string teamName)
  6320. {
  6321. var jw = JsonView(false);
  6322. bool beginDtBool = DateTime.TryParse(beginDt, out DateTime _beginDt),
  6323. endDtBool = DateTime.TryParse(endDt, out DateTime _endDt);
  6324. if (!beginDtBool && !endDtBool)
  6325. {
  6326. jw.Msg = $"开始或者结束时间格式不正确!";
  6327. return Ok(jw);
  6328. }
  6329. // 主查询
  6330. var query = _sqlSugar.Queryable<Grp_DelegationInfo>()
  6331. .Where(x => x.IsDel == 0 &&
  6332. x.VisitDate >= _beginDt &&
  6333. x.VisitDate <= _endDt);
  6334. if (!string.IsNullOrEmpty(teamName))
  6335. {
  6336. query = query.Where(x => x.TeamName.Contains(teamName));
  6337. var keywords = teamName.Trim()
  6338. .Split(new[] { ' ', ',', ',' }, StringSplitOptions.RemoveEmptyEntries);
  6339. foreach (var keyword in keywords.Where(k => !string.IsNullOrWhiteSpace(k)))
  6340. {
  6341. query = query.Where(x => x.TeamName.Contains(keyword.Trim()));
  6342. }
  6343. }
  6344. var _groupDatas = query
  6345. .OrderByDescending(x => x.CreateTime)
  6346. .ToList();
  6347. var _groupIds = _groupDatas.Select(x => x.Id).ToList();
  6348. if (_groupIds.Count < 1)
  6349. {
  6350. jw.Msg = $"该时间段暂无出访的团组!";
  6351. return Ok(jw);
  6352. }
  6353. var _DailyFeePaymentResult = new tree_Group_DailyFeePaymentResult();
  6354. var dataList = new List<tree_Group_DailyFeePaymentPageListView>();
  6355. var _paymentDatas = _sqlSugar.Queryable<Grp_CreditCardPayment>()
  6356. .Where(x => x.IsDel == 0 &&
  6357. _groupIds.Contains(x.DIId) &&
  6358. x.IsAuditGM == 0
  6359. )
  6360. .ToList();
  6361. _DailyFeePaymentResult.gz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 0).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); //公转
  6362. _DailyFeePaymentResult.sz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 1).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); ; //私转
  6363. #region 相关基础数据源
  6364. var userDatas = _sqlSugar.Queryable<Sys_Users>().ToList();
  6365. var setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  6366. var countryFeeDatas = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(it => it.IsDel == 0).ToList();
  6367. //76 酒店预订
  6368. var hotelDatas = _sqlSugar.Queryable<Grp_HotelReservations>()
  6369. .InnerJoin<Grp_CreditCardPayment>((hr, ccp) => hr.Id == ccp.CId &&
  6370. ccp.CTable == 76 &&
  6371. ccp.IsDel == 0
  6372. )
  6373. .Where((hr, ccp) => hr.IsDel == 0 && _groupIds.Contains(hr.DiId) && ccp.IsAuditGM == 0)
  6374. .ToList();
  6375. var hotelContentDatas = _sqlSugar.Queryable<Grp_HotelReservationsContent>()
  6376. .Where(it => it.IsDel == 0 &&
  6377. it.IsPay == 0 &&
  6378. it.Price != 0 &&
  6379. _groupIds.Contains(it.DiId)
  6380. )
  6381. .ToList();
  6382. //79 车/导游地接
  6383. var opDatas = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>()
  6384. .InnerJoin<Grp_CreditCardPayment>((ctggr, ccp) => ctggr.Id == ccp.CId &&
  6385. ccp.CTable == 79 &&
  6386. ccp.IsDel == 0
  6387. )
  6388. .Where((ctggr, ccp) => ctggr.IsDel == 0 && _groupIds.Contains(ctggr.DiId) && ccp.IsAuditGM == 0)
  6389. .ToList();
  6390. // 80 签证
  6391. var visaDatas = _sqlSugar.Queryable<Grp_VisaInfo>()
  6392. .InnerJoin<Grp_CreditCardPayment>((vi, ccp) => vi.Id == ccp.CId &&
  6393. ccp.CTable == 80 &&
  6394. ccp.IsDel == 0
  6395. )
  6396. .Where((vi, ccp) => vi.IsDel == 0 && _groupIds.Contains(vi.DIId) && ccp.IsAuditGM == 0)
  6397. .ToList();
  6398. // 81 邀请/公务活动
  6399. var ioaDatas = _sqlSugar.Queryable<Grp_InvitationOfficialActivities>()
  6400. .InnerJoin<Grp_CreditCardPayment>((ioa, ccp) => ioa.Id == ccp.CId &&
  6401. ccp.CTable == 81 &&
  6402. ccp.IsDel == 0
  6403. )
  6404. .Where((ioa, ccp) => ioa.IsDel == 0 && _groupIds.Contains(ioa.DiId) && ccp.IsAuditGM == 0)
  6405. .ToList();
  6406. // 82 团组客户保险
  6407. var insureDatas = _sqlSugar.Queryable<Grp_Customers>()
  6408. .InnerJoin<Grp_CreditCardPayment>((c, ccp) => c.Id == ccp.CId &&
  6409. ccp.CTable == 82 &&
  6410. ccp.IsDel == 0
  6411. )
  6412. .Where((c, ccp) => c.IsDel == 0 && _groupIds.Contains(c.DiId) && ccp.IsAuditGM == 0)
  6413. .ToList();
  6414. // 85 机票预订
  6415. var airDatas = _sqlSugar.Queryable<Grp_AirTicketReservations>()
  6416. .InnerJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId &&
  6417. ccp.CTable == 85 &&
  6418. ccp.IsDel == 0
  6419. )
  6420. .Where((atr, ccp) => atr.IsDel == 0 && _groupIds.Contains(atr.DIId) && ccp.IsAuditGM == 0)
  6421. .ToList();
  6422. // 98 其他款项
  6423. var otherMoneyDatas = _sqlSugar.Queryable<Grp_DecreasePayments>()
  6424. .InnerJoin<Grp_CreditCardPayment>((dp, ccp) => dp.Id == ccp.CId &&
  6425. ccp.CTable == 98 &&
  6426. ccp.IsDel == 0
  6427. )
  6428. .Where((dp, ccp) => dp.IsDel == 0 && _groupIds.Contains(dp.DiId) && ccp.IsAuditGM == 0)
  6429. .ToList();
  6430. // 285 收款退还
  6431. var refundPaymentDatas = _sqlSugar.Queryable<Fin_PaymentRefundAndOtherMoney>()
  6432. .InnerJoin<Grp_CreditCardPayment>((prom, ccp) => prom.Id == ccp.CId &&
  6433. ccp.CTable == 285 &&
  6434. ccp.IsDel == 0
  6435. )
  6436. .Where((prom, ccp) => prom.IsDel == 0 && _groupIds.Contains(prom.DiId) && ccp.IsAuditGM == 0)
  6437. .ToList();
  6438. // 1015 超支费用
  6439. var extraCostDatas = _sqlSugar.Queryable<Fin_GroupExtraCost>()
  6440. .InnerJoin<Grp_CreditCardPayment>((gec, ccp) => gec.Id == ccp.CId &&
  6441. ccp.CTable == 1015 &&
  6442. ccp.IsDel == 0
  6443. )
  6444. .Where((gec, ccp) => gec.IsDel == 0 && _groupIds.Contains(gec.DiId) && ccp.IsAuditGM == 0)
  6445. .ToList();
  6446. #endregion
  6447. //Expense company
  6448. foreach (var groupInfo in _groupDatas)
  6449. {
  6450. var childList = new List<Group_DailyFeePaymentContentInfolView>();
  6451. var groupPaymentDatas = _paymentDatas.Where(it => groupInfo.Id == it.DIId).ToList();
  6452. if (groupPaymentDatas.Count > 0)
  6453. {
  6454. int rouNumber = 1;
  6455. foreach (var payInfo in groupPaymentDatas)
  6456. {
  6457. string priName = "-";
  6458. string orbitalPrivateTransfer = payInfo.OrbitalPrivateTransfer == 0 ? "公转" : payInfo.OrbitalPrivateTransfer == 1 ? "私转" : "-";
  6459. switch (payInfo.CTable)
  6460. {
  6461. case 76: //76 酒店预订
  6462. priName = $"[费用名称:{hotelDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.HotelName ?? ""}]";
  6463. break;
  6464. case 79: //79 车/导游地接
  6465. var opData = opDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id);
  6466. if (opData != null)
  6467. {
  6468. string area = "";
  6469. bool b = int.TryParse(opData.Area, out int areaId);
  6470. if (b)
  6471. {
  6472. string area1 = countryFeeDatas.Find(it => it.Id == areaId)?.Country ?? "-";
  6473. area = $"{area1}({setDatas.Find(it => it.Id == opData.PriceType)?.Name ?? "-"})";
  6474. }
  6475. else area = opData.Area;
  6476. string opPriName = "-";
  6477. if (!string.IsNullOrEmpty(opData.PriceName)) opPriName = opData.PriceName;
  6478. area += $"({opPriName})";
  6479. if (payInfo.OrbitalPrivateTransfer == 0) //公转
  6480. {
  6481. priName = $"【{orbitalPrivateTransfer}】【导游: {opData.ServiceGuide} 】[费用名称:{area}]";
  6482. }
  6483. else if (payInfo.OrbitalPrivateTransfer == 1) //私转
  6484. {
  6485. priName = $"【{orbitalPrivateTransfer}】【导游:{opData.ServiceGuide}】[费用名称:{area}]";
  6486. }
  6487. }
  6488. break;
  6489. case 80: // 80 签证
  6490. string sql = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", groupInfo.Id);
  6491. List<SimplClientInfo> arr = _sqlSugar.SqlQueryable<SimplClientInfo>(sql).ToList();
  6492. string visaClientName = visaDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.VisaClient ?? "";
  6493. string clientName = "-";
  6494. if (Regex.Match(visaClientName, @"\d+,?").Value.Length > 0)
  6495. {
  6496. string[] temparr = visaClientName.Split(',');
  6497. string fistrStr = temparr[0];
  6498. int count = temparr.Length;
  6499. int tempId;
  6500. bool success = int.TryParse(fistrStr, out tempId);
  6501. if (success)
  6502. {
  6503. SimplClientInfo tempInfo = arr.FirstOrDefault(s => s.Id == tempId);
  6504. if (tempInfo != null)
  6505. {
  6506. string lastName = AesEncryptionHelper.Decrypt(tempInfo.LastName),
  6507. firstName = AesEncryptionHelper.Decrypt(tempInfo.FirstName);
  6508. if (count > 1)
  6509. {
  6510. clientName = string.Format(@"{0}{1}等{2}人", lastName, firstName, count);
  6511. }
  6512. else
  6513. {
  6514. clientName = string.Format(@"{0}{1}", lastName, firstName);
  6515. }
  6516. }
  6517. }
  6518. else
  6519. {
  6520. clientName = fistrStr;
  6521. }
  6522. }
  6523. priName = $"[费用名称:{clientName}]";
  6524. break;
  6525. case 81: // 81 邀请/公务活动
  6526. priName = $"[费用名称:{ioaDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.Inviter ?? " -"}]";
  6527. break;
  6528. case 82: // 82 团组客户保险
  6529. string bx_sql = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", groupInfo.Id);
  6530. List<SimplClientInfo> bx_arr = _sqlSugar.SqlQueryable<SimplClientInfo>(bx_sql).ToList();
  6531. string bx_ClientName = insureDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.ClientName ?? "";
  6532. string bx_clientName = "-";
  6533. if (Regex.Match(bx_ClientName, @"\d+,?").Value.Length > 0)
  6534. {
  6535. string[] temparr = bx_ClientName.Split(',');
  6536. string fistrStr = temparr[0];
  6537. int count = temparr.Length;
  6538. int tempId;
  6539. bool success = int.TryParse(fistrStr, out tempId);
  6540. if (success)
  6541. {
  6542. SimplClientInfo tempInfo = bx_arr.FirstOrDefault(s => s.Id == tempId);
  6543. if (tempInfo != null)
  6544. {
  6545. string lastName = AesEncryptionHelper.Decrypt(tempInfo.LastName),
  6546. firstName = AesEncryptionHelper.Decrypt(tempInfo.FirstName);
  6547. if (count > 1)
  6548. {
  6549. bx_clientName = string.Format(@"{0}{1}等{2}人", lastName, firstName, count);
  6550. }
  6551. else
  6552. {
  6553. bx_clientName = string.Format(@"{0}{1}", lastName, firstName);
  6554. }
  6555. }
  6556. }
  6557. else
  6558. {
  6559. bx_clientName = fistrStr;
  6560. }
  6561. }
  6562. //priName = $"[费用名称:{insureDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.ClientName ?? " -"}]";
  6563. priName = $"[费用名称:{bx_clientName}]";
  6564. break;
  6565. case 85: // 85 机票预订
  6566. string flightsCode = airDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.FlightsCode ?? "-";
  6567. string airPayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "-";
  6568. priName = $"{flightsCode}【{airPayType}】";
  6569. break;
  6570. case 98: // 98 其他款项
  6571. priName = $"[费用名称:{otherMoneyDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  6572. break;
  6573. case 285: // 285 收款退还
  6574. priName = $"[费用名称:{refundPaymentDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  6575. break;
  6576. case 1015: // 1015 超支费用
  6577. priName = $"[费用名称:{extraCostDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  6578. break;
  6579. default:
  6580. priName = "";
  6581. break;
  6582. }
  6583. if (payInfo.CTable == 76) //酒店单独处理
  6584. {
  6585. var hotelContents = hotelContentDatas.Where(it => it.HrId == payInfo.CId);
  6586. List<Group_DailyFeePaymentContentInfolView> childInfos = new List<Group_DailyFeePaymentContentInfolView>();
  6587. foreach (var hotelContent in hotelContents)
  6588. {
  6589. string subPriceName = "";
  6590. if (hotelContent.PriceType == 1) subPriceName = "房费";
  6591. else if (hotelContent.PriceType == 2) subPriceName = "早餐";
  6592. else if (hotelContent.PriceType == 3) subPriceName = "地税";
  6593. else if (hotelContent.PriceType == 4) subPriceName = "城市税";
  6594. if (string.IsNullOrEmpty(subPriceName)) subPriceName = priName;
  6595. else subPriceName = $"{priName.Replace("]", "")}-{subPriceName}]";
  6596. string payeeStr1 = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
  6597. string.IsNullOrEmpty(hotelContent.Payee) ? "-" : hotelContent.Payee,
  6598. string.IsNullOrEmpty(hotelContent.OtherBankName) ? "-" : hotelContent.OtherBankName,
  6599. string.IsNullOrEmpty(hotelContent.OtherSideNo) ? "-" : hotelContent.OtherSideNo);
  6600. decimal _PaymentAmount1 = hotelContent.Price;//此次付款金额
  6601. decimal _CNYSubTotalAmount1 = _PaymentAmount1 * hotelContent.Rate;//此次付款金额
  6602. _CNYSubTotalAmount1 = Convert.ToDecimal(_CNYSubTotalAmount1.ToString("#0.00"));
  6603. var childInfo1 = new Group_DailyFeePaymentContentInfolView()
  6604. {
  6605. Id = payInfo.Id,
  6606. HotelSubId = hotelContent.Id,
  6607. Payee = payeeStr1,
  6608. RowNumber = rouNumber,
  6609. Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
  6610. ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  6611. PayType = setDatas.Find(it => it.Id == hotelContent.PayDId)?.Name ?? "",
  6612. TransferMark = orbitalPrivateTransfer,
  6613. PriceName = subPriceName,
  6614. ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
  6615. PayCurrCode = setDatas.Find(it => it.Id == hotelContent.Currency)?.Name ?? "",
  6616. PaymentAmount = _PaymentAmount1,
  6617. PayRate = hotelContent.Rate,
  6618. CNYSubTotalAmount = _CNYSubTotalAmount1,
  6619. AuditStatus = payInfo.IsAuditGM
  6620. };
  6621. string remaksDescription1 = $"【{childInfo1.PayType}】【{childInfo1.ModuleName}】{rouNumber}、[申请人:{childInfo1.Applicant}]{subPriceName}[收款方:{childInfo1.Payee}] {childInfo1.PayCurrCode} {_PaymentAmount1:#0.00}、CNY:{childInfo1.CNYSubTotalAmount:#0.00}(团组:{groupInfo.TeamName})";
  6622. childInfo1.RemaksDescription = remaksDescription1;
  6623. childInfos.Add(childInfo1);
  6624. rouNumber++;
  6625. }
  6626. childList.AddRange(childInfos);
  6627. }
  6628. else
  6629. {
  6630. string payeeStr = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
  6631. string.IsNullOrEmpty(payInfo.Payee) ? "-" : payInfo.Payee,
  6632. string.IsNullOrEmpty(payInfo.OtherBankName) ? "-" : payInfo.OtherBankName,
  6633. string.IsNullOrEmpty(payInfo.OtherSideNo) ? "-" : payInfo.OtherSideNo);
  6634. decimal _PaymentAmount = (payInfo.PayMoney / 100) * payInfo.PayPercentage;//此次付款金额
  6635. decimal _CNYSubTotalAmount = _PaymentAmount * payInfo.DayRate;//此次付款金额
  6636. _CNYSubTotalAmount = Convert.ToDecimal(_CNYSubTotalAmount.ToString("#0.00"));
  6637. var childInfo = new Group_DailyFeePaymentContentInfolView()
  6638. {
  6639. Id = payInfo.Id,
  6640. Payee = payeeStr,
  6641. RowNumber = rouNumber,
  6642. Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
  6643. ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  6644. PayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "",
  6645. TransferMark = orbitalPrivateTransfer,
  6646. PriceName = priName,
  6647. ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
  6648. PayCurrCode = setDatas.Find(it => it.Id == payInfo.PaymentCurrency)?.Name ?? "",
  6649. PaymentAmount = _PaymentAmount,
  6650. PayRate = payInfo.DayRate,
  6651. CNYSubTotalAmount = _CNYSubTotalAmount,
  6652. AuditStatus = payInfo.IsAuditGM
  6653. };
  6654. string remaksDescription = $"【{childInfo.PayType}】【{childInfo.ModuleName}】{rouNumber}、[申请人:{childInfo.Applicant}]{priName}[收款方:{childInfo.Payee}] {childInfo.PayCurrCode} {_PaymentAmount:#0.00}、CNY:{childInfo.CNYSubTotalAmount:#0.00}(团组:{groupInfo.TeamName})";
  6655. childInfo.RemaksDescription = remaksDescription;
  6656. childList.Add(childInfo);
  6657. rouNumber++;
  6658. }
  6659. }
  6660. var companyInfo = ExpenseCompanyByTeamId(groupInfo.TeamDid);
  6661. dataList.Add(new tree_Group_DailyFeePaymentPageListView()
  6662. {
  6663. Id = Guid.NewGuid().ToString("N"),
  6664. GroupName = groupInfo.TeamName,
  6665. CompanyId = companyInfo.Id,
  6666. ConpanyName = companyInfo.ConpanyName,
  6667. CNYTotalAmount = childList.Sum(it => it.CNYSubTotalAmount),
  6668. ChildList = childList,
  6669. });
  6670. }
  6671. }
  6672. var dataList1 = new List<tree_Group_DailyFeePaymentPageListView>();
  6673. //移除没有数据的团
  6674. foreach (var item in dataList)
  6675. {
  6676. if (item.CNYTotalAmount > 0 && item.ChildList.Count > 0)
  6677. {
  6678. dataList1.Add(item);
  6679. }
  6680. }
  6681. _DailyFeePaymentResult.dataList = dataList1;
  6682. jw.Code = StatusCodes.Status200OK;
  6683. jw.Msg = $"操作成功!";
  6684. jw.Data = _DailyFeePaymentResult;
  6685. return Ok(jw);
  6686. }
  6687. #endregion
  6688. }
  6689. }