commonHelper.cs 178 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029
  1. using BizCom;
  2. using Newtonsoft.Json;
  3. using SiteCore.taoObj;
  4. using SQLData;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Data;
  8. using System.Data.SqlClient;
  9. using System.IO;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using Match = System.Text.RegularExpressions.Match;
  13. using SiteCore.Handler;
  14. using System.Threading;
  15. using Newtonsoft.Json.Linq;
  16. using System.Net.Security;
  17. using System.Net;
  18. using System.Security.Cryptography.X509Certificates;
  19. using System.Security.Policy;
  20. using NHibernate.Engine;
  21. using static NHibernate.Linq.Visitors.LeftJoinDetector;
  22. using NHibernate.Loader.Custom;
  23. using System.Runtime.Remoting.Metadata.W3cXsd2001;
  24. using NPOI.OpenXmlFormats.Shared;
  25. using static SiteCore.taoObj.work_core_vo;
  26. using System.Linq;
  27. using System.Security.Cryptography;
  28. using System.Net.Http.Headers;
  29. using System.Net.Http;
  30. namespace SiteCore
  31. {
  32. public class commonHelper
  33. {
  34. public static void autoRefreshRefundState()
  35. {
  36. StringBuilder sql = new StringBuilder();
  37. sql.AppendFormat("update CE_ErpTradeRefund set RefundState=3 where RefundState=2 and DATEDIFF(hh,modified,getdate())>=72;");
  38. //sql.AppendFormat("update ce_erptradecell with(rowlock) set AfterSaleState=4,FinishAfterSaleTime=getdate() where AfterSaleState=3 and IsArbitrate=0 and DATEDIFF(hh,AfterSalePreTime,getdate())>=168;");
  39. //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;");
  40. //sql.AppendFormat("update CE_ErpTradeResponsible set VerifyState=1 where VerifyState=0 and IsArbitrate=0 and DATEDIFF(hh,createdTime,getdate())>=168;");
  41. //DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  42. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  43. sql = new StringBuilder();
  44. 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;");
  45. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  46. foreach (DataRow dr in dt.Rows)
  47. {
  48. string state = dr["VerifyState"].ToString();
  49. string tid = dr["tid"].ToString();
  50. int userId = Convert.ToInt32(dr["UserId"]);
  51. int reasonId = Convert.ToInt32(dr["ID"]);
  52. int type = Convert.ToInt32(dr["type"]);
  53. if (type == 0)
  54. {
  55. if (state == "0")//主管审核超时
  56. {
  57. CeErpTradeResponsible ceErpTradeResponsible = CeErpTradeResponsible.GetById(dr["ID"].ToString());
  58. if (ceErpTradeResponsible != null)
  59. {
  60. ceErpTradeResponsible.VerifyTime = DateTime.Now;
  61. ceErpTradeResponsible.VerifyState = 3;
  62. ceErpTradeResponsible.Update();
  63. LogHelper.AddAfterSaleLog(tid, reasonId, "主管审核超时", userId);
  64. LogHelper.addLog(tid, 0, "主管审核超时", 4, 4);
  65. }
  66. }
  67. if (state == "3")//责任人审核超时
  68. {
  69. CeErpTradeResponsible ceErpTradeResponsible = CeErpTradeResponsible.GetById(dr["ID"].ToString());
  70. if (ceErpTradeResponsible != null)
  71. {
  72. ceErpTradeResponsible.VerifyTime = DateTime.Now;
  73. ceErpTradeResponsible.VerifyState = 1;
  74. ceErpTradeResponsible.Update();
  75. LogHelper.AddAfterSaleLog(tid, reasonId, "责任人审核超时", userId);
  76. LogHelper.addLog(tid, 0, "责任人审核超时", 4, 4);
  77. CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ceErpTradeResponsible.tid);
  78. bool isAll = tradeResponsibleAll(entity);
  79. if (isAll)
  80. {
  81. entity.AfterSaleState = 4;
  82. entity.FinishAfterSaleTime = DateTime.Now;
  83. entity.UpdateTime = DateTime.Now;
  84. entity.AfterSaleSupplierState = 1;
  85. ApiVo apiVo = new ApiVo();
  86. apiVo.orderNumber = entity.ctid;
  87. apiVo.actionName = "afterOver";
  88. designHelper.API_WorkCore(apiVo); //afterOver
  89. entity.Update();
  90. }
  91. }
  92. }
  93. }
  94. else
  95. {
  96. DateTime date = DateTime.Parse(dr["VerifyTime"].ToString());
  97. if (type == 2)
  98. {
  99. if (DateTime.Compare(DateTime.Now, date.AddHours(96)) <= 0)
  100. {
  101. continue;
  102. }
  103. }
  104. //车间自动审核
  105. if (state == "0")
  106. {
  107. //节假日120小时
  108. /*if (DateTime.Compare(DateTime.Now, date.AddHours(120)) <= 0)
  109. {
  110. continue;
  111. }*/
  112. CeErpTradeResponsible ceErpTradeResponsible = CeErpTradeResponsible.GetById(dr["ID"].ToString());
  113. if (ceErpTradeResponsible != null)
  114. {
  115. ceErpTradeResponsible.VerifyTime = DateTime.Now;
  116. ceErpTradeResponsible.VerifyState = 1;
  117. ceErpTradeResponsible.Update();
  118. CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ceErpTradeResponsible.tid);
  119. bool isAll = tradeResponsibleAll(entity);
  120. if (isAll)
  121. {
  122. entity.AfterSaleState = 4;
  123. entity.FinishAfterSaleTime = DateTime.Now;
  124. entity.UpdateTime = DateTime.Now;
  125. entity.AfterSaleSupplierState = 1;
  126. entity.Update();
  127. ApiVo apiVo = new ApiVo();
  128. apiVo.orderNumber = entity.ctid;
  129. apiVo.actionName = "afterOver";
  130. designHelper.API_WorkCore(apiVo); //afterOver
  131. }
  132. CeErpSukuraData.createInfo(entity.ctid, 8);
  133. LogHelper.addLog(tid, 0, "审核超时,自动完成售后", 4, 4);
  134. }
  135. }
  136. }
  137. }
  138. }
  139. public static void tradeSaleState(CeErpTradeCell ceErpTradeCell)
  140. {
  141. string sql = "select * from ce_erptraderesponsible where tid='" + ceErpTradeCell.ctid + "' and VerifyState != -1";
  142. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql).Tables[0];
  143. CeErpTradeAfterSaleExtend ceErpTradeAfterSaleExtend = CeErpTradeAfterSaleExtend.getByTid(ceErpTradeCell.ctid);
  144. if (ceErpTradeAfterSaleExtend == null)
  145. {
  146. ceErpTradeAfterSaleExtend = new CeErpTradeAfterSaleExtend();
  147. ceErpTradeAfterSaleExtend.tid = ceErpTradeCell.ctid;
  148. ceErpTradeAfterSaleExtend.Create();
  149. }
  150. List<string> list = new List<string>();
  151. foreach (DataRow row in dt.Rows)
  152. {
  153. list.Add(row["VerifyState"].ToString());
  154. }
  155. ceErpTradeAfterSaleExtend.VerifyStates = String.Join(",", list);
  156. ceErpTradeAfterSaleExtend.Update();
  157. }
  158. public static bool tradeResponsibleAll(CeErpTradeCell ceErpTradeCell)
  159. {
  160. //判断是否全部处理完成
  161. string sql = "select * from ce_erptraderesponsible where tid='" + ceErpTradeCell.ctid + "' and VerifyState != -1";
  162. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql).Tables[0];
  163. bool isAll = true;
  164. if (dt.Rows.Count > 0 && dt.Rows.Count == 1)
  165. {
  166. }
  167. else if (dt.Rows.Count > 1)
  168. {
  169. foreach (DataRow row in dt.Rows)
  170. {
  171. if (row["VerifyState"].ToString() != "1")
  172. {
  173. isAll = false;
  174. break;
  175. }
  176. }
  177. }
  178. return isAll;
  179. }
  180. public static string getSupplierNameById(int sid)
  181. {
  182. CeErpSupplier sup = CeErpSupplier.Get(sid);
  183. if (sup != null)
  184. {
  185. return sup.ComName;
  186. }
  187. else
  188. {
  189. return "";
  190. }
  191. }
  192. public static void aftersaleSend(string ctid, string cpCode, string curUseWayBillCode)
  193. {
  194. if (ctid.IndexOf("S_") > -1)
  195. {
  196. try
  197. {
  198. string tradeCtid = ctid.Remove(0, 2);
  199. CeErpTradeAfterSaleExtend ceErpTradeAfterSaleExtend = CeErpTradeAfterSaleExtend.getByTid(tradeCtid);
  200. if (ceErpTradeAfterSaleExtend == null)
  201. {
  202. ceErpTradeAfterSaleExtend = new CeErpTradeAfterSaleExtend();
  203. ceErpTradeAfterSaleExtend.tid = tradeCtid;
  204. ceErpTradeAfterSaleExtend.ExpressNo = cpCode + "-" + curUseWayBillCode;
  205. ceErpTradeAfterSaleExtend.AfterSalSend = 1;
  206. ceErpTradeAfterSaleExtend.Create();
  207. }
  208. else
  209. {
  210. ceErpTradeAfterSaleExtend.ExpressNo = cpCode + "-" + curUseWayBillCode;
  211. ceErpTradeAfterSaleExtend.AfterSalSend = 1;
  212. ceErpTradeAfterSaleExtend.Update();
  213. }
  214. }
  215. catch (Exception ex)
  216. {
  217. }
  218. }
  219. }
  220. public static string getUserNameById(int sid)
  221. {
  222. CeErpUser sup = CeErpUser.Get(sid);
  223. if (sup != null)
  224. {
  225. return sup.Name;
  226. }
  227. else
  228. {
  229. return "";
  230. }
  231. }
  232. public static int getSupplierIDByName(string name)
  233. {
  234. StringBuilder sql2 = new StringBuilder();
  235. sql2.AppendFormat("select top 1 * from CE_ErpSupplier where ComName='{0}';", name);
  236. DataTable dt2 = DbHelper.DbConn.ExecuteDataset(sql2.ToString()).Tables[0];
  237. if (dt2.Rows.Count > 0)
  238. {
  239. return Convert.ToInt32(dt2.Rows[0]["ID"]);
  240. }
  241. return 0;
  242. }
  243. public static int autoDistributeToSupplier(CeErpTradeCell trade)
  244. {
  245. if (trade.seller_memo.IndexOf("电子稿") != -1) return 0;
  246. int count = 0;
  247. string sc = trade.ProductCount;
  248. count = handleProductCount(sc, true);
  249. //string needSc = System.Text.RegularExpressions.Regex.Replace(sc, @"[^0-9]+", "");
  250. //if (!int.TryParse(needSc, out count))
  251. //{
  252. // XLog.SaveLog(0, "autoDistributeToSupplier:获取数量[" + trade.ProductCount + "]转换出错");
  253. //}
  254. //老客户指派之前供应商
  255. if (trade.IsOldCustomer == 1 && (trade.seller_memo.IndexOf("改稿") != -1 || trade.OtherMemo.IndexOf("老客户") != -1))
  256. {
  257. CeErpTrade ceErpTrade = CeErpTrade.Get(trade.tid);
  258. if (ceErpTrade != null)
  259. {
  260. //用昵称找之前的订单
  261. string name = ceErpTrade.buyer_nick;
  262. if (!string.IsNullOrEmpty(name))
  263. {
  264. StringBuilder CeErpTradeSql = new StringBuilder();
  265. 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);
  266. DataSet data = DbHelper.DbConn.ExecuteDataset(CeErpTradeSql.ToString());
  267. DataTable datatable = data.Tables[0];
  268. if (datatable.Rows.Count > 0)
  269. {
  270. CeErpTradeCell oldOrder = CeErpTradeCell.GetByTid(datatable.Rows[0]["tid"].ToString());
  271. if (oldOrder != null)
  272. {
  273. CeErpSupplier ceErpSupplier = CeErpSupplier.Get(oldOrder.SupplierId);
  274. if (ceErpSupplier != null && ceErpSupplier.IsClose == 0)
  275. {
  276. return oldOrder.SupplierId;
  277. }
  278. }
  279. }
  280. }
  281. }
  282. }
  283. if (trade.Craft.IndexOf("门挂卡") != -1)
  284. {
  285. return 7;// ljl
  286. }
  287. else if (trade.Craft.IndexOf("打印") != -1 || trade.Craft.IndexOf("专版") != -1)
  288. {
  289. return 10; //得力
  290. }
  291. else if (trade.Craft.IndexOf("打码") != -1 || trade.Craft.IndexOf("压点线") != -1)
  292. {
  293. if (count < 300)
  294. {
  295. return 10;
  296. }
  297. else
  298. return 25;
  299. }
  300. if (trade.seller_memo.Contains("金属标") && (trade.ShopId == 26 || trade.ShopId == 45))
  301. {
  302. return 9;
  303. }
  304. //if (trade.IsOldCustomer == 1)
  305. //{
  306. // StringBuilder oldsql = new StringBuilder();
  307. // oldsql.AppendFormat("select top 1 SupplierId from view_erptradecell where buyer_nick={0} and IsAutoDistribute=1 ;",trad, trade.ProductId);
  308. //}
  309. StringBuilder sql = new StringBuilder();
  310. sql.AppendFormat("select count(0) from ce_erpproduct where id={0} and IsAutoDistribute=1 ;", trade.ProductId);
  311. sql.AppendFormat("select top 1 * from ce_erptrade where tid='{0}';", trade.tid);
  312. DataSet oDs = DbHelper.DbConn.ExecuteDataset(sql.ToString());
  313. DataTable pDt = oDs.Tables[0];
  314. DataTable rDt = oDs.Tables[1];
  315. string material = trade.Material;
  316. material = material.Replace("铜板纸", "铜版纸");
  317. string crafts = trade.Craft;
  318. string supplierCrafts = trade.MakeSupplier;
  319. if (supplierCrafts == "")
  320. {
  321. supplierCrafts = "123123";
  322. }
  323. decimal size = getOrderSizeFromString(trade.ProductSize);
  324. if (pDt != null && pDt.Rows.Count > 0)
  325. {
  326. string receiver_state = "";
  327. if (rDt != null || rDt.Rows.Count > 0)
  328. {
  329. receiver_state = rDt.Rows[0]["receiver_state"].ToString();
  330. if (trade.IsOldCustomer == 1 && !string.IsNullOrEmpty(rDt.Rows[0]["buyer_nick"].ToString()))
  331. {
  332. StringBuilder oldsql = new StringBuilder();
  333. 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);
  334. DataTable oldDt = DbHelper.DbConn.ExecuteDataset(oldsql.ToString()).Tables[0];
  335. if (oldDt.Rows.Count > 0)
  336. {
  337. CeErpSupplier ceErpSupplier = CeErpSupplier.Get(Convert.ToInt32(oldDt.Rows[0]["SupplierId"]));
  338. if (ceErpSupplier != null && ceErpSupplier.IsClose == 0)
  339. {
  340. return Convert.ToInt32(oldDt.Rows[0]["SupplierId"]);
  341. }
  342. }
  343. }
  344. }
  345. try
  346. {
  347. //CHARINDEX(','+'{0}'+',',','+ProductID+',')>0
  348. sql = new StringBuilder();
  349. 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);
  350. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  351. if (dt == null || dt.Rows.Count < 1) return 0;
  352. DataView dv = new DataView(dt);
  353. int topOneProductSupplier = Convert.ToInt32(dv[0]["SupplierID"]);
  354. if (receiver_state.Length > 0)
  355. {
  356. 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);
  357. if (dv.Count > 0)
  358. {
  359. return Convert.ToInt32(dv[0]["SupplierID"]);
  360. }
  361. }
  362. if (count > 0)
  363. {
  364. if (size > 0)
  365. {
  366. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1} and SizeL<={2} and SizeW>={2} ", material, count, size);
  367. if (dv.Count > 0)
  368. {
  369. return Convert.ToInt32(dv[0]["SupplierID"]);
  370. }
  371. }
  372. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1}", material, count);
  373. if (dv.Count > 0)
  374. {
  375. LogHelper.addLog(trade.ctid, 0, "筛选供应商:产品 材质 工艺 数量 符合!"); return Convert.ToInt32(dv[0]["SupplierID"]);
  376. }
  377. }
  378. if (size > 0)
  379. {
  380. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1} and SizeL<={2} and SizeW>={2}", material, count, size);
  381. if (dv.Count > 0)
  382. {
  383. return Convert.ToInt32(dv[0]["SupplierID"]);
  384. }
  385. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and SizeL<={1} and SizeW>={1}", material, size);
  386. if (dv.Count > 0)
  387. {
  388. return Convert.ToInt32(dv[0]["SupplierID"]);
  389. }
  390. }
  391. dv.RowFilter = string.Format("ProductCrafts like '%{0}%'", material);
  392. if (count > 0)
  393. {
  394. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1}", material, count);
  395. if (dv.Count > 0)
  396. {
  397. return Convert.ToInt32(dv[0]["SupplierID"]);
  398. }
  399. dv.RowFilter = string.Format("MinNum<={0} and MaxNum>={0}", count);
  400. if (dv.Count > 0)
  401. {
  402. return Convert.ToInt32(dv[0]["SupplierID"]);
  403. }
  404. }
  405. if (size > 0)
  406. {
  407. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and SizeL<={1} and SizeW>={1}", material, size);
  408. if (dv.Count > 0)
  409. {
  410. return Convert.ToInt32(dv[0]["SupplierID"]);
  411. }
  412. dv.RowFilter = string.Format(" SizeL<={0} and SizeW>={0}", size);
  413. if (dv.Count > 0)
  414. {
  415. return Convert.ToInt32(dv[0]["SupplierID"]);
  416. }
  417. }
  418. dv.RowFilter = string.Format("Crafts like '%{0}%' or Crafts like '%{1}%'", crafts, supplierCrafts);
  419. if (dv.Count > 0)
  420. {
  421. return Convert.ToInt32(dv[0]["SupplierID"]);
  422. }
  423. //产品 材质符合
  424. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' ", material);
  425. if (dv.Count > 0)
  426. {
  427. return Convert.ToInt32(dv[0]["SupplierID"]);
  428. }
  429. else
  430. {
  431. return topOneProductSupplier;
  432. }
  433. }
  434. catch (Exception ex)
  435. {
  436. XLog.SaveLog(0, "commmonHelper:autoDistributeToSupplier" + ex.Message);
  437. }
  438. }
  439. return 0;
  440. }
  441. public static void setDeliveryUnusualOrder2()
  442. {
  443. StringBuilder sql = new StringBuilder();
  444. 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( DAY, FinishPlaceTime, GETDATE( ) ) < 20 and IsXianHuo=0 and IsSample=0 ;");
  445. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  446. string timer_sql = string.Format("select * from CE_ErpSupplierProductTime");
  447. DataTable timer_data = DbHelper.DbConn.ExecuteDataset(timer_sql).Tables[0];
  448. Dictionary<int, List<CeErpSupplierProductTime>> timer_map = new Dictionary<int, List<CeErpSupplierProductTime>>();
  449. foreach (DataRow datarow in timer_data.Rows)
  450. {
  451. List<CeErpSupplierProductTime> list = null;
  452. int supplierId = Convert.ToInt32(datarow["SupplierId"]);
  453. if (timer_map.ContainsKey(supplierId))
  454. {
  455. timer_map.TryGetValue(supplierId, out list);
  456. }
  457. else
  458. {
  459. list = new List<CeErpSupplierProductTime>();
  460. timer_map.Add(supplierId, list);
  461. timer_map.TryGetValue(supplierId, out list);
  462. }
  463. CeErpSupplierProductTime ceErpSupplierProductTime = new CeErpSupplierProductTime();
  464. ceErpSupplierProductTime.quantity = Convert.ToInt32(datarow["quantity"]);
  465. ceErpSupplierProductTime.dayDeadLine = datarow["dayDeadLine"].ToString();
  466. ceErpSupplierProductTime.deadLine = datarow["deadLine"].ToString();
  467. ceErpSupplierProductTime.productId = datarow["productId"].ToString();
  468. ceErpSupplierProductTime.craft = datarow["craft"].ToString();
  469. ceErpSupplierProductTime.sendDay = Convert.ToInt32(datarow["sendDay"]);
  470. list.Add(ceErpSupplierProductTime);
  471. }
  472. List<string> tLst = new List<string>();
  473. if (dt != null && dt.Rows.Count > 0)
  474. {
  475. foreach (DataRow row in dt.Rows)
  476. {
  477. try
  478. {
  479. int supplierId = Convert.ToInt32(row["SupplierId"]);
  480. int productId = Convert.ToInt32(row["productId"]);
  481. if (supplierId == 0 || productId == 0)
  482. {
  483. continue;
  484. }
  485. //没配置时间
  486. if (!timer_map.ContainsKey(supplierId))
  487. {
  488. continue;
  489. }
  490. List<CeErpSupplierProductTime> timmerList = timer_map[supplierId];
  491. if (timmerList.Count == 0)
  492. {
  493. continue;
  494. }
  495. string[] productIds = null;
  496. string finishPlaceTime = row["FinishPlaceTime"].ToString();
  497. string sellmer_mome = row["seller_memo"].ToString();
  498. string txtCount = row["ProductCount"].ToString();
  499. DateTime placeTime = DateTime.Now;
  500. if (string.IsNullOrEmpty(finishPlaceTime))
  501. {
  502. continue;
  503. }
  504. placeTime = DateTime.Parse(finishPlaceTime);
  505. foreach (CeErpSupplierProductTime productTime in timmerList)
  506. {
  507. string txtIds = productTime.productId;
  508. string[] crafts = { };
  509. int count = productTime.quantity;
  510. if (string.IsNullOrEmpty(txtIds))
  511. {
  512. continue;
  513. }
  514. if (count > 0)
  515. {
  516. int quantity = handleProductCount(txtCount, true);
  517. //订单数量大于写入的数量则跳过
  518. if (quantity > count)
  519. {
  520. continue;
  521. }
  522. }
  523. productIds = txtIds.Split(',');
  524. if (productIds.Contains(productId.ToString()))
  525. {
  526. string textCraft = productTime.craft;
  527. textCraft = textCraft.Replace(",", ",");//统一格式
  528. if (!string.IsNullOrEmpty(textCraft))
  529. {
  530. crafts = textCraft.Split(',');
  531. }
  532. if (crafts.Length > 0)
  533. {
  534. bool isinCraft = false;
  535. for (int i = 0; i < crafts.Length; i++)
  536. {
  537. if (sellmer_mome.IndexOf(crafts[i]) >= 0)
  538. {
  539. isinCraft = true;
  540. break;
  541. }
  542. }
  543. //有写工艺并且备注中没匹配中则跳过
  544. if (!isinCraft)
  545. {
  546. continue;
  547. }
  548. }
  549. DateTime deadLine = DateTime.Parse(productTime.deadLine);
  550. DateTime dayDeadLine = DateTime.Parse(productTime.dayDeadLine);
  551. int sendDay = productTime.sendDay;
  552. //订单发货时间
  553. DateTime sendtime = placeTime;
  554. //下单时间小于当日发货时间则不用判断
  555. //当日发货必须发货
  556. if (dayDeadLine.Hour > 0 && dayDeadLine.Hour > placeTime.Hour)
  557. {
  558. sendtime = DateTime.Parse(placeTime.ToString("yyyy-MM-dd 23:59:59"));
  559. }
  560. else if (deadLine.Hour > 0 && deadLine.Hour > placeTime.Hour)
  561. {
  562. //在截稿时间之前下单的可以减去一天时间
  563. sendDay = Math.Max(1, sendDay - 1);
  564. sendtime = DateTime.Parse(placeTime.ToString("yyyy-MM-dd 00:00:00")).AddDays(sendDay);
  565. }
  566. else
  567. {
  568. sendDay = Math.Max(1, sendDay - 1);
  569. sendtime = DateTime.Parse(placeTime.ToString("yyyy-MM-dd 23:59:59")).AddDays(sendDay);
  570. }
  571. //判断有没有到发货日期大于0还没到发货时间
  572. if (DateTime.Compare(sendtime.Date, DateTime.Now.Date) < 0)
  573. {
  574. tLst.Add("'" + row["ctid"].ToString() + "'");
  575. //匹配到就不要继续匹配了
  576. break;
  577. }
  578. }
  579. }
  580. }
  581. catch (Exception ex)
  582. {
  583. XLog.SaveLog(0, row["ctid"].ToString() + "更新发货异常订单错误:" + ex);
  584. }
  585. }
  586. }
  587. if (tLst.Count > 0)
  588. {
  589. string needctids = string.Join(",", tLst.ToArray());
  590. StringBuilder updsql = new StringBuilder();
  591. //DateTime unusualTime = new DateTime();
  592. updsql.AppendFormat("update ce_erptradecell with(rowlock) set unusualTag=5,UnusualTime=getDate() where ctid in ({0});", needctids);
  593. DbHelper.DbConn.ExecuteNonQuery(updsql.ToString());
  594. }
  595. }
  596. public static void setDeliveryUnusualOrder()
  597. {
  598. try
  599. {
  600. StringBuilder sql = new StringBuilder();
  601. 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);");
  602. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  603. List<string> tLst = new List<string>();
  604. if (dt.Rows.Count > 0)
  605. {
  606. foreach (DataRow dr in dt.Rows)
  607. {
  608. double hour = 0;
  609. string fptime = dr["FinishPlaceTime"].ToString();
  610. if (fptime.Length > 0)
  611. {
  612. hour = DateTime.Now.Subtract(Convert.ToDateTime(fptime)).TotalHours;
  613. }
  614. else
  615. continue;
  616. int useHour = 10000;
  617. StringBuilder sqlhour = new StringBuilder();
  618. 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());
  619. DataTable dthour = DbHelper.DbConn.ExecuteDataset(sqlhour.ToString()).Tables[0];
  620. if (dthour.Rows.Count > 0)
  621. {
  622. useHour = Convert.ToInt32(dthour.Rows[0]["fhTime"]);
  623. }
  624. else
  625. {
  626. sqlhour = new StringBuilder();
  627. sqlhour.AppendFormat("select top 1 * from CE_ErpProductHour where ProductID={0} and (CHARINDEX(Craft,'{1}')>0 or Craft='*');", dr["ProductId"].ToString(), dr["Craft"].ToString());
  628. dthour = DbHelper.DbConn.ExecuteDataset(sqlhour.ToString()).Tables[0];
  629. if (dthour.Rows.Count > 0)
  630. {
  631. useHour = Convert.ToInt32(dthour.Rows[0]["fhTime"]);
  632. }
  633. else
  634. {
  635. sqlhour = new StringBuilder();
  636. sqlhour.AppendFormat("select top 1 * from CE_ErpProductHour where ProductID={0};", dr["ProductId"].ToString());
  637. dthour = DbHelper.DbConn.ExecuteDataset(sqlhour.ToString()).Tables[0];
  638. if (dthour.Rows.Count > 0)
  639. {
  640. useHour = Convert.ToInt32(dthour.Rows[0]["fhTime"]);
  641. }
  642. }
  643. }
  644. if (hour > useHour)
  645. {
  646. tLst.Add("'" + dr["ctid"].ToString() + "'");
  647. }
  648. }
  649. }
  650. sql = new StringBuilder();
  651. 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 ;");
  652. dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  653. if (dt.Rows.Count > 0)
  654. {
  655. foreach (DataRow dr in dt.Rows)
  656. {
  657. double hour = 0;
  658. string fptime = dr["FinishPlaceTime"].ToString();
  659. string paytime = dr["pay_time"].ToString();
  660. DateTime dtPaytime = Convert.ToDateTime(paytime);
  661. if (fptime.Length > 0)
  662. {
  663. hour = DateTime.Now.Subtract(Convert.ToDateTime(paytime)).TotalHours;
  664. }
  665. else
  666. continue;
  667. DateTime nowtime = DateTime.Now;
  668. if (hour > 18)
  669. {
  670. tLst.Add("'" + dr["ctid"].ToString() + "'");
  671. }
  672. //if (hour > 72 && Convert.ToInt32(dr["ShopId"])==34)//公司自用
  673. //{
  674. // tLst.Add("'" + dr["ctid"].ToString() + "'");
  675. //}
  676. //else if (nowtime.Hour >= 17)
  677. //{
  678. // if((dtPaytime.Hour >= 14 && dtPaytime.Hour < 17) || (dtPaytime.Hour == 17 && dtPaytime.Minute < 40))
  679. // {
  680. // string sptime = nowtime.Year + "/" + nowtime.Month + "/" + nowtime.Day + " 17:40:00";
  681. // DateTime spDatetime = Convert.ToDateTime(sptime);
  682. // if (spDatetime.Subtract(Convert.ToDateTime(paytime)).TotalMinutes > 0)
  683. // {
  684. // tLst.Add("'" + dr["ctid"].ToString() + "'");
  685. // }
  686. // }
  687. //}
  688. //else if (nowtime.Hour >= 14)
  689. //{
  690. // if(dtPaytime.Hour >= 10 && dtPaytime.Hour < 14)
  691. // {
  692. // string sptime = nowtime.Year + "/" + nowtime.Month + "/" + nowtime.Day + " 14:00:00";
  693. // DateTime spDatetime = Convert.ToDateTime(sptime);
  694. // if (spDatetime.Subtract(Convert.ToDateTime(paytime)).TotalMinutes > 0)
  695. // {
  696. // tLst.Add("'" + dr["ctid"].ToString() + "'");
  697. // }
  698. // }
  699. //}
  700. //else if (nowtime.Hour >= 10)
  701. //{
  702. // if (dtPaytime.Hour >= 18 || dtPaytime.Hour < 10)
  703. // {
  704. // string sptime = nowtime.Year + "/" + nowtime.Month + "/" + nowtime.Day + " 10:00:00";
  705. // DateTime spDatetime = Convert.ToDateTime(sptime);
  706. // if (spDatetime.Subtract(Convert.ToDateTime(paytime)).TotalMinutes > 0)
  707. // {
  708. // tLst.Add("'" + dr["ctid"].ToString() + "'");
  709. // }
  710. // }
  711. //}
  712. }
  713. }
  714. if (tLst.Count > 0)
  715. {
  716. string needctids = string.Join(",", tLst.ToArray());
  717. StringBuilder updsql = new StringBuilder();
  718. //DateTime unusualTime = new DateTime();
  719. updsql.AppendFormat("update ce_erptradecell with(rowlock) set unusualTag=5,UnusualTime=getDate() where ctid in ({0});", needctids);
  720. DbHelper.DbConn.ExecuteNonQuery(updsql.ToString());
  721. }
  722. }
  723. catch (Exception ex)
  724. {
  725. XLog.SaveLog(0, "更新发货异常订单错误:" + ex.Message);
  726. }
  727. splitCell2AllPlaceOrder();
  728. }
  729. public static void splitCell2AllPlaceOrder()
  730. {
  731. //
  732. int spid = 0;
  733. try
  734. {
  735. StringBuilder sql = new StringBuilder();
  736. sql.AppendFormat("select * from CE_ErpTradeCell2 where DATEDIFF(DAY, FinishPlaceTime, GETDATE())<5 and MakeSupplier like '%,%';");
  737. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  738. List<string> idList = new List<string>();
  739. foreach (DataRow dr in dt.Rows)
  740. {
  741. string msup = dr["MakeSupplier"].ToString();
  742. string[] suplist = msup.Split(',');
  743. spid = Convert.ToInt32(dr["ID"]);
  744. foreach (string supItem in suplist)
  745. {
  746. StringBuilder newsql = new StringBuilder();
  747. newsql.AppendFormat(" insert into CE_ErpTradeCell2 ([ctid],[tid],[DesignUserId],[OrderState],[CustomerUserId],[IsUrgency],[IsRefund],[IsReturn],[IsNeedBill]," +
  748. "[SupplierId],[DeliveryAddress],[CallTimes],[NoteTimes],[OvertimeUserId],[UnusualTag],[UnusualCon],[ReturnReason],[MemoOpt],[AfterSaleTime],[AfterSaleUserId]," +
  749. "[AfterSaleReason],[PlaceUserId],[AfterSaleState],[AfterSaleMethod],[AfterSaleMemo],[AfterSaleResponsible],[AfterSalePreTime],[FinishAfterSaleTime],[DeductFee]," +
  750. "[RefundFee],[HandleTime],[IsHaveNewOrder],[ResponsibleUserId],[ptid],[IsPreDelivery],[IsSample],[seller_memo],[ProductId],[WaitDesignTime],[StartDesignTime]," +
  751. "[FinishDesignTime],[FinishPlaceTime],[FinishDeliveryTime],[DesignSelfMemo],[DesignPrice],[Material],[Craft],[ProductSize],[ProductCount],[UnusualTime],[IsAutoDispatch]," +
  752. "[IsVerifyToSupplier],[CustomerMemo],[payment],[OutSid],[AfterSalePayment],[ShopId],[SplitTag],[isAfterSaleOrder],[isDianziOrder],[LastBillCpCode],[LastBillWaybillCode]," +
  753. "[pay_time],[IsSF],[IsXianHuo],[ReturnTime],[OtherMemo],[AfterSaleBackReason],[CheckMemo],[IsOldCustomer],[IsSupplierRefund],[IsReadTag],[AfterSaleMemoType]," +
  754. "[UrgencyTime],[IsOffLineOrder],[PayProofImg],[wechatTag],[MakeSupplier]) select [ctid],[tid],[DesignUserId],[OrderState],[CustomerUserId],[IsUrgency],[IsRefund]," +
  755. "[IsReturn],[IsNeedBill],[SupplierId],[DeliveryAddress],[CallTimes],[NoteTimes],[OvertimeUserId],[UnusualTag],[UnusualCon],[ReturnReason],[MemoOpt],[AfterSaleTime]," +
  756. "[AfterSaleUserId],[AfterSaleReason],[PlaceUserId],[AfterSaleState],[AfterSaleMethod],[AfterSaleMemo],[AfterSaleResponsible],[AfterSalePreTime],[FinishAfterSaleTime]," +
  757. "[DeductFee],[RefundFee],[HandleTime],[IsHaveNewOrder],[ResponsibleUserId],[ptid],[IsPreDelivery],[IsSample],[seller_memo],[ProductId],[WaitDesignTime],[StartDesignTime]," +
  758. "[FinishDesignTime],[FinishPlaceTime],[FinishDeliveryTime],[DesignSelfMemo],[DesignPrice],[Material],[Craft],[ProductSize],[ProductCount],[UnusualTime],[IsAutoDispatch]," +
  759. "[IsVerifyToSupplier],[CustomerMemo],[payment],[OutSid],[AfterSalePayment],[ShopId],[SplitTag],[isAfterSaleOrder],[isDianziOrder],[LastBillCpCode],[LastBillWaybillCode]," +
  760. "[pay_time],[IsSF],[IsXianHuo],[ReturnTime],[OtherMemo],[AfterSaleBackReason],[CheckMemo],[IsOldCustomer],[IsSupplierRefund],[IsReadTag],[AfterSaleMemoType],[UrgencyTime]," +
  761. "[IsOffLineOrder],[PayProofImg],[wechatTag],'{1}' from CE_ErpTradeCell2 where ID={0}", Convert.ToInt32(dr["ID"]), supItem);
  762. DbHelper.DbConn.ExecuteNonQuery(newsql.ToString());
  763. }
  764. idList.Add(dr["ID"].ToString());
  765. }
  766. string idsstr = string.Join(",", idList.ToArray());
  767. sql.AppendFormat("delete from CE_ErpTradeCell2 where ID in ({0})", idsstr);
  768. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  769. }
  770. catch (Exception ex)
  771. {
  772. XLog.SaveLog(0, "拆分ce_erptradecell2表的制作车间出错:" + spid + ex.Message);
  773. }
  774. }
  775. public static void DoAutoDispatch(string conn)
  776. {
  777. if (webConfig.Dispatch_TimeList.Contains(DateTime.Now.ToString("HH:mm")))
  778. {
  779. WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "开始自动派单!"));
  780. SqlParameter[] sqlParameter ={
  781. new SqlParameter("@res", SqlDbType.VarChar, 50)};
  782. sqlParameter[0].Direction = ParameterDirection.Output;
  783. CeErpOpt.ExecuteNonQueryStore("sp_autodispatch", sqlParameter);
  784. string res = sqlParameter[0].Value.ToString();
  785. if (res == "派单完成") WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "结束自动派单!"));
  786. else WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "无法成功派单"));
  787. }
  788. //sp_autodispatch
  789. }
  790. public static void DoAutoDispatch2(string conn)
  791. {
  792. if (webConfig.Dispatch_TimeList.Contains(DateTime.Now.ToString("HH:mm")))
  793. {
  794. WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "开始自动派单!"));
  795. SqlConnection sqlCnt = new SqlConnection(conn);
  796. try
  797. {
  798. sqlCnt.Open();
  799. string sql = "select * from view_ErpTradeCell where OrderState = 2 and ProductId <> 0";
  800. SqlDataAdapter myDataAdapter = new SqlDataAdapter(sql, sqlCnt);
  801. DataSet myDataSet = new DataSet();
  802. myDataAdapter.Fill(myDataSet, "Trade");
  803. DataTable myTable = myDataSet.Tables[0];
  804. List<string> ids = new List<string>();
  805. foreach (DataRow Dr in myTable.Rows)
  806. {
  807. if (Convert.ToInt32(Dr["OrderState"]) > 2 || Convert.ToInt32(Dr["DesignUserId"]) > 0)
  808. {
  809. continue;
  810. }
  811. ids.Add(Dr["ctid"].ToString());
  812. CeErpShop nShop = CeErpShop.GetShopIdByName(Dr["seller_nick"].ToString());
  813. string shopId = "0";
  814. if (nShop != null)
  815. {
  816. shopId = nShop.ID.ToString();
  817. }
  818. string proId = Dr["ProductId"].ToString();
  819. string Amount = Dr["payment"].ToString();
  820. string ctid = Dr["ctid"].ToString();
  821. string ctids = "";
  822. if (ctid.IndexOf("C") != -1)
  823. {
  824. ctids = getSameTradeByTid(Dr["tid"].ToString());
  825. if (ctids.Length <= 0)
  826. {
  827. continue;
  828. }
  829. }
  830. else
  831. {
  832. ctids = "'" + ctid + "'";
  833. }
  834. sql = "select top 1 * from view_ErpUser " +
  835. "where PostCode = 'Designer' and " + //设计师
  836. "OnDuty = 1 and " + //上班状态
  837. "DayOrderReceive < DayOrderLimit and " + //当日接单数小于可接单数量上限
  838. "OrderAmountLimit >= " + Amount + " and " + //额度上限大于付款金额
  839. "CHARINDEX('," + shopId + ",',','+OrgShop+ ',')>0 and " + //部门关联店铺
  840. "CHARINDEX('," + shopId + ",',','+pemShop+ ',')>0 and " + //个人关联店铺
  841. "CHARINDEX('," + proId + ",',','+pemDesign+ ',')>0 " + //个人关联产品
  842. "order by DayOrderPer, PostLevel desc, Id";
  843. SqlDataAdapter userAdapter = new SqlDataAdapter(sql, sqlCnt);
  844. DataSet userSet = new DataSet();
  845. userAdapter.Fill(userSet, "user");
  846. DataTable userTable = userSet.Tables[0];
  847. //有满足条件的设计师
  848. if (userTable.Rows.Count > 0)
  849. {
  850. SqlCommand updCMD = sqlCnt.CreateCommand();
  851. try
  852. {
  853. updCMD.Transaction = sqlCnt.BeginTransaction();//开启事务
  854. //派单
  855. updCMD.CommandText = "update CE_ErpTradeCell set OrderState = 3, IsAutoDispatch = 1, WaitDesignTime = getdate(), DesignUserId = " + userTable.Rows[0]["ID"].ToString() + " where ctid in (" + ctids + ")";
  856. updCMD.ExecuteNonQuery();
  857. //更新日数量上限和可接单比例
  858. 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();
  859. updCMD.ExecuteNonQuery();
  860. //写订单日志
  861. updCMD.CommandText = "insert into CE_ErpTradeLog(tid,OrderState,UserId,OperateTime,Con) select ctid,OrderState,0,getdate(),'自动派单' from ce_erptradecell where ctid in(" + ctids + ")";
  862. updCMD.ExecuteNonQuery();
  863. updCMD.Transaction.Commit();//提交事务(真正的从数据库中修改了数据)
  864. }
  865. catch (Exception ee)
  866. {
  867. updCMD.Transaction.Rollback();
  868. }
  869. }
  870. }
  871. string sql1 = "select ctid from view_ErpTradeCell where orderstate=3 and DesignUserId = 2125 and ctid in ('" + string.Join(",", ids) + "');";
  872. /* string sql1 = "select ctid from view_ErpTradeCell where orderstate=3 and DesignUserId = 2125 ";*/
  873. DataTable dt1 = SqlHelper.ExecuteDataSet(sql1).Tables[0];
  874. foreach (DataRow dr1 in dt1.Rows)
  875. {
  876. apiDesign.API_GetPrintData_CreateOrder(CeErpTradeCell.GetByCtid(dr1["ctid"].ToString()));
  877. WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "开始派单" + dr1["ctid"].ToString() + "至设计系统!"));
  878. Thread.Sleep(1000); // 添加五秒延迟
  879. }
  880. WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "结束自动派单!"));
  881. }
  882. catch (Exception ed)
  883. {
  884. WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), ed.Message));
  885. }
  886. finally
  887. {
  888. if (sqlCnt.State == ConnectionState.Open)
  889. sqlCnt.Close();
  890. }
  891. }
  892. }
  893. public static string getSameTradeByTid(string tid)
  894. {
  895. StringBuilder sql = new StringBuilder();
  896. sql.AppendFormat("select ctid from view_ErpTradeCell where tid='{0}';", tid);
  897. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  898. if (dt.Rows.Count > 0)
  899. {
  900. string ctids = "";
  901. foreach (DataRow dr in dt.Rows)
  902. {
  903. ctids += "'";
  904. ctids += dr["ctid"].ToString();
  905. ctids += "'";
  906. ctids += ",";
  907. }
  908. ctids = ctids.Substring(0, ctids.Length - 1);
  909. return ctids;
  910. }
  911. else
  912. return "";
  913. }
  914. public static void WriteLog(string LogText)
  915. {
  916. string sDir = System.IO.Path.GetTempPath() + @"Log\" + DateTime.Now.ToString("yyyyMM");
  917. if (!Directory.Exists(sDir))
  918. Directory.CreateDirectory(sDir);
  919. using (StreamWriter sw = new StreamWriter(sDir + @"\Log_" + DateTime.Now.ToString("dd") + ".txt", true, Encoding.UTF8))
  920. {
  921. sw.Write(LogText + System.Environment.NewLine);
  922. }
  923. }
  924. public static void UpdateRelationOrder(string ctid)
  925. {
  926. if (ctid.Length <= 0) return;
  927. CeErpTradeCell.UpdateRelationOrder(ctid);
  928. //try
  929. //{
  930. // //父订单变化,更新补差价订单
  931. // //List<string> lw = new List<string>();
  932. // //lw.Add(string.Format("OrderState={0}", father.OrderState));
  933. // //lw.Add(string.Format("CustomerUserId={0}", father.CustomerUserId));
  934. // //lw.Add(string.Format("DesignUserId={0}", father.DesignUserId));
  935. // //lw.Add(string.Format("AfterSaleState={0}", father.AfterSaleState));
  936. // //lw.Add(string.Format("IsNeedBill={0}", father.IsNeedBill));
  937. // ////lw.Add(string.Format("IsUrgency={0}", father.IsUrgency == true ? 1 : 0));
  938. // //lw.Add(string.Format("IsRefund={0}", father.IsRefund));
  939. // //lw.Add(string.Format("WaitDesignTime='{0}'", father.WaitDesignTime.ToString()));
  940. // //lw.Add(string.Format("StartDesignTime='{0}'", father.StartDesignTime.ToString()));
  941. // //lw.Add(string.Format("FinishDesignTime='{0}'", father.FinishDesignTime.ToString()));
  942. // //lw.Add(string.Format("FinishPlaceTime='{0}'", father.FinishPlaceTime.ToString()));
  943. // //lw.Add(string.Format("FinishDeliveryTime='{0}'", father.FinishDeliveryTime.ToString()));
  944. // ////lw.Add(string.Format("IsReturn={0}", father.IsReturn));
  945. // //string sqlstr = string.Join(" , ", lw.ToArray());
  946. // //StringBuilder sql = new StringBuilder();
  947. // //sql.AppendFormat("update ce_erptradecell set " + sqlstr + " where ptid='{0}'", father.tid);
  948. // ////sql.AppendFormat("update view_erptrade set status={1} where ptid={0}", father.ctid, father.status);
  949. // //DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  950. // //StringBuilder sql = new StringBuilder();
  951. // //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,");
  952. // //sql.Append("AfterSaleState=b.AfterSaleState,IsNeedBill=b.IsNeedBill,IsRefund=b.IsRefund from ce_erptradecell,ce_erptradecell as b ");
  953. // //sql.AppendFormat("where ce_erptradecell.ptid =b.tid and ce_erptradecell.ptid='{0}'", tid);//='1827905618077154637'
  954. // //DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  955. // //SqlParameter[] sqlParameter ={
  956. // // new SqlParameter("@mainctids", SqlDbType.VarChar,100),
  957. // // new SqlParameter("@res", SqlDbType.VarChar, 4000)
  958. // //};
  959. // //sqlParameter[0].Value = ctid;
  960. // //sqlParameter[1].Direction = ParameterDirection.Output;
  961. // //DbHelper.DbConn.ExecuteNonQuery(CommandType.StoredProcedure, "sp_set_bucha", sqlParameter);
  962. //}
  963. //catch (Exception ex)
  964. //{
  965. // XLog.SaveLog(0, "commmonHelper:UpdateRelationOrder" + ex.Message);
  966. //}
  967. }
  968. public static void UpdateSameOrderToDesigner(CeErpTradeCell entity, int designId)
  969. {
  970. CeErpTrade trade = CeErpTrade.Get(entity.tid);
  971. if (trade != null)
  972. {
  973. StringBuilder sql = new StringBuilder();
  974. if (trade.type == "PDD" || trade.type == "JD")
  975. {
  976. 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);
  977. }
  978. else
  979. 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);
  980. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  981. }
  982. }
  983. public static void SetSameSupplierToOrder(CeErpTradeCell entity, int supId)
  984. {
  985. StringBuilder sql = new StringBuilder();
  986. sql.AppendFormat("update CE_ErpTradeCell with(rowlock) set SupplierId={0} where orderstate=5 and tid='{1}';", supId, entity.tid);
  987. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  988. }
  989. public static string MidStrEx(string sourse, string startstr, string endstr)
  990. {
  991. string result = string.Empty;
  992. int startindex, endindex;
  993. try
  994. {
  995. startindex = sourse.IndexOf(startstr);
  996. if (startindex == -1)
  997. return result;
  998. string tmpstr = sourse.Substring(startindex + startstr.Length);
  999. endindex = tmpstr.IndexOf(endstr);
  1000. if (endindex == -1)
  1001. return result;
  1002. result = tmpstr.Remove(endindex);
  1003. }
  1004. catch (Exception ex)
  1005. {
  1006. Console.WriteLine("MidStrEx Err:" + ex.Message);
  1007. }
  1008. return result;
  1009. }
  1010. public static string KeepChinese(string str)
  1011. {
  1012. string chineseString = "";
  1013. for (int i = 0; i < str.Length; i++)
  1014. {
  1015. if (str[i] >= 0x4E00 && str[i] <= 0x9FA5)
  1016. {
  1017. chineseString += str[i];
  1018. }
  1019. }
  1020. return chineseString;
  1021. }
  1022. public static string GetD3ComCode(string code, string name)
  1023. {
  1024. string useStr = code;
  1025. if (code.Length == 0)
  1026. {
  1027. useStr = name;
  1028. }
  1029. string sql = "select * from CE_ErpMailInfo";
  1030. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  1031. foreach (DataRow dr in dt.Rows)
  1032. {
  1033. if (dr["cpCode"].ToString().IndexOf(useStr) != -1)
  1034. {
  1035. return dr["cpCode"].ToString();
  1036. }
  1037. }
  1038. //声明存储结果的字符串
  1039. //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," +
  1040. // "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," +
  1041. // "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," +
  1042. // "YUNDA-CAINIAO-JA,SF-CAINIAO-GDGZ,YUNDA-CAINIAO-GDFS,";
  1043. //string[] codeList = codeStr.Split(',');
  1044. ////将传入参数中的中文字符添加到结果字符串中
  1045. //for (int i = 0; i < codeList.Length; i++)
  1046. //{
  1047. // if (codeList[i].IndexOf(useStr) != -1)
  1048. // {
  1049. // return codeList[i];
  1050. // }
  1051. //}
  1052. //返回保留中文的处理结果
  1053. return "";
  1054. }
  1055. public static int getRefundTagByState(string st, int isPart = 0)
  1056. {
  1057. int state = 0;
  1058. if (st == "NO_REFUND" || st == "SELLER_REFUSE_BUYER" || st == "CLOSED" || st == "FAILED")
  1059. {
  1060. state = 0;
  1061. }
  1062. else if (st == "REFUNDING")
  1063. {
  1064. state = 1;
  1065. }
  1066. else if (st == "REFUNDED" || st == "SUCCESS")
  1067. {
  1068. state = 2;
  1069. }
  1070. else if (st == "PART_REFUNDED" || isPart == 1)
  1071. {
  1072. state = 3;
  1073. }
  1074. else if (st == "WAIT_BUYER_RETURN_GOODS")
  1075. {
  1076. state = 4;
  1077. }
  1078. else if (st == "REJECT_REFUNDED")
  1079. {
  1080. state = 5;
  1081. }
  1082. else if (st == "WAIT_SELLER_CONFIRM_GOODS")
  1083. {
  1084. state = 6;
  1085. }
  1086. return state;
  1087. }
  1088. public static string getRefundStringByState(string st)
  1089. {
  1090. string stateStr = "";
  1091. if (st == "NOT_SHIPPED")
  1092. {
  1093. stateStr = "待发货";
  1094. }
  1095. else if (st == "PART_SHIPPED")
  1096. {
  1097. stateStr = "部分发货";
  1098. }
  1099. else if (st == "SHIPPED")
  1100. {
  1101. stateStr = "已发货";
  1102. }
  1103. else if (st == "COMPLETE")
  1104. {
  1105. stateStr = "已完成";
  1106. }
  1107. else if (st == "CLOSE")
  1108. {
  1109. stateStr = "已关闭";
  1110. }
  1111. else if (st == "REFUNDED")
  1112. {
  1113. stateStr = "退款成功";
  1114. }
  1115. else if (st == "PART_REFUNDED")
  1116. {
  1117. stateStr = "部分退款";
  1118. }
  1119. else if (st == "WAIT_BUYER_RETURN_GOODS")
  1120. {
  1121. stateStr = "等待买家退货";
  1122. }
  1123. else if (st == "REJECT_REFUNDED")
  1124. {
  1125. stateStr = "拒绝退货";
  1126. }
  1127. else if (st == "WAIT_SELLER_CONFIRM_GOODS")
  1128. {
  1129. stateStr = "等待卖家确认收货";
  1130. }
  1131. else if (st == "SELLER_REFUSE_BUYER")
  1132. {
  1133. stateStr = "卖家拒绝退款";
  1134. }
  1135. else if (st == "SUCCESS")
  1136. {
  1137. stateStr = "退款成功";
  1138. }
  1139. else if (st == "CLOSED")
  1140. {
  1141. stateStr = "退款关闭";
  1142. }
  1143. else if (st == "FAILED")
  1144. {
  1145. stateStr = "退款失败";
  1146. }
  1147. return stateStr;
  1148. }
  1149. public static void UpdateRefundOrderState(string tid, int rstate)
  1150. {
  1151. StringBuilder sql = new StringBuilder();
  1152. sql.AppendFormat("insert into S_BuChaJia(ctid,addtime,dotype,refundState) values('{0}',getdate(),'refund',{1}); ", tid, rstate);
  1153. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  1154. }
  1155. public static void checkBillResult(int billId)
  1156. {
  1157. CeErpBill entiy = CeErpBill.Get(billId);
  1158. if (entiy != null)
  1159. {
  1160. try
  1161. {
  1162. string[] billOrderList = entiy.billOrderId.Split(',');
  1163. int iTag = 0;
  1164. entiy.fplsh = "";
  1165. entiy.fpdm = "";
  1166. entiy.fphm = "";
  1167. foreach (string billOrderId in billOrderList)
  1168. {
  1169. iTag++;
  1170. string res = taobaoHelper.get_invoicing(billId.ToString(), billOrderId);
  1171. int fcount = StrCount(res, "c_orderno");
  1172. if (res.IndexOf("success") != -1 && res.IndexOf("开票中") != -1)
  1173. {
  1174. StringBuilder sql = new StringBuilder();
  1175. sql.AppendFormat("insert into S_BuChaJia(ctid,addtime,dotype) values('{0}',getdate(),'billres'); ", billId.ToString());
  1176. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  1177. return;
  1178. }
  1179. else if (res.IndexOf("success") != -1 && (res.IndexOf("开票成功") != -1 || res.IndexOf("开票完成") != -1))
  1180. {
  1181. //res = GetUTF8String2(Encoding.UTF8.GetBytes(res));
  1182. try
  1183. {
  1184. Invoicing_get_response_Obj iObj = null;
  1185. iObj = JsonConvert.DeserializeObject<Invoicing_get_response_Obj>(res);
  1186. if (iObj != null)
  1187. {
  1188. if (fcount > 1)
  1189. {
  1190. entiy.state = 4; //红冲作废
  1191. }
  1192. else
  1193. entiy.state = 2; //开票完成
  1194. entiy.fplsh += iObj.list[0].c_fpqqlsh;
  1195. entiy.fpdm += iObj.list[0].c_fpdm;
  1196. entiy.fphm += iObj.list[0].c_fphm;
  1197. if (iTag < billOrderList.Length)
  1198. {
  1199. entiy.fplsh += ",";
  1200. entiy.fpdm += ",";
  1201. entiy.fphm += ",";
  1202. }
  1203. entiy.Update();
  1204. }
  1205. if (fcount <= 1)
  1206. {
  1207. StringBuilder sql = new StringBuilder();
  1208. sql.AppendFormat("update CE_ErpTradeCell WITH(ROWLOCK) set IsNeedBill=2 where tid='{0}';", entiy.tid);
  1209. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  1210. }
  1211. }
  1212. catch (Exception ex)
  1213. {
  1214. StringBuilder sql = new StringBuilder();
  1215. sql.AppendFormat("insert into S_BuChaJia(ctid,addtime,dotype) values('{0}',getdate(),'billres'); ", billId.ToString());
  1216. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  1217. XLog.SaveLog(0, "查看开票结果,更新状态失败" + ex.Message + res);
  1218. }
  1219. return;
  1220. }
  1221. else
  1222. {
  1223. string redError = "";
  1224. if (fcount > 1)
  1225. {
  1226. redError = "红冲失败";
  1227. }
  1228. int eidx = res.IndexOf("c_resultmsg");
  1229. string emsg = KeepChinese(res.Substring(eidx, res.Length - eidx));
  1230. //开票失败
  1231. entiy.state = 5;
  1232. entiy.failerror = entiy.failerror + (iTag + "&" + redError + emsg + "|");
  1233. entiy.Update();
  1234. return;
  1235. }
  1236. }
  1237. }
  1238. catch (Exception ex)
  1239. {
  1240. XLog.SaveLog(0, "buchajia查看开票结果错误," + ex.Message);
  1241. }
  1242. }
  1243. }
  1244. public static void insertToBuchaForDelivery(string Maintid, string posCode, string comCode, string outSid)
  1245. {
  1246. if (Maintid.Length <= 0) return;
  1247. try
  1248. {
  1249. StringBuilder sql = new StringBuilder();
  1250. 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);
  1251. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  1252. //}
  1253. }
  1254. catch (Exception ex)
  1255. {
  1256. XLog.SaveLog(0, "commhelper,insertToBuchaForDelivery,insert" + ex.Message);
  1257. //}
  1258. }
  1259. }
  1260. public static void setBuChaDelivery(string tid, string posCode, string comCode, string outSid)
  1261. {
  1262. outSid = outSid.Trim();
  1263. posCode = posCode.Trim();
  1264. comCode = comCode.Trim();
  1265. CeErpTrade mainEn = CeErpTrade.Get(tid);
  1266. if (mainEn != null)
  1267. {
  1268. if (mainEn.status == "SHIPPED" || mainEn.status == "PART_SHIPPED" || mainEn.status == "COMPLETE" || mainEn.status == "CLOSE") //已发货的不处理直接返回面单
  1269. {
  1270. return;
  1271. //不处理
  1272. }
  1273. string apires = apiHelper.API_LogisticsDummySend(tid, posCode);
  1274. if (apires.IndexOf("发货成功") == -1)
  1275. {
  1276. XLog.SaveLog(0, "补差价单虚拟发货失败," + tid + "," + posCode + "," + apires);
  1277. string wures = apiHelper.API_LogisticsOnlineSend(tid, posCode, comCode, outSid, "");
  1278. if (wures.IndexOf("发货成功") == -1)
  1279. {
  1280. XLog.SaveLog(0, "补差价单实物发货失败," + tid + "," + posCode + "," + wures);
  1281. return;
  1282. }
  1283. else
  1284. {
  1285. LogHelper.addLog(tid, 0, "补差价发货-" + comCode + "-" + outSid);
  1286. }
  1287. return;
  1288. }
  1289. else
  1290. {
  1291. LogHelper.addLog(tid, 0, "补差价发货-" + comCode + "-" + outSid);
  1292. }
  1293. }
  1294. }
  1295. public static int StrCount(string str, string constr)
  1296. {
  1297. return System.Text.RegularExpressions.Regex.Matches(str, constr).Count;
  1298. }
  1299. public static void saveErpDesignerGather()
  1300. {
  1301. string date1 = DateTime.Now.AddDays(-1).ToString();
  1302. string date2 = DateTime.Now.AddDays(-1).ToString();
  1303. //string date1 = DateTime.Now.ToString();
  1304. //string date2 = DateTime.Now.ToString();
  1305. StringBuilder sql = new StringBuilder();
  1306. 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);
  1307. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  1308. foreach (DataRow dr in dt.Rows)
  1309. {
  1310. SqlParameter[] sqlParameter ={
  1311. new SqlParameter("@sDisDate", SqlDbType.DateTime, 20),
  1312. new SqlParameter("@eDisDate", SqlDbType.DateTime, 20),
  1313. new SqlParameter("@designid", SqlDbType.Int, 4)
  1314. };
  1315. sqlParameter[0].Value = date1;
  1316. sqlParameter[1].Value = date2;
  1317. sqlParameter[2].Value = Convert.ToInt32(dr["ID"]);
  1318. //CeErpTradeCell.ExecuteNonQueryStore("sp_getdesigngather", sqlParameter);
  1319. DbHelper.DbConn.ExecuteNonQuery(CommandType.StoredProcedure, "sp_savedesigngather", sqlParameter);
  1320. }
  1321. new_Designer_Rate(date1);
  1322. }
  1323. public static void new_Designer_Rate(String date1)
  1324. {
  1325. /*String date1 = DateTime.Now.ToString();*/
  1326. /* if (date1 ==null) {
  1327. date1 = DateTime.Now.ToString();
  1328. }*/
  1329. DateTime currentDate = DateTime.Parse(date1);
  1330. // 获取指定日期的开始时间
  1331. DateTime startTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 0, 0, 0);//日
  1332. // 获取指定日期的结束时间(即下一天的开始时间,减去1秒)
  1333. DateTime endTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 23, 59, 59).AddSeconds(-1);//日
  1334. DateTime now = DateTime.Now; // 获取当前日期和时间
  1335. DateTime dateOnly = now.Date; // 限制日期为年月日
  1336. StringBuilder sql = new StringBuilder();
  1337. CeErpDesignerFinishRateNew.Del(startTime.ToString("yyyy-MM-dd HH:mm:ss"));
  1338. 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"));
  1339. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  1340. foreach (DataRow dr in dt.Rows)
  1341. {
  1342. CeErpDesignerFinishRateNew ceErpDesignerFinishRateNew = new CeErpDesignerFinishRateNew();
  1343. if (!Convert.IsDBNull(dr["DesignUserId"]))
  1344. {
  1345. ceErpDesignerFinishRateNew.did = Convert.ToInt32(dr["DesignUserId"] == null ? 0 : dr["DesignUserId"]);
  1346. }
  1347. if (!Convert.IsDBNull(dr["OrgID"]))
  1348. {
  1349. ceErpDesignerFinishRateNew.orgid = Convert.ToInt32(dr["OrgID"] == null ? 0 : dr["OrgID"]);
  1350. }
  1351. if (!Convert.IsDBNull(dr["DesignerName"]))
  1352. {
  1353. ceErpDesignerFinishRateNew.name = dr["DesignerName"].ToString() == null ? "" : dr["DesignerName"].ToString();
  1354. }
  1355. if (!Convert.IsDBNull(dr["Amount"]))
  1356. {
  1357. ceErpDesignerFinishRateNew.Amount = dr["Amount"].ToString() == null ? "" : dr["Amount"].ToString();
  1358. }
  1359. if (!Convert.IsDBNull(dr["AllOrder"]))
  1360. {
  1361. ceErpDesignerFinishRateNew.AllOrder = Convert.ToInt32(dr["AllOrder"] == null ? 0 : dr["AllOrder"]);
  1362. }
  1363. if (!Convert.IsDBNull(dr["FinalizationRate"]))
  1364. {
  1365. ceErpDesignerFinishRateNew.FinalizationRate = Convert.ToInt32(dr["FinalizationRate"] == null ? 0 : dr["FinalizationRate"]);
  1366. }
  1367. if (!Convert.IsDBNull(dr["afterSaleSum"]))
  1368. {
  1369. ceErpDesignerFinishRateNew.afterSaleSum = Convert.ToInt32(dr["afterSaleSum"] == null ? 0 : dr["afterSaleSum"]);
  1370. }
  1371. if (!Convert.IsDBNull(dr["resolutionSum"]))
  1372. {
  1373. ceErpDesignerFinishRateNew.resolutionSum = Convert.ToInt32(dr["resolutionSum"] == null ? 0 : dr["resolutionSum"]);
  1374. }
  1375. if (!Convert.IsDBNull(dr["splitSum"]))
  1376. {
  1377. ceErpDesignerFinishRateNew.splitSum = Convert.ToInt32(dr["splitSum"] == null ? 0 : dr["splitSum"]);
  1378. }
  1379. if (!Convert.IsDBNull(dr["splitSum2"]))
  1380. {
  1381. ceErpDesignerFinishRateNew.csplitum = Convert.ToInt32(dr["splitSum2"] == null ? 0 : dr["splitSum2"]);
  1382. }
  1383. if (!Convert.IsDBNull(dr["FinalizationRate2"]))
  1384. {
  1385. ceErpDesignerFinishRateNew.FinalizationRate2 = Convert.ToInt32(dr["FinalizationRate2"] == null ? 0 : dr["FinalizationRate2"]);
  1386. }
  1387. if (!Convert.IsDBNull(dr["AllOrder"]) && !Convert.IsDBNull(dr["FinalizationRate"]) && !Convert.IsDBNull(dr["splitSum2"]) && !Convert.IsDBNull(dr["splitSum"]))
  1388. {
  1389. try
  1390. {
  1391. int num1 = Convert.ToInt32(dr["FinalizationRate"]) + Convert.ToInt32(dr["splitSum"]);
  1392. int num2 = Convert.ToInt32(dr["AllOrder"]) + Convert.ToInt32(dr["splitSum2"]);
  1393. if (num2 != 0)
  1394. {
  1395. double result = (double)num1 / num2;
  1396. if (double.IsNaN(result))
  1397. {
  1398. result = 0;
  1399. }
  1400. double roundedResult = Math.Round(result, 4);
  1401. ceErpDesignerFinishRateNew.onFinalizationRate = roundedResult.ToString();
  1402. int num3 = Convert.ToInt32(dr["refund"]);
  1403. double result2 = (double)num3 / num2;
  1404. if (double.IsNaN(result2))
  1405. {
  1406. result2 = 0;
  1407. }
  1408. double roundedResult2 = Math.Round(result2, 4);
  1409. ceErpDesignerFinishRateNew.onRefund = roundedResult2.ToString();
  1410. }
  1411. else
  1412. {
  1413. ceErpDesignerFinishRateNew.onFinalizationRate = "0.0000";
  1414. ceErpDesignerFinishRateNew.onRefund = "0.0000";
  1415. }
  1416. }
  1417. catch (Exception ex)
  1418. {
  1419. ceErpDesignerFinishRateNew.onFinalizationRate = "0";
  1420. }
  1421. }
  1422. ceErpDesignerFinishRateNew.ctime = startTime;
  1423. ceErpDesignerFinishRateNew.Createtime = now;
  1424. if (!Convert.IsDBNull(dr["refund"]))
  1425. {
  1426. ceErpDesignerFinishRateNew.refund = Convert.ToInt32(dr["refund"] == null ? 0 : dr["refund"]);
  1427. }
  1428. ceErpDesignerFinishRateNew.Create();
  1429. }
  1430. }
  1431. public static DateTime FirstDayOfMonth(DateTime datetime)
  1432. {
  1433. return datetime.AddDays(1 - datetime.Day);
  1434. }
  1435. public static DateTime LastDayOfMonth(DateTime datetime)
  1436. {
  1437. return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
  1438. }
  1439. public static DateTime GetDateTimeWeekFirstDaySun(DateTime dateTime)
  1440. {
  1441. DateTime firstWeekDay = DateTime.Now;
  1442. try
  1443. {
  1444. //得到是星期几,然后从当前日期减去相应天数
  1445. int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
  1446. int daydiff = (-1) * weeknow;
  1447. firstWeekDay = dateTime.AddDays(daydiff);
  1448. }
  1449. catch { }
  1450. return firstWeekDay;
  1451. }
  1452. public static DateTime GetDateTimeWeekFirstDayMon(DateTime dateTime)
  1453. {
  1454. DateTime firstWeekDay = DateTime.Now;
  1455. try
  1456. {
  1457. int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
  1458. //星期一为第一天,weeknow等于0时,要向前推6天。
  1459. weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
  1460. int daydiff = (-1) * weeknow;
  1461. firstWeekDay = dateTime.AddDays(daydiff);
  1462. }
  1463. catch { }
  1464. return firstWeekDay;
  1465. }
  1466. public static DateTime GetDateTimeWeekLastDaySat(DateTime dateTime)
  1467. {
  1468. DateTime lastWeekDay = DateTime.Now;
  1469. try
  1470. {
  1471. int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
  1472. int daydiff = (7 - weeknow) - 1;
  1473. lastWeekDay = dateTime.AddDays(daydiff);
  1474. }
  1475. catch { }
  1476. return lastWeekDay;
  1477. }
  1478. public static DateTime GetDateTimeWeekLastDaySun(DateTime dateTime)
  1479. {
  1480. DateTime lastWeekDay = DateTime.Now;
  1481. try
  1482. {
  1483. int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
  1484. weeknow = (weeknow == 0 ? 7 : weeknow);
  1485. int daydiff = (7 - weeknow);
  1486. lastWeekDay = dateTime.AddDays(daydiff);
  1487. }
  1488. catch { }
  1489. return lastWeekDay;
  1490. }
  1491. public static void updateOrderStateForShipped(string ctid, int ost, string stateType)
  1492. {
  1493. try
  1494. {
  1495. CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ctid);
  1496. if (entity != null)
  1497. {
  1498. if (entity.isAfterSaleOrder == 1) return;
  1499. if (stateType == "updatestate_complete")
  1500. {
  1501. if (entity.IsPreDelivery == 1) return;
  1502. entity.OrderState = 8;
  1503. entity.Update();
  1504. if (entity.ProductId == 9 || entity.ProductId == 17 || entity.ProductId == 20 || entity.ProductId == 29 || entity.ProductId == 30)//卡片、手提袋价格自动核算
  1505. {
  1506. CeErpDesignerBill.updateDesignerBill(entity.ctid, entity.ProductId);
  1507. LogHelper.addDesignerBillLog(entity.ctid, 0, "自动核算设计费", "系统", 1);
  1508. }
  1509. else if (entity.ProductId == 22)
  1510. {
  1511. CeErpDesignerBill.updateBill(entity.ctid, entity.ProductId, entity.seller_memo);
  1512. LogHelper.addDesignerBillLog(entity.ctid, 0, "自动核算设计费", "系统", 1);
  1513. }
  1514. }
  1515. else if (stateType == "updatestate_shipped")
  1516. {
  1517. if (entity.IsPreDelivery == 1) return;
  1518. entity.OrderState = 7;
  1519. entity.Update();
  1520. }
  1521. else if (stateType == "updatestate_close")
  1522. {
  1523. entity.OrderState = 9;
  1524. entity.Update();
  1525. }
  1526. }
  1527. else
  1528. {
  1529. StringBuilder sql = new StringBuilder();
  1530. sql.AppendFormat("insert into S_BuChaJia(ctid,orderState,dotype,addtime) values('{0}',{1},'{2}',getdate());", ctid, ost, stateType);
  1531. CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  1532. }
  1533. }
  1534. catch (Exception ex)
  1535. {
  1536. XLog.SaveLog(0, "updateOrderStateForShipped函数出错," + ctid + "," + ex.Message);
  1537. StringBuilder sql = new StringBuilder();
  1538. sql.AppendFormat("insert into S_BuChaJia(ctid,orderState,dotype,addtime) values('{0}',{1},'{2}',getdate());", ctid, ost, stateType);
  1539. CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  1540. }
  1541. }
  1542. public static string changeCountFromChiness(string countStr)
  1543. {
  1544. try
  1545. {
  1546. return handleProductCount(countStr).ToString();
  1547. }
  1548. catch (Exception ex)
  1549. {
  1550. return countStr;
  1551. }
  1552. }
  1553. public static int getIntCountFromString(string fstr)
  1554. {
  1555. try
  1556. {
  1557. string str = fstr;
  1558. string r = @"[0-9]+";
  1559. Regex reg = new Regex(r, RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromSeconds(2));//2秒后超时
  1560. MatchCollection mc = reg.Matches(str);//设定要查找的字符串
  1561. int count = 0;
  1562. foreach (Match m in mc)
  1563. {
  1564. string s = m.Groups[0].Value;
  1565. int cc = Convert.ToInt32(s);
  1566. if (count == 0)
  1567. {
  1568. count = cc;
  1569. }
  1570. else
  1571. {
  1572. count = count * cc;
  1573. }
  1574. }
  1575. return count;
  1576. }
  1577. catch (Exception ex)
  1578. {
  1579. return 0;
  1580. }
  1581. }
  1582. public static int getPlaceProductCount(string count_str)
  1583. {
  1584. count_str = count_str.Trim();
  1585. string[] count_list = count_str.Split(',');
  1586. int count = 0;
  1587. foreach (string item in count_list)
  1588. {
  1589. int tem_count = getSingleIntCountFromString(item);
  1590. if (tem_count > count)
  1591. {
  1592. count = tem_count;
  1593. }
  1594. }
  1595. return count;
  1596. }
  1597. public static int getSingleIntCountFromString(string fstr)
  1598. {
  1599. try
  1600. {
  1601. string str = fstr;
  1602. string r = @"[0-9]+";
  1603. Regex reg = new Regex(r, RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromSeconds(2));//2秒后超时
  1604. MatchCollection mc = reg.Matches(str);//设定要查找的字符串
  1605. if (mc.Count <= 0) return 0;
  1606. if (mc.Count == 1)
  1607. {
  1608. string s = mc[0].Groups[0].Value;
  1609. int cc = Convert.ToInt32(s);
  1610. return cc;
  1611. }
  1612. else if (mc.Count > 1)
  1613. {
  1614. string s = mc[1].Groups[0].Value;
  1615. int cc = Convert.ToInt32(s);
  1616. return cc;
  1617. }
  1618. //foreach (Match m in mc)
  1619. //{
  1620. // string s = m.Groups[0].Value;
  1621. // int cc = Convert.ToInt32(s);
  1622. // if (count == 0)
  1623. // {
  1624. // count = cc;
  1625. // }
  1626. // else
  1627. // {
  1628. // count = count * cc;
  1629. // }
  1630. //}
  1631. return 0;
  1632. }
  1633. catch (Exception ex)
  1634. {
  1635. return 0;
  1636. }
  1637. }
  1638. public static int handleProductCount(string pCount, bool isSingle = false)
  1639. {
  1640. string cstr = pCount;
  1641. if (cstr.IndexOf("百万") != -1)
  1642. {
  1643. cstr = cstr.Replace("百万", "000000");
  1644. }
  1645. else if (cstr.IndexOf("十万") != -1)
  1646. {
  1647. cstr = cstr.Replace("十万", "00000");
  1648. }
  1649. else if (cstr.IndexOf("万") != -1)
  1650. {
  1651. cstr = cstr.Replace("万", "0000");
  1652. }
  1653. else if (cstr.IndexOf("千") != -1)
  1654. {
  1655. cstr = cstr.Replace("千", "000");
  1656. }
  1657. else if (cstr.IndexOf("百") != -1)
  1658. {
  1659. cstr = cstr.Replace("百", "00");
  1660. }
  1661. else if (cstr.IndexOf("十") != -1)
  1662. {
  1663. cstr = cstr.Replace("十", "0");
  1664. }
  1665. int rCount = 0;
  1666. if (isSingle) rCount = getSingleIntCountFromString(cstr);
  1667. else rCount = getIntCountFromString(cstr);
  1668. return rCount;
  1669. }
  1670. public static decimal getOrderSizeFromString(string size)
  1671. {
  1672. string rsize = size.Replace("mm", "");
  1673. string[] sizeList = rsize.Split('x');
  1674. if (sizeList.Length != 2) return 0;
  1675. try
  1676. {
  1677. decimal mianji = Convert.ToDecimal(sizeList[0]) * Convert.ToDecimal(sizeList[1]);
  1678. return mianji;
  1679. }
  1680. catch (Exception ex)
  1681. {
  1682. return 0;
  1683. }
  1684. return 0;
  1685. }
  1686. public static string getDateFromString(string fstr)
  1687. {
  1688. try
  1689. {
  1690. string str = fstr;
  1691. string r = @"[0-9]+";
  1692. Regex reg = new Regex(r, RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromSeconds(2));//2秒后超时
  1693. MatchCollection mc = reg.Matches(str);//设定要查找的字符串
  1694. if (mc.Count < 3) return "";
  1695. int tag = 0;
  1696. string datestr = "";
  1697. foreach (Match m in mc)
  1698. {
  1699. string s = m.Groups[0].Value;
  1700. datestr += s;
  1701. if (tag < 2) { datestr += "-"; }
  1702. else break;
  1703. tag++;
  1704. }
  1705. DateTime dd = Convert.ToDateTime(datestr);
  1706. return datestr;
  1707. }
  1708. catch (Exception ex)
  1709. {
  1710. return "";
  1711. }
  1712. }
  1713. public static void DeleteOriginalOrderIfIsSplitOrder(string tid, string splitTag)
  1714. {
  1715. if (splitTag.Length > 0)
  1716. {
  1717. CeErpTradeCell.DelByCtid(tid);
  1718. }
  1719. }
  1720. public static bool SetOrderDummyDelivery(string tid)
  1721. {
  1722. try
  1723. {
  1724. CeErpTrade trade = CeErpTrade.Get(tid);
  1725. if (trade != null)
  1726. {
  1727. string xuniapires = apiHelper.API_LogisticsDummySend(tid, trade.posCode);
  1728. if (xuniapires.IndexOf("成功") != -1)
  1729. {
  1730. LogHelper.addLog(tid, 0, "电子稿自动发货");
  1731. return true;
  1732. }
  1733. else if (xuniapires.IndexOf("失败") != -1)
  1734. {
  1735. string chiness = KeepChinese(xuniapires);
  1736. XLog.SaveLog(0, "setOrderDummyDelivery虚拟发货失败," + tid + "," + chiness);
  1737. return false;
  1738. }
  1739. }
  1740. return false;
  1741. }
  1742. catch (Exception ex)
  1743. {
  1744. XLog.SaveLog(0, "setOrderDummyDelivery虚拟发货出错," + tid + "," + ex.Message);
  1745. return false;
  1746. }
  1747. }
  1748. public static void getuserId()
  1749. {
  1750. string createtime = "2024-01-01 00:50:39.000";
  1751. string textContent = "";
  1752. int row_num = 100;
  1753. Dictionary<string, List<string>> shop_userNick = new Dictionary<string, List<string>>();
  1754. while (row_num == 100)
  1755. {
  1756. 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);
  1757. DataTable table = DbHelper.DbConn.ExecuteDataset(conSql).Tables[0];
  1758. if (table != null)
  1759. {
  1760. row_num = table.Rows.Count;
  1761. foreach (DataRow row in table.Rows)
  1762. {
  1763. string posCode = row["posCode"].ToString();
  1764. string buyer_nick = row["buyer_nick"].ToString();
  1765. createtime = row["pay_time"].ToString();
  1766. List<string> userNickName = new List<string>();
  1767. if (shop_userNick.ContainsKey(posCode))
  1768. {
  1769. shop_userNick.TryGetValue(posCode, out userNickName);
  1770. }
  1771. userNickName.Add(buyer_nick);
  1772. userNickName = userNickName.Distinct().ToList();
  1773. if (userNickName.Count == 10)
  1774. {
  1775. sendApi(posCode, userNickName);
  1776. userNickName = new List<string>();
  1777. }
  1778. if (shop_userNick.ContainsKey(posCode))
  1779. {
  1780. shop_userNick[posCode] = userNickName;
  1781. }
  1782. else
  1783. {
  1784. shop_userNick.Add(posCode, userNickName);
  1785. }
  1786. }
  1787. }
  1788. }
  1789. foreach (string key in shop_userNick.Keys)
  1790. {
  1791. List<string> nameList = shop_userNick[key];
  1792. sendApi(key, nameList);
  1793. }
  1794. }
  1795. static void sendApi(string posCode, List<string> userNickName)
  1796. {
  1797. string textContent = "";
  1798. List<api_userId_response.ContentItem> buyerIds = apiHelper.API_GetUserId(posCode, string.Join(",", userNickName));
  1799. if (buyerIds != null && buyerIds.Count > 0)
  1800. {
  1801. foreach (api_userId_response.ContentItem item in buyerIds)
  1802. {
  1803. if (item != null && !string.IsNullOrEmpty(item.buyerOpenUid))
  1804. {
  1805. 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);
  1806. }
  1807. }
  1808. try
  1809. {
  1810. StreamWriter fs = new StreamWriter("C:/Users/231010/Desktop/updateSql.txt", true);
  1811. fs.WriteLine(textContent);
  1812. fs.Close();
  1813. }
  1814. catch (Exception e)
  1815. {
  1816. }
  1817. }
  1818. }
  1819. public static designApiResponseVo checkOrderListDesignInfo(string tid, string ctid = "")
  1820. {
  1821. if (string.IsNullOrEmpty(tid))
  1822. {
  1823. return new designApiResponseVo(-1, "无订单信息");
  1824. }
  1825. if (!string.IsNullOrEmpty(ctid))
  1826. {
  1827. CeErpTradeCellExtend ceErpTradeCellExtend = CeErpTradeCellExtend.getByTid(ctid);
  1828. if (ceErpTradeCellExtend != null)
  1829. {
  1830. if ("外协".Equals(ceErpTradeCellExtend.ToType))
  1831. {
  1832. string sql_pay = "update CE_ErpTradeCell with(rowlock) set DispatchSort=2 where ctid='" + ctid + "';";
  1833. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  1834. return new designApiResponseVo(200, "");
  1835. }
  1836. if ("内部".Equals(ceErpTradeCellExtend.ToType))
  1837. {
  1838. return new designApiResponseVo(-1, "设计系统判断内部");
  1839. }
  1840. }
  1841. }
  1842. string info_sql = string.Format("SELECT ctid,ProductId,seller_memo FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}' AND OrderState < 5", tid);
  1843. DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
  1844. string check_info = "无订单信息";
  1845. if (data.Rows.Count > 0)
  1846. {
  1847. bool need_send = false;
  1848. bool has_design = false;
  1849. foreach (DataRow row in data.Rows)
  1850. {
  1851. CeErpTradeCell cell = CeErpTradeCell.GetByCtid(row["ctid"].ToString());
  1852. if (cell != null)
  1853. {
  1854. if (cell.DesignUserId == 0 || cell.DispatchSort == 2 || cell.ctid.Contains("S_"))
  1855. {
  1856. designApiResponseVo result = checkOrderDesignInfo(cell, "", data);
  1857. check_info = result.msg;
  1858. if (result.code == 200)
  1859. {
  1860. need_send = true;
  1861. has_design = false;
  1862. }
  1863. }
  1864. else
  1865. {
  1866. has_design = true;
  1867. }
  1868. }
  1869. }
  1870. if (need_send && !has_design)
  1871. {
  1872. string sql_pay = "update CE_ErpTradeCell with(rowlock) set DispatchSort=2 where ctid='" + ctid + "' AND OrderState < 5;";
  1873. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  1874. return new designApiResponseVo(200, "");
  1875. }
  1876. }
  1877. return new designApiResponseVo(-1, check_info);
  1878. }
  1879. 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 };
  1880. 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 };
  1881. static List<int> no_design_shops = new List<int>() { 134 };
  1882. public static designApiResponseVo checkOrderDesignInfo(CeErpTradeCell ceErpTradeCell, string post = "", DataTable dt = null)
  1883. {
  1884. if (ceErpTradeCell.DispatchSort == 2)
  1885. {
  1886. return new designApiResponseVo(200, "");
  1887. }
  1888. if (ceErpTradeCell.ProductId == 0)
  1889. {
  1890. return new designApiResponseVo(-1, "订单无品类");
  1891. }
  1892. if (ceErpTradeCell.ShopId == 0)
  1893. {
  1894. return new designApiResponseVo(-1, "订单无店铺");
  1895. }
  1896. if (ceErpTradeCell.ProductId == 1797 && ceErpTradeCell.seller_memo.Contains("手绘"))
  1897. {
  1898. return new designApiResponseVo(200, "");
  1899. }
  1900. if (ceErpTradeCell.isDianziOrder == 1)
  1901. {
  1902. return new designApiResponseVo(200, "");
  1903. }
  1904. if ((post != "SysAdmin" && post != "Summarize"))
  1905. {
  1906. if (ceErpTradeCell.DesignUserId != 0 && (ceErpTradeCell.DispatchSort != 2 && !ceErpTradeCell.ctid.Contains("S_")))
  1907. {
  1908. return new designApiResponseVo(-1, "已有设计师无法指派");
  1909. }
  1910. CeErpTradeCellExtend ceErpTradeCellExtend = CeErpTradeCellExtend.getByTid(ceErpTradeCell.ctid);
  1911. if (ceErpTradeCellExtend != null && "内部".Equals(ceErpTradeCellExtend.ToType))
  1912. {
  1913. return new designApiResponseVo(-1, "无法指派不是共创的订单");
  1914. }
  1915. string info_sql = string.Format("SELECT count(*) as total FROM [dbo].[Ce_ErpDesignInfo] WHERE type = 1 and tarId = 3542 and shopId = {0}", ceErpTradeCell.ShopId);
  1916. DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
  1917. int a = Convert.ToInt32(data.Rows[0]["total"]);
  1918. bool drop = false;
  1919. if (DateTime.Now.Hour >= 17 && DateTime.Now.Hour <= 7 && products.IndexOf(ceErpTradeCell.ProductId) > -1 && (ceErpTradeCell.ShopId == 14 || ceErpTradeCell.ShopId == 56))
  1920. {
  1921. drop = false;
  1922. }
  1923. if (!drop && no_design_shops.IndexOf(ceErpTradeCell.ShopId) == -1)
  1924. {
  1925. CeErpDesignInfo ceErpDesignInfo = CeErpDesignInfo.GetByShopDesign(3542, ceErpTradeCell.ShopId, ceErpTradeCell.ProductId);
  1926. if (ceErpDesignInfo == null)
  1927. {
  1928. return new designApiResponseVo(-1, "该店铺无该技能权限");
  1929. }
  1930. }
  1931. //卡片五款
  1932. /*if (products.IndexOf(ceErpTradeCell.ProductId) > -1 && ceErpTradeCell.ShopId > 0)
  1933. {
  1934. bool num_bool = true;
  1935. bool size_bool = false;
  1936. int min_num = 2;
  1937. int num = 0;
  1938. if (shops.IndexOf(ceErpTradeCell.ShopId) == -1)//限制不是全品的店铺限制
  1939. {
  1940. *//*if (ceErpTradeCell.payment >= 500)
  1941. {
  1942. return new designApiResponseVo(-1, "订单价格超出");
  1943. }*//*
  1944. string pattern = @"\b(\d{1,5}[x\*]\d{1,5}(mm|cm))\b";
  1945. string memo = ceErpTradeCell.seller_memo.Replace("MM", "mm").Replace("CM", "cm");
  1946. Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(2));//2秒后超时
  1947. MatchCollection matches = reg.Matches(memo);//设定要查找的字符串
  1948. string size = "";
  1949. double min_width = 90;
  1950. double min_height = 90;
  1951. double width = 0;
  1952. double height = 0;
  1953. try
  1954. {
  1955. num = matches.Count;
  1956. foreach (System.Text.RegularExpressions.Match match in matches)
  1957. {
  1958. if (match.Success)
  1959. {
  1960. size = match.Groups[0].Value;
  1961. if (size.Contains("cm"))
  1962. {
  1963. size = size.Replace("cm", "");
  1964. string[] size_list = size.Split('x');
  1965. if (size_list.Length > 1)
  1966. {
  1967. width = Convert.ToDouble(size_list[0]) * 10;
  1968. height = Convert.ToDouble(size_list[1]) * 10;
  1969. }
  1970. }
  1971. else if (size.Contains("mm"))
  1972. {
  1973. size = size.Replace("mm", "");
  1974. string[] size_list = size.Split('x');
  1975. if (size_list.Length > 1)
  1976. {
  1977. width = Convert.ToDouble(size_list[0]);
  1978. height = Convert.ToDouble(size_list[1]);
  1979. }
  1980. }
  1981. if (width >= min_width && height >= min_height && height >= min_width && width >= min_height)
  1982. {
  1983. size_bool = true;
  1984. break;
  1985. }
  1986. else
  1987. {
  1988. size_bool = false;
  1989. }
  1990. }
  1991. }
  1992. }
  1993. catch (Exception ex)
  1994. {
  1995. }
  1996. num = getSellerMemoNum(ceErpTradeCell.seller_memo);
  1997. if (dt != null && dt.Rows != null && dt.Rows.Count > 1)
  1998. {
  1999. foreach (DataRow item in dt.Rows)
  2000. {
  2001. int tempNum = 0;
  2002. if (!string.IsNullOrEmpty(item["ProductId"].ToString()))
  2003. {
  2004. if (Convert.ToInt32(item["ProductId"]) == ceErpTradeCell.ProductId)
  2005. {
  2006. tempNum = getSellerMemoNum(item["seller_memo"].ToString());
  2007. tempNum = tempNum == 0 ? 1 : tempNum;
  2008. }
  2009. }
  2010. num += tempNum;
  2011. }
  2012. }
  2013. //2款不进
  2014. if (num < min_num)
  2015. {
  2016. num_bool = false;
  2017. }
  2018. if (!num_bool && !size_bool)
  2019. {
  2020. return new designApiResponseVo(-1, "尺寸小于90x90或款数小于2");
  2021. }
  2022. }
  2023. }*/
  2024. }
  2025. return new designApiResponseVo(200, "");
  2026. }
  2027. private static int getSellerMemoNum(string memo)
  2028. {
  2029. int num = 0;
  2030. string pattern = @"\b(\d{1,5}[x\*]\d{1,5}(mm|cm))\b";
  2031. Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(2));//2秒后超时
  2032. MatchCollection matches = reg.Matches(memo);//设定要查找的字符串
  2033. if (memo.Contains("刮刮"))
  2034. {
  2035. num = Math.Max(num - 1, 1);
  2036. }
  2037. pattern = @"(\d+)款";
  2038. matches = Regex.Matches(memo, pattern);
  2039. try
  2040. {
  2041. num = Math.Max(num - matches.Count, 0);
  2042. foreach (System.Text.RegularExpressions.Match match in matches)
  2043. {
  2044. if (match.Success)
  2045. {
  2046. num += Convert.ToInt32(match.Groups[1].Value);
  2047. break;
  2048. }
  2049. }
  2050. }
  2051. catch (Exception ex)
  2052. {
  2053. }
  2054. return num;
  2055. }
  2056. private static string cytUserId = "77886";
  2057. public static void sendCytAfterSale(CeErpTradeCell entity)
  2058. {
  2059. try
  2060. {
  2061. CeErpTradeAfterSaleExtend ceErpTradeAfterSaleExtend = CeErpTradeAfterSaleExtend.getByTid(entity.ctid);
  2062. string after = "";
  2063. if (entity != null && entity.AfterSaleReason.Contains("质量问题"))
  2064. {
  2065. after = "质量问题";
  2066. }
  2067. else if (entity != null && entity.AfterSaleReason.Contains("发货问题"))
  2068. {
  2069. after = "没收到货";
  2070. }
  2071. else
  2072. {
  2073. after = "其他问题";
  2074. }
  2075. string refund_type = "退款退货";
  2076. if (entity.supRefundType != null && entity.supRefundType == "重印" && (after == "质量问题" || after == "其他问题"))
  2077. {
  2078. refund_type = "补印";
  2079. }
  2080. JObject jsonObject12 = new JObject
  2081. {
  2082. { "Userid",cytUserId },
  2083. //{ "pwd", "lt666888" },
  2084. { "LTOrderId", entity.ctid },
  2085. { "IdCode", entity.OrderSn },
  2086. { "CytMallId", string.IsNullOrEmpty(entity.SupplierOrderSn) ? "" : entity.SupplierOrderSn},
  2087. { "RefundType", refund_type },
  2088. { "ReprintReasons", after },
  2089. { "ReasonsImgUrls", entity.AfterSaleSupplierImg },
  2090. { "ReasonRemarks", ceErpTradeAfterSaleExtend.supplierResponsible },
  2091. { "RefundAmount", entity.DeductFee }
  2092. };
  2093. /**JObject jsonObject12 = new JObject
  2094. {
  2095. { "Userid", "10095" },
  2096. { "pwd", "test123456" },
  2097. { "LTOrderId", "test123456" },
  2098. { "RefundType", "退款退货" },
  2099. { "ReprintReasons", "其他问题" },
  2100. { "ReasonRemarks", "测试" }
  2101. };**/
  2102. string response1 = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/ApplyOrderRefund", jsonObject12.ToString());
  2103. JObject jsonObjects1 = JObject.Parse(response1);
  2104. string msg = (string)jsonObjects1["msg"];
  2105. if (msg.Length > 200)
  2106. {
  2107. msg = msg.Substring(0, 200);
  2108. }
  2109. LogHelper.addLog(entity.ctid, 0, "CYT售后单推送:" + msg);
  2110. }
  2111. catch (Exception ex)
  2112. {
  2113. XLog.SaveLog(0, "CYT售后单推送:" + ex);
  2114. }
  2115. }
  2116. public static void sendCytExpress(CeErpExpressInfo exinfo)
  2117. {
  2118. if (exinfo == null)
  2119. {
  2120. return;
  2121. }
  2122. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(exinfo.tid);
  2123. if (ceErpTradeCell == null)
  2124. {
  2125. return;
  2126. }
  2127. string msg = "";
  2128. try
  2129. {
  2130. JObject jsonObject12 = new JObject
  2131. {
  2132. { "Userid",cytUserId },
  2133. //{ "pwd", "lt666888" },
  2134. { "LTOrderId", ceErpTradeCell.OrderSn },
  2135. { "OrderId", ceErpTradeCell.ctid },
  2136. { "CourierNumber", exinfo.out_sid },
  2137. { "ExpressCompanyName", exinfo.company_name }
  2138. };
  2139. string response1 = HttpPost("http://www.kiy.cn/webapi/Himall.NewShop.UpdOrderExpress", jsonObject12.ToString());
  2140. JObject jsonObjects1 = JObject.Parse(response1);
  2141. msg = (string)jsonObjects1["msg"];
  2142. LogHelper.addLog(exinfo.tid, 0, "CYT打单推送:" + msg);
  2143. }
  2144. catch (Exception ex)
  2145. {
  2146. LogHelper.addLog(exinfo.tid, 0, "CYT打单推送:" + ceErpTradeCell.OrderSn + "," + ceErpTradeCell.ctid + "," + exinfo.out_sid + "," + exinfo.company_name);
  2147. XLog.SaveLog(0, "CYT打单推送失败," + msg + "->" + ex);
  2148. }
  2149. }
  2150. public static void getCytPrice(CeErpTradeCell entity)
  2151. {
  2152. try
  2153. {
  2154. if (entity.seller_memo.IndexOf("种子纸") > -1)
  2155. {
  2156. return;
  2157. }
  2158. CeErpProduct cp = CeErpProduct.GetById(entity.ProductId);
  2159. double price = 0;
  2160. if (cp == null)
  2161. {
  2162. JObject jsonObject12 = new JObject
  2163. {
  2164. { "UserId", cytUserId },
  2165. { "Pwd", "lt666888" },
  2166. { "Filename", entity.seller_memo }
  2167. };
  2168. string response1 = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/LTBaojia", jsonObject12.ToString());
  2169. JObject jsonObjects1 = JObject.Parse(response1);
  2170. string ms1g = (string)jsonObjects1["msg"];
  2171. if (ms1g == "报价成功")
  2172. {
  2173. JObject jsonObject1 = (JObject)jsonObjects1["data"];
  2174. string data = (string)jsonObject1["price"];
  2175. 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 + "');";
  2176. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  2177. price = Convert.ToDouble(data);
  2178. }
  2179. else
  2180. {
  2181. 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 + "');";
  2182. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  2183. return;
  2184. }
  2185. }
  2186. String[] beizhu = entity.seller_memo.Split('-');
  2187. String chanp = "";
  2188. if (beizhu.Length > 1)
  2189. {
  2190. chanp = "(" + entity.ctid + ")-" + entity.ProductSize + "-" + entity.ProductCount + "-" + entity.Material + cp.PSupType + entity.Craft + "-备注:" + beizhu[1];
  2191. }
  2192. else
  2193. {
  2194. chanp = "(" + entity.ctid + ")-" + entity.ProductSize + "-" + entity.ProductCount + "-" + entity.Material + cp.PSupType + entity.Craft;
  2195. }
  2196. JObject jsonObject = new JObject
  2197. {
  2198. { "UserId", cytUserId },
  2199. { "Pwd", "lt666888" },
  2200. { "Filename", chanp }
  2201. };
  2202. string response = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/LTBaojia", jsonObject.ToString());
  2203. JObject jsonObjects = JObject.Parse(response);
  2204. string msg = (string)jsonObjects["msg"];
  2205. if (msg == "报价成功")
  2206. {
  2207. JObject jsonObject1 = (JObject)jsonObjects["data"];
  2208. string data = (string)jsonObject1["price"];
  2209. 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 + "');";
  2210. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  2211. price = Convert.ToDouble(data);
  2212. }
  2213. else
  2214. {
  2215. 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 + "');";
  2216. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  2217. return;
  2218. }
  2219. if (price > 0)
  2220. {
  2221. CeErpTradeCellExtend ceErpTradeCellExtend = CeErpTradeCellExtend.getByTid(entity.ctid);
  2222. if (ceErpTradeCellExtend == null)
  2223. {
  2224. ceErpTradeCellExtend = new CeErpTradeCellExtend();
  2225. ceErpTradeCellExtend.ctid = entity.ctid;
  2226. ceErpTradeCellExtend.payment_cyt = price;
  2227. ceErpTradeCellExtend.Create();
  2228. }
  2229. else
  2230. {
  2231. ceErpTradeCellExtend.payment_cyt = price;
  2232. ceErpTradeCellExtend.Update();
  2233. }
  2234. }
  2235. }
  2236. catch (Exception ex)
  2237. {
  2238. }
  2239. return;
  2240. }
  2241. /// <summary>
  2242. /// 更新设计信息
  2243. /// </summary>
  2244. /// <param name="ceErpTradeCell"></param>
  2245. public static void updateDataTradeCellDesignInfo(string ctid)
  2246. {
  2247. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  2248. if (ceErpTradeCell == null)
  2249. {
  2250. return;
  2251. }
  2252. string info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}'", ceErpTradeCell.tid);
  2253. DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
  2254. foreach (DataRow row in data.Rows)
  2255. {
  2256. ceErpTradeCell = CeErpTradeCell.GetByCtid(row["ctid"].ToString());
  2257. if (ceErpTradeCell == null)
  2258. {
  2259. continue;
  2260. }
  2261. Dictionary<string, string> map = new Dictionary<string, string>();
  2262. if (ceErpTradeCell.DesignUserId > 0)
  2263. {
  2264. string design_sql = string.Format("SELECT * FROM [dbo].[view_ErpUser] WHERE ID = {0}", ceErpTradeCell.DesignUserId);
  2265. DataTable design_dt = DbHelper.DbConn.ExecuteDataset(design_sql).Tables[0];
  2266. if (design_dt != null && design_dt.Rows.Count > 0)
  2267. {
  2268. map.Add("ShortText1717743889973", design_dt.Rows[0]["Name"].ToString());
  2269. map.Add("ShortText1717743889516", design_dt.Rows[0]["OrgName"].ToString());
  2270. if (!string.IsNullOrEmpty(design_dt.Rows[0]["OrgID"].ToString()))
  2271. {
  2272. int orgId = Convert.ToInt32(design_dt.Rows[0]["OrgID"]);
  2273. if (orgId > 0)
  2274. {
  2275. 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"]);
  2276. DataTable mDesign_dt = DbHelper.DbConn.ExecuteDataset(mDesign_sql).Tables[0];
  2277. if (mDesign_dt != null && mDesign_dt.Rows.Count > 0)
  2278. {
  2279. map.Add("ShortText1717743890850", mDesign_dt.Rows[0]["Name"].ToString());
  2280. }
  2281. }
  2282. }
  2283. }
  2284. map.Add("Date1717743893776", ceErpTradeCell.WaitDesignTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  2285. map.Add("ShortText1717743882604", ((OrderState)ceErpTradeCell.OrderState).ToString());
  2286. }
  2287. dataHelper.updateErpTradeCell(map, ctid);
  2288. }
  2289. }
  2290. /// <summary>
  2291. /// 下单更新
  2292. /// </summary>
  2293. /// <param name="ceErpTradeCell"></param>
  2294. public static void updateDataTradeCellPlaceInfo(string ctid)
  2295. {
  2296. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  2297. if (ceErpTradeCell == null)
  2298. {
  2299. return;
  2300. }
  2301. Dictionary<string, string> map = new Dictionary<string, string>();
  2302. if (ceErpTradeCell.OrderState >= 6 && ceErpTradeCell.SupplierId > 0)
  2303. {
  2304. map.Add("Date1717743895362", ceErpTradeCell.FinishDesignTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  2305. map.Add("Date1717744246168", ceErpTradeCell.FinishPlaceTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  2306. string supplierId = dataHelper.getSupplerDataInfo(ceErpTradeCell.SupplierId.ToString());
  2307. map.Add("RelevanceForm1718100412422", supplierId);
  2308. CeErpTradeCellExtend ceErpTradeCellExtend = CeErpTradeCellExtend.getByTid(ceErpTradeCell.ctid);
  2309. if (ceErpTradeCellExtend != null)
  2310. {
  2311. map.Add("Number1718099884613", ceErpTradeCellExtend.payment_cyt.ToString());
  2312. }
  2313. map.Add("ShortText1717743882604", ((OrderState)ceErpTradeCell.OrderState).ToString());
  2314. }
  2315. dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
  2316. }
  2317. /// <summary>
  2318. /// 发货更新
  2319. /// </summary>
  2320. /// <param name="ceErpTradeCell"></param>
  2321. public static void updateDataTradeCellDeliveInfo(string ctid)
  2322. {
  2323. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  2324. if (ceErpTradeCell == null)
  2325. {
  2326. return;
  2327. }
  2328. string info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}'", ceErpTradeCell.tid);
  2329. DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
  2330. foreach (DataRow row in data.Rows)
  2331. {
  2332. ceErpTradeCell = CeErpTradeCell.GetByCtid(row["ctid"].ToString());
  2333. if (ceErpTradeCell == null)
  2334. {
  2335. continue;
  2336. }
  2337. Dictionary<string, string> map = new Dictionary<string, string>();
  2338. if (ceErpTradeCell.OrderState >= 7 && ceErpTradeCell.SupplierId > 0)
  2339. {
  2340. map.Add("Date1717744254301", ceErpTradeCell.FinishDeliveryTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  2341. map.Add("ShortText1717744255441", ceErpTradeCell.OutSid);
  2342. map.Add("ShortText1717743882604", ((OrderState)ceErpTradeCell.OrderState).ToString());
  2343. }
  2344. dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
  2345. }
  2346. }
  2347. /// <summary>
  2348. /// 打回
  2349. /// </summary>
  2350. /// <param name="ceErpTradeCell"></param>
  2351. public static void updateDataTradeCellBackInfo(string ctid)
  2352. {
  2353. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  2354. if (ceErpTradeCell == null)
  2355. {
  2356. return;
  2357. }
  2358. Dictionary<string, string> map = new Dictionary<string, string>();
  2359. map.Add("Date1717745436357", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  2360. map.Add("ShortText1717745435559", "是");
  2361. map.Add("ShortText1717745481283", ceErpTradeCell.ReturnReason);
  2362. map.Add("ShortText1717743882604", ((OrderState)ceErpTradeCell.OrderState).ToString());
  2363. dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
  2364. }
  2365. /// <summary>
  2366. /// 查货
  2367. /// </summary>
  2368. /// <param name="ceErpTradeCell"></param>
  2369. public static void updateDataTradeCellCheckGoodInfo(string ctid)
  2370. {
  2371. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  2372. if (ceErpTradeCell == null)
  2373. {
  2374. return;
  2375. }
  2376. Dictionary<string, string> map = new Dictionary<string, string>();
  2377. map.Add("Date1717745495718", ceErpTradeCell.CheckOrderTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  2378. map.Add("ShortText1717745492918", "是");
  2379. map.Add("ShortText1717745497837", ceErpTradeCell.CheckMemo);
  2380. map.Add("ShortText1717745499141", ceErpTradeCell.UnusualCon);
  2381. dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
  2382. }
  2383. /// <summary>
  2384. /// 加急
  2385. /// </summary>
  2386. /// <param name="ceErpTradeCell"></param>
  2387. public static void updateDataTradeCellUrgentInfo(string ctid)
  2388. {
  2389. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  2390. if (ceErpTradeCell == null)
  2391. {
  2392. return;
  2393. }
  2394. Dictionary<string, string> map = new Dictionary<string, string>();
  2395. map.Add("Date1717745535736", ceErpTradeCell.UrgencyTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  2396. map.Add("ShortText1717745533062", "是");
  2397. dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
  2398. }
  2399. /// <summary>
  2400. /// 售后
  2401. /// </summary>
  2402. /// <param name="ceErpTradeCell"></param>
  2403. public static void updateDataTradeCellAfterSaleInfo(string ctid)
  2404. {
  2405. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  2406. if (ceErpTradeCell == null)
  2407. {
  2408. return;
  2409. }
  2410. Dictionary<string, string> map = new Dictionary<string, string>();
  2411. map.Add("ShortText1717745540758", "是");
  2412. map.Add("Date1717745544245", ceErpTradeCell.AfterSaleTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  2413. if (ceErpTradeCell.AfterSaleResSupId > 0)
  2414. {
  2415. CeErpUser user = CeErpUser.Get(ceErpTradeCell.AfterSaleResSupId);
  2416. if (user != null)
  2417. {
  2418. map.Add("ShortText1717745541664", user.Name);
  2419. }
  2420. }
  2421. map.Add("Date1717745545841", ceErpTradeCell.FinishAfterSaleTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  2422. if (!string.IsNullOrEmpty(ceErpTradeCell.AfterSaleReason))
  2423. {
  2424. string[] list = ceErpTradeCell.AfterSaleReason.Split('|');
  2425. for (int i = 0; i < list.Length; i++)
  2426. {
  2427. if (i == 0)
  2428. {
  2429. map.Add("ShortText1717745548220", list[i]);
  2430. }
  2431. if (i == 1)
  2432. {
  2433. map.Add("ShortText1717745549835", list[i]);
  2434. }
  2435. if (i == 2)
  2436. {
  2437. map.Add("ShortText1717745550687", list[i]);
  2438. }
  2439. }
  2440. }
  2441. if (!string.IsNullOrEmpty(ceErpTradeCell.ResponsibleUserId))
  2442. {
  2443. string[] list = ceErpTradeCell.ResponsibleUserId.Split(',');
  2444. for (int i = 0; i < list.Length; i++)
  2445. {
  2446. string[] user = list[i].Split('_');
  2447. if (user.Length > 0)
  2448. {
  2449. if (user[1] == "g")
  2450. {
  2451. CeErpSupplier ceErpSupplier = CeErpSupplier.Get(user[0]);
  2452. if (i == 0)
  2453. {
  2454. map.Add("ShortText1717745553842", list[i]);
  2455. map.Add("ShortText1717745554626", "");
  2456. }
  2457. if (i == 1)
  2458. {
  2459. map.Add("ShortText1717811042513", list[i]);
  2460. map.Add("ShortText1717811049407", "");
  2461. }
  2462. }
  2463. else if (user[1] == "w")
  2464. {
  2465. if (i == 0)
  2466. {
  2467. map.Add("ShortText1717745553842", "物流问题");
  2468. map.Add("ShortText1717745554626", "");
  2469. }
  2470. if (i == 1)
  2471. {
  2472. map.Add("ShortText1717811042513", "物流问题");
  2473. map.Add("ShortText1717811049407", "");
  2474. }
  2475. }
  2476. else
  2477. {
  2478. string customer_sql = string.Format("SELECT * FROM [dbo].[view_ErpUser] WHERE ID = {0}", ceErpTradeCell.CustomerUserId);
  2479. DataTable customer_dt = DbHelper.DbConn.ExecuteDataset(customer_sql).Tables[0];
  2480. if (customer_dt.Rows.Count > 0)
  2481. {
  2482. if (i == 0)
  2483. {
  2484. map.Add("ShortText1717745553842", customer_dt.Rows[0]["Name"].ToString());
  2485. map.Add("ShortText1717745554626", customer_dt.Rows[0]["OrgName"].ToString());
  2486. }
  2487. if (i == 1)
  2488. {
  2489. map.Add("ShortText1717811042513", customer_dt.Rows[0]["Name"].ToString());
  2490. map.Add("ShortText1717811049407", customer_dt.Rows[0]["OrgName"].ToString());
  2491. }
  2492. }
  2493. }
  2494. }
  2495. }
  2496. }
  2497. map.Add("number1717745810151", ceErpTradeCell.RefundFee.ToString());
  2498. CeErpTradeAfterSaleExtend ceErpTradeAfterSaleExtend = CeErpTradeAfterSaleExtend.getByTid(ceErpTradeCell.ctid);
  2499. if (ceErpTradeAfterSaleExtend != null && !string.IsNullOrEmpty(ceErpTradeAfterSaleExtend.RefundFees))
  2500. {
  2501. string[] list = ceErpTradeAfterSaleExtend.RefundFees.Split(',');
  2502. for (int i = 0; i < list.Length; i++)
  2503. {
  2504. if (i == 0)
  2505. {
  2506. map.Add("Number1717745564936", list[i]);
  2507. }
  2508. if (i == 1)
  2509. {
  2510. map.Add("Number1717745565580", list[i]);
  2511. }
  2512. }
  2513. }
  2514. map.Add("ShortText1717745580986", ceErpTradeCell.AfterSaleSupplierState == 1 ? "认可" : "不认可");
  2515. map.Add("ShortText1717745582613", ceErpTradeCell.AfterSaleSupplierMemo);
  2516. map.Add("ShortText1717745583256", ceErpTradeCell.AfterSaleMethod);
  2517. map.Add("ShortText1717745583810", ceErpTradeCell.AfterSaleMemo);
  2518. dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
  2519. }
  2520. /// <summary>
  2521. /// 退款
  2522. /// </summary>
  2523. /// <param name="content"></param>
  2524. public static void updateDataTradeCellRefundInfo(Api_tmc_refund_info_Obj.Content content)
  2525. {
  2526. Dictionary<string, string> map = new Dictionary<string, string>();
  2527. map.Add("Date1717745588048", StampToDateTime(content.createTime).ToString("yyyy-MM-dd HH:mm:ss"));
  2528. map.Add("ShortText1717745585444", "是");
  2529. map.Add("Number1717743148189", content.refundFee);
  2530. map.Add("ShortText1717745591810", content.reason);
  2531. map.Add("ShortText1717745592639", content.desc);
  2532. string tid = content.refOid;
  2533. string info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}'", tid);
  2534. DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
  2535. foreach (DataRow row in data.Rows)
  2536. {
  2537. dataHelper.updateErpTradeCell(map, row["ctid"].ToString());
  2538. }
  2539. }
  2540. /// <summary>
  2541. /// 返现
  2542. /// </summary>
  2543. /// <param name="entity"></param>
  2544. /// <param name="cash"></param>
  2545. public static void updateDataTradeCellCashInfo(CeErpTradeCell entity, CeErpReturnCash cash)
  2546. {
  2547. Dictionary<string, string> map = new Dictionary<string, string>();
  2548. map.Add("ShortText1717745601056", "是");
  2549. map.Add("ShortText1717745602313", cash.rtype);
  2550. map.Add("Number1717745604245", cash.payment.ToString());
  2551. map.Add("ShortText1717745607208", cash.con);
  2552. dataHelper.updateErpTradeCell(map, entity.ctid);
  2553. }
  2554. /// <summary>
  2555. /// 推购
  2556. /// </summary>
  2557. /// <param name="entity"></param>
  2558. public static void updateDataTradeCellStayInfo(CeErpTradeCell entity)
  2559. {
  2560. Dictionary<string, string> map = new Dictionary<string, string>();
  2561. map.Add("ShortText1717745608381", "是");
  2562. dataHelper.updateErpTradeCell(map, entity.ctid);
  2563. }
  2564. public static DateTime StampToDateTime(string timeStamp)
  2565. {
  2566. DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  2567. long lTime = long.Parse(timeStamp + "0000");
  2568. TimeSpan toNow = new TimeSpan(lTime);
  2569. return dateTimeStart.Add(toNow);
  2570. }
  2571. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  2572. {
  2573. return true; //总是接受
  2574. }
  2575. public static string HttpPost(string url, string param = null)
  2576. {
  2577. HttpWebRequest request;
  2578. //如果是发送HTTPS请求
  2579. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  2580. {
  2581. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  2582. request = WebRequest.Create(url) as HttpWebRequest;
  2583. request.ProtocolVersion = HttpVersion.Version10;
  2584. }
  2585. else
  2586. {
  2587. request = WebRequest.Create(url) as HttpWebRequest;
  2588. }
  2589. request.Method = "POST";
  2590. request.ContentType = "application/json";
  2591. request.Accept = "*/*";
  2592. request.Timeout = 60000;
  2593. request.AllowAutoRedirect = false;
  2594. StreamWriter requestStream = null;
  2595. WebResponse response = null;
  2596. string responseStr = null;
  2597. try
  2598. {
  2599. requestStream = new StreamWriter(request.GetRequestStream());
  2600. requestStream.Write(param);
  2601. requestStream.Close();
  2602. response = request.GetResponse();
  2603. if (response != null)
  2604. {
  2605. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  2606. responseStr = reader.ReadToEnd();
  2607. reader.Close();
  2608. }
  2609. }
  2610. catch (Exception ex)
  2611. {
  2612. return ex.Message;
  2613. }
  2614. finally
  2615. {
  2616. request = null;
  2617. requestStream = null;
  2618. response = null;
  2619. }
  2620. return responseStr;
  2621. }
  2622. 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 };
  2623. 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 };
  2624. public static List<string> receiver_state = new List<string> { "内蒙古", "西藏", "甘肃", "青海", "宁夏", "新疆" };
  2625. public static bool isFarAddress(string state)
  2626. {
  2627. for (int i = 0; receiver_state.Count > i; i++)
  2628. {
  2629. if (state.Contains(receiver_state[i]))
  2630. {
  2631. return true;
  2632. }
  2633. }
  2634. return false;
  2635. }
  2636. public static void setSpuData(CeErpTrade father)
  2637. {
  2638. if (string.IsNullOrEmpty(father.seller_memo))
  2639. {
  2640. return;
  2641. }
  2642. string orderSql = string.Format("SELECT * FROM [dbo].[CE_ErpTradeOrder] WHERE tid = '{0}' and total_fee > 0", father.tid);
  2643. DataTable table = SqlHelper.ExecuteDataSet(orderSql).Tables[0];
  2644. string spu_id = "";
  2645. if (table != null && table.Rows.Count == 1)
  2646. {
  2647. spu_id = table.Rows[0]["spu_id"].ToString();
  2648. }
  2649. string cellSql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid = '{0}'", father.tid);
  2650. DataTable data = SqlHelper.ExecuteDataSet(cellSql).Tables[0];
  2651. if (data != null && data.Rows.Count > 0)
  2652. {
  2653. foreach (DataRow row in data.Rows)
  2654. {
  2655. CeErpTradeCellExtend ceErpTradeCellExtend = CeErpTradeCellExtend.getByTid(row["ctid"].ToString());
  2656. if (ceErpTradeCellExtend == null)
  2657. {
  2658. ceErpTradeCellExtend = new CeErpTradeCellExtend();
  2659. ceErpTradeCellExtend.ctid = row["ctid"].ToString();
  2660. }
  2661. ceErpTradeCellExtend.spu_id = spu_id;
  2662. if (!string.IsNullOrEmpty(spu_id))
  2663. {
  2664. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ceErpTradeCellExtend.ctid);
  2665. ceErpTradeCellExtend = sendSpuData(ceErpTradeCell, ceErpTradeCellExtend);
  2666. }
  2667. if (ceErpTradeCellExtend.ID == 0)
  2668. {
  2669. ceErpTradeCellExtend.Create();
  2670. }
  2671. else
  2672. {
  2673. ceErpTradeCellExtend.Update();
  2674. }
  2675. }
  2676. }
  2677. List<string> list = new List<string>() { "kevin_boz", "奥丽芙旗舰店", "鼎怡旗舰店", "格图旗舰店", "宫契旗舰店", "海角七旗舰店", "航和旗舰店", "岚恬旗舰店", "琳19890725", "领淘文具旗舰店", "麦郁旗舰店", "米笛儿旗舰店", "颂盼旗舰店", "涛莱旗舰店", "腾科吉旗舰店", "万慕办公旗舰店", "喜印说旗舰店", "欣克利旗舰店", "阳光猫旗舰店", "翊喜旗舰店", "尹灵旗舰店", "悦加旗舰店", "竹范旗舰店", "卓胜旗舰店" };
  2678. if (string.IsNullOrEmpty(spu_id) && list.IndexOf(father.seller_nick) > -1)
  2679. {
  2680. string sql_pay = "update CE_ErpTradeCell with(rowlock) set orderstate=-1 where tid='" + father.tid + "';";
  2681. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  2682. }
  2683. }
  2684. public static CeErpTradeCellExtend sendSpuData(CeErpTradeCell ceErpTradeCell, CeErpTradeCellExtend ceErpTradeCellExtend)
  2685. {
  2686. if (ceErpTradeCellExtend == null)
  2687. {
  2688. return null;
  2689. }
  2690. string result = designHelper.API_CheckOrderTo(ceErpTradeCellExtend.ctid, ceErpTradeCellExtend.spu_id, ceErpTradeCell.ShopId);
  2691. ceErpTradeCellExtend.ToType = result;
  2692. int dispatchSort = 0;
  2693. if ("无".Equals(result) && spu_shopIds.Contains(ceErpTradeCell.ShopId))
  2694. {
  2695. ceErpTradeCellExtend.ToType = "内部";
  2696. dispatchSort = 0;
  2697. }
  2698. if ((ceErpTradeCell.seller_memo.Contains("改稿") || ceErpTradeCell.OtherMemo.Contains("改稿")) && spu_shopIds.Contains(ceErpTradeCell.ShopId) && !spu_products.Contains(ceErpTradeCell.ProductId))
  2699. {
  2700. ceErpTradeCellExtend.ToType = "内部";
  2701. dispatchSort = 0;
  2702. }
  2703. if (ceErpTradeCell.payment >= 500 && spu_shopIds.Contains(ceErpTradeCell.ShopId) && !spu_products.Contains(ceErpTradeCell.ProductId))
  2704. {
  2705. ceErpTradeCellExtend.ToType = "内部";
  2706. dispatchSort = 0;
  2707. }
  2708. if (spu_products.Contains(ceErpTradeCell.ProductId) || ceErpTradeCell.seller_memo.IndexOf("手绘") > -1 || ceErpTradeCell.seller_memo.IndexOf("电子稿") > -1 || ceErpTradeCell.isDianziOrder > 0)
  2709. {
  2710. ceErpTradeCellExtend.ToType = "外协";
  2711. dispatchSort = 2;
  2712. }
  2713. string sql_pay = string.Format("update CE_ErpTradeCell with(rowlock) set DispatchSort={0} where ctid='{1}';", dispatchSort, ceErpTradeCell.ctid);
  2714. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  2715. if (ceErpTradeCellExtend.ID > 0)
  2716. {
  2717. ceErpTradeCellExtend.Update();
  2718. }
  2719. return ceErpTradeCellExtend;
  2720. }
  2721. public static DataTable getSameOrderList(CeErpTradeCell entity, CeErpTrade ceErpTrade)
  2722. {
  2723. StringBuilder sql = new StringBuilder();
  2724. 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);
  2725. if (string.IsNullOrEmpty(ceErpTrade.receiverId))
  2726. {
  2727. sql.AppendFormat(" and (tid='{0}');", entity.tid);
  2728. }
  2729. else
  2730. {
  2731. sql.AppendFormat(" and (tid='{0}' or (receiverId = '{1}' and IsSF = '{2}'));", entity.tid, ceErpTrade.receiverId, entity.IsSF);
  2732. }
  2733. DataTable dt = null;
  2734. try
  2735. {
  2736. dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  2737. StringBuilder timerSql = new StringBuilder();
  2738. timerSql.AppendFormat("SELECT * FROM CE_ErpSupplierProductTime WHERE supplierId={0}", entity.SupplierId);
  2739. DataTable timerTable = DbHelper.DbConn.ExecuteDataset(timerSql.ToString()).Tables[0];
  2740. //没有设置时间则不判断
  2741. dt.Columns.Add(new DataColumn("default", typeof(int)));
  2742. if (timerTable == null || timerTable.Rows.Count == 0)
  2743. {
  2744. return dt;
  2745. }
  2746. foreach (DataRow dr in dt.Rows)
  2747. {
  2748. dr["default"] = 0;
  2749. //当前订单
  2750. if (entity.ctid.Equals(dr["ctid"]))
  2751. {
  2752. continue;
  2753. }
  2754. //已经标记过发货
  2755. CeErpDeliverMark ceErpDeliverMark = CeErpDeliverMark.GetByCtid(dr["ctid"].ToString());
  2756. if (ceErpDeliverMark != null)
  2757. {
  2758. dr["default"] = 1;
  2759. continue;
  2760. }
  2761. string[] productIds = null;
  2762. string productId = dr["productId"].ToString();
  2763. string finishPlaceTime = dr["FinishPlaceTime"].ToString();
  2764. string sellmer_mome = dr["seller_memo"].ToString();
  2765. string txtCount = dr["ProductCount"].ToString();
  2766. DateTime placeTime = DateTime.Now;
  2767. //没有品类
  2768. if (string.IsNullOrEmpty(productId) || "0".Equals(productId))
  2769. {
  2770. continue;
  2771. }
  2772. if (string.IsNullOrEmpty(finishPlaceTime))
  2773. {
  2774. continue;
  2775. }
  2776. placeTime = DateTime.Parse(finishPlaceTime);
  2777. foreach (DataRow row in timerTable.Rows)
  2778. {
  2779. string txtIds = row["productId"].ToString();
  2780. string[] crafts = { };
  2781. int count = Convert.ToUInt16(row["quantity"]);
  2782. if (string.IsNullOrEmpty(txtIds))
  2783. {
  2784. continue;
  2785. }
  2786. if (count > 0)
  2787. {
  2788. int quantity = commonHelper.handleProductCount(txtCount, true);
  2789. //订单数量大于写入的数量则跳过
  2790. if (quantity > count)
  2791. {
  2792. continue;
  2793. }
  2794. }
  2795. productIds = txtIds.Split(',');
  2796. if (productIds.Contains(productId))
  2797. {
  2798. string textCraft = row["craft"].ToString();
  2799. textCraft = textCraft.Replace(",", ",");//统一格式
  2800. if (!string.IsNullOrEmpty(textCraft))
  2801. {
  2802. crafts = textCraft.Split(',');
  2803. }
  2804. if (crafts.Length > 0)
  2805. {
  2806. bool isinCraft = false;
  2807. for (int i = 0; i < crafts.Length; i++)
  2808. {
  2809. if (sellmer_mome.IndexOf(crafts[i]) >= 0)
  2810. {
  2811. isinCraft = true;
  2812. break;
  2813. }
  2814. }
  2815. //有写工艺并且备注中没匹配中则跳过
  2816. if (!isinCraft)
  2817. {
  2818. continue;
  2819. }
  2820. }
  2821. DateTime deadLine = DateTime.Parse(row["deadLine"].ToString());
  2822. DateTime dayDeadLine = DateTime.Parse(row["dayDeadLine"].ToString());
  2823. int sendDay = Convert.ToInt16(row["sendDay"]);
  2824. //下单时间小于当日发货时间则不用判断
  2825. //当日发货必须发货
  2826. if (dayDeadLine.Hour > 0 && dayDeadLine.Hour > placeTime.Hour)
  2827. {
  2828. dr["default"] = 1;
  2829. break;
  2830. }
  2831. //在截稿时间之前下单的可以减去一天时间
  2832. /*if (deadLine.Hour > 0 && deadLine.Hour > placeTime.Hour)
  2833. {
  2834. sendDay = Math.Max(1, sendDay - 1);
  2835. }
  2836. DateTime sendtime = placeTime.AddDays(sendDay);
  2837. //判断有没有到发货日期
  2838. if (DateTime.Compare(sendtime.Date, DateTime.Now.Date) > 0)
  2839. {
  2840. break;
  2841. }*/
  2842. }
  2843. }
  2844. }
  2845. }
  2846. catch (Exception ex)
  2847. {
  2848. }
  2849. return dt;
  2850. }
  2851. public static double calculationPrice(CeErpTradeCell ceErpTradeCell)
  2852. {
  2853. double price = 0;
  2854. return 200;
  2855. List<string> list = new List<string>();
  2856. //查补差订单
  2857. DataTable dt = DbHelper.DbConn.ExecuteDataset(string.Format("select tid from CE_ErpTradeCell where ptid = '{0}' and IsSample =2", ceErpTradeCell.tid)).Tables[0];
  2858. list.Add("'" + ceErpTradeCell.tid + "'");
  2859. if (dt != null && dt.Rows.Count > 0)
  2860. {
  2861. foreach (DataRow dr in dt.Rows)
  2862. {
  2863. list.Add("'" + dr["tid"].ToString() + "'");
  2864. }
  2865. }
  2866. DataTable tradeTables = DbHelper.DbConn.ExecuteDataset(string.Format("select payment from CE_ErpTrade where tid in ({0})", string.Join(",", list))).Tables[0];
  2867. if (tradeTables != null && tradeTables.Rows.Count > 0)
  2868. {
  2869. foreach (DataRow dr in tradeTables.Rows)
  2870. {
  2871. price += Convert.ToDouble(dr["payment"]);
  2872. }
  2873. }
  2874. return price;
  2875. }
  2876. public static bool loginGetOrder(int userId)
  2877. {
  2878. DataTable dt = null;
  2879. try
  2880. {
  2881. dt = DbHelper.DbConn.ExecuteDataset(string.Format("select * from view_ErpUser where ID = {0}", userId)).Tables[0];
  2882. }
  2883. catch (Exception e)
  2884. {
  2885. }
  2886. if (dt == null || dt.Rows.Count == 0)
  2887. {
  2888. return false;
  2889. }
  2890. DataRow dr = dt.Rows[0];
  2891. int isOpen = Convert.ToInt32(dr["isOpen"]);
  2892. int dayOrderReceive = Convert.ToInt32(dr["DayOrderReceive"]);//已经派了多少
  2893. int dayOrderLimit = Convert.ToInt32(dr["DayOrderLimit"]);//总的能派多少
  2894. int orderAmountLimit = Convert.ToInt32(dr["OrderAmountLimit"]);//能派的金额多少
  2895. int oldOrder = Convert.ToInt32(dr["OldOrder"]);//能派的金额多少
  2896. string orgShop = dr["OrgShop"].ToString();
  2897. string pemShop = dr["pemShop"].ToString();
  2898. string pemDesign = dr["pemDesign"].ToString();
  2899. if (isOpen == 0)
  2900. {
  2901. return false;
  2902. }
  2903. if (string.IsNullOrEmpty(orgShop) || string.IsNullOrEmpty(pemShop) || string.IsNullOrEmpty(pemDesign))
  2904. {
  2905. return false;
  2906. }
  2907. string normolSql = string.Format("and payment <={0} and shopid in ({1}) and shopid in ({2}) and ProductId in ({3})", orderAmountLimit, orgShop, pemShop, pemDesign);
  2908. 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);
  2909. DataTable dataTable = DbHelper.DbConn.ExecuteDataset(orderSql).Tables[0];
  2910. if (dataTable == null || dataTable.Rows.Count == 0)
  2911. {
  2912. return true;
  2913. }
  2914. designApiResponseVo result = null;
  2915. List<string> list = new List<string>();
  2916. foreach (DataRow row in dataTable.Rows)
  2917. {
  2918. if (dayOrderReceive >= dayOrderLimit)
  2919. {
  2920. break;
  2921. }
  2922. string IsOldCustomer = dr["IsOldCustomer"].ToString();
  2923. int ProductId = Convert.ToInt32(dr["ProductId"]);
  2924. CeErpShop ceErpShop = CeErpShop.Get(dr["shopid"]);
  2925. int shopUserId = 0;
  2926. if (ceErpShop != null)
  2927. {
  2928. shopUserId = ceErpShop.UserID;
  2929. }
  2930. bool isIn = false;
  2931. if ((IsOldCustomer == "1" && shopUserId == 241) || (shopUserId == 241 && Convert.ToDouble(dr["payment"]) >= 500))
  2932. {
  2933. if (oldOrder == 1)
  2934. {
  2935. //手绘 logo 画册 海报 宣传单
  2936. if ((IsOldCustomer == "1" && (ProductId == 28 || ProductId == 57 || ProductId == 40 || ProductId == 4 || ProductId == 13)))
  2937. {
  2938. result = commonHelper.checkOrderListDesignInfo(dr["tid"].ToString(), dr["ctid"].ToString());
  2939. if (result != null && result.code == 200)
  2940. {
  2941. continue;
  2942. }
  2943. }
  2944. isIn = true;
  2945. }
  2946. }
  2947. else
  2948. {
  2949. if (oldOrder == 0)
  2950. {
  2951. if (shopUserId != 82)
  2952. {
  2953. result = commonHelper.checkOrderListDesignInfo(dr["tid"].ToString(), dr["ctid"].ToString());
  2954. if (result != null && result.code == 200)
  2955. {
  2956. continue;
  2957. }
  2958. }
  2959. isIn = true;
  2960. }
  2961. }
  2962. if (isIn)
  2963. {
  2964. 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));
  2965. //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()));
  2966. dayOrderReceive += rowCount;
  2967. }
  2968. }
  2969. return true;
  2970. }
  2971. public static bool setFromDataInfo(string tid, string content, int userId)
  2972. {
  2973. CeErpTradeCell tradeCell = CeErpTradeCell.GetByCtid(tid);
  2974. if (tradeCell == null)
  2975. {
  2976. return false;
  2977. }
  2978. string info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}'", tradeCell.tid);
  2979. if (tradeCell.ctid.Contains("S_"))
  2980. {
  2981. info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE ctid ='{0}'", tradeCell.ctid);
  2982. }
  2983. DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
  2984. CeErpOrderFormData formData = null;
  2985. if (data.Rows.Count > 0)
  2986. {
  2987. List<CeErpTradeCell> cell_list = new List<CeErpTradeCell>();
  2988. foreach (DataRow row in data.Rows)
  2989. {
  2990. string ctid = row["ctid"].ToString();
  2991. CeErpTradeCell cell = CeErpTradeCell.GetByCtid(ctid);
  2992. cell_list.Add(cell);
  2993. formData = CeErpOrderFormData.GetByTid(ctid);
  2994. if (formData == null)
  2995. {
  2996. formData = new CeErpOrderFormData();
  2997. }
  2998. formData.tid = ctid;
  2999. formData.content = content;
  3000. if (formData.ID > 0)
  3001. {
  3002. formData.Update();
  3003. }
  3004. else
  3005. {
  3006. formData.userId = userId;
  3007. formData.Create();
  3008. }
  3009. }
  3010. if (tradeCell.OrderState >= 5)
  3011. {
  3012. LogHelper.addLog(tradeCell.ctid, formData.userId > 0 ? formData.userId : 3542, "外链派单:订单状态不正确!", tradeCell.OrderState);
  3013. return false;
  3014. }
  3015. //能进来并且没有设计师
  3016. foreach (CeErpTradeCell entity in cell_list)
  3017. {
  3018. try
  3019. {
  3020. if (entity != null && entity.seller_memo.Length > 0)
  3021. {
  3022. if (entity.OrderState >= 5)
  3023. {
  3024. LogHelper.addLog(entity.ctid, formData.userId > 0 ? formData.userId : 3542, "外链派单:订单状态不正确!", entity.OrderState);
  3025. continue;
  3026. }
  3027. //判断能不能推送
  3028. designApiResponseVo result = checkOrderListDesignInfo(entity.tid, entity.ctid);
  3029. if (result != null && result.code == 200)
  3030. {
  3031. designApiResponseVo response = designHelper.API_GetPrintData_CreateOrder(entity, "SysAdmin");
  3032. if (response.code == 200)
  3033. {
  3034. if (response.msg == "设计共创:成功")
  3035. {
  3036. if (entity.ctid.IndexOf("S_") == -1)
  3037. {
  3038. int suid = autoDistributeToSupplier(entity); //自动分配供应商
  3039. entity.SupplierId = suid;
  3040. string suname = getSupplierNameById(entity.SupplierId);
  3041. LogHelper.addLog(entity.ctid, 0, "匹配供应商:" + suname, entity.OrderState);
  3042. }
  3043. entity.OrderState = Convert.ToInt32(OrderState.待设计);
  3044. entity.DesignUserId = 3542;
  3045. entity.WaitDesignTime = DateTime.Now;
  3046. entity.DispatchSort = 2;
  3047. entity.UpdateTime = DateTime.Now;
  3048. entity.Update();
  3049. }
  3050. }
  3051. LogHelper.addLog(entity.ctid, formData.userId > 0 ? formData.userId : 3542, "外链派单:" + response.msg, Convert.ToInt32(OrderState.待设计));
  3052. }
  3053. else
  3054. {
  3055. LogHelper.addLog(entity.ctid, formData.userId > 0 ? formData.userId : 3542, "外链派单:" + result.msg, Convert.ToInt32(OrderState.待设计));
  3056. }
  3057. }
  3058. }
  3059. catch (Exception ex)
  3060. {
  3061. XLog.SaveLog(0, "外链派单:" + ex.Message);
  3062. }
  3063. }
  3064. }
  3065. return true;
  3066. }
  3067. public static void checkIsVipOld(CeErpTrade ceErpTrade)
  3068. {
  3069. if (ceErpTrade == null || string.IsNullOrEmpty(ceErpTrade.buyer_nick))
  3070. {
  3071. return;
  3072. }
  3073. int VipCustomer = 2;
  3074. string last_tid = "";
  3075. string sql = "";
  3076. if (ceErpTrade.payment > 20)
  3077. {
  3078. 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);
  3079. if (string.IsNullOrEmpty(ceErpTrade.buyer_nick))
  3080. {
  3081. 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);
  3082. }
  3083. DataTable dataTable = DbHelper.DbConn.ExecuteDataset(sql).Tables[0];
  3084. if (dataTable != null && dataTable.Rows.Count > 0)
  3085. {
  3086. last_tid = dataTable.Rows[0]["tid"].ToString();
  3087. if (!string.IsNullOrEmpty(last_tid))
  3088. {
  3089. VipCustomer = 1;
  3090. }
  3091. }
  3092. }
  3093. if (VipCustomer == 1)
  3094. {
  3095. LogHelper.addLog(ceErpTrade.tid, 0, "老客户订单号:" + last_tid, Convert.ToInt32(OrderState.待设计));
  3096. }
  3097. DbHelper.DbConn.ExecuteNonQuery(string.Format("UPDATE [dbo].[CE_ErpTradeCell] set VipCustomer = {1} WHERE tid='{0}';", ceErpTrade.tid, VipCustomer));
  3098. return;
  3099. }
  3100. public static bool interceptionSizeUnit(string size, CeErpProduct ceErpProduct)
  3101. {
  3102. size = size.Replace(",", ",");
  3103. size = size.Replace("C", "c");
  3104. size = size.Replace("M", "m");
  3105. List<string> list = ExtractUnitsOnly(size);
  3106. if (list.Count == 0)
  3107. {
  3108. return true;
  3109. }
  3110. if (ceErpProduct == null)
  3111. {
  3112. return true;
  3113. }
  3114. //未设置的不处理
  3115. if (string.IsNullOrEmpty(ceErpProduct.SizeUnit))
  3116. {
  3117. return true;
  3118. }
  3119. //提取到的单位数量不符合
  3120. if (size.Contains(",") && size.Split(',').Length != list.Count)
  3121. {
  3122. return false;
  3123. }
  3124. if (size.Contains("+") && size.Split('+').Length != list.Count)
  3125. {
  3126. return false;
  3127. }
  3128. list = list.Distinct().ToList();
  3129. //不能同时存在两个尺寸单位
  3130. if (list.Count != 1)
  3131. {
  3132. return false;
  3133. }
  3134. if (!list[0].Equals(ceErpProduct.SizeUnit))
  3135. {
  3136. return false;
  3137. }
  3138. return true;
  3139. }
  3140. static List<string> ExtractUnitsOnly(string text)
  3141. {
  3142. List<string> units = new List<string>();
  3143. string pattern = @"(cm|mm|m)";
  3144. foreach (Match match in Regex.Matches(text, pattern))
  3145. {
  3146. units.Add(match.Value);
  3147. }
  3148. return units;
  3149. }
  3150. public static string getProductCount(string txt)
  3151. {
  3152. txt = txt.Replace(",", ",");
  3153. string[] txtList = txt.Split(',');
  3154. int total = 0;
  3155. for (int i = 0; i < txtList.Length; i++)
  3156. {
  3157. string kuanPattern = @"(\d+)(?=款)";
  3158. Match kuanMatch = Regex.Match(txtList[i], kuanPattern);
  3159. string kuanNum = kuanMatch.Success ? kuanMatch.Groups[1].Value : "1";
  3160. // 提取"个"或"张"前面的数字
  3161. string unitPattern = @"(\d+)(?=个|张|本|套|件|卷|劵|条|箱 )";
  3162. Match unitMatch = Regex.Match(txtList[i], unitPattern);
  3163. string unitNum = unitMatch.Success ? unitMatch.Groups[1].Value : "1";
  3164. int kuan = 1;
  3165. int unit = 1;
  3166. if (!int.TryParse(kuanNum, out kuan))
  3167. {
  3168. return txt;
  3169. }
  3170. if (!int.TryParse(unitNum, out unit))
  3171. {
  3172. return txt;
  3173. }
  3174. total += kuan * unit;
  3175. }
  3176. return (total).ToString();
  3177. }
  3178. public static string convertQNMemo(string itemMemo, ref CeErpTradeCell entity)
  3179. {
  3180. if (string.IsNullOrEmpty(itemMemo))
  3181. {
  3182. return "";
  3183. }
  3184. CeErpTrade father = CeErpTrade.Get(entity.tid);
  3185. //删除备注中的旺旺
  3186. if (father.type == "TMALL" || father.type == "TB")
  3187. {
  3188. string[] memoList = itemMemo.Split('-');
  3189. List<string> list = new List<string>(memoList);
  3190. string buyer_nick = "";
  3191. if ((itemMemo.IndexOf("logo") != -1 || itemMemo.IndexOf("LOGO") != -1))
  3192. {
  3193. if (list.Count > 3)
  3194. {
  3195. buyer_nick = list[3];
  3196. }
  3197. }
  3198. else if (itemMemo.IndexOf("补差") != -1 && list.Count < 6)
  3199. {
  3200. if (list.Count > 1)
  3201. {
  3202. buyer_nick = list[1];
  3203. }
  3204. }
  3205. else if (itemMemo.IndexOf("默拍单") != -1 && list.Count < 6)
  3206. {
  3207. if (list.Count > 1)
  3208. {
  3209. buyer_nick = list[1];
  3210. }
  3211. }
  3212. else if (itemMemo.IndexOf("寄样") != -1)
  3213. {
  3214. if (list.Count > 3)
  3215. {
  3216. buyer_nick = list[3];
  3217. }
  3218. }
  3219. else if (itemMemo.IndexOf("拿样订单") != -1)
  3220. {
  3221. if (list.Count > 1)
  3222. {
  3223. buyer_nick = list[1];
  3224. }
  3225. }
  3226. else if (itemMemo.IndexOf("礼物") != -1 && list.Count < 6)
  3227. {
  3228. if (list.Count > 1)
  3229. {
  3230. buyer_nick = list[1];
  3231. }
  3232. }
  3233. else
  3234. {
  3235. if (list.Count > 5)
  3236. {
  3237. buyer_nick = list[5];
  3238. }
  3239. }
  3240. itemMemo = string.Join("-", list);
  3241. itemMemo = itemMemo.Replace("-" + buyer_nick, string.Empty);
  3242. }
  3243. itemMemo = itemMemo.Replace("\r", " ");
  3244. itemMemo = itemMemo.Replace("\n", " ");
  3245. string newmemo = "";
  3246. if (itemMemo.Contains("logo") || itemMemo.Contains("LOGO"))
  3247. {
  3248. string[] acclist = itemMemo.Split('-');
  3249. if (acclist.Length < 4) return null;
  3250. string count = acclist[0];
  3251. string product = acclist[1];
  3252. string account = acclist[3];
  3253. DataRow cusInfo = tmcHelper.getUserInfoByAccount(account); //客服id
  3254. entity.ProductId = tmcHelper.getProductIdByName("logo");
  3255. entity.ProductCount = commonHelper.getProductCount(count);// commonHelper.changeCountFromChiness(count); ;
  3256. newmemo = "(" + entity.OrderSn + ")-";
  3257. string newOtherMemo = "";
  3258. for (int i = 0; i < acclist.Length; i++)
  3259. {
  3260. if (i == 3) continue;
  3261. if (i >= 4)
  3262. {
  3263. newOtherMemo += acclist[i];
  3264. }
  3265. else
  3266. newmemo += acclist[i];
  3267. if (i < acclist.Length - 2)
  3268. {
  3269. newmemo += "-";
  3270. }
  3271. }
  3272. string sName = tmcHelper.getShopSNameByName(father.seller_nick);//获取店铺简称
  3273. newmemo += ("-" + sName);
  3274. if (father.buyer_nick.IndexOf("*") < 0)
  3275. {
  3276. newmemo += ("-" + father.buyer_nick);
  3277. }
  3278. newmemo += ("-" + father.receiver_state);
  3279. if (cusInfo != null)
  3280. {
  3281. newmemo += ("-" + Convert.ToString(cusInfo["Tb"]));
  3282. }
  3283. entity.seller_memo = newmemo;
  3284. entity.OtherMemo = newOtherMemo;
  3285. }
  3286. else if (itemMemo.Contains("合包"))
  3287. {
  3288. itemMemo = itemMemo.Replace(",", ",");
  3289. string[] hebaoMemoList = itemMemo.Split(',');
  3290. string newOtherMemo = "";
  3291. bool isMulity = true;
  3292. if (string.IsNullOrEmpty(entity.SplitTag))
  3293. {
  3294. isMulity = false;
  3295. }
  3296. string memo_index1 = hebaoMemoList[0];
  3297. string[] acclist = memo_index1.Split('-');
  3298. string account = acclist[5];
  3299. newmemo = "(" + entity.OrderSn + ")-";
  3300. for (int idx = 0; idx < hebaoMemoList.Length; idx++)
  3301. {
  3302. string smallitem = hebaoMemoList[idx];
  3303. if (idx == 0 && smallitem.IndexOf("海报") != -1)
  3304. {
  3305. newmemo = "";
  3306. }
  3307. string[] smallList = smallitem.Split('-');
  3308. if (smallList.Length > 5 && idx > 0)
  3309. {
  3310. string itemsize = smallList[0];
  3311. string itemcount = smallList[1];
  3312. string itemmt = "", itemct = "";
  3313. if ((smallList[3] == "不干胶" || smallitem.IndexOf("PVC卡片") != -1 || smallitem.IndexOf("pvc卡片") != -1 || smallitem.IndexOf("海报") != -1) && smallitem.IndexOf("礼物") == -1)
  3314. {
  3315. itemmt = acclist[2];
  3316. }
  3317. else
  3318. {
  3319. itemmt = acclist[3];
  3320. }
  3321. itemct = acclist[4];
  3322. entity.ProductSize = entity.ProductSize + "," + itemsize;
  3323. entity.ProductCount = entity.ProductCount + "," + itemcount;
  3324. entity.Material = entity.Material + "," + itemmt;
  3325. entity.Craft = entity.Craft + "," + itemct;
  3326. }
  3327. if (smallList.Length >= 7)
  3328. {
  3329. smallList[6] = smallList[6].Replace("(", "");
  3330. smallList[6] = smallList[6].Replace(")", "");
  3331. smallList[6] = smallList[6].Replace("(", "");
  3332. smallList[6] = smallList[6].Replace(")", "");
  3333. entity.MakeSupplier = smallList[6];
  3334. smallList[6] = "(" + smallList[6] + ")";
  3335. newmemo += smallList[6];
  3336. newmemo += "-";
  3337. }
  3338. if (false)
  3339. {
  3340. newmemo += smallList[2];
  3341. newmemo += smallList[0];
  3342. newmemo += "-";
  3343. newmemo += smallList[1];
  3344. newmemo += "(";
  3345. newmemo += entity.OrderSn;
  3346. newmemo += ")";
  3347. newmemo += "-";
  3348. newmemo += smallList[4];
  3349. if (smallList.Length > 7)
  3350. {
  3351. for (int i = 7; i < smallList.Length; i++)
  3352. {
  3353. newOtherMemo += smallList[i];
  3354. newOtherMemo += "-";
  3355. }
  3356. }
  3357. if (smallitem.IndexOf("5mmpvc") != -1)
  3358. {
  3359. entity.ProductId = 8; //pvc卡片
  3360. }
  3361. }
  3362. else
  3363. {
  3364. for (int i = 0; i < smallList.Length; i++)
  3365. {
  3366. if (isMulity && i == 5)
  3367. {
  3368. continue;
  3369. }
  3370. if (i >= 7)
  3371. {
  3372. newOtherMemo += smallList[i];
  3373. if (i < smallList.Length - 2 && i != 2 && i != 3)
  3374. {
  3375. newOtherMemo += "-";
  3376. }
  3377. }
  3378. else
  3379. {
  3380. if (i == 5 || i == 6)
  3381. {
  3382. continue;
  3383. }
  3384. else
  3385. newmemo += smallList[i];
  3386. if (i != 2 && i != 3)
  3387. {
  3388. newmemo += "-";
  3389. }
  3390. }
  3391. }
  3392. }
  3393. if (hebaoMemoList.Length > idx + 1)
  3394. {
  3395. newmemo += ",";
  3396. newOtherMemo += ",";
  3397. }
  3398. }
  3399. entity.ProductCount = commonHelper.getProductCount(entity.ProductCount);
  3400. string sName = tmcHelper.getShopSNameByName(father.seller_nick);
  3401. newmemo += (sName);
  3402. if (father.buyer_nick.IndexOf("*") < 0)
  3403. {
  3404. newmemo += ("-" + father.buyer_nick);
  3405. }
  3406. newmemo += ("-" + father.receiver_state);
  3407. DataRow cusInfo = tmcHelper.getUserInfoByAccount(account); //客服id
  3408. if (cusInfo != null)
  3409. {
  3410. entity.CustomerUserId = Convert.ToInt32(cusInfo["ID"]);
  3411. }
  3412. if (cusInfo != null)
  3413. {
  3414. newmemo += ("-" + Convert.ToString(cusInfo["Tb"]));
  3415. }
  3416. entity.seller_memo = newmemo;
  3417. entity.OtherMemo = newOtherMemo;
  3418. }
  3419. else
  3420. {
  3421. string[] acclist = itemMemo.Split('-');
  3422. bool isXianhuo = false;
  3423. if (acclist[0] == "现货")
  3424. {
  3425. isXianhuo = true;
  3426. System.Array.Copy(acclist, 1, acclist, 0, acclist.Length - 1);
  3427. System.Array.Resize(ref acclist, acclist.Length - 1);
  3428. }
  3429. if (acclist.Length < 6)
  3430. {
  3431. return "";
  3432. }
  3433. string size = acclist[0];
  3434. string count = acclist[1];
  3435. bool isBuGanJiao = false;
  3436. string product = "";
  3437. string mt = "", ct = "";
  3438. string account = "";
  3439. itemMemo = itemMemo.Replace("PVC", "pvc");
  3440. if ((acclist[3] == "不干胶" || itemMemo.IndexOf("电子稿") != -1 || itemMemo.IndexOf("pvc卡片") != -1 || itemMemo.IndexOf("海报") != -1) && itemMemo.IndexOf("礼物") == -1)
  3441. {
  3442. isBuGanJiao = true;
  3443. product = acclist[3];
  3444. mt = acclist[2];
  3445. }
  3446. else
  3447. {
  3448. product = acclist[2];
  3449. mt = acclist[3];
  3450. }
  3451. account = acclist[5];
  3452. ct = acclist[4];
  3453. if (acclist.Length >= 7)
  3454. {
  3455. acclist[6] = acclist[6].Replace("(", "");
  3456. acclist[6] = acclist[6].Replace(")", "");
  3457. acclist[6] = acclist[6].Replace("(", "");
  3458. acclist[6] = acclist[6].Replace(")", "");
  3459. entity.MakeSupplier = acclist[6];
  3460. acclist[6] = "(" + acclist[6] + ")";
  3461. }
  3462. entity.ProductId = tmcHelper.getProductIdByName(product);
  3463. if (entity.ProductId == 0)
  3464. {
  3465. return "";
  3466. }
  3467. DataRow cusInfo = tmcHelper.getUserInfoByAccount(account); //客服id
  3468. if (cusInfo != null)
  3469. {
  3470. entity.CustomerUserId = Convert.ToInt32(cusInfo["ID"]);
  3471. }
  3472. if (mt.IndexOf("铜板纸") != -1)
  3473. {
  3474. mt = mt.Replace("铜板纸", "铜版纸");
  3475. }
  3476. entity.Material = mt;
  3477. entity.ProductSize = size;
  3478. entity.ProductCount = getProductCount(count); ;//commonHelper.changeCountFromChiness(count);
  3479. entity.Craft = ct;
  3480. newmemo = "(" + entity.OrderSn + ")-";
  3481. if (isXianhuo)
  3482. {
  3483. newmemo += "现货-";
  3484. }
  3485. string newOtherMemo = "";
  3486. bool isMulity = true;
  3487. if (string.IsNullOrEmpty(entity.SplitTag))
  3488. {
  3489. isMulity = false;
  3490. }
  3491. if (acclist.Length >= 7 && !isMulity)
  3492. {
  3493. newmemo += acclist[6];
  3494. newmemo += "-";
  3495. }
  3496. if (isMulity && acclist.Length >= 8)
  3497. {
  3498. newmemo += acclist[7];
  3499. newmemo += "-";
  3500. }
  3501. for (int i = 0; i < acclist.Length; i++)
  3502. {
  3503. if ((isMulity && i == 6) || i == 5)
  3504. {
  3505. continue;
  3506. }
  3507. if ((i >= 7 && !isMulity) || (isMulity && i >= 8))
  3508. {
  3509. newOtherMemo += acclist[i];
  3510. newOtherMemo += "-";
  3511. }
  3512. else
  3513. {
  3514. if ((i == 6 && !isMulity) || (isMulity && i == 7))
  3515. {
  3516. continue;
  3517. }
  3518. else
  3519. newmemo += acclist[i];
  3520. if (i != 2 && i != 3)
  3521. {
  3522. newmemo += "-";
  3523. }
  3524. }
  3525. }
  3526. string sName = tmcHelper.getShopSNameByName(father.seller_nick);//获取店铺简称
  3527. newmemo += (sName);
  3528. if (father.buyer_nick.IndexOf("*") < 0)
  3529. {
  3530. newmemo += ("-" + father.buyer_nick);
  3531. }
  3532. newmemo += ("-" + father.receiver_state);
  3533. if (cusInfo != null)
  3534. {
  3535. newmemo += ("-" + Convert.ToString(cusInfo["Tb"]));
  3536. }
  3537. if (!string.IsNullOrEmpty(entity.SplitTag))
  3538. {
  3539. newmemo += "-[" + entity.SplitTag + "]";
  3540. }
  3541. newmemo = newmemo.Replace("\n", " ");
  3542. entity.seller_memo = newmemo;
  3543. entity.OtherMemo = newOtherMemo;
  3544. }
  3545. return newmemo;
  3546. }
  3547. public static bool isMultiSize(string memo)
  3548. {
  3549. bool result = false;
  3550. if (memo.Contains("合包"))
  3551. {
  3552. return result;
  3553. }
  3554. string[] memolist = memo.Split('-');
  3555. if (memolist.Length < 3)
  3556. {
  3557. return result;
  3558. }
  3559. string size_text = memolist[1];
  3560. if (size_text.Contains(")") || size_text.Contains(")"))
  3561. {
  3562. size_text = memolist[2];
  3563. }
  3564. if (size_text.Contains(",") || size_text.Contains(",") || size_text.Contains("+"))
  3565. {
  3566. result = true;
  3567. }
  3568. if (!result)
  3569. {
  3570. int a = size_text.Split(new string[] { "mm" }, StringSplitOptions.None).Length - 1;
  3571. a += size_text.Split(new string[] { "cm" }, StringSplitOptions.None).Length - 1;
  3572. if (size_text.Count(c => c == 'x') > 1 && a > 1)
  3573. {
  3574. result = true;
  3575. }
  3576. }
  3577. return result;
  3578. }
  3579. public static void sendOrderInfo(string tid, string order_status, string buyer_id, string buyer_nick, int type = 0)
  3580. {
  3581. Thread thread = new Thread(new ThreadStart(() =>
  3582. {
  3583. string url = "https://wx.lingtao8.com/api/v1/msg/new_order";
  3584. HttpClient client = new HttpClient();
  3585. string param = JsonConvert.SerializeObject(new
  3586. {
  3587. order_type = type,
  3588. order_id = tid,
  3589. buyer_nick = buyer_nick,
  3590. buyer_id = buyer_id,
  3591. order_status = order_status,
  3592. });
  3593. var request = new HttpRequestMessage
  3594. {
  3595. Method = HttpMethod.Post,
  3596. RequestUri = new Uri(url),
  3597. Content = new StringContent(param)
  3598. {
  3599. Headers =
  3600. {
  3601. ContentType = new MediaTypeHeaderValue("application/json")
  3602. }
  3603. }
  3604. };
  3605. try
  3606. {
  3607. var response = client.SendAsync(request).Result;
  3608. response.EnsureSuccessStatusCode();
  3609. }
  3610. catch (Exception e)
  3611. {
  3612. }
  3613. }));
  3614. thread.Start();
  3615. }
  3616. public static string generateDateTimeRandomNos()
  3617. {
  3618. Random random = new Random();
  3619. const int maxAttempts = 10;
  3620. for (int i = 0; i < maxAttempts; i++)
  3621. {
  3622. string orderSn = DateTimeNow("yyMMddHHmmssfff") + RandomNumbers(random, 3);
  3623. return orderSn;
  3624. }
  3625. return "";
  3626. }
  3627. /// <summary>
  3628. /// 获取当前日期时间的指定格式字符串
  3629. /// </summary>
  3630. private static string DateTimeNow(string format)
  3631. {
  3632. return DateTime.Now.ToString(format);
  3633. }
  3634. /// <summary>
  3635. /// 生成指定长度的随机数字字符串
  3636. /// </summary>
  3637. private static string RandomNumbers(Random random, int length)
  3638. {
  3639. if (length <= 0) return string.Empty;
  3640. var rng = RandomNumberGenerator.Create();
  3641. while (true)
  3642. {
  3643. byte[] randomBytes = new byte[2]; // 2字节=16位,足够0-900范围
  3644. int value;
  3645. do
  3646. {
  3647. rng.GetBytes(randomBytes);
  3648. value = randomBytes[0] * 256 + randomBytes[1];
  3649. } while (value >= 900 * (65536 / 900)); // 拒绝采样,避免偏差
  3650. value = value % 900 + 100;
  3651. if (value > 100 && value < 1000)
  3652. {
  3653. return value.ToString();
  3654. }
  3655. }
  3656. }
  3657. }
  3658. }