FinancialController.cs 299 KB

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