FinancialController.cs 298 KB

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