| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938 |
- using BizCom;
- using Newtonsoft.Json;
- using SiteCore.taoObj;
- using SQLData;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.SqlClient;
- using System.IO;
- using System.Text;
- using System.Text.RegularExpressions;
- using Match = System.Text.RegularExpressions.Match;
- using SiteCore.Handler;
- using System.Threading;
- using Newtonsoft.Json.Linq;
- using System.Net.Security;
- using System.Net;
- using System.Security.Cryptography.X509Certificates;
- using System.Security.Policy;
- using NHibernate.Engine;
- using static NHibernate.Linq.Visitors.LeftJoinDetector;
- using NHibernate.Loader.Custom;
- using System.Runtime.Remoting.Metadata.W3cXsd2001;
- using NPOI.OpenXmlFormats.Shared;
- using static SiteCore.taoObj.work_core_vo;
- using System.Linq;
- using NHibernate.Mapping;
- using System.Reflection.Emit;
- using NPOI.SS.Formula.Functions;
- using System.Security.Cryptography;
- using NHibernate.Hql.Ast;
- using System.Security.Principal;
- using Microsoft.SqlServer.Server;
- using System.Net.Http.Headers;
- using System.Net.Http;
- using System.Threading.Tasks;
- using System.Diagnostics;
- using NPOI.Util;
- namespace SiteCore
- {
- public class commonHelper
- {
- public static void autoRefreshRefundState()
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("update CE_ErpTradeRefund set RefundState=3 where RefundState=2 and DATEDIFF(hh,modified,getdate())>=72;");
- //sql.AppendFormat("update ce_erptradecell with(rowlock) set AfterSaleState=4,FinishAfterSaleTime=getdate() where AfterSaleState=3 and IsArbitrate=0 and DATEDIFF(hh,AfterSalePreTime,getdate())>=168;");
- //sql.AppendFormat("update ce_erptradecell with(rowlock) set AfterSaleSupplierState=1,set FinishAfterSaleTime=GETDATE(),set AfterSaleState=4 where AfterSaleSupplierState=0 and AfterSaleState>1 and AfterSaleResSupId>0 and DATEDIFF(hh,HandleTime,getdate())>=72;");
- //sql.AppendFormat("update CE_ErpTradeResponsible set VerifyState=1 where VerifyState=0 and IsArbitrate=0 and DATEDIFF(hh,createdTime,getdate())>=168;");
- //DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
- DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
- sql = new StringBuilder();
- sql.AppendFormat("SELECT r.ID, r.tid, r.VerifyState, r.UserId, r.VerifyTime, type FROM CE_ErpTradeResponsible r LEFT JOIN CE_ErpTradeCell t ON r.tid= t.ctid WHERE VerifyState > -1 AND VerifyState != 1 AND t.AfterSaleState = 3 AND DATEDIFF( hh, VerifyTime, getdate( ) ) >= 72;");
- DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
- foreach (DataRow dr in dt.Rows)
- {
- string state = dr["VerifyState"].ToString();
- string tid = dr["tid"].ToString();
- int userId = Convert.ToInt32(dr["UserId"]);
- int reasonId = Convert.ToInt32(dr["ID"]);
- int type = Convert.ToInt32(dr["type"]);
- if (type == 0)
- {
- if (state == "0")//主管审核超时
- {
- CeErpTradeResponsible ceErpTradeResponsible = CeErpTradeResponsible.GetById(dr["ID"].ToString());
- if (ceErpTradeResponsible != null)
- {
- ceErpTradeResponsible.VerifyTime = DateTime.Now;
- ceErpTradeResponsible.VerifyState = 3;
- ceErpTradeResponsible.Update();
- LogHelper.AddAfterSaleLog(tid, reasonId, "主管审核超时", userId);
- LogHelper.addLog(tid, 0, "主管审核超时", 4, 4);
- }
- }
- if (state == "3")//责任人审核超时
- {
- CeErpTradeResponsible ceErpTradeResponsible = CeErpTradeResponsible.GetById(dr["ID"].ToString());
- if (ceErpTradeResponsible != null)
- {
- ceErpTradeResponsible.VerifyTime = DateTime.Now;
- ceErpTradeResponsible.VerifyState = 1;
- ceErpTradeResponsible.Update();
- LogHelper.AddAfterSaleLog(tid, reasonId, "责任人审核超时", userId);
- LogHelper.addLog(tid, 0, "责任人审核超时", 4, 4);
- CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ceErpTradeResponsible.tid);
- bool isAll = tradeResponsibleAll(entity);
- if (isAll)
- {
- entity.AfterSaleState = 4;
- entity.FinishAfterSaleTime = DateTime.Now;
- entity.UpdateTime = DateTime.Now;
- entity.AfterSaleSupplierState = 1;
- ApiVo apiVo = new ApiVo();
- apiVo.orderNumber = entity.ctid;
- apiVo.actionName = "afterOver";
- designHelper.API_WorkCore(apiVo); //afterOver
- entity.Update();
- }
- }
- }
- }
- else
- {
- DateTime date = DateTime.Parse(dr["VerifyTime"].ToString());
- if (type == 2)
- {
- if (DateTime.Compare(DateTime.Now, date.AddHours(96)) <= 0)
- {
- continue;
- }
- }
- //车间自动审核
- if (state == "0")
- {
- //节假日120小时
- /*if (DateTime.Compare(DateTime.Now, date.AddHours(120)) <= 0)
- {
- continue;
- }*/
- CeErpTradeResponsible ceErpTradeResponsible = CeErpTradeResponsible.GetById(dr["ID"].ToString());
- if (ceErpTradeResponsible != null)
- {
- ceErpTradeResponsible.VerifyTime = DateTime.Now;
- ceErpTradeResponsible.VerifyState = 1;
- ceErpTradeResponsible.Update();
- CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ceErpTradeResponsible.tid);
- bool isAll = tradeResponsibleAll(entity);
- if (isAll)
- {
- entity.AfterSaleState = 4;
- entity.FinishAfterSaleTime = DateTime.Now;
- entity.UpdateTime = DateTime.Now;
- entity.AfterSaleSupplierState = 1;
- entity.Update();
- ApiVo apiVo = new ApiVo();
- apiVo.orderNumber = entity.ctid;
- apiVo.actionName = "afterOver";
- designHelper.API_WorkCore(apiVo); //afterOver
- }
- CeErpSukuraData.createInfo(entity.ctid, 8);
- LogHelper.addLog(tid, 0, "审核超时,自动完成售后", 4, 4);
- }
- }
- }
- }
- }
- public static void tradeSaleState(CeErpTradeCell ceErpTradeCell)
- {
- string sql = "select * from ce_erptraderesponsible where tid='" + ceErpTradeCell.ctid + "' and VerifyState != -1";
- DataTable dt = DbHelper.DbConn.ExecuteDataset(sql).Tables[0];
- CeErpTradeAfterSaleExtend ceErpTradeAfterSaleExtend = CeErpTradeAfterSaleExtend.getByTid(ceErpTradeCell.ctid);
- if (ceErpTradeAfterSaleExtend == null)
- {
- ceErpTradeAfterSaleExtend = new CeErpTradeAfterSaleExtend();
- ceErpTradeAfterSaleExtend.tid = ceErpTradeCell.ctid;
- ceErpTradeAfterSaleExtend.Create();
- }
- List<string> list = new List<string>();
- foreach (DataRow row in dt.Rows)
- {
- list.Add(row["VerifyState"].ToString());
- }
- ceErpTradeAfterSaleExtend.VerifyStates = String.Join(",", list);
- ceErpTradeAfterSaleExtend.Update();
- }
- public static bool tradeResponsibleAll(CeErpTradeCell ceErpTradeCell)
- {
- //判断是否全部处理完成
- string sql = "select * from ce_erptraderesponsible where tid='" + ceErpTradeCell.ctid + "' and VerifyState != -1";
- DataTable dt = DbHelper.DbConn.ExecuteDataset(sql).Tables[0];
- bool isAll = true;
- if (dt.Rows.Count > 0 && dt.Rows.Count == 1)
- {
- }
- else if (dt.Rows.Count > 1)
- {
- foreach (DataRow row in dt.Rows)
- {
- if (row["VerifyState"].ToString() != "1")
- {
- isAll = false;
- break;
- }
- }
- }
- return isAll;
- }
- public static string getSupplierNameById(int sid)
- {
- CeErpSupplier sup = CeErpSupplier.Get(sid);
- if (sup != null)
- {
- return sup.ComName;
- }
- else
- {
- return "";
- }
- }
- public static void aftersaleSend(string ctid, string cpCode, string curUseWayBillCode)
- {
- if (ctid.IndexOf("S_") > -1)
- {
- try
- {
- string tradeCtid = ctid.Remove(0, 2);
- CeErpTradeAfterSaleExtend ceErpTradeAfterSaleExtend = CeErpTradeAfterSaleExtend.getByTid(tradeCtid);
- if (ceErpTradeAfterSaleExtend == null)
- {
- ceErpTradeAfterSaleExtend = new CeErpTradeAfterSaleExtend();
- ceErpTradeAfterSaleExtend.tid = tradeCtid;
- ceErpTradeAfterSaleExtend.ExpressNo = cpCode + "-" + curUseWayBillCode;
- ceErpTradeAfterSaleExtend.Create();
- }
- else
- {
- ceErpTradeAfterSaleExtend.ExpressNo = cpCode + "-" + curUseWayBillCode;
- ceErpTradeAfterSaleExtend.Update();
- }
- }
- catch (Exception ex)
- {
- }
- }
- }
- public static string getUserNameById(int sid)
- {
- CeErpUser sup = CeErpUser.Get(sid);
- if (sup != null)
- {
- return sup.Name;
- }
- else
- {
- return "";
- }
- }
- public static int getSupplierIDByName(string name)
- {
- StringBuilder sql2 = new StringBuilder();
- sql2.AppendFormat("select top 1 * from CE_ErpSupplier where ComName='{0}';", name);
- DataTable dt2 = DbHelper.DbConn.ExecuteDataset(sql2.ToString()).Tables[0];
- if (dt2.Rows.Count > 0)
- {
- return Convert.ToInt32(dt2.Rows[0]["ID"]);
- }
- return 0;
- }
- public static int autoDistributeToSupplier(CeErpTradeCell trade)
- {
- if (trade.seller_memo.IndexOf("电子稿") != -1) return 0;
- int count = 0;
- string sc = trade.ProductCount;
- count = handleProductCount(sc, true);
- //string needSc = System.Text.RegularExpressions.Regex.Replace(sc, @"[^0-9]+", "");
- //if (!int.TryParse(needSc, out count))
- //{
- // XLog.SaveLog(0, "autoDistributeToSupplier:获取数量[" + trade.ProductCount + "]转换出错");
- //}
- //老客户指派之前供应商
- if (trade.IsOldCustomer == 1 && (trade.seller_memo.IndexOf("改稿") != -1 || trade.OtherMemo.IndexOf("老客户") != -1))
- {
- CeErpTrade ceErpTrade = CeErpTrade.Get(trade.tid);
- if (ceErpTrade != null)
- {
- //用昵称找之前的订单
- string name = ceErpTrade.buyer_nick;
- if (!string.IsNullOrEmpty(name))
- {
- StringBuilder CeErpTradeSql = new StringBuilder();
- CeErpTradeSql.AppendFormat("select top 1 * from ce_erptrade o left join CE_ErpTradeCell c on c.tid=o.tid where o.buyer_nick='{0}' and o.tid <> '{1}' and c.SupplierId <> 35 AND c.SupplierId <> 33 and c.SupplierId > 0 order by created desc;", name, trade.tid);
- DataSet data = DbHelper.DbConn.ExecuteDataset(CeErpTradeSql.ToString());
- DataTable datatable = data.Tables[0];
- if (datatable.Rows.Count > 0)
- {
- CeErpTradeCell oldOrder = CeErpTradeCell.GetByTid(datatable.Rows[0]["tid"].ToString());
- if (oldOrder != null)
- {
- CeErpSupplier ceErpSupplier = CeErpSupplier.Get(oldOrder.SupplierId);
- if (ceErpSupplier != null && ceErpSupplier.IsClose == 0)
- {
- return oldOrder.SupplierId;
- }
- }
- }
- }
- }
- }
- if (trade.Craft.IndexOf("门挂卡") != -1)
- {
- return 7;// ljl
- }
- else if (trade.Craft.IndexOf("打印") != -1 || trade.Craft.IndexOf("专版") != -1)
- {
- return 10; //得力
- }
- else if (trade.Craft.IndexOf("打码") != -1 || trade.Craft.IndexOf("压点线") != -1)
- {
- if (count < 300)
- {
- return 10;
- }
- else
- return 25;
- }
- if (trade.seller_memo.Contains("金属标") && (trade.ShopId == 26 || trade.ShopId == 45))
- {
- return 9;
- }
- //if (trade.IsOldCustomer == 1)
- //{
- // StringBuilder oldsql = new StringBuilder();
- // oldsql.AppendFormat("select top 1 SupplierId from view_erptradecell where buyer_nick={0} and IsAutoDistribute=1 ;",trad, trade.ProductId);
- //}
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("select count(0) from ce_erpproduct where id={0} and IsAutoDistribute=1 ;", trade.ProductId);
- sql.AppendFormat("select top 1 * from ce_erptrade where tid='{0}';", trade.tid);
- DataSet oDs = DbHelper.DbConn.ExecuteDataset(sql.ToString());
- DataTable pDt = oDs.Tables[0];
- DataTable rDt = oDs.Tables[1];
- string material = trade.Material;
- material = material.Replace("铜板纸", "铜版纸");
- string crafts = trade.Craft;
- string supplierCrafts = trade.MakeSupplier;
- if (supplierCrafts == "")
- {
- supplierCrafts = "123123";
- }
- decimal size = getOrderSizeFromString(trade.ProductSize);
- if (pDt != null && pDt.Rows.Count > 0)
- {
- string receiver_state = "";
- if (rDt != null || rDt.Rows.Count > 0)
- {
- receiver_state = rDt.Rows[0]["receiver_state"].ToString();
- if (trade.IsOldCustomer == 1 && !string.IsNullOrEmpty(rDt.Rows[0]["buyer_nick"].ToString()))
- {
- StringBuilder oldsql = new StringBuilder();
- oldsql.AppendFormat("select top 1 * from view_erptradecell where buyer_nick='{0}' and ProductId={1} and SupplierId!=0 order by ID desc;", rDt.Rows[0]["buyer_nick"].ToString(), trade.ProductId);
- DataTable oldDt = DbHelper.DbConn.ExecuteDataset(oldsql.ToString()).Tables[0];
- if (oldDt.Rows.Count > 0)
- {
- CeErpSupplier ceErpSupplier = CeErpSupplier.Get(Convert.ToInt32(oldDt.Rows[0]["SupplierId"]));
- if (ceErpSupplier != null && ceErpSupplier.IsClose == 0)
- {
- return Convert.ToInt32(oldDt.Rows[0]["SupplierId"]);
- }
- }
- }
- }
- try
- {
- //CHARINDEX(','+'{0}'+',',','+ProductID+',')>0
- sql = new StringBuilder();
- sql.AppendFormat("select A.* from CE_ErpSupplierProduct A LEFT JOIN CE_ErpSupplier B on A.SupplierID = B.ID where B.IsClose=0 and CHARINDEX(','+'{0}'+',',','+A.ProductIds+',')>0 order by A.Bsort asc;", trade.ProductId);
- DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
- if (dt == null || dt.Rows.Count < 1) return 0;
- DataView dv = new DataView(dt);
- int topOneProductSupplier = Convert.ToInt32(dv[0]["SupplierID"]);
- if (receiver_state.Length > 0)
- {
- dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1} and SizeL<={2} and SizeW>={2} and (Area like '%{3}%' or Area='*')", material, count, size, receiver_state);
- if (dv.Count > 0)
- {
- return Convert.ToInt32(dv[0]["SupplierID"]);
- }
- }
- if (count > 0)
- {
- if (size > 0)
- {
- dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1} and SizeL<={2} and SizeW>={2} ", material, count, size);
- if (dv.Count > 0)
- {
- return Convert.ToInt32(dv[0]["SupplierID"]);
- }
- }
- dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1}", material, count);
- if (dv.Count > 0)
- {
- LogHelper.addLog(trade.ctid, 0, "筛选供应商:产品 材质 工艺 数量 符合!"); return Convert.ToInt32(dv[0]["SupplierID"]);
- }
- }
- if (size > 0)
- {
- dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1} and SizeL<={2} and SizeW>={2}", material, count, size);
- if (dv.Count > 0)
- {
- return Convert.ToInt32(dv[0]["SupplierID"]);
- }
- dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and SizeL<={1} and SizeW>={1}", material, size);
- if (dv.Count > 0)
- {
- return Convert.ToInt32(dv[0]["SupplierID"]);
- }
- }
- dv.RowFilter = string.Format("ProductCrafts like '%{0}%'", material);
- if (count > 0)
- {
- dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1}", material, count);
- if (dv.Count > 0)
- {
- return Convert.ToInt32(dv[0]["SupplierID"]);
- }
- dv.RowFilter = string.Format("MinNum<={0} and MaxNum>={0}", count);
- if (dv.Count > 0)
- {
- return Convert.ToInt32(dv[0]["SupplierID"]);
- }
- }
- if (size > 0)
- {
- dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and SizeL<={1} and SizeW>={1}", material, size);
- if (dv.Count > 0)
- {
- return Convert.ToInt32(dv[0]["SupplierID"]);
- }
- dv.RowFilter = string.Format(" SizeL<={0} and SizeW>={0}", size);
- if (dv.Count > 0)
- {
- return Convert.ToInt32(dv[0]["SupplierID"]);
- }
- }
- dv.RowFilter = string.Format("Crafts like '%{0}%' or Crafts like '%{1}%'", crafts, supplierCrafts);
- if (dv.Count > 0)
- {
- return Convert.ToInt32(dv[0]["SupplierID"]);
- }
- //产品 材质符合
- dv.RowFilter = string.Format("ProductCrafts like '%{0}%' ", material);
- if (dv.Count > 0)
- {
- return Convert.ToInt32(dv[0]["SupplierID"]);
- }
- else
- {
- return topOneProductSupplier;
- }
- }
- catch (Exception ex)
- {
- XLog.SaveLog(0, "commmonHelper:autoDistributeToSupplier" + ex.Message);
- }
- }
- return 0;
- }
- public static void setDeliveryUnusualOrder2()
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("select ctid,IsSF,seller_memo,SupplierId,productId,FinishPlaceTime,ProductCount from view_ErpTradeCell where orderstate=6 and unusualTag=0 and FinishPlaceTime is not null AND DATEDIFF( HH, FinishPlaceTime, GETDATE( ) ) > 24 AND DATEDIFF( DAY, FinishPlaceTime, GETDATE( ) ) < 20 and IsXianHuo=0 and IsSample=0;");
- DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
- List<string> tLst = new List<string>();
- if (dt != null && dt.Rows.Count > 0)
- {
- foreach (DataRow row in dt.Rows)
- {
- try
- {
- int supplierId = Convert.ToInt32(row["SupplierId"]);
- int productId = Convert.ToInt32(row["productId"]);
- if (supplierId == 0 || productId == 0)
- {
- continue;
- }
- StringBuilder timerSql = new StringBuilder();
- timerSql.AppendFormat("SELECT * FROM CE_ErpSupplierProductTime WHERE supplierId={0}", supplierId);
- DataTable timerTable = DbHelper.DbConn.ExecuteDataset(timerSql.ToString()).Tables[0];
- //没配置时间
- if (timerTable == null || timerTable.Rows.Count == 0)
- {
- continue;
- }
- string[] productIds = null;
- string finishPlaceTime = row["FinishPlaceTime"].ToString();
- string sellmer_mome = row["seller_memo"].ToString();
- string txtCount = row["ProductCount"].ToString();
- DateTime placeTime = DateTime.Now;
- if (string.IsNullOrEmpty(finishPlaceTime))
- {
- continue;
- }
- placeTime = DateTime.Parse(finishPlaceTime);
- foreach (DataRow dr in timerTable.Rows)
- {
- string txtIds = dr["productId"].ToString();
- string[] crafts = { };
- int count = Convert.ToUInt16(dr["quantity"]);
- if (string.IsNullOrEmpty(txtIds))
- {
- continue;
- }
- if (count > 0)
- {
- int quantity = handleProductCount(txtCount, true);
- //订单数量大于写入的数量则跳过
- if (quantity > count)
- {
- continue;
- }
- }
- productIds = txtIds.Split(',');
- if (productIds.Contains(productId.ToString()))
- {
- string textCraft = dr["craft"].ToString();
- textCraft = textCraft.Replace(",", ",");//统一格式
- if (!string.IsNullOrEmpty(textCraft))
- {
- crafts = textCraft.Split(',');
- }
- if (crafts.Length > 0)
- {
- bool isinCraft = false;
- for (int i = 0; i < crafts.Length; i++)
- {
- if (sellmer_mome.IndexOf(crafts[i]) >= 0)
- {
- isinCraft = true;
- break;
- }
- }
- //有写工艺并且备注中没匹配中则跳过
- if (!isinCraft)
- {
- continue;
- }
- }
- DateTime deadLine = DateTime.Parse(dr["deadLine"].ToString());
- DateTime dayDeadLine = DateTime.Parse(dr["dayDeadLine"].ToString());
- int sendDay = Convert.ToInt16(dr["sendDay"]);
- //订单发货时间
- DateTime sendtime = placeTime;
- //下单时间小于当日发货时间则不用判断
- //当日发货必须发货
- if (dayDeadLine.Hour > 0 && dayDeadLine.Hour > placeTime.Hour)
- {
- sendtime = DateTime.Parse(placeTime.ToString("yyyy-MM-dd 23:59:59"));
- }
- else if (deadLine.Hour > 0 && deadLine.Hour > placeTime.Hour)
- {
- //在截稿时间之前下单的可以减去一天时间
- sendDay = Math.Max(1, sendDay - 2);
- sendtime = DateTime.Parse(placeTime.ToString("yyyy-MM-dd 23:59:59")).AddDays(sendDay);
- }
- else
- {
- sendDay = Math.Max(1, sendDay - 1);
- sendtime = DateTime.Parse(placeTime.ToString("yyyy-MM-dd 23:59:59")).AddDays(sendDay);
- }
- //判断有没有到发货日期大于0还没到发货时间
- if (DateTime.Compare(sendtime.Date, DateTime.Now.Date) < 0)
- {
- tLst.Add("'" + row["ctid"].ToString() + "'");
- //匹配到就不要继续匹配了
- break;
- }
- }
- }
- }
- catch (Exception ex)
- {
- XLog.SaveLog(0, row["ctid"].ToString() + "更新发货异常订单错误:" + ex);
- }
- }
- }
- if (tLst.Count > 0)
- {
- string needctids = string.Join(",", tLst.ToArray());
- StringBuilder updsql = new StringBuilder();
- //DateTime unusualTime = new DateTime();
- updsql.AppendFormat("update ce_erptradecell with(rowlock) set unusualTag=5,UnusualTime=getDate() where ctid in ({0});", needctids);
- DbHelper.DbConn.ExecuteNonQuery(updsql.ToString());
- }
- }
- public static void setDeliveryUnusualOrder()
- {
- try
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("select * from view_ErpTradeCell where orderstate=6 and unusualTag=0 and FinishPlaceTime is not null and DATEDIFF(HH,FinishPlaceTime,GETDATE())>48 and DATEDIFF(DAY,FinishPlaceTime,GETDATE())<20 and IsXianHuo=0 and (IsSample=0 or IsSample=2);");
- DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
- List<string> tLst = new List<string>();
- if (dt.Rows.Count > 0)
- {
- foreach (DataRow dr in dt.Rows)
- {
- double hour = 0;
- string fptime = dr["FinishPlaceTime"].ToString();
- if (fptime.Length > 0)
- {
- hour = DateTime.Now.Subtract(Convert.ToDateTime(fptime)).TotalHours;
- }
- else
- continue;
- int useHour = 10000;
- StringBuilder sqlhour = new StringBuilder();
- sqlhour.AppendFormat("select top 1 * from CE_ErpProductHour where ProductID={0} and (CHARINDEX(Material,'{1}')>0 or Material='*') and (CHARINDEX(Craft,'{2}')>0 or Craft='*');", dr["ProductId"].ToString(), dr["Material"].ToString(), dr["Craft"].ToString());
- DataTable dthour = DbHelper.DbConn.ExecuteDataset(sqlhour.ToString()).Tables[0];
- if (dthour.Rows.Count > 0)
- {
- useHour = Convert.ToInt32(dthour.Rows[0]["fhTime"]);
- }
- else
- {
- sqlhour = new StringBuilder();
- sqlhour.AppendFormat("select top 1 * from CE_ErpProductHour where ProductID={0} and (CHARINDEX(Craft,'{1}')>0 or Craft='*');", dr["ProductId"].ToString(), dr["Craft"].ToString());
- dthour = DbHelper.DbConn.ExecuteDataset(sqlhour.ToString()).Tables[0];
- if (dthour.Rows.Count > 0)
- {
- useHour = Convert.ToInt32(dthour.Rows[0]["fhTime"]);
- }
- else
- {
- sqlhour = new StringBuilder();
- sqlhour.AppendFormat("select top 1 * from CE_ErpProductHour where ProductID={0};", dr["ProductId"].ToString());
- dthour = DbHelper.DbConn.ExecuteDataset(sqlhour.ToString()).Tables[0];
- if (dthour.Rows.Count > 0)
- {
- useHour = Convert.ToInt32(dthour.Rows[0]["fhTime"]);
- }
- }
- }
- if (hour > useHour)
- {
- tLst.Add("'" + dr["ctid"].ToString() + "'");
- }
- }
- }
- sql = new StringBuilder();
- sql.AppendFormat("select * from view_ErpTradeCell where orderstate=6 and unusualTag=0 and FinishPlaceTime is not null and DATEDIFF(HH,FinishPlaceTime,GETDATE())>3 and DATEDIFF(DAY,FinishPlaceTime,GETDATE())<20 and IsXianHuo=1 ;");
- dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
- if (dt.Rows.Count > 0)
- {
- foreach (DataRow dr in dt.Rows)
- {
- double hour = 0;
- string fptime = dr["FinishPlaceTime"].ToString();
- string paytime = dr["pay_time"].ToString();
- DateTime dtPaytime = Convert.ToDateTime(paytime);
- if (fptime.Length > 0)
- {
- hour = DateTime.Now.Subtract(Convert.ToDateTime(paytime)).TotalHours;
- }
- else
- continue;
- DateTime nowtime = DateTime.Now;
- if (hour > 18)
- {
- tLst.Add("'" + dr["ctid"].ToString() + "'");
- }
- //if (hour > 72 && Convert.ToInt32(dr["ShopId"])==34)//公司自用
- //{
- // tLst.Add("'" + dr["ctid"].ToString() + "'");
- //}
- //else if (nowtime.Hour >= 17)
- //{
- // if((dtPaytime.Hour >= 14 && dtPaytime.Hour < 17) || (dtPaytime.Hour == 17 && dtPaytime.Minute < 40))
- // {
- // string sptime = nowtime.Year + "/" + nowtime.Month + "/" + nowtime.Day + " 17:40:00";
- // DateTime spDatetime = Convert.ToDateTime(sptime);
- // if (spDatetime.Subtract(Convert.ToDateTime(paytime)).TotalMinutes > 0)
- // {
- // tLst.Add("'" + dr["ctid"].ToString() + "'");
- // }
- // }
- //}
- //else if (nowtime.Hour >= 14)
- //{
- // if(dtPaytime.Hour >= 10 && dtPaytime.Hour < 14)
- // {
- // string sptime = nowtime.Year + "/" + nowtime.Month + "/" + nowtime.Day + " 14:00:00";
- // DateTime spDatetime = Convert.ToDateTime(sptime);
- // if (spDatetime.Subtract(Convert.ToDateTime(paytime)).TotalMinutes > 0)
- // {
- // tLst.Add("'" + dr["ctid"].ToString() + "'");
- // }
- // }
- //}
- //else if (nowtime.Hour >= 10)
- //{
- // if (dtPaytime.Hour >= 18 || dtPaytime.Hour < 10)
- // {
- // string sptime = nowtime.Year + "/" + nowtime.Month + "/" + nowtime.Day + " 10:00:00";
- // DateTime spDatetime = Convert.ToDateTime(sptime);
- // if (spDatetime.Subtract(Convert.ToDateTime(paytime)).TotalMinutes > 0)
- // {
- // tLst.Add("'" + dr["ctid"].ToString() + "'");
- // }
- // }
- //}
- }
- }
- if (tLst.Count > 0)
- {
- string needctids = string.Join(",", tLst.ToArray());
- StringBuilder updsql = new StringBuilder();
- //DateTime unusualTime = new DateTime();
- updsql.AppendFormat("update ce_erptradecell with(rowlock) set unusualTag=5,UnusualTime=getDate() where ctid in ({0});", needctids);
- DbHelper.DbConn.ExecuteNonQuery(updsql.ToString());
- }
- }
- catch (Exception ex)
- {
- XLog.SaveLog(0, "更新发货异常订单错误:" + ex.Message);
- }
- splitCell2AllPlaceOrder();
- }
- public static void splitCell2AllPlaceOrder()
- {
- //
- int spid = 0;
- try
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("select * from CE_ErpTradeCell2 where DATEDIFF(DAY, FinishPlaceTime, GETDATE())<5 and MakeSupplier like '%,%';");
- DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
- List<string> idList = new List<string>();
- foreach (DataRow dr in dt.Rows)
- {
- string msup = dr["MakeSupplier"].ToString();
- string[] suplist = msup.Split(',');
- spid = Convert.ToInt32(dr["ID"]);
- foreach (string supItem in suplist)
- {
- StringBuilder newsql = new StringBuilder();
- newsql.AppendFormat(" insert into CE_ErpTradeCell2 ([ctid],[tid],[DesignUserId],[OrderState],[CustomerUserId],[IsUrgency],[IsRefund],[IsReturn],[IsNeedBill]," +
- "[SupplierId],[DeliveryAddress],[CallTimes],[NoteTimes],[OvertimeUserId],[UnusualTag],[UnusualCon],[ReturnReason],[MemoOpt],[AfterSaleTime],[AfterSaleUserId]," +
- "[AfterSaleReason],[PlaceUserId],[AfterSaleState],[AfterSaleMethod],[AfterSaleMemo],[AfterSaleResponsible],[AfterSalePreTime],[FinishAfterSaleTime],[DeductFee]," +
- "[RefundFee],[HandleTime],[IsHaveNewOrder],[ResponsibleUserId],[ptid],[IsPreDelivery],[IsSample],[seller_memo],[ProductId],[WaitDesignTime],[StartDesignTime]," +
- "[FinishDesignTime],[FinishPlaceTime],[FinishDeliveryTime],[DesignSelfMemo],[DesignPrice],[Material],[Craft],[ProductSize],[ProductCount],[UnusualTime],[IsAutoDispatch]," +
- "[IsVerifyToSupplier],[CustomerMemo],[payment],[OutSid],[AfterSalePayment],[ShopId],[SplitTag],[isAfterSaleOrder],[isDianziOrder],[LastBillCpCode],[LastBillWaybillCode]," +
- "[pay_time],[IsSF],[IsXianHuo],[ReturnTime],[OtherMemo],[AfterSaleBackReason],[CheckMemo],[IsOldCustomer],[IsSupplierRefund],[IsReadTag],[AfterSaleMemoType]," +
- "[UrgencyTime],[IsOffLineOrder],[PayProofImg],[wechatTag],[MakeSupplier]) select [ctid],[tid],[DesignUserId],[OrderState],[CustomerUserId],[IsUrgency],[IsRefund]," +
- "[IsReturn],[IsNeedBill],[SupplierId],[DeliveryAddress],[CallTimes],[NoteTimes],[OvertimeUserId],[UnusualTag],[UnusualCon],[ReturnReason],[MemoOpt],[AfterSaleTime]," +
- "[AfterSaleUserId],[AfterSaleReason],[PlaceUserId],[AfterSaleState],[AfterSaleMethod],[AfterSaleMemo],[AfterSaleResponsible],[AfterSalePreTime],[FinishAfterSaleTime]," +
- "[DeductFee],[RefundFee],[HandleTime],[IsHaveNewOrder],[ResponsibleUserId],[ptid],[IsPreDelivery],[IsSample],[seller_memo],[ProductId],[WaitDesignTime],[StartDesignTime]," +
- "[FinishDesignTime],[FinishPlaceTime],[FinishDeliveryTime],[DesignSelfMemo],[DesignPrice],[Material],[Craft],[ProductSize],[ProductCount],[UnusualTime],[IsAutoDispatch]," +
- "[IsVerifyToSupplier],[CustomerMemo],[payment],[OutSid],[AfterSalePayment],[ShopId],[SplitTag],[isAfterSaleOrder],[isDianziOrder],[LastBillCpCode],[LastBillWaybillCode]," +
- "[pay_time],[IsSF],[IsXianHuo],[ReturnTime],[OtherMemo],[AfterSaleBackReason],[CheckMemo],[IsOldCustomer],[IsSupplierRefund],[IsReadTag],[AfterSaleMemoType],[UrgencyTime]," +
- "[IsOffLineOrder],[PayProofImg],[wechatTag],'{1}' from CE_ErpTradeCell2 where ID={0}", Convert.ToInt32(dr["ID"]), supItem);
- DbHelper.DbConn.ExecuteNonQuery(newsql.ToString());
- }
- idList.Add(dr["ID"].ToString());
- }
- string idsstr = string.Join(",", idList.ToArray());
- sql.AppendFormat("delete from CE_ErpTradeCell2 where ID in ({0})", idsstr);
- DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
- }
- catch (Exception ex)
- {
- XLog.SaveLog(0, "拆分ce_erptradecell2表的制作车间出错:" + spid + ex.Message);
- }
- }
- public static void DoAutoDispatch(string conn)
- {
- if (webConfig.Dispatch_TimeList.Contains(DateTime.Now.ToString("HH:mm")))
- {
- WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "开始自动派单!"));
- SqlParameter[] sqlParameter ={
- new SqlParameter("@res", SqlDbType.VarChar, 50)};
- sqlParameter[0].Direction = ParameterDirection.Output;
- CeErpOpt.ExecuteNonQueryStore("sp_autodispatch", sqlParameter);
- string res = sqlParameter[0].Value.ToString();
- if (res == "派单完成") WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "结束自动派单!"));
- else WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "无法成功派单"));
- }
- //sp_autodispatch
- }
- public static void DoAutoDispatch2(string conn)
- {
- if (webConfig.Dispatch_TimeList.Contains(DateTime.Now.ToString("HH:mm")))
- {
- WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "开始自动派单!"));
- SqlConnection sqlCnt = new SqlConnection(conn);
- try
- {
- sqlCnt.Open();
- string sql = "select * from view_ErpTradeCell where OrderState = 2 and ProductId <> 0";
- SqlDataAdapter myDataAdapter = new SqlDataAdapter(sql, sqlCnt);
- DataSet myDataSet = new DataSet();
- myDataAdapter.Fill(myDataSet, "Trade");
- DataTable myTable = myDataSet.Tables[0];
- List<string> ids = new List<string>();
- foreach (DataRow Dr in myTable.Rows)
- {
- if (Convert.ToInt32(Dr["OrderState"]) > 2 || Convert.ToInt32(Dr["DesignUserId"]) > 0)
- {
- continue;
- }
- ids.Add(Dr["ctid"].ToString());
- CeErpShop nShop = CeErpShop.GetShopIdByName(Dr["seller_nick"].ToString());
- string shopId = "0";
- if (nShop != null)
- {
- shopId = nShop.ID.ToString();
- }
- string proId = Dr["ProductId"].ToString();
- string Amount = Dr["payment"].ToString();
- string ctid = Dr["ctid"].ToString();
- string ctids = "";
- if (ctid.IndexOf("C") != -1)
- {
- ctids = getSameTradeByTid(Dr["tid"].ToString());
- if (ctids.Length <= 0)
- {
- continue;
- }
- }
- else
- {
- ctids = "'" + ctid + "'";
- }
- sql = "select top 1 * from view_ErpUser " +
- "where PostCode = 'Designer' and " + //设计师
- "OnDuty = 1 and " + //上班状态
- "DayOrderReceive < DayOrderLimit and " + //当日接单数小于可接单数量上限
- "OrderAmountLimit >= " + Amount + " and " + //额度上限大于付款金额
- "CHARINDEX('," + shopId + ",',','+OrgShop+ ',')>0 and " + //部门关联店铺
- "CHARINDEX('," + shopId + ",',','+pemShop+ ',')>0 and " + //个人关联店铺
- "CHARINDEX('," + proId + ",',','+pemDesign+ ',')>0 " + //个人关联产品
- "order by DayOrderPer, PostLevel desc, Id";
- SqlDataAdapter userAdapter = new SqlDataAdapter(sql, sqlCnt);
- DataSet userSet = new DataSet();
- userAdapter.Fill(userSet, "user");
- DataTable userTable = userSet.Tables[0];
- //有满足条件的设计师
- if (userTable.Rows.Count > 0)
- {
- SqlCommand updCMD = sqlCnt.CreateCommand();
- try
- {
- updCMD.Transaction = sqlCnt.BeginTransaction();//开启事务
- //派单
- updCMD.CommandText = "update CE_ErpTradeCell set OrderState = 3, IsAutoDispatch = 1, WaitDesignTime = getdate(), DesignUserId = " + userTable.Rows[0]["ID"].ToString() + " where ctid in (" + ctids + ")";
- updCMD.ExecuteNonQuery();
- //更新日数量上限和可接单比例
- updCMD.CommandText = "update view_ErpUser set DayOrderReceive = DayOrderReceive + 1, DayOrderPer = CAST((CAST(((DayOrderReceive + 1)) as decimal(8,5)) / DayOrderLimit) as decimal(8,3)) where id = " + userTable.Rows[0]["ID"].ToString();
- updCMD.ExecuteNonQuery();
- //写订单日志
- updCMD.CommandText = "insert into CE_ErpTradeLog(tid,OrderState,UserId,OperateTime,Con) select ctid,OrderState,0,getdate(),'自动派单' from ce_erptradecell where ctid in(" + ctids + ")";
- updCMD.ExecuteNonQuery();
- updCMD.Transaction.Commit();//提交事务(真正的从数据库中修改了数据)
- }
- catch (Exception ee)
- {
- updCMD.Transaction.Rollback();
- }
- }
- }
- string sql1 = "select ctid from view_ErpTradeCell where orderstate=3 and DesignUserId = 2125 and ctid in ('" + string.Join(",", ids) + "');";
- /* string sql1 = "select ctid from view_ErpTradeCell where orderstate=3 and DesignUserId = 2125 ";*/
- DataTable dt1 = SqlHelper.ExecuteDataSet(sql1).Tables[0];
- foreach (DataRow dr1 in dt1.Rows)
- {
- apiDesign.API_GetPrintData_CreateOrder(CeErpTradeCell.GetByCtid(dr1["ctid"].ToString()));
- WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "开始派单" + dr1["ctid"].ToString() + "至设计系统!"));
- Thread.Sleep(1000); // 添加五秒延迟
- }
- WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "结束自动派单!"));
- }
- catch (Exception ed)
- {
- WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), ed.Message));
- }
- finally
- {
- if (sqlCnt.State == ConnectionState.Open)
- sqlCnt.Close();
- }
- }
- }
- public static string getSameTradeByTid(string tid)
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("select ctid from view_ErpTradeCell where tid='{0}';", tid);
- DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
- if (dt.Rows.Count > 0)
- {
- string ctids = "";
- foreach (DataRow dr in dt.Rows)
- {
- ctids += "'";
- ctids += dr["ctid"].ToString();
- ctids += "'";
- ctids += ",";
- }
- ctids = ctids.Substring(0, ctids.Length - 1);
- return ctids;
- }
- else
- return "";
- }
- public static void WriteLog(string LogText)
- {
- string sDir = System.IO.Path.GetTempPath() + @"Log\" + DateTime.Now.ToString("yyyyMM");
- if (!Directory.Exists(sDir))
- Directory.CreateDirectory(sDir);
- using (StreamWriter sw = new StreamWriter(sDir + @"\Log_" + DateTime.Now.ToString("dd") + ".txt", true, Encoding.UTF8))
- {
- sw.Write(LogText + System.Environment.NewLine);
- }
- }
- public static void UpdateRelationOrder(string ctid)
- {
- if (ctid.Length <= 0) return;
- CeErpTradeCell.UpdateRelationOrder(ctid);
- //try
- //{
- // //父订单变化,更新补差价订单
- // //List<string> lw = new List<string>();
- // //lw.Add(string.Format("OrderState={0}", father.OrderState));
- // //lw.Add(string.Format("CustomerUserId={0}", father.CustomerUserId));
- // //lw.Add(string.Format("DesignUserId={0}", father.DesignUserId));
- // //lw.Add(string.Format("AfterSaleState={0}", father.AfterSaleState));
- // //lw.Add(string.Format("IsNeedBill={0}", father.IsNeedBill));
- // ////lw.Add(string.Format("IsUrgency={0}", father.IsUrgency == true ? 1 : 0));
- // //lw.Add(string.Format("IsRefund={0}", father.IsRefund));
- // //lw.Add(string.Format("WaitDesignTime='{0}'", father.WaitDesignTime.ToString()));
- // //lw.Add(string.Format("StartDesignTime='{0}'", father.StartDesignTime.ToString()));
- // //lw.Add(string.Format("FinishDesignTime='{0}'", father.FinishDesignTime.ToString()));
- // //lw.Add(string.Format("FinishPlaceTime='{0}'", father.FinishPlaceTime.ToString()));
- // //lw.Add(string.Format("FinishDeliveryTime='{0}'", father.FinishDeliveryTime.ToString()));
- // ////lw.Add(string.Format("IsReturn={0}", father.IsReturn));
- // //string sqlstr = string.Join(" , ", lw.ToArray());
- // //StringBuilder sql = new StringBuilder();
- // //sql.AppendFormat("update ce_erptradecell set " + sqlstr + " where ptid='{0}'", father.tid);
- // ////sql.AppendFormat("update view_erptrade set status={1} where ptid={0}", father.ctid, father.status);
- // //DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
- // //StringBuilder sql = new StringBuilder();
- // //sql.Append("update ce_erptradecell set OrderState=b.OrderState,CustomerUserId=b.CustomerUserId,DesignUserId=b.DesignUserId,WaitDesignTime=b.WaitDesignTime,StartDesignTime=b.StartDesignTime,FinishDesignTime=b.FinishDesignTime,FinishPlaceTime=b.FinishPlaceTime,");
- // //sql.Append("AfterSaleState=b.AfterSaleState,IsNeedBill=b.IsNeedBill,IsRefund=b.IsRefund from ce_erptradecell,ce_erptradecell as b ");
- // //sql.AppendFormat("where ce_erptradecell.ptid =b.tid and ce_erptradecell.ptid='{0}'", tid);//='1827905618077154637'
- // //DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
- // //SqlParameter[] sqlParameter ={
- // // new SqlParameter("@mainctids", SqlDbType.VarChar,100),
- // // new SqlParameter("@res", SqlDbType.VarChar, 4000)
- // //};
- // //sqlParameter[0].Value = ctid;
- // //sqlParameter[1].Direction = ParameterDirection.Output;
- // //DbHelper.DbConn.ExecuteNonQuery(CommandType.StoredProcedure, "sp_set_bucha", sqlParameter);
- //}
- //catch (Exception ex)
- //{
- // XLog.SaveLog(0, "commmonHelper:UpdateRelationOrder" + ex.Message);
- //}
- }
- public static void UpdateSameOrderToDesigner(CeErpTradeCell entity, int designId)
- {
- CeErpTrade trade = CeErpTrade.Get(entity.tid);
- if (trade != null)
- {
- StringBuilder sql = new StringBuilder();
- if (trade.type == "PDD" || trade.type == "JD")
- {
- sql.AppendFormat("update view_ErpTradeCell with(rowlock) set OrderState=3,WaitDesignTime=getDate(),DesignUserId={0} where buyer_nick='{1}' and tid='{4}' and seller_nick='{2}' and ABS(DATEDIFF(HH,'{3}',pay_time))<24 and orderstate=2 and productid<>0 and designuserid=0 and payment>0 and IsRefund=0;", designId, trade.buyer_nick, trade.seller_nick, trade.pay_time, trade.tid);
- }
- else
- sql.AppendFormat("update view_ErpTradeCell with(rowlock) set OrderState=3,WaitDesignTime=getDate(),DesignUserId={0} where buyer_nick='{1}' and seller_nick='{2}' and ABS(DATEDIFF(HH,'{3}',pay_time))<24 and orderstate=2 and productid<>0 and designuserid=0 and payment>0 and IsRefund=0;", designId, trade.buyer_nick, trade.seller_nick, trade.pay_time);
- DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
- }
- }
- public static void SetSameSupplierToOrder(CeErpTradeCell entity, int supId)
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("update CE_ErpTradeCell with(rowlock) set SupplierId={0} where orderstate=5 and tid='{1}';", supId, entity.tid);
- DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
- }
- public static string MidStrEx(string sourse, string startstr, string endstr)
- {
- string result = string.Empty;
- int startindex, endindex;
- try
- {
- startindex = sourse.IndexOf(startstr);
- if (startindex == -1)
- return result;
- string tmpstr = sourse.Substring(startindex + startstr.Length);
- endindex = tmpstr.IndexOf(endstr);
- if (endindex == -1)
- return result;
- result = tmpstr.Remove(endindex);
- }
- catch (Exception ex)
- {
- Console.WriteLine("MidStrEx Err:" + ex.Message);
- }
- return result;
- }
- public static string KeepChinese(string str)
- {
- string chineseString = "";
- for (int i = 0; i < str.Length; i++)
- {
- if (str[i] >= 0x4E00 && str[i] <= 0x9FA5)
- {
- chineseString += str[i];
- }
- }
- return chineseString;
- }
- public static string GetD3ComCode(string code, string name)
- {
- string useStr = code;
- if (code.Length == 0)
- {
- useStr = name;
- }
- string sql = "select * from CE_ErpMailInfo";
- DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
- foreach (DataRow dr in dt.Rows)
- {
- if (dr["cpCode"].ToString().IndexOf(useStr) != -1)
- {
- return dr["cpCode"].ToString();
- }
- }
- //声明存储结果的字符串
- //string codeStr = "YTO-CAINIAO,HTKY-CAINIAO-GZ,YUNDA-CAINIAO-GZ,STO-CAINIAO-SC,STO-CAINIAO-JS,STO-CAINIAO-LN,ZTO-CAINIAO-GZ,ZTO-CAINIAO-FS,ZTO-CAINIAO-KF,ZTO-CAINIAO-ZZ,DISTRIBUTOR_1710055-LY,STO-CAINIAO-AH," +
- // "EYB-CAINIAO-LY,EMS-CAINIAO-LY,POST-CAINIAO-LY,UC-CAINIAO-LY,DBL-CAINIAO-LY,DBKD-CAINIAO-LY,XFWL-CAINIAO-LY,AN-CAINIAO-LY,STO-CAINIAO-LY,DISTRIBUTOR_13222803-LY,BESTQJT-CAINIAO-LY,ZTO-CAINIAO-YW," +
- // "SF-CAINIAO-LY,SF-DF-CAINIAO-LY,SF-CAINIAO-HNXX,SF-CAINIAO-GDFS,SF-CAINIAO-JSTZ,SF-DF-CAINIAO-HNXX,SF-DF-CAINIAO-GDFS,SF-DF-CAINIAO-JSTZ,POSTB-CAINIAO-LY,ZTO-CAINIAO-JS,POSTB-CAINIAO-FS," +
- // "YUNDA-CAINIAO-JA,SF-CAINIAO-GDGZ,YUNDA-CAINIAO-GDFS,";
- //string[] codeList = codeStr.Split(',');
- ////将传入参数中的中文字符添加到结果字符串中
- //for (int i = 0; i < codeList.Length; i++)
- //{
- // if (codeList[i].IndexOf(useStr) != -1)
- // {
- // return codeList[i];
- // }
- //}
- //返回保留中文的处理结果
- return "";
- }
- public static int getRefundTagByState(string st, int isPart = 0)
- {
- int state = 0;
- if (st == "NO_REFUND" || st == "SELLER_REFUSE_BUYER" || st == "CLOSED" || st == "FAILED")
- {
- state = 0;
- }
- else if (st == "REFUNDING")
- {
- state = 1;
- }
- else if (st == "REFUNDED" || st == "SUCCESS")
- {
- state = 2;
- }
- else if (st == "PART_REFUNDED" || isPart == 1)
- {
- state = 3;
- }
- else if (st == "WAIT_BUYER_RETURN_GOODS")
- {
- state = 4;
- }
- else if (st == "REJECT_REFUNDED")
- {
- state = 5;
- }
- else if (st == "WAIT_SELLER_CONFIRM_GOODS")
- {
- state = 6;
- }
- return state;
- }
- public static string getRefundStringByState(string st)
- {
- string stateStr = "";
- if (st == "NOT_SHIPPED")
- {
- stateStr = "待发货";
- }
- else if (st == "PART_SHIPPED")
- {
- stateStr = "部分发货";
- }
- else if (st == "SHIPPED")
- {
- stateStr = "已发货";
- }
- else if (st == "COMPLETE")
- {
- stateStr = "已完成";
- }
- else if (st == "CLOSE")
- {
- stateStr = "已关闭";
- }
- else if (st == "REFUNDED")
- {
- stateStr = "退款成功";
- }
- else if (st == "PART_REFUNDED")
- {
- stateStr = "部分退款";
- }
- else if (st == "WAIT_BUYER_RETURN_GOODS")
- {
- stateStr = "等待买家退货";
- }
- else if (st == "REJECT_REFUNDED")
- {
- stateStr = "拒绝退货";
- }
- else if (st == "WAIT_SELLER_CONFIRM_GOODS")
- {
- stateStr = "等待卖家确认收货";
- }
- else if (st == "SELLER_REFUSE_BUYER")
- {
- stateStr = "卖家拒绝退款";
- }
- else if (st == "SUCCESS")
- {
- stateStr = "退款成功";
- }
- else if (st == "CLOSED")
- {
- stateStr = "退款关闭";
- }
- else if (st == "FAILED")
- {
- stateStr = "退款失败";
- }
- return stateStr;
- }
- public static void UpdateRefundOrderState(string tid, int rstate)
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("insert into S_BuChaJia(ctid,addtime,dotype,refundState) values('{0}',getdate(),'refund',{1}); ", tid, rstate);
- DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
- }
- public static void checkBillResult(int billId)
- {
- CeErpBill entiy = CeErpBill.Get(billId);
- if (entiy != null)
- {
- try
- {
- string[] billOrderList = entiy.billOrderId.Split(',');
- int iTag = 0;
- entiy.fplsh = "";
- entiy.fpdm = "";
- entiy.fphm = "";
- foreach (string billOrderId in billOrderList)
- {
- iTag++;
- string res = taobaoHelper.get_invoicing(billId.ToString(), billOrderId);
- int fcount = StrCount(res, "c_orderno");
- if (res.IndexOf("success") != -1 && res.IndexOf("开票中") != -1)
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("insert into S_BuChaJia(ctid,addtime,dotype) values('{0}',getdate(),'billres'); ", billId.ToString());
- DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
- return;
- }
- else if (res.IndexOf("success") != -1 && (res.IndexOf("开票成功") != -1 || res.IndexOf("开票完成") != -1))
- {
- //res = GetUTF8String2(Encoding.UTF8.GetBytes(res));
- try
- {
- Invoicing_get_response_Obj iObj = null;
- iObj = JsonConvert.DeserializeObject<Invoicing_get_response_Obj>(res);
- if (iObj != null)
- {
- if (fcount > 1)
- {
- entiy.state = 4; //红冲作废
- }
- else
- entiy.state = 2; //开票完成
- entiy.fplsh += iObj.list[0].c_fpqqlsh;
- entiy.fpdm += iObj.list[0].c_fpdm;
- entiy.fphm += iObj.list[0].c_fphm;
- if (iTag < billOrderList.Length)
- {
- entiy.fplsh += ",";
- entiy.fpdm += ",";
- entiy.fphm += ",";
- }
- entiy.Update();
- }
- if (fcount <= 1)
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("update CE_ErpTradeCell WITH(ROWLOCK) set IsNeedBill=2 where tid='{0}';", entiy.tid);
- DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
- }
- }
- catch (Exception ex)
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("insert into S_BuChaJia(ctid,addtime,dotype) values('{0}',getdate(),'billres'); ", billId.ToString());
- DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
- XLog.SaveLog(0, "查看开票结果,更新状态失败" + ex.Message + res);
- }
- return;
- }
- else
- {
- string redError = "";
- if (fcount > 1)
- {
- redError = "红冲失败";
- }
- int eidx = res.IndexOf("c_resultmsg");
- string emsg = KeepChinese(res.Substring(eidx, res.Length - eidx));
- //开票失败
- entiy.state = 5;
- entiy.failerror = entiy.failerror + (iTag + "&" + redError + emsg + "|");
- entiy.Update();
- return;
- }
- }
- }
- catch (Exception ex)
- {
- XLog.SaveLog(0, "buchajia查看开票结果错误," + ex.Message);
- }
- }
- }
- public static void insertToBuchaForDelivery(string Maintid, string posCode, string comCode, string outSid)
- {
- if (Maintid.Length <= 0) return;
- try
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("insert into S_BuChaJia(ctid,addtime,dotype,posCode,comCode,outSid) select tid,getdate(),'bucha_delivery','{1}','{2}','{3}' from ce_erptradecell where ptid='{0}'; ", Maintid, posCode, comCode, outSid);
- DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
- //}
- }
- catch (Exception ex)
- {
- XLog.SaveLog(0, "commhelper,insertToBuchaForDelivery,insert" + ex.Message);
- //}
- }
- }
- public static void setBuChaDelivery(string tid, string posCode, string comCode, string outSid)
- {
- outSid = outSid.Trim();
- posCode = posCode.Trim();
- comCode = comCode.Trim();
- CeErpTrade mainEn = CeErpTrade.Get(tid);
- if (mainEn != null)
- {
- if (mainEn.status == "SHIPPED" || mainEn.status == "PART_SHIPPED" || mainEn.status == "COMPLETE" || mainEn.status == "CLOSE") //已发货的不处理直接返回面单
- {
- return;
- //不处理
- }
- string apires = apiHelper.API_LogisticsDummySend(tid, posCode);
- if (apires.IndexOf("发货成功") == -1)
- {
- XLog.SaveLog(0, "补差价单虚拟发货失败," + tid + "," + posCode + "," + apires);
- string wures = apiHelper.API_LogisticsOnlineSend(tid, posCode, comCode, outSid, "");
- if (wures.IndexOf("发货成功") == -1)
- {
- XLog.SaveLog(0, "补差价单实物发货失败," + tid + "," + posCode + "," + wures);
- return;
- }
- else
- {
- LogHelper.addLog(tid, 0, "补差价发货-" + comCode + "-" + outSid);
- }
- return;
- }
- else
- {
- LogHelper.addLog(tid, 0, "补差价发货-" + comCode + "-" + outSid);
- }
- }
- }
- public static int StrCount(string str, string constr)
- {
- return System.Text.RegularExpressions.Regex.Matches(str, constr).Count;
- }
- public static void saveErpDesignerGather()
- {
- string date1 = DateTime.Now.AddDays(-1).ToString();
- string date2 = DateTime.Now.AddDays(-1).ToString();
- //string date1 = DateTime.Now.ToString();
- //string date2 = DateTime.Now.ToString();
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("select ID from view_ErpUser where (PostCode = 'Designer' or PostCode = 'DesignerMr'or PostCode = 'Designerhd' or PostCode = 'wxDesigner' or PostCode='wxDesignerMr') and isOpen = 1 and ID not in(select did from CE_ErpDesignerFinishRate where DATEDIFF(day, '{0}', CTime) = 0)", date1);
- DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
- foreach (DataRow dr in dt.Rows)
- {
- SqlParameter[] sqlParameter ={
- new SqlParameter("@sDisDate", SqlDbType.DateTime, 20),
- new SqlParameter("@eDisDate", SqlDbType.DateTime, 20),
- new SqlParameter("@designid", SqlDbType.Int, 4)
- };
- sqlParameter[0].Value = date1;
- sqlParameter[1].Value = date2;
- sqlParameter[2].Value = Convert.ToInt32(dr["ID"]);
- //CeErpTradeCell.ExecuteNonQueryStore("sp_getdesigngather", sqlParameter);
- DbHelper.DbConn.ExecuteNonQuery(CommandType.StoredProcedure, "sp_savedesigngather", sqlParameter);
- }
- new_Designer_Rate(date1);
- }
- public static void new_Designer_Rate(String date1)
- {
- /*String date1 = DateTime.Now.ToString();*/
- /* if (date1 ==null) {
- date1 = DateTime.Now.ToString();
- }*/
- DateTime currentDate = DateTime.Parse(date1);
- // 获取指定日期的开始时间
- DateTime startTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 0, 0, 0);//日
- // 获取指定日期的结束时间(即下一天的开始时间,减去1秒)
- DateTime endTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 23, 59, 59).AddSeconds(-1);//日
- DateTime now = DateTime.Now; // 获取当前日期和时间
- DateTime dateOnly = now.Date; // 限制日期为年月日
- StringBuilder sql = new StringBuilder();
- CeErpDesignerFinishRateNew.Del(startTime.ToString("yyyy-MM-dd HH:mm:ss"));
- sql.AppendFormat("\t\tSELECT\r\n A.DesignUserId,\r\n B.OrgID,\r\n B.Name AS DesignerName,\r\nCOUNT(CASE WHEN CONVERT(date, A.WaitDesignTime) BETWEEN '{0}' AND '{1}' and A.IsRefund ='2' THEN 1 END) AS refund, SUM(CASE WHEN CONVERT(date, A.WaitDesignTime) BETWEEN '{0}' AND '{1}' THEN A.payment ELSE 0 END) AS Amount,\r\n COUNT(CASE WHEN CONVERT(date, A.WaitDesignTime) BETWEEN '{0}' AND '{1}' and A.ctid NOT LIKE 'C%' and A.ctid NOT LIKE 'S%' THEN 1 END) AS AllOrder,\r\n COUNT(CASE WHEN CONVERT(date, A.WaitDesignTime) BETWEEN '{0}' AND '{1}' AND A.OrderState ='3' THEN 1 END) AS WaitDesign,\r\n COUNT(CASE WHEN CONVERT(date, A.WaitDesignTime) BETWEEN '{0}' AND '{1}' AND A.OrderState ='4' THEN 1 END) AS Designing,\r\n COUNT(CASE WHEN CONVERT(date, A.WaitDesignTime) BETWEEN '{0}' AND '{1}' AND A.OrderState >='5' THEN 1 END) AS DesignFinish,\r\n COUNT(CASE WHEN CONVERT(date, A.WaitDesignTime) = CONVERT(date, A.FinishDesignTime) AND CONVERT(date, A.WaitDesignTime) BETWEEN '{0}' AND '{1}' and A.ctid NOT LIKE 'C%' and A.ctid NOT LIKE 'S%' THEN 1 END) AS FinalizationRate,\r\n (SELECT COUNT(*) FROM CE_ErpTradeCell WHERE ctid LIKE 'S%' AND WaitDesignTime BETWEEN '{0}' AND '{1}' and DesignUserId =A.DesignUserId) AS afterSaleSum,\r\n\t\t(SELECT COUNT(tid) \r\n FROM CE_ErpTradeCell \r\n WHERE ctid LIKE 'C%' \r\n AND WaitDesignTime BETWEEN '{0}' AND '{1}' \r\n AND DesignUserId = A.DesignUserId) AS resolutionSum,\r\n\t\t \t(SELECT COUNT(DISTINCT tid) \r\n FROM CE_ErpTradeCell \r\n WHERE ctid LIKE 'C%' \r\n AND WaitDesignTime BETWEEN '{0}' AND '{1}' \r\n AND DesignUserId = A.DesignUserId and FinishDesignTime BETWEEN '{0}' AND '{1}') AS splitSum,\r\n\t\t \t \t(SELECT COUNT(DISTINCT tid) \r\n FROM CE_ErpTradeCell \r\n WHERE ctid LIKE 'C%' \r\n AND WaitDesignTime BETWEEN '{0}' AND '{1}' \r\n AND DesignUserId = A.DesignUserId ) AS splitSum2 ,COUNT(CASE WHEN CONVERT(date, A.WaitDesignTime) = CONVERT(date, A.FinishDesignTime) AND CONVERT(date, A.WaitDesignTime) BETWEEN '{0}' AND '{1}' and A.ctid LIKE 'C%' THEN 1 END) AS FinalizationRate2 \r\nFROM\r\n dbo.CE_ErpTradeCell AS A\r\n LEFT OUTER JOIN dbo.view_ErpUser AS B ON A.DesignUserId = B.ID\r\nWHERE\r\n b.state = '0' and a.IsSample!=2\r\nGROUP BY\r\n A.DesignUserId, B.OrgID, B.Name\r\nORDER BY\r\n Amount DESC;", startTime.ToString("yyyy-MM-dd HH:mm:ss"), endTime.ToString("yyyy-MM-dd HH:mm:ss"));
- DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
- foreach (DataRow dr in dt.Rows)
- {
- CeErpDesignerFinishRateNew ceErpDesignerFinishRateNew = new CeErpDesignerFinishRateNew();
- if (!Convert.IsDBNull(dr["DesignUserId"]))
- {
- ceErpDesignerFinishRateNew.did = Convert.ToInt32(dr["DesignUserId"] == null ? 0 : dr["DesignUserId"]);
- }
- if (!Convert.IsDBNull(dr["OrgID"]))
- {
- ceErpDesignerFinishRateNew.orgid = Convert.ToInt32(dr["OrgID"] == null ? 0 : dr["OrgID"]);
- }
- if (!Convert.IsDBNull(dr["DesignerName"]))
- {
- ceErpDesignerFinishRateNew.name = dr["DesignerName"].ToString() == null ? "" : dr["DesignerName"].ToString();
- }
- if (!Convert.IsDBNull(dr["Amount"]))
- {
- ceErpDesignerFinishRateNew.Amount = dr["Amount"].ToString() == null ? "" : dr["Amount"].ToString();
- }
- if (!Convert.IsDBNull(dr["AllOrder"]))
- {
- ceErpDesignerFinishRateNew.AllOrder = Convert.ToInt32(dr["AllOrder"] == null ? 0 : dr["AllOrder"]);
- }
- if (!Convert.IsDBNull(dr["FinalizationRate"]))
- {
- ceErpDesignerFinishRateNew.FinalizationRate = Convert.ToInt32(dr["FinalizationRate"] == null ? 0 : dr["FinalizationRate"]);
- }
- if (!Convert.IsDBNull(dr["afterSaleSum"]))
- {
- ceErpDesignerFinishRateNew.afterSaleSum = Convert.ToInt32(dr["afterSaleSum"] == null ? 0 : dr["afterSaleSum"]);
- }
- if (!Convert.IsDBNull(dr["resolutionSum"]))
- {
- ceErpDesignerFinishRateNew.resolutionSum = Convert.ToInt32(dr["resolutionSum"] == null ? 0 : dr["resolutionSum"]);
- }
- if (!Convert.IsDBNull(dr["splitSum"]))
- {
- ceErpDesignerFinishRateNew.splitSum = Convert.ToInt32(dr["splitSum"] == null ? 0 : dr["splitSum"]);
- }
- if (!Convert.IsDBNull(dr["splitSum2"]))
- {
- ceErpDesignerFinishRateNew.csplitum = Convert.ToInt32(dr["splitSum2"] == null ? 0 : dr["splitSum2"]);
- }
- if (!Convert.IsDBNull(dr["FinalizationRate2"]))
- {
- ceErpDesignerFinishRateNew.FinalizationRate2 = Convert.ToInt32(dr["FinalizationRate2"] == null ? 0 : dr["FinalizationRate2"]);
- }
- if (!Convert.IsDBNull(dr["AllOrder"]) && !Convert.IsDBNull(dr["FinalizationRate"]) && !Convert.IsDBNull(dr["splitSum2"]) && !Convert.IsDBNull(dr["splitSum"]))
- {
- try
- {
- int num1 = Convert.ToInt32(dr["FinalizationRate"]) + Convert.ToInt32(dr["splitSum"]);
- int num2 = Convert.ToInt32(dr["AllOrder"]) + Convert.ToInt32(dr["splitSum2"]);
- if (num2 != 0)
- {
- double result = (double)num1 / num2;
- if (double.IsNaN(result))
- {
- result = 0;
- }
- double roundedResult = Math.Round(result, 4);
- ceErpDesignerFinishRateNew.onFinalizationRate = roundedResult.ToString();
- int num3 = Convert.ToInt32(dr["refund"]);
- double result2 = (double)num3 / num2;
- if (double.IsNaN(result2))
- {
- result2 = 0;
- }
- double roundedResult2 = Math.Round(result2, 4);
- ceErpDesignerFinishRateNew.onRefund = roundedResult2.ToString();
- }
- else
- {
- ceErpDesignerFinishRateNew.onFinalizationRate = "0.0000";
- ceErpDesignerFinishRateNew.onRefund = "0.0000";
- }
- }
- catch (Exception ex)
- {
- ceErpDesignerFinishRateNew.onFinalizationRate = "0";
- }
- }
- ceErpDesignerFinishRateNew.ctime = startTime;
- ceErpDesignerFinishRateNew.Createtime = now;
- if (!Convert.IsDBNull(dr["refund"]))
- {
- ceErpDesignerFinishRateNew.refund = Convert.ToInt32(dr["refund"] == null ? 0 : dr["refund"]);
- }
- ceErpDesignerFinishRateNew.Create();
- }
- }
- public static DateTime FirstDayOfMonth(DateTime datetime)
- {
- return datetime.AddDays(1 - datetime.Day);
- }
- public static DateTime LastDayOfMonth(DateTime datetime)
- {
- return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
- }
- public static DateTime GetDateTimeWeekFirstDaySun(DateTime dateTime)
- {
- DateTime firstWeekDay = DateTime.Now;
- try
- {
- //得到是星期几,然后从当前日期减去相应天数
- int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
- int daydiff = (-1) * weeknow;
- firstWeekDay = dateTime.AddDays(daydiff);
- }
- catch { }
- return firstWeekDay;
- }
- public static DateTime GetDateTimeWeekFirstDayMon(DateTime dateTime)
- {
- DateTime firstWeekDay = DateTime.Now;
- try
- {
- int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
- //星期一为第一天,weeknow等于0时,要向前推6天。
- weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
- int daydiff = (-1) * weeknow;
- firstWeekDay = dateTime.AddDays(daydiff);
- }
- catch { }
- return firstWeekDay;
- }
- public static DateTime GetDateTimeWeekLastDaySat(DateTime dateTime)
- {
- DateTime lastWeekDay = DateTime.Now;
- try
- {
- int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
- int daydiff = (7 - weeknow) - 1;
- lastWeekDay = dateTime.AddDays(daydiff);
- }
- catch { }
- return lastWeekDay;
- }
- public static DateTime GetDateTimeWeekLastDaySun(DateTime dateTime)
- {
- DateTime lastWeekDay = DateTime.Now;
- try
- {
- int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
- weeknow = (weeknow == 0 ? 7 : weeknow);
- int daydiff = (7 - weeknow);
- lastWeekDay = dateTime.AddDays(daydiff);
- }
- catch { }
- return lastWeekDay;
- }
- public static void updateOrderStateForShipped(string ctid, int ost, string stateType)
- {
- try
- {
- CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ctid);
- if (entity != null)
- {
- if (entity.isAfterSaleOrder == 1) return;
- if (stateType == "updatestate_complete")
- {
- if (entity.IsPreDelivery == 1) return;
- entity.OrderState = 8;
- entity.Update();
- if (entity.ProductId == 9 || entity.ProductId == 17 || entity.ProductId == 20 || entity.ProductId == 29 || entity.ProductId == 30)//卡片、手提袋价格自动核算
- {
- CeErpDesignerBill.updateDesignerBill(entity.ctid, entity.ProductId);
- LogHelper.addDesignerBillLog(entity.ctid, 0, "自动核算设计费", "系统", 1);
- }
- else if (entity.ProductId == 22)
- {
- CeErpDesignerBill.updateBill(entity.ctid, entity.ProductId, entity.seller_memo);
- LogHelper.addDesignerBillLog(entity.ctid, 0, "自动核算设计费", "系统", 1);
- }
- }
- else if (stateType == "updatestate_shipped")
- {
- if (entity.IsPreDelivery == 1) return;
- entity.OrderState = 7;
- entity.Update();
- }
- else if (stateType == "updatestate_close")
- {
- entity.OrderState = 9;
- entity.Update();
- }
- }
- else
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("insert into S_BuChaJia(ctid,orderState,dotype,addtime) values('{0}',{1},'{2}',getdate());", ctid, ost, stateType);
- CeErpTradeCell.ExecuteNonQuery(sql.ToString());
- }
- }
- catch (Exception ex)
- {
- XLog.SaveLog(0, "updateOrderStateForShipped函数出错," + ctid + "," + ex.Message);
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("insert into S_BuChaJia(ctid,orderState,dotype,addtime) values('{0}',{1},'{2}',getdate());", ctid, ost, stateType);
- CeErpTradeCell.ExecuteNonQuery(sql.ToString());
- }
- }
- public static string changeCountFromChiness(string countStr)
- {
- try
- {
- return handleProductCount(countStr).ToString();
- }
- catch (Exception ex)
- {
- return countStr;
- }
- }
- public static int getIntCountFromString(string fstr)
- {
- try
- {
- string str = fstr;
- string r = @"[0-9]+";
- Regex reg = new Regex(r, RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromSeconds(2));//2秒后超时
- MatchCollection mc = reg.Matches(str);//设定要查找的字符串
- int count = 0;
- foreach (Match m in mc)
- {
- string s = m.Groups[0].Value;
- int cc = Convert.ToInt32(s);
- if (count == 0)
- {
- count = cc;
- }
- else
- {
- count = count * cc;
- }
- }
- return count;
- }
- catch (Exception ex)
- {
- return 0;
- }
- }
- public static int getPlaceProductCount(string count_str)
- {
- count_str = count_str.Trim();
- string[] count_list = count_str.Split(',');
- int count = 0;
- foreach (string item in count_list)
- {
- int tem_count = getSingleIntCountFromString(item);
- if (tem_count > count)
- {
- count = tem_count;
- }
- }
- return count;
- }
- public static int getSingleIntCountFromString(string fstr)
- {
- try
- {
- string str = fstr;
- string r = @"[0-9]+";
- Regex reg = new Regex(r, RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromSeconds(2));//2秒后超时
- MatchCollection mc = reg.Matches(str);//设定要查找的字符串
- if (mc.Count <= 0) return 0;
- if (mc.Count == 1)
- {
- string s = mc[0].Groups[0].Value;
- int cc = Convert.ToInt32(s);
- return cc;
- }
- else if (mc.Count > 1)
- {
- string s = mc[1].Groups[0].Value;
- int cc = Convert.ToInt32(s);
- return cc;
- }
- //foreach (Match m in mc)
- //{
- // string s = m.Groups[0].Value;
- // int cc = Convert.ToInt32(s);
- // if (count == 0)
- // {
- // count = cc;
- // }
- // else
- // {
- // count = count * cc;
- // }
- //}
- return 0;
- }
- catch (Exception ex)
- {
- return 0;
- }
- }
- public static int handleProductCount(string pCount, bool isSingle = false)
- {
- string cstr = pCount;
- if (cstr.IndexOf("百万") != -1)
- {
- cstr = cstr.Replace("百万", "000000");
- }
- else if (cstr.IndexOf("十万") != -1)
- {
- cstr = cstr.Replace("十万", "00000");
- }
- else if (cstr.IndexOf("万") != -1)
- {
- cstr = cstr.Replace("万", "0000");
- }
- else if (cstr.IndexOf("千") != -1)
- {
- cstr = cstr.Replace("千", "000");
- }
- else if (cstr.IndexOf("百") != -1)
- {
- cstr = cstr.Replace("百", "00");
- }
- else if (cstr.IndexOf("十") != -1)
- {
- cstr = cstr.Replace("十", "0");
- }
- int rCount = 0;
- if (isSingle) rCount = getSingleIntCountFromString(cstr);
- else rCount = getIntCountFromString(cstr);
- return rCount;
- }
- public static decimal getOrderSizeFromString(string size)
- {
- string rsize = size.Replace("mm", "");
- string[] sizeList = rsize.Split('x');
- if (sizeList.Length != 2) return 0;
- try
- {
- decimal mianji = Convert.ToDecimal(sizeList[0]) * Convert.ToDecimal(sizeList[1]);
- return mianji;
- }
- catch (Exception ex)
- {
- return 0;
- }
- return 0;
- }
- public static string getDateFromString(string fstr)
- {
- try
- {
- string str = fstr;
- string r = @"[0-9]+";
- Regex reg = new Regex(r, RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromSeconds(2));//2秒后超时
- MatchCollection mc = reg.Matches(str);//设定要查找的字符串
- if (mc.Count < 3) return "";
- int tag = 0;
- string datestr = "";
- foreach (Match m in mc)
- {
- string s = m.Groups[0].Value;
- datestr += s;
- if (tag < 2) { datestr += "-"; }
- else break;
- tag++;
- }
- DateTime dd = Convert.ToDateTime(datestr);
- return datestr;
- }
- catch (Exception ex)
- {
- return "";
- }
- }
- public static void DeleteOriginalOrderIfIsSplitOrder(string tid, string splitTag)
- {
- if (splitTag.Length > 0)
- {
- CeErpTradeCell.DelByCtid(tid);
- }
- }
- public static bool SetOrderDummyDelivery(string tid)
- {
- try
- {
- CeErpTrade trade = CeErpTrade.Get(tid);
- if (trade != null)
- {
- string xuniapires = apiHelper.API_LogisticsDummySend(tid, trade.posCode);
- if (xuniapires.IndexOf("成功") != -1)
- {
- LogHelper.addLog(tid, 0, "电子稿自动发货");
- return true;
- }
- else if (xuniapires.IndexOf("失败") != -1)
- {
- string chiness = KeepChinese(xuniapires);
- XLog.SaveLog(0, "setOrderDummyDelivery虚拟发货失败," + tid + "," + chiness);
- return false;
- }
- }
- return false;
- }
- catch (Exception ex)
- {
- XLog.SaveLog(0, "setOrderDummyDelivery虚拟发货出错," + tid + "," + ex.Message);
- return false;
- }
- }
- public static void getuserId()
- {
- string createtime = "2024-01-01 00:50:39.000";
- string textContent = "";
- int row_num = 100;
- Dictionary<string, List<string>> shop_userNick = new Dictionary<string, List<string>>();
- while (row_num == 100)
- {
- string conSql = string.Format("SELECT TOP 100 posCode, buyer_nick,pay_time FROM [dbo].[CE_ErpTrade] WHERE pay_time > '{0}' AND ( buyer_id IS NULL OR buyer_id = '' ) AND posCode != '' AND buyer_nick != '' ORDER By pay_time ASC", createtime);
- DataTable table = DbHelper.DbConn.ExecuteDataset(conSql).Tables[0];
- if (table != null)
- {
- row_num = table.Rows.Count;
- foreach (DataRow row in table.Rows)
- {
- string posCode = row["posCode"].ToString();
- string buyer_nick = row["buyer_nick"].ToString();
- createtime = row["pay_time"].ToString();
- List<string> userNickName = new List<string>();
- if (shop_userNick.ContainsKey(posCode))
- {
- shop_userNick.TryGetValue(posCode, out userNickName);
- }
- userNickName.Add(buyer_nick);
- userNickName = userNickName.Distinct().ToList();
- if (userNickName.Count == 10)
- {
- sendApi(posCode, userNickName);
- userNickName = new List<string>();
- }
- if (shop_userNick.ContainsKey(posCode))
- {
- shop_userNick[posCode] = userNickName;
- }
- else
- {
- shop_userNick.Add(posCode, userNickName);
- }
- }
- }
- }
- foreach (string key in shop_userNick.Keys)
- {
- List<string> nameList = shop_userNick[key];
- sendApi(key, nameList);
- }
- }
- static void sendApi(string posCode, List<string> userNickName)
- {
- string textContent = "";
- List<api_userId_response.ContentItem> buyerIds = apiHelper.API_GetUserId(posCode, string.Join(",", userNickName));
- if (buyerIds != null && buyerIds.Count > 0)
- {
- foreach (api_userId_response.ContentItem item in buyerIds)
- {
- if (item != null && !string.IsNullOrEmpty(item.buyerOpenUid))
- {
- textContent += string.Format("update [dbo].[CE_ErpTrade] set buyer_id='{2}' WHERE posCode='{0}' and buyer_nick='{1}';\r\n", posCode, item.buyerNick, item.buyerOpenUid);
- }
- }
- try
- {
- StreamWriter fs = new StreamWriter("C:/Users/231010/Desktop/updateSql.txt", true);
- fs.WriteLine(textContent);
- fs.Close();
- }
- catch (Exception e)
- {
- }
- }
- }
- public static designApiResponseVo checkOrderListDesignInfo(string tid, string ctid = "")
- {
- if (string.IsNullOrEmpty(tid))
- {
- return new designApiResponseVo(-1, "无订单信息");
- }
- if (!string.IsNullOrEmpty(ctid))
- {
- CeErpTradeCellExtend ceErpTradeCellExtend = CeErpTradeCellExtend.getByTid(ctid);
- if (ceErpTradeCellExtend != null)
- {
- if ("外协".Equals(ceErpTradeCellExtend.ToType))
- {
- string sql_pay = "update CE_ErpTradeCell with(rowlock) set DispatchSort=2 where ctid='" + ctid + "';";
- CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
- return new designApiResponseVo(200, "");
- }
- if ("内部".Equals(ceErpTradeCellExtend.ToType))
- {
- return new designApiResponseVo(-1, "设计系统判断内部");
- }
- }
- }
- string info_sql = string.Format("SELECT ctid,ProductId,seller_memo FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}' AND OrderState < 5", tid);
- DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
- string check_info = "无订单信息";
- if (data.Rows.Count > 0)
- {
- bool need_send = false;
- bool has_design = false;
- foreach (DataRow row in data.Rows)
- {
- CeErpTradeCell cell = CeErpTradeCell.GetByCtid(row["ctid"].ToString());
- if (cell != null)
- {
- if (cell.DesignUserId == 0 || cell.DispatchSort == 2 || cell.ctid.Contains("S_"))
- {
- designApiResponseVo result = checkOrderDesignInfo(cell, "", data);
- check_info = result.msg;
- if (result.code == 200)
- {
- need_send = true;
- has_design = false;
- }
- }
- else
- {
- has_design = true;
- }
- }
- }
- if (need_send && !has_design)
- {
- string sql_pay = "update CE_ErpTradeCell with(rowlock) set DispatchSort=2 where ctid='" + ctid + "' AND OrderState < 5;";
- CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
- return new designApiResponseVo(200, "");
- }
- }
- return new designApiResponseVo(-1, check_info);
- }
- static List<int> products = new List<int>() { 29, 2489, 2517, 2518, 2519, 2520, 2533, 2534, 2558, 2576, 2577, 2578, 2579, 2580, 2581, 2582, 2583, 2584, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2595, 2596, 2597, 2598, 2599, 2600, 2601, 2602, 2603, 2604, 2605, 2606, 2607, 2608, 2609, 2610, 2611, 2612, 2613, 2614, 2615, 2616, 2617, 2618, 2619, 2620, 2621, 2622, 2634, 2644, 2645, 2646, 2648, 2649, 2650 };
- static List<int> shops = new List<int>() { 2, 77, 121, 122, 65, 87, 26, 45, 17, 21, 52, 54, 103, 107, 108, 109, 118, 63, 64, 66, 49, 67, 105, 35, 57, 29, 53, 62, 134 };
- static List<int> no_design_shops = new List<int>() { 134 };
- public static designApiResponseVo checkOrderDesignInfo(CeErpTradeCell ceErpTradeCell, string post = "", DataTable dt = null)
- {
- if (ceErpTradeCell.DispatchSort == 2)
- {
- return new designApiResponseVo(200, "");
- }
- if (ceErpTradeCell.ProductId == 0)
- {
- return new designApiResponseVo(-1, "订单无品类");
- }
- if (ceErpTradeCell.ShopId == 0)
- {
- return new designApiResponseVo(-1, "订单无店铺");
- }
- if (ceErpTradeCell.ProductId == 1797 && ceErpTradeCell.seller_memo.Contains("手绘"))
- {
- return new designApiResponseVo(200, "");
- }
- if (ceErpTradeCell.isDianziOrder == 1)
- {
- return new designApiResponseVo(200, "");
- }
- if ((post != "SysAdmin" && post != "Summarize"))
- {
- if (ceErpTradeCell.DesignUserId != 0 && (ceErpTradeCell.DispatchSort != 2 && !ceErpTradeCell.ctid.Contains("S_")))
- {
- return new designApiResponseVo(-1, "已有设计师无法指派");
- }
- CeErpTradeCellExtend ceErpTradeCellExtend = CeErpTradeCellExtend.getByTid(ceErpTradeCell.ctid);
- if (ceErpTradeCellExtend != null && "内部".Equals(ceErpTradeCellExtend.ToType))
- {
- return new designApiResponseVo(-1, "无法指派不是共创的订单");
- }
- string info_sql = string.Format("SELECT count(*) as total FROM [dbo].[Ce_ErpDesignInfo] WHERE type = 1 and tarId = 3542 and shopId = {0}", ceErpTradeCell.ShopId);
- DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
- int a = Convert.ToInt32(data.Rows[0]["total"]);
- bool drop = false;
- if (DateTime.Now.Hour >= 17 && DateTime.Now.Hour <= 7 && products.IndexOf(ceErpTradeCell.ProductId) > -1 && (ceErpTradeCell.ShopId == 14 || ceErpTradeCell.ShopId == 56))
- {
- drop = false;
- }
- if (!drop && no_design_shops.IndexOf(ceErpTradeCell.ShopId) == -1)
- {
- CeErpDesignInfo ceErpDesignInfo = CeErpDesignInfo.GetByShopDesign(3542, ceErpTradeCell.ShopId, ceErpTradeCell.ProductId);
- if (ceErpDesignInfo == null)
- {
- return new designApiResponseVo(-1, "该店铺无该技能权限");
- }
- }
- //卡片五款
- /*if (products.IndexOf(ceErpTradeCell.ProductId) > -1 && ceErpTradeCell.ShopId > 0)
- {
- bool num_bool = true;
- bool size_bool = false;
- int min_num = 2;
- int num = 0;
- if (shops.IndexOf(ceErpTradeCell.ShopId) == -1)//限制不是全品的店铺限制
- {
- *//*if (ceErpTradeCell.payment >= 500)
- {
- return new designApiResponseVo(-1, "订单价格超出");
- }*//*
- string pattern = @"\b(\d{1,5}[x\*]\d{1,5}(mm|cm))\b";
- string memo = ceErpTradeCell.seller_memo.Replace("MM", "mm").Replace("CM", "cm");
- Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(2));//2秒后超时
- MatchCollection matches = reg.Matches(memo);//设定要查找的字符串
- string size = "";
- double min_width = 90;
- double min_height = 90;
- double width = 0;
- double height = 0;
- try
- {
- num = matches.Count;
- foreach (System.Text.RegularExpressions.Match match in matches)
- {
- if (match.Success)
- {
- size = match.Groups[0].Value;
- if (size.Contains("cm"))
- {
- size = size.Replace("cm", "");
- string[] size_list = size.Split('x');
- if (size_list.Length > 1)
- {
- width = Convert.ToDouble(size_list[0]) * 10;
- height = Convert.ToDouble(size_list[1]) * 10;
- }
- }
- else if (size.Contains("mm"))
- {
- size = size.Replace("mm", "");
- string[] size_list = size.Split('x');
- if (size_list.Length > 1)
- {
- width = Convert.ToDouble(size_list[0]);
- height = Convert.ToDouble(size_list[1]);
- }
- }
- if (width >= min_width && height >= min_height && height >= min_width && width >= min_height)
- {
- size_bool = true;
- break;
- }
- else
- {
- size_bool = false;
- }
- }
- }
- }
- catch (Exception ex)
- {
- }
- num = getSellerMemoNum(ceErpTradeCell.seller_memo);
- if (dt != null && dt.Rows != null && dt.Rows.Count > 1)
- {
- foreach (DataRow item in dt.Rows)
- {
- int tempNum = 0;
- if (!string.IsNullOrEmpty(item["ProductId"].ToString()))
- {
- if (Convert.ToInt32(item["ProductId"]) == ceErpTradeCell.ProductId)
- {
- tempNum = getSellerMemoNum(item["seller_memo"].ToString());
- tempNum = tempNum == 0 ? 1 : tempNum;
- }
- }
- num += tempNum;
- }
- }
- //2款不进
- if (num < min_num)
- {
- num_bool = false;
- }
- if (!num_bool && !size_bool)
- {
- return new designApiResponseVo(-1, "尺寸小于90x90或款数小于2");
- }
- }
- }*/
- }
- return new designApiResponseVo(200, "");
- }
- private static int getSellerMemoNum(string memo)
- {
- int num = 0;
- string pattern = @"\b(\d{1,5}[x\*]\d{1,5}(mm|cm))\b";
- Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(2));//2秒后超时
- MatchCollection matches = reg.Matches(memo);//设定要查找的字符串
- if (memo.Contains("刮刮"))
- {
- num = Math.Max(num - 1, 1);
- }
- pattern = @"(\d+)款";
- matches = Regex.Matches(memo, pattern);
- try
- {
- num = Math.Max(num - matches.Count, 0);
- foreach (System.Text.RegularExpressions.Match match in matches)
- {
- if (match.Success)
- {
- num += Convert.ToInt32(match.Groups[1].Value);
- break;
- }
- }
- }
- catch (Exception ex)
- {
- }
- return num;
- }
- private static string cytUserId = "77886";
- public static void sendCytAfterSale(CeErpTradeCell entity)
- {
- try
- {
- CeErpTradeAfterSaleExtend ceErpTradeAfterSaleExtend = CeErpTradeAfterSaleExtend.getByTid(entity.ctid);
- string after = "";
- if (entity != null && entity.AfterSaleReason.Contains("质量问题"))
- {
- after = "质量问题";
- }
- else if (entity != null && entity.AfterSaleReason.Contains("发货问题"))
- {
- after = "没收到货";
- }
- else
- {
- after = "其他问题";
- }
- string refund_type = "退款退货";
- if (entity.supRefundType != null && entity.supRefundType == "重印" && (after == "质量问题" || after == "其他问题"))
- {
- refund_type = "补印";
- }
- JObject jsonObject12 = new JObject
- {
- { "Userid",cytUserId },
- //{ "pwd", "lt666888" },
- { "LTOrderId", entity.ctid },
- { "IdCode", entity.OrderSn },
- { "CytMallId", string.IsNullOrEmpty(entity.SupplierOrderSn) ? "" : entity.SupplierOrderSn},
- { "RefundType", refund_type },
- { "ReprintReasons", after },
- { "ReasonsImgUrls", entity.AfterSaleSupplierImg },
- { "ReasonRemarks", ceErpTradeAfterSaleExtend.supplierResponsible },
- { "RefundAmount", entity.DeductFee }
- };
- /**JObject jsonObject12 = new JObject
- {
- { "Userid", "10095" },
- { "pwd", "test123456" },
- { "LTOrderId", "test123456" },
- { "RefundType", "退款退货" },
- { "ReprintReasons", "其他问题" },
- { "ReasonRemarks", "测试" }
- };**/
- string response1 = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/ApplyOrderRefund", jsonObject12.ToString());
- JObject jsonObjects1 = JObject.Parse(response1);
- string msg = (string)jsonObjects1["msg"];
- LogHelper.addLog(entity.ctid, 0, "CYT售后单推送:" + msg);
- }
- catch (Exception ex)
- {
- LogHelper.addLog(entity.ctid, 0, "CYT售后单推送:" + ex);
- }
- }
- public static void sendCytExpress(CeErpExpressInfo exinfo)
- {
- if (exinfo == null)
- {
- return;
- }
- CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(exinfo.tid);
- if (ceErpTradeCell == null)
- {
- return;
- }
- string msg = "";
- try
- {
- JObject jsonObject12 = new JObject
- {
- { "Userid",cytUserId },
- //{ "pwd", "lt666888" },
- { "LTOrderId", ceErpTradeCell.OrderSn },
- { "OrderId", ceErpTradeCell.ctid },
- { "CourierNumber", exinfo.out_sid },
- { "ExpressCompanyName", exinfo.company_name }
- };
- string response1 = HttpPost("http://www.kiy.cn/webapi/Himall.NewShop.UpdOrderExpress", jsonObject12.ToString());
- JObject jsonObjects1 = JObject.Parse(response1);
- msg = (string)jsonObjects1["msg"];
- LogHelper.addLog(exinfo.tid, 0, "CYT打单推送:" + msg);
- }
- catch (Exception ex)
- {
- LogHelper.addLog(exinfo.tid, 0, "CYT打单推送:" + ceErpTradeCell.OrderSn + "," + ceErpTradeCell.ctid + "," + exinfo.out_sid + "," + exinfo.company_name);
- XLog.SaveLog(0, "CYT打单推送失败," + msg + "->" + ex);
- }
- }
- public static void getCytPrice(CeErpTradeCell entity)
- {
- try
- {
- if (entity.seller_memo.IndexOf("种子纸") > -1)
- {
- return;
- }
- CeErpProduct cp = CeErpProduct.GetById(entity.ProductId);
- double price = 0;
- if (cp == null)
- {
- JObject jsonObject12 = new JObject
- {
- { "UserId", cytUserId },
- { "Pwd", "lt666888" },
- { "Filename", entity.seller_memo }
- };
- string response1 = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/LTBaojia", jsonObject12.ToString());
- JObject jsonObjects1 = JObject.Parse(response1);
- string ms1g = (string)jsonObjects1["msg"];
- if (ms1g == "报价成功")
- {
- JObject jsonObject1 = (JObject)jsonObjects1["data"];
- string data = (string)jsonObject1["price"];
- string sql_pay = "INSERT INTO CE_CaiYingTongLog (ctid, ctime,type,msg) VALUES ('" + entity.ctid + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," + 2 + ",'" + data + "');";
- CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
- price = Convert.ToDouble(data);
- }
- else
- {
- string sql_pay = "INSERT INTO CE_CaiYingTongLog (ctid, ctime,type,msg) VALUES ('" + entity.ctid + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," + 2 + ",'" + response1 + "');";
- CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
- return;
- }
- }
- String[] beizhu = entity.seller_memo.Split('-');
- String chanp = "";
- if (beizhu.Length > 1)
- {
- chanp = "(" + entity.ctid + ")-" + entity.ProductSize + "-" + entity.ProductCount + "-" + entity.Material + cp.PSupType + entity.Craft + "-备注:" + beizhu[1];
- }
- else
- {
- chanp = "(" + entity.ctid + ")-" + entity.ProductSize + "-" + entity.ProductCount + "-" + entity.Material + cp.PSupType + entity.Craft;
- }
- JObject jsonObject = new JObject
- {
- { "UserId", cytUserId },
- { "Pwd", "lt666888" },
- { "Filename", chanp }
- };
- string response = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/LTBaojia", jsonObject.ToString());
- JObject jsonObjects = JObject.Parse(response);
- string msg = (string)jsonObjects["msg"];
- if (msg == "报价成功")
- {
- JObject jsonObject1 = (JObject)jsonObjects["data"];
- string data = (string)jsonObject1["price"];
- string sql_pay = "INSERT INTO CE_CaiYingTongLog (ctid, ctime,type,msg) VALUES ('" + entity.ctid + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," + 2 + ",'" + data + "');";
- CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
- price = Convert.ToDouble(data);
- }
- else
- {
- string sql_pay = "INSERT INTO CE_CaiYingTongLog (ctid, ctime,type,msg) VALUES ('" + entity.ctid + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," + 2 + ",'" + response + "');";
- CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
- return;
- }
- if (price > 0)
- {
- CeErpTradeCellExtend ceErpTradeCellExtend = CeErpTradeCellExtend.getByTid(entity.ctid);
- if (ceErpTradeCellExtend == null)
- {
- ceErpTradeCellExtend = new CeErpTradeCellExtend();
- ceErpTradeCellExtend.ctid = entity.ctid;
- ceErpTradeCellExtend.payment_cyt = price;
- ceErpTradeCellExtend.Create();
- }
- else
- {
- ceErpTradeCellExtend.payment_cyt = price;
- ceErpTradeCellExtend.Update();
- }
- }
- }
- catch (Exception ex)
- {
- }
- return;
- }
- /// <summary>
- /// 更新设计信息
- /// </summary>
- /// <param name="ceErpTradeCell"></param>
- public static void updateDataTradeCellDesignInfo(string ctid)
- {
- CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
- if (ceErpTradeCell == null)
- {
- return;
- }
- string info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}'", ceErpTradeCell.tid);
- DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
- foreach (DataRow row in data.Rows)
- {
- ceErpTradeCell = CeErpTradeCell.GetByCtid(row["ctid"].ToString());
- if (ceErpTradeCell == null)
- {
- continue;
- }
- Dictionary<string, string> map = new Dictionary<string, string>();
- if (ceErpTradeCell.DesignUserId > 0)
- {
- string design_sql = string.Format("SELECT * FROM [dbo].[view_ErpUser] WHERE ID = {0}", ceErpTradeCell.DesignUserId);
- DataTable design_dt = DbHelper.DbConn.ExecuteDataset(design_sql).Tables[0];
- if (design_dt != null && design_dt.Rows.Count > 0)
- {
- map.Add("ShortText1717743889973", design_dt.Rows[0]["Name"].ToString());
- map.Add("ShortText1717743889516", design_dt.Rows[0]["OrgName"].ToString());
- if (!string.IsNullOrEmpty(design_dt.Rows[0]["OrgID"].ToString()))
- {
- int orgId = Convert.ToInt32(design_dt.Rows[0]["OrgID"]);
- if (orgId > 0)
- {
- string mDesign_sql = string.Format("SELECT Name FROM [dbo].[view_ErpUser] WHERE OrgId={0} and PostCode in ('wxDesignerhd','wxDesignerMr','DesignerMr','Designerhd')", design_dt.Rows[0]["OrgID"]);
- DataTable mDesign_dt = DbHelper.DbConn.ExecuteDataset(mDesign_sql).Tables[0];
- if (mDesign_dt != null && mDesign_dt.Rows.Count > 0)
- {
- map.Add("ShortText1717743890850", mDesign_dt.Rows[0]["Name"].ToString());
- }
- }
- }
- }
- map.Add("Date1717743893776", ceErpTradeCell.WaitDesignTime?.ToString("yyyy-MM-dd HH:mm:ss"));
- map.Add("ShortText1717743882604", ((OrderState)ceErpTradeCell.OrderState).ToString());
- }
- dataHelper.updateErpTradeCell(map, ctid);
- }
- }
- /// <summary>
- /// 下单更新
- /// </summary>
- /// <param name="ceErpTradeCell"></param>
- public static void updateDataTradeCellPlaceInfo(string ctid)
- {
- CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
- if (ceErpTradeCell == null)
- {
- return;
- }
- Dictionary<string, string> map = new Dictionary<string, string>();
- if (ceErpTradeCell.OrderState >= 6 && ceErpTradeCell.SupplierId > 0)
- {
- map.Add("Date1717743895362", ceErpTradeCell.FinishDesignTime?.ToString("yyyy-MM-dd HH:mm:ss"));
- map.Add("Date1717744246168", ceErpTradeCell.FinishPlaceTime?.ToString("yyyy-MM-dd HH:mm:ss"));
- string supplierId = dataHelper.getSupplerDataInfo(ceErpTradeCell.SupplierId.ToString());
- map.Add("RelevanceForm1718100412422", supplierId);
- CeErpTradeCellExtend ceErpTradeCellExtend = CeErpTradeCellExtend.getByTid(ceErpTradeCell.ctid);
- if (ceErpTradeCellExtend != null)
- {
- map.Add("Number1718099884613", ceErpTradeCellExtend.payment_cyt.ToString());
- }
- map.Add("ShortText1717743882604", ((OrderState)ceErpTradeCell.OrderState).ToString());
- }
- dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
- }
- /// <summary>
- /// 发货更新
- /// </summary>
- /// <param name="ceErpTradeCell"></param>
- public static void updateDataTradeCellDeliveInfo(string ctid)
- {
- CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
- if (ceErpTradeCell == null)
- {
- return;
- }
- string info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}'", ceErpTradeCell.tid);
- DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
- foreach (DataRow row in data.Rows)
- {
- ceErpTradeCell = CeErpTradeCell.GetByCtid(row["ctid"].ToString());
- if (ceErpTradeCell == null)
- {
- continue;
- }
- Dictionary<string, string> map = new Dictionary<string, string>();
- if (ceErpTradeCell.OrderState >= 7 && ceErpTradeCell.SupplierId > 0)
- {
- map.Add("Date1717744254301", ceErpTradeCell.FinishDeliveryTime?.ToString("yyyy-MM-dd HH:mm:ss"));
- map.Add("ShortText1717744255441", ceErpTradeCell.OutSid);
- map.Add("ShortText1717743882604", ((OrderState)ceErpTradeCell.OrderState).ToString());
- }
- dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
- }
- }
- /// <summary>
- /// 打回
- /// </summary>
- /// <param name="ceErpTradeCell"></param>
- public static void updateDataTradeCellBackInfo(string ctid)
- {
- CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
- if (ceErpTradeCell == null)
- {
- return;
- }
- Dictionary<string, string> map = new Dictionary<string, string>();
- map.Add("Date1717745436357", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
- map.Add("ShortText1717745435559", "是");
- map.Add("ShortText1717745481283", ceErpTradeCell.ReturnReason);
- map.Add("ShortText1717743882604", ((OrderState)ceErpTradeCell.OrderState).ToString());
- dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
- }
- /// <summary>
- /// 查货
- /// </summary>
- /// <param name="ceErpTradeCell"></param>
- public static void updateDataTradeCellCheckGoodInfo(string ctid)
- {
- CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
- if (ceErpTradeCell == null)
- {
- return;
- }
- Dictionary<string, string> map = new Dictionary<string, string>();
- map.Add("Date1717745495718", ceErpTradeCell.CheckOrderTime?.ToString("yyyy-MM-dd HH:mm:ss"));
- map.Add("ShortText1717745492918", "是");
- map.Add("ShortText1717745497837", ceErpTradeCell.CheckMemo);
- map.Add("ShortText1717745499141", ceErpTradeCell.UnusualCon);
- dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
- }
- /// <summary>
- /// 加急
- /// </summary>
- /// <param name="ceErpTradeCell"></param>
- public static void updateDataTradeCellUrgentInfo(string ctid)
- {
- CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
- if (ceErpTradeCell == null)
- {
- return;
- }
- Dictionary<string, string> map = new Dictionary<string, string>();
- map.Add("Date1717745535736", ceErpTradeCell.UrgencyTime?.ToString("yyyy-MM-dd HH:mm:ss"));
- map.Add("ShortText1717745533062", "是");
- dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
- }
- /// <summary>
- /// 售后
- /// </summary>
- /// <param name="ceErpTradeCell"></param>
- public static void updateDataTradeCellAfterSaleInfo(string ctid)
- {
- CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
- if (ceErpTradeCell == null)
- {
- return;
- }
- Dictionary<string, string> map = new Dictionary<string, string>();
- map.Add("ShortText1717745540758", "是");
- map.Add("Date1717745544245", ceErpTradeCell.AfterSaleTime?.ToString("yyyy-MM-dd HH:mm:ss"));
- if (ceErpTradeCell.AfterSaleResSupId > 0)
- {
- CeErpUser user = CeErpUser.Get(ceErpTradeCell.AfterSaleResSupId);
- if (user != null)
- {
- map.Add("ShortText1717745541664", user.Name);
- }
- }
- map.Add("Date1717745545841", ceErpTradeCell.FinishAfterSaleTime?.ToString("yyyy-MM-dd HH:mm:ss"));
- if (!string.IsNullOrEmpty(ceErpTradeCell.AfterSaleReason))
- {
- string[] list = ceErpTradeCell.AfterSaleReason.Split('|');
- for (int i = 0; i < list.Length; i++)
- {
- if (i == 0)
- {
- map.Add("ShortText1717745548220", list[i]);
- }
- if (i == 1)
- {
- map.Add("ShortText1717745549835", list[i]);
- }
- if (i == 2)
- {
- map.Add("ShortText1717745550687", list[i]);
- }
- }
- }
- if (!string.IsNullOrEmpty(ceErpTradeCell.ResponsibleUserId))
- {
- string[] list = ceErpTradeCell.ResponsibleUserId.Split(',');
- for (int i = 0; i < list.Length; i++)
- {
- string[] user = list[i].Split('_');
- if (user.Length > 0)
- {
- if (user[1] == "g")
- {
- CeErpSupplier ceErpSupplier = CeErpSupplier.Get(user[0]);
- if (i == 0)
- {
- map.Add("ShortText1717745553842", list[i]);
- map.Add("ShortText1717745554626", "");
- }
- if (i == 1)
- {
- map.Add("ShortText1717811042513", list[i]);
- map.Add("ShortText1717811049407", "");
- }
- }
- else if (user[1] == "w")
- {
- if (i == 0)
- {
- map.Add("ShortText1717745553842", "物流问题");
- map.Add("ShortText1717745554626", "");
- }
- if (i == 1)
- {
- map.Add("ShortText1717811042513", "物流问题");
- map.Add("ShortText1717811049407", "");
- }
- }
- else
- {
- string customer_sql = string.Format("SELECT * FROM [dbo].[view_ErpUser] WHERE ID = {0}", ceErpTradeCell.CustomerUserId);
- DataTable customer_dt = DbHelper.DbConn.ExecuteDataset(customer_sql).Tables[0];
- if (customer_dt.Rows.Count > 0)
- {
- if (i == 0)
- {
- map.Add("ShortText1717745553842", customer_dt.Rows[0]["Name"].ToString());
- map.Add("ShortText1717745554626", customer_dt.Rows[0]["OrgName"].ToString());
- }
- if (i == 1)
- {
- map.Add("ShortText1717811042513", customer_dt.Rows[0]["Name"].ToString());
- map.Add("ShortText1717811049407", customer_dt.Rows[0]["OrgName"].ToString());
- }
- }
- }
- }
- }
- }
- map.Add("number1717745810151", ceErpTradeCell.RefundFee.ToString());
- CeErpTradeAfterSaleExtend ceErpTradeAfterSaleExtend = CeErpTradeAfterSaleExtend.getByTid(ceErpTradeCell.ctid);
- if (ceErpTradeAfterSaleExtend != null && !string.IsNullOrEmpty(ceErpTradeAfterSaleExtend.RefundFees))
- {
- string[] list = ceErpTradeAfterSaleExtend.RefundFees.Split(',');
- for (int i = 0; i < list.Length; i++)
- {
- if (i == 0)
- {
- map.Add("Number1717745564936", list[i]);
- }
- if (i == 1)
- {
- map.Add("Number1717745565580", list[i]);
- }
- }
- }
- map.Add("ShortText1717745580986", ceErpTradeCell.AfterSaleSupplierState == 1 ? "认可" : "不认可");
- map.Add("ShortText1717745582613", ceErpTradeCell.AfterSaleSupplierMemo);
- map.Add("ShortText1717745583256", ceErpTradeCell.AfterSaleMethod);
- map.Add("ShortText1717745583810", ceErpTradeCell.AfterSaleMemo);
- dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
- }
- /// <summary>
- /// 退款
- /// </summary>
- /// <param name="content"></param>
- public static void updateDataTradeCellRefundInfo(Api_tmc_refund_info_Obj.Content content)
- {
- Dictionary<string, string> map = new Dictionary<string, string>();
- map.Add("Date1717745588048", StampToDateTime(content.createTime).ToString("yyyy-MM-dd HH:mm:ss"));
- map.Add("ShortText1717745585444", "是");
- map.Add("Number1717743148189", content.refundFee);
- map.Add("ShortText1717745591810", content.reason);
- map.Add("ShortText1717745592639", content.desc);
- string tid = content.refOid;
- string info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}'", tid);
- DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
- foreach (DataRow row in data.Rows)
- {
- dataHelper.updateErpTradeCell(map, row["ctid"].ToString());
- }
- }
- /// <summary>
- /// 返现
- /// </summary>
- /// <param name="entity"></param>
- /// <param name="cash"></param>
- public static void updateDataTradeCellCashInfo(CeErpTradeCell entity, CeErpReturnCash cash)
- {
- Dictionary<string, string> map = new Dictionary<string, string>();
- map.Add("ShortText1717745601056", "是");
- map.Add("ShortText1717745602313", cash.rtype);
- map.Add("Number1717745604245", cash.payment.ToString());
- map.Add("ShortText1717745607208", cash.con);
- dataHelper.updateErpTradeCell(map, entity.ctid);
- }
- /// <summary>
- /// 推购
- /// </summary>
- /// <param name="entity"></param>
- public static void updateDataTradeCellStayInfo(CeErpTradeCell entity)
- {
- Dictionary<string, string> map = new Dictionary<string, string>();
- map.Add("ShortText1717745608381", "是");
- dataHelper.updateErpTradeCell(map, entity.ctid);
- }
- public static DateTime StampToDateTime(string timeStamp)
- {
- DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
- long lTime = long.Parse(timeStamp + "0000");
- TimeSpan toNow = new TimeSpan(lTime);
- return dateTimeStart.Add(toNow);
- }
- private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
- {
- return true; //总是接受
- }
- public static string HttpPost(string url, string param = null)
- {
- HttpWebRequest request;
- //如果是发送HTTPS请求
- if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
- {
- ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
- request = WebRequest.Create(url) as HttpWebRequest;
- request.ProtocolVersion = HttpVersion.Version10;
- }
- else
- {
- request = WebRequest.Create(url) as HttpWebRequest;
- }
- request.Method = "POST";
- request.ContentType = "application/json";
- request.Accept = "*/*";
- request.Timeout = 60000;
- request.AllowAutoRedirect = false;
- StreamWriter requestStream = null;
- WebResponse response = null;
- string responseStr = null;
- try
- {
- requestStream = new StreamWriter(request.GetRequestStream());
- requestStream.Write(param);
- requestStream.Close();
- response = request.GetResponse();
- if (response != null)
- {
- StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- responseStr = reader.ReadToEnd();
- reader.Close();
- }
- }
- catch (Exception ex)
- {
- return ex.Message;
- }
- finally
- {
- request = null;
- requestStream = null;
- response = null;
- }
- return responseStr;
- }
- public static List<int> spu_products = new List<int>() { 4, 13, 19, 24, 28, 32, 40, 51, 57, 1971, 2319, 2377, 2521, 2524, 2533, 2538, 2542, 2554, 2556, 2557, 2559, 2560, 2561, 2562, 2563, 2564, 2565, 2566, 2568, 2569, 2570, 2571, 2572, 2619, 2625, 2636, 2637, 2638, 2645, 2646 };
- public static List<int> spu_shopIds = new List<int>() { 5, 6, 8, 10, 11, 12, 14, 15, 16, 18, 24, 27, 28, 31, 32, 56, 61 };
- public static List<string> receiver_state = new List<string> { "内蒙古", "西藏", "甘肃", "青海", "宁夏", "新疆" };
- public static bool isFarAddress(string state)
- {
- for (int i = 0; receiver_state.Count > i; i++)
- {
- if (state.Contains(receiver_state[i]))
- {
- return true;
- }
- }
- return false;
- }
- public static void setSpuData(CeErpTrade father)
- {
- string orderSql = string.Format("SELECT * FROM [dbo].[CE_ErpTradeOrder] WHERE tid = '{0}' and total_fee > 0", father.tid);
- DataTable table = SqlHelper.ExecuteDataSet(orderSql).Tables[0];
- string spu_id = "";
- if (table != null && table.Rows.Count == 1)
- {
- spu_id = table.Rows[0]["spu_id"].ToString();
- }
- string cellSql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid = '{0}'", father.tid);
- DataTable data = SqlHelper.ExecuteDataSet(cellSql).Tables[0];
- if (data != null && data.Rows.Count > 0)
- {
- foreach (DataRow row in data.Rows)
- {
- CeErpTradeCellExtend ceErpTradeCellExtend = CeErpTradeCellExtend.getByTid(row["ctid"].ToString());
- if (ceErpTradeCellExtend == null)
- {
- ceErpTradeCellExtend = new CeErpTradeCellExtend();
- ceErpTradeCellExtend.ctid = row["ctid"].ToString();
- }
- ceErpTradeCellExtend.spu_id = spu_id;
- if (!string.IsNullOrEmpty(spu_id))
- {
- CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ceErpTradeCellExtend.ctid);
- ceErpTradeCellExtend = sendSpuData(ceErpTradeCell, ceErpTradeCellExtend);
- }
- if (ceErpTradeCellExtend.ID == 0)
- {
- ceErpTradeCellExtend.Create();
- }
- else
- {
- ceErpTradeCellExtend.Update();
- }
- }
- }
- List<string> list = new List<string>() { "kevin_boz", "奥丽芙旗舰店", "鼎怡旗舰店", "格图旗舰店", "宫契旗舰店", "海角七旗舰店", "航和旗舰店", "岚恬旗舰店", "琳19890725", "领淘文具旗舰店", "麦郁旗舰店", "米笛儿旗舰店", "颂盼旗舰店", "涛莱旗舰店", "腾科吉旗舰店", "万慕办公旗舰店", "喜印说旗舰店", "欣克利旗舰店", "阳光猫旗舰店", "翊喜旗舰店", "尹灵旗舰店", "悦加旗舰店", "竹范旗舰店", "卓胜旗舰店" };
- if (string.IsNullOrEmpty(spu_id) && list.IndexOf(father.seller_nick) > -1)
- {
- string sql_pay = "update CE_ErpTradeCell with(rowlock) set orderstate=-1 where tid='" + father.tid + "';";
- CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
- }
- }
- public static CeErpTradeCellExtend sendSpuData(CeErpTradeCell ceErpTradeCell, CeErpTradeCellExtend ceErpTradeCellExtend)
- {
- string result = designHelper.API_CheckOrderTo(ceErpTradeCellExtend.ctid, ceErpTradeCellExtend.spu_id, ceErpTradeCell.ShopId);
- ceErpTradeCellExtend.ToType = result;
- int dispatchSort = 0;
- if ("无".Equals(result) && spu_shopIds.Contains(ceErpTradeCell.ShopId))
- {
- ceErpTradeCellExtend.ToType = "内部";
- dispatchSort = 0;
- }
- if ((ceErpTradeCell.seller_memo.Contains("改稿") || ceErpTradeCell.OtherMemo.Contains("改稿")) && spu_shopIds.Contains(ceErpTradeCell.ShopId) && !spu_products.Contains(ceErpTradeCell.ProductId))
- {
- ceErpTradeCellExtend.ToType = "内部";
- dispatchSort = 0;
- }
- if (ceErpTradeCell.payment >= 500 && spu_shopIds.Contains(ceErpTradeCell.ShopId) && !spu_products.Contains(ceErpTradeCell.ProductId))
- {
- ceErpTradeCellExtend.ToType = "内部";
- dispatchSort = 0;
- }
- if (spu_products.Contains(ceErpTradeCell.ProductId) || ceErpTradeCell.seller_memo.IndexOf("手绘") > -1 || ceErpTradeCell.seller_memo.IndexOf("电子稿") > -1 || ceErpTradeCell.isDianziOrder > 0)
- {
- ceErpTradeCellExtend.ToType = "外协";
- dispatchSort = 2;
- }
- string sql_pay = string.Format("update CE_ErpTradeCell with(rowlock) set DispatchSort={0} where ctid='{1}';", dispatchSort, ceErpTradeCell.ctid);
- CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
- if (ceErpTradeCellExtend.ID > 0)
- {
- ceErpTradeCellExtend.Update();
- }
- return ceErpTradeCellExtend;
- }
- public static DataTable getSameOrderList(CeErpTradeCell entity, CeErpTrade ceErpTrade)
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("select ctid,IsSF,seller_memo,OtherMemo,productId,FinishPlaceTime,ProductCount,OrderSn from view_ErpTradeCell where SupplierId={0} and orderstate=6 and IsSample = 0 AND ShopId = {1}", entity.SupplierId, entity.ShopId);
- if (string.IsNullOrEmpty(ceErpTrade.receiverId))
- {
- sql.AppendFormat(" and (tid='{0}');", entity.tid);
- }
- else
- {
- sql.AppendFormat(" and (tid='{0}' or (receiverId = '{1}' and IsSF = '{2}'));", entity.tid, ceErpTrade.receiverId, entity.IsSF);
- }
- DataTable dt = null;
- try
- {
- dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
- StringBuilder timerSql = new StringBuilder();
- timerSql.AppendFormat("SELECT * FROM CE_ErpSupplierProductTime WHERE supplierId={0}", entity.SupplierId);
- DataTable timerTable = DbHelper.DbConn.ExecuteDataset(timerSql.ToString()).Tables[0];
- //没有设置时间则不判断
- dt.Columns.Add(new DataColumn("default", typeof(int)));
- if (timerTable == null || timerTable.Rows.Count == 0)
- {
- return dt;
- }
- foreach (DataRow dr in dt.Rows)
- {
- dr["default"] = 0;
- //当前订单
- if (entity.ctid.Equals(dr["ctid"]))
- {
- continue;
- }
- //已经标记过发货
- CeErpDeliverMark ceErpDeliverMark = CeErpDeliverMark.GetByCtid(dr["ctid"].ToString());
- if (ceErpDeliverMark != null)
- {
- dr["default"] = 1;
- continue;
- }
- string[] productIds = null;
- string productId = dr["productId"].ToString();
- string finishPlaceTime = dr["FinishPlaceTime"].ToString();
- string sellmer_mome = dr["seller_memo"].ToString();
- string txtCount = dr["ProductCount"].ToString();
- DateTime placeTime = DateTime.Now;
- //没有品类
- if (string.IsNullOrEmpty(productId) || "0".Equals(productId))
- {
- continue;
- }
- if (string.IsNullOrEmpty(finishPlaceTime))
- {
- continue;
- }
- placeTime = DateTime.Parse(finishPlaceTime);
- foreach (DataRow row in timerTable.Rows)
- {
- string txtIds = row["productId"].ToString();
- string[] crafts = { };
- int count = Convert.ToUInt16(row["quantity"]);
- if (string.IsNullOrEmpty(txtIds))
- {
- continue;
- }
- if (count > 0)
- {
- int quantity = commonHelper.handleProductCount(txtCount, true);
- //订单数量大于写入的数量则跳过
- if (quantity > count)
- {
- continue;
- }
- }
- productIds = txtIds.Split(',');
- if (productIds.Contains(productId))
- {
- string textCraft = row["craft"].ToString();
- textCraft = textCraft.Replace(",", ",");//统一格式
- if (!string.IsNullOrEmpty(textCraft))
- {
- crafts = textCraft.Split(',');
- }
- if (crafts.Length > 0)
- {
- bool isinCraft = false;
- for (int i = 0; i < crafts.Length; i++)
- {
- if (sellmer_mome.IndexOf(crafts[i]) >= 0)
- {
- isinCraft = true;
- break;
- }
- }
- //有写工艺并且备注中没匹配中则跳过
- if (!isinCraft)
- {
- continue;
- }
- }
- DateTime deadLine = DateTime.Parse(row["deadLine"].ToString());
- DateTime dayDeadLine = DateTime.Parse(row["dayDeadLine"].ToString());
- int sendDay = Convert.ToInt16(row["sendDay"]);
- //下单时间小于当日发货时间则不用判断
- //当日发货必须发货
- if (dayDeadLine.Hour > 0 && dayDeadLine.Hour > placeTime.Hour)
- {
- dr["default"] = 1;
- break;
- }
- //在截稿时间之前下单的可以减去一天时间
- /*if (deadLine.Hour > 0 && deadLine.Hour > placeTime.Hour)
- {
- sendDay = Math.Max(1, sendDay - 1);
- }
- DateTime sendtime = placeTime.AddDays(sendDay);
- //判断有没有到发货日期
- if (DateTime.Compare(sendtime.Date, DateTime.Now.Date) > 0)
- {
- break;
- }*/
- }
- }
- }
- }
- catch (Exception ex)
- {
- }
- return dt;
- }
- public static double calculationPrice(CeErpTradeCell ceErpTradeCell)
- {
- double price = 0;
- return 200;
- List<string> list = new List<string>();
- //查补差订单
- DataTable dt = DbHelper.DbConn.ExecuteDataset(string.Format("select tid from CE_ErpTradeCell where ptid = '{0}' and IsSample =2", ceErpTradeCell.tid)).Tables[0];
- list.Add("'" + ceErpTradeCell.tid + "'");
- if (dt != null && dt.Rows.Count > 0)
- {
- foreach (DataRow dr in dt.Rows)
- {
- list.Add("'" + dr["tid"].ToString() + "'");
- }
- }
- DataTable tradeTables = DbHelper.DbConn.ExecuteDataset(string.Format("select payment from CE_ErpTrade where tid in ({0})", string.Join(",", list))).Tables[0];
- if (tradeTables != null && tradeTables.Rows.Count > 0)
- {
- foreach (DataRow dr in tradeTables.Rows)
- {
- price += Convert.ToDouble(dr["payment"]);
- }
- }
- return price;
- }
- public static bool loginGetOrder(int userId)
- {
- DataTable dt = null;
- try
- {
- dt = DbHelper.DbConn.ExecuteDataset(string.Format("select * from view_ErpUser where ID = {0}", userId)).Tables[0];
- }
- catch (Exception e)
- {
- }
- if (dt == null || dt.Rows.Count == 0)
- {
- return false;
- }
- DataRow dr = dt.Rows[0];
- int isOpen = Convert.ToInt32(dr["isOpen"]);
- int dayOrderReceive = Convert.ToInt32(dr["DayOrderReceive"]);//已经派了多少
- int dayOrderLimit = Convert.ToInt32(dr["DayOrderLimit"]);//总的能派多少
- int orderAmountLimit = Convert.ToInt32(dr["OrderAmountLimit"]);//能派的金额多少
- int oldOrder = Convert.ToInt32(dr["OldOrder"]);//能派的金额多少
- string orgShop = dr["OrgShop"].ToString();
- string pemShop = dr["pemShop"].ToString();
- string pemDesign = dr["pemDesign"].ToString();
- if (isOpen == 0)
- {
- return false;
- }
- if (string.IsNullOrEmpty(orgShop) || string.IsNullOrEmpty(pemShop) || string.IsNullOrEmpty(pemDesign))
- {
- return false;
- }
- string normolSql = string.Format("and payment <={0} and shopid in ({1}) and shopid in ({2}) and ProductId in ({3})", orderAmountLimit, orgShop, pemShop, pemDesign);
- string orderSql = string.Format("select tid,ctid,IsOldCustomer,shopid,payment,ProductId from view_ErpTradeCell where orderstate=2 and productid<>0 and designuserid=0 and payment>0 and isrefund=0 and isDianziOrder = 0 {0} order by IsUrgency DESC, YEAR ( pay_time ), MONTH ( pay_time ), DAY ( pay_time ), payment DESC;", normolSql);
- DataTable dataTable = DbHelper.DbConn.ExecuteDataset(orderSql).Tables[0];
- if (dataTable == null || dataTable.Rows.Count == 0)
- {
- return true;
- }
- designApiResponseVo result = null;
- List<string> list = new List<string>();
- foreach (DataRow row in dataTable.Rows)
- {
- if (dayOrderReceive >= dayOrderLimit)
- {
- break;
- }
- string IsOldCustomer = dr["IsOldCustomer"].ToString();
- int ProductId = Convert.ToInt32(dr["ProductId"]);
- CeErpShop ceErpShop = CeErpShop.Get(dr["shopid"]);
- int shopUserId = 0;
- if (ceErpShop != null)
- {
- shopUserId = ceErpShop.UserID;
- }
- bool isIn = false;
- if ((IsOldCustomer == "1" && shopUserId == 241) || (shopUserId == 241 && Convert.ToDouble(dr["payment"]) >= 500))
- {
- if (oldOrder == 1)
- {
- //手绘 logo 画册 海报 宣传单
- if ((IsOldCustomer == "1" && (ProductId == 28 || ProductId == 57 || ProductId == 40 || ProductId == 4 || ProductId == 13)))
- {
- result = commonHelper.checkOrderListDesignInfo(dr["tid"].ToString(), dr["ctid"].ToString());
- if (result != null && result.code == 200)
- {
- continue;
- }
- }
- isIn = true;
- }
- }
- else
- {
- if (oldOrder == 0)
- {
- if (shopUserId != 82)
- {
- result = commonHelper.checkOrderListDesignInfo(dr["tid"].ToString(), dr["ctid"].ToString());
- if (result != null && result.code == 200)
- {
- continue;
- }
- }
- isIn = true;
- }
- }
- if (isIn)
- {
- int rowCount = DbHelper.DbConn.ExecuteNonQuery(string.Format("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where tid={0} and OrderState=2 and DesignUserId=0 ;", dr["tid"].ToString(), (int)OrderState.下单完成, userId, "3测试自动派单" + userId));
- //int rowCount = DbHelper.DbConn.ExecuteNonQuery(string.Format("update CE_ErpTradeCell set OrderState=3,IsAutoDispatch=1,WaitDesignTime=getdate(),UpdateTime=getdate(),DesignUserId={0},DispatchSort=0 where tid={1} and OrderState=2 and DesignUserId=0", userId, dr["tid"].ToString()));
- dayOrderReceive += rowCount;
- }
- }
- return true;
- }
- public static bool setFromDataInfo(string tid, string content, int userId)
- {
- CeErpTradeCell tradeCell = CeErpTradeCell.GetByCtid(tid);
- if (tradeCell == null)
- {
- return false;
- }
- string info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}'", tradeCell.tid);
- if (tradeCell.ctid.Contains("S_"))
- {
- info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE ctid ='{0}'", tradeCell.ctid);
- }
- DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
- CeErpOrderFormData formData = null;
- if (data.Rows.Count > 0)
- {
- List<CeErpTradeCell> cell_list = new List<CeErpTradeCell>();
- foreach (DataRow row in data.Rows)
- {
- string ctid = row["ctid"].ToString();
- CeErpTradeCell cell = CeErpTradeCell.GetByCtid(ctid);
- cell_list.Add(cell);
- formData = CeErpOrderFormData.GetByTid(ctid);
- if (formData == null)
- {
- formData = new CeErpOrderFormData();
- }
- formData.tid = ctid;
- formData.content = content;
- if (formData.ID > 0)
- {
- formData.Update();
- }
- else
- {
- formData.userId = userId;
- formData.Create();
- }
- }
- if (tradeCell.OrderState >= 5)
- {
- LogHelper.addLog(tradeCell.ctid, formData.userId > 0 ? formData.userId : 3542, "外链派单:订单状态不正确!", tradeCell.OrderState);
- return false;
- }
- //能进来并且没有设计师
- foreach (CeErpTradeCell entity in cell_list)
- {
- try
- {
- if (entity != null && entity.seller_memo.Length > 0)
- {
- if (entity.OrderState >= 5)
- {
- LogHelper.addLog(entity.ctid, formData.userId > 0 ? formData.userId : 3542, "外链派单:订单状态不正确!", entity.OrderState);
- continue;
- }
- //判断能不能推送
- designApiResponseVo result = checkOrderListDesignInfo(entity.tid, entity.ctid);
- if (result != null && result.code == 200)
- {
- designApiResponseVo response = designHelper.API_GetPrintData_CreateOrder(entity, "SysAdmin");
- if (response.code == 200)
- {
- if (response.msg == "设计共创:成功")
- {
- if (entity.ctid.IndexOf("S_") == -1)
- {
- int suid = autoDistributeToSupplier(entity); //自动分配供应商
- entity.SupplierId = suid;
- string suname = getSupplierNameById(entity.SupplierId);
- LogHelper.addLog(entity.ctid, 0, "匹配供应商:" + suname, entity.OrderState);
- }
- entity.OrderState = Convert.ToInt32(OrderState.待设计);
- entity.DesignUserId = 3542;
- entity.WaitDesignTime = DateTime.Now;
- entity.DispatchSort = 2;
- entity.UpdateTime = DateTime.Now;
- entity.Update();
- }
- }
- LogHelper.addLog(entity.ctid, formData.userId > 0 ? formData.userId : 3542, "外链派单:" + response.msg, Convert.ToInt32(OrderState.待设计));
- }
- else
- {
- LogHelper.addLog(entity.ctid, formData.userId > 0 ? formData.userId : 3542, "外链派单:" + result.msg, Convert.ToInt32(OrderState.待设计));
- }
- }
- }
- catch (Exception ex)
- {
- XLog.SaveLog(0, "外链派单:" + ex.Message);
- }
- }
- }
- return true;
- }
- public static void checkIsVipOld(CeErpTrade ceErpTrade)
- {
- if (ceErpTrade == null || string.IsNullOrEmpty(ceErpTrade.buyer_nick))
- {
- return;
- }
- int VipCustomer = 2;
- string last_tid = "";
- string sql = "";
- if (ceErpTrade.payment > 20)
- {
- sql = string.Format("SELECT top 1 tid FROM [dbo].[view_ErpTradeCell] WITH(NOLOCK) WHERE (buyer_nick = '{0}' or buyer_id = '{1}' ) and status = 'COMPLETE' and seller_nick = '{2}' and tid <> '{3}' AND end_time < '{4}' and IsSample = 0 and payment >= 20 order by pay_time desc;", ceErpTrade.buyer_nick, ceErpTrade.buyer_id, ceErpTrade.seller_nick, ceErpTrade.tid, ceErpTrade.pay_time);
- if (string.IsNullOrEmpty(ceErpTrade.buyer_nick))
- {
- sql = string.Format("SELECT tid FROM [dbo].[CE_ErpTrade] WITH(NOLOCK) WHERE (buyer_id = '{1}' ) and status = 'COMPLETE' and seller_nick = '{2}' and tid <> '{3}' AND end_time < '{4}' and payment >= 20", ceErpTrade.buyer_nick, ceErpTrade.buyer_id, ceErpTrade.seller_nick, ceErpTrade.tid, ceErpTrade.pay_time);
- }
- DataTable dataTable = DbHelper.DbConn.ExecuteDataset(sql).Tables[0];
- if (dataTable != null && dataTable.Rows.Count > 0)
- {
- last_tid = dataTable.Rows[0]["tid"].ToString();
- if (!string.IsNullOrEmpty(last_tid))
- {
- VipCustomer = 1;
- }
- }
- }
- if (VipCustomer == 1)
- {
- LogHelper.addLog(ceErpTrade.tid, 0, "老客户订单号:" + last_tid, Convert.ToInt32(OrderState.待设计));
- }
- DbHelper.DbConn.ExecuteNonQuery(string.Format("UPDATE [dbo].[CE_ErpTradeCell] set VipCustomer = {1} WHERE tid='{0}';", ceErpTrade.tid, VipCustomer));
- return;
- }
- public static string getProductCount(string txt)
- {
- txt = txt.Replace(",", ",");
- string[] txtList = txt.Split(',');
- int total = 0;
- for (int i = 0; i < txtList.Length; i++)
- {
- string kuanPattern = @"(\d+)(?=款)";
- Match kuanMatch = Regex.Match(txtList[i], kuanPattern);
- string kuanNum = kuanMatch.Success ? kuanMatch.Groups[1].Value : "1";
- // 提取"个"或"张"前面的数字
- string unitPattern = @"(\d+)(?=个|张|本|套|件|卷|劵 )";
- Match unitMatch = Regex.Match(txtList[i], unitPattern);
- string unitNum = unitMatch.Success ? unitMatch.Groups[1].Value : "1";
- int kuan = 1;
- int unit = 1;
- if (!int.TryParse(kuanNum, out kuan))
- {
- return txt;
- }
- if (!int.TryParse(unitNum, out unit))
- {
- return txt;
- }
- total += kuan * unit;
- }
- return (total).ToString();
- }
- public static string convertQNMemo(string itemMemo, ref CeErpTradeCell entity)
- {
- if (string.IsNullOrEmpty(itemMemo))
- {
- return "";
- }
- CeErpTrade father = CeErpTrade.Get(entity.tid);
- //删除备注中的旺旺
- if (father.type == "TMALL" || father.type == "TB")
- {
- string[] memoList = itemMemo.Split('-');
- List<string> list = new List<string>(memoList);
- string buyer_nick = "";
- if ((itemMemo.IndexOf("logo") != -1 || itemMemo.IndexOf("LOGO") != -1))
- {
- if (list.Count > 3)
- {
- buyer_nick = list[3];
- }
- }
- else if (itemMemo.IndexOf("补差") != -1 && list.Count < 6)
- {
- if (list.Count > 1)
- {
- buyer_nick = list[1];
- }
- }
- else if (itemMemo.IndexOf("默拍单") != -1 && list.Count < 6)
- {
- if (list.Count > 1)
- {
- buyer_nick = list[1];
- }
- }
- else if (itemMemo.IndexOf("寄样") != -1)
- {
- if (list.Count > 3)
- {
- buyer_nick = list[3];
- }
- }
- else if (itemMemo.IndexOf("拿样订单") != -1)
- {
- if (list.Count > 1)
- {
- buyer_nick = list[1];
- }
- }
- else if (itemMemo.IndexOf("礼物") != -1 && list.Count < 6)
- {
- if (list.Count > 1)
- {
- buyer_nick = list[1];
- }
- }
- else
- {
- if (list.Count > 5)
- {
- buyer_nick = list[5];
- }
- }
- itemMemo = string.Join("-", list);
- itemMemo = itemMemo.Replace("-" + buyer_nick, string.Empty);
- }
- itemMemo = itemMemo.Replace("\r", " ");
- itemMemo = itemMemo.Replace("\n", " ");
- string newmemo = "";
- if (itemMemo.Contains("logo") || itemMemo.Contains("LOGO"))
- {
- string[] acclist = itemMemo.Split('-');
- if (acclist.Length < 4) return null;
- string count = acclist[0];
- string product = acclist[1];
- string account = acclist[3];
- DataRow cusInfo = tmcHelper.getUserInfoByAccount(account); //客服id
- entity.ProductId = tmcHelper.getProductIdByName("logo");
- entity.ProductCount = commonHelper.getProductCount(count);// commonHelper.changeCountFromChiness(count); ;
- newmemo = "(" + entity.OrderSn + ")-";
- string newOtherMemo = "";
- for (int i = 0; i < acclist.Length; i++)
- {
- if (i == 3) continue;
- if (i >= 4)
- {
- newOtherMemo += acclist[i];
- }
- else
- newmemo += acclist[i];
- if (i < acclist.Length - 2)
- {
- newmemo += "-";
- }
- }
- string sName = tmcHelper.getShopSNameByName(father.seller_nick);//获取店铺简称
- newmemo += ("-" + sName);
- if (father.buyer_nick.IndexOf("*") < 0)
- {
- newmemo += ("-" + father.buyer_nick);
- }
- newmemo += ("-" + father.receiver_state);
- if (cusInfo != null)
- {
- newmemo += ("-" + Convert.ToString(cusInfo["Tb"]));
- }
- entity.seller_memo = newmemo;
- entity.OtherMemo = newOtherMemo;
- }
- else if (itemMemo.Contains("合包"))
- {
- itemMemo = itemMemo.Replace(",", ",");
- string[] hebaoMemoList = itemMemo.Split(',');
- string newOtherMemo = "";
- bool isMulity = true;
- if (string.IsNullOrEmpty(entity.SplitTag))
- {
- isMulity = false;
- }
- string memo_index1 = hebaoMemoList[0];
- string[] acclist = memo_index1.Split('-');
- string account = acclist[5];
- newmemo = "(" + entity.OrderSn + ")-";
- for (int idx = 0; idx < hebaoMemoList.Length; idx++)
- {
- string smallitem = hebaoMemoList[idx];
- if (idx == 0 && smallitem.IndexOf("海报") != -1)
- {
- newmemo = "";
- }
- string[] smallList = smallitem.Split('-');
- if (smallList.Length > 5 && idx > 0)
- {
- string itemsize = smallList[0];
- string itemcount = smallList[1];
- string itemmt = "", itemct = "";
- if ((smallList[3] == "不干胶" || smallitem.IndexOf("PVC卡片") != -1 || smallitem.IndexOf("pvc卡片") != -1 || smallitem.IndexOf("海报") != -1) && smallitem.IndexOf("礼物") == -1)
- {
- itemmt = acclist[2];
- }
- else
- {
- itemmt = acclist[3];
- }
- itemct = acclist[4];
- entity.ProductSize = entity.ProductSize + "," + itemsize;
- entity.ProductCount = entity.ProductCount + "," + itemcount;
- entity.Material = entity.Material + "," + itemmt;
- entity.Craft = entity.Craft + "," + itemct;
- }
- if (smallList.Length >= 7)
- {
- smallList[6] = smallList[6].Replace("(", "");
- smallList[6] = smallList[6].Replace(")", "");
- smallList[6] = smallList[6].Replace("(", "");
- smallList[6] = smallList[6].Replace(")", "");
- entity.MakeSupplier = smallList[6];
- smallList[6] = "(" + smallList[6] + ")";
- newmemo += smallList[6];
- newmemo += "-";
- }
- if (false)
- {
- newmemo += smallList[2];
- newmemo += smallList[0];
- newmemo += "-";
- newmemo += smallList[1];
- newmemo += "(";
- newmemo += entity.OrderSn;
- newmemo += ")";
- newmemo += "-";
- newmemo += smallList[4];
- if (smallList.Length > 7)
- {
- for (int i = 7; i < smallList.Length; i++)
- {
- newOtherMemo += smallList[i];
- newOtherMemo += "-";
- }
- }
- if (smallitem.IndexOf("5mmpvc") != -1)
- {
- entity.ProductId = 8; //pvc卡片
- }
- }
- else
- {
- for (int i = 0; i < smallList.Length; i++)
- {
- if (isMulity && i == 5)
- {
- continue;
- }
- if (i >= 7)
- {
- newOtherMemo += smallList[i];
- if (i < smallList.Length - 2 && i != 2 && i != 3)
- {
- newOtherMemo += "-";
- }
- }
- else
- {
- if (i == 5 || i == 6)
- {
- continue;
- }
- else
- newmemo += smallList[i];
- if (i != 2 && i != 3)
- {
- newmemo += "-";
- }
- }
- }
- }
- if (hebaoMemoList.Length > idx + 1)
- {
- newmemo += ",";
- newOtherMemo += ",";
- }
- }
- entity.ProductCount = commonHelper.getProductCount(entity.ProductCount);
- string sName = tmcHelper.getShopSNameByName(father.seller_nick);
- newmemo += (sName);
- if (father.buyer_nick.IndexOf("*") < 0)
- {
- newmemo += ("-" + father.buyer_nick);
- }
- newmemo += ("-" + father.receiver_state);
- DataRow cusInfo = tmcHelper.getUserInfoByAccount(account); //客服id
- if (cusInfo != null)
- {
- entity.CustomerUserId = Convert.ToInt32(cusInfo["ID"]);
- }
- if (cusInfo != null)
- {
- newmemo += ("-" + Convert.ToString(cusInfo["Tb"]));
- }
- entity.seller_memo = newmemo;
- entity.OtherMemo = newOtherMemo;
- }
- else
- {
- string[] acclist = itemMemo.Split('-');
- bool isXianhuo = false;
- if (acclist[0] == "现货")
- {
- isXianhuo = true;
- System.Array.Copy(acclist, 1, acclist, 0, acclist.Length - 1);
- System.Array.Resize(ref acclist, acclist.Length - 1);
- }
- if (acclist.Length < 6)
- {
- return "";
- }
- string size = acclist[0];
- string count = acclist[1];
- bool isBuGanJiao = false;
- string product = "";
- string mt = "", ct = "";
- string account = "";
- itemMemo = itemMemo.Replace("PVC", "pvc");
- if ((acclist[3] == "不干胶" || itemMemo.IndexOf("电子稿") != -1 || itemMemo.IndexOf("pvc卡片") != -1 || itemMemo.IndexOf("海报") != -1) && itemMemo.IndexOf("礼物") == -1)
- {
- isBuGanJiao = true;
- product = acclist[3];
- mt = acclist[2];
- }
- else
- {
- product = acclist[2];
- mt = acclist[3];
- }
- account = acclist[5];
- ct = acclist[4];
- if (acclist.Length >= 7)
- {
- acclist[6] = acclist[6].Replace("(", "");
- acclist[6] = acclist[6].Replace(")", "");
- acclist[6] = acclist[6].Replace("(", "");
- acclist[6] = acclist[6].Replace(")", "");
- entity.MakeSupplier = acclist[6];
- acclist[6] = "(" + acclist[6] + ")";
- }
- entity.ProductId = tmcHelper.getProductIdByName(product);
- if (entity.ProductId == 0)
- {
- return "";
- }
- DataRow cusInfo = tmcHelper.getUserInfoByAccount(account); //客服id
- if (cusInfo != null)
- {
- entity.CustomerUserId = Convert.ToInt32(cusInfo["ID"]);
- }
- if (mt.IndexOf("铜板纸") != -1)
- {
- mt = mt.Replace("铜板纸", "铜版纸");
- }
- entity.Material = mt;
- entity.ProductSize = size;
- entity.ProductCount = getProductCount(count); ;//commonHelper.changeCountFromChiness(count);
- entity.Craft = ct;
- newmemo = "(" + entity.OrderSn + ")-";
- if (isXianhuo)
- {
- newmemo += "现货-";
- }
- string newOtherMemo = "";
- bool isMulity = true;
- if (string.IsNullOrEmpty(entity.SplitTag))
- {
- isMulity = false;
- }
- if (acclist.Length >= 7 && !isMulity)
- {
- newmemo += acclist[6];
- newmemo += "-";
- }
- if (isMulity && acclist.Length >= 8)
- {
- newmemo += acclist[7];
- newmemo += "-";
- }
- for (int i = 0; i < acclist.Length; i++)
- {
- if ((isMulity && i == 6) || i == 5)
- {
- continue;
- }
- if ((i >= 7 && !isMulity) || (isMulity && i >= 8))
- {
- newOtherMemo += acclist[i];
- newOtherMemo += "-";
- }
- else
- {
- if ((i == 6 && !isMulity) || (isMulity && i == 7))
- {
- continue;
- }
- else
- newmemo += acclist[i];
- if (i != 2 && i != 3)
- {
- newmemo += "-";
- }
- }
- }
- string sName = tmcHelper.getShopSNameByName(father.seller_nick);//获取店铺简称
- newmemo += (sName);
- if (father.buyer_nick.IndexOf("*") < 0)
- {
- newmemo += ("-" + father.buyer_nick);
- }
- newmemo += ("-" + father.receiver_state);
- if (cusInfo != null)
- {
- newmemo += ("-" + Convert.ToString(cusInfo["Tb"]));
- }
- if (!string.IsNullOrEmpty(entity.SplitTag))
- {
- newmemo += "-[" + entity.SplitTag + "]";
- }
- newmemo = newmemo.Replace("\n", " ");
- entity.seller_memo = newmemo;
- entity.OtherMemo = newOtherMemo;
- }
- return newmemo;
- }
- public static bool isMultiSize(string memo)
- {
- bool result = false;
- if (memo.Contains("合包"))
- {
- return result;
- }
- string[] memolist = memo.Split('-');
- if (memolist.Length < 3)
- {
- return result;
- }
- string size_text = memolist[1];
- if (size_text.Contains(")") || size_text.Contains(")"))
- {
- size_text = memolist[2];
- }
- if (size_text.Contains(",") || size_text.Contains(",") || size_text.Contains("+"))
- {
- result = true;
- }
- if (!result)
- {
- int a = size_text.Split(new string[] { "mm" }, StringSplitOptions.None).Length - 1;
- a += size_text.Split(new string[] { "cm" }, StringSplitOptions.None).Length - 1;
- if (size_text.Count(c => c == 'x') > 1 && a > 1)
- {
- result = true;
- }
- }
- return result;
- }
- public static void sendOrderInfo(string tid, string order_status, string buyer_id, string buyer_nick, int type = 0)
- {
- Thread thread = new Thread(new ThreadStart(() =>
- {
- string url = "https://wx.lingtao8.com/api/v1/msg/new_order";
- HttpClient client = new HttpClient();
- string param = JsonConvert.SerializeObject(new
- {
- order_type = type,
- order_id = tid,
- buyer_nick = buyer_nick,
- buyer_id = buyer_id,
- order_status = order_status,
- });
- var request = new HttpRequestMessage
- {
- Method = HttpMethod.Post,
- RequestUri = new Uri(url),
- Content = new StringContent(param)
- {
- Headers =
- {
- ContentType = new MediaTypeHeaderValue("application/json")
- }
- }
- };
- try
- {
- var response = client.SendAsync(request).Result;
- response.EnsureSuccessStatusCode();
- }
- catch (Exception e)
- {
- }
- }));
- thread.Start();
- }
- public static string generateDateTimeRandomNos()
- {
- Random random = new Random();
- const int maxAttempts = 10;
- for (int i = 0; i < maxAttempts; i++)
- {
- string orderSn = DateTimeNow("yyMMddHHmmssfff") + RandomNumbers(random, 3);
- return orderSn;
- }
- return "";
- }
- /// <summary>
- /// 获取当前日期时间的指定格式字符串
- /// </summary>
- private static string DateTimeNow(string format)
- {
- return DateTime.Now.ToString(format);
- }
- /// <summary>
- /// 生成指定长度的随机数字字符串
- /// </summary>
- private static string RandomNumbers(Random random, int length)
- {
- if (length <= 0) return string.Empty;
- var rng = RandomNumberGenerator.Create();
- while (true)
- {
- byte[] randomBytes = new byte[2]; // 2字节=16位,足够0-900范围
- int value;
- do
- {
- rng.GetBytes(randomBytes);
- value = randomBytes[0] * 256 + randomBytes[1];
- } while (value >= 900 * (65536 / 900)); // 拒绝采样,避免偏差
- value = value % 900 + 100;
- if (value > 100 && value < 1000)
- {
- return value.ToString();
- }
- }
- }
- }
- }
|