FinancialController.cs 294 KB

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