FinancialController.cs 298 KB

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