FinancialController.cs 315 KB

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