commonHelper.cs 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529
  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. namespace SiteCore
  27. {
  28. public class commonHelper
  29. {
  30. public static void autoRefreshRefundState()
  31. {
  32. StringBuilder sql = new StringBuilder();
  33. sql.AppendFormat("update CE_ErpTradeRefund set RefundState=3 where RefundState=2 and DATEDIFF(hh,modified,getdate())>=72;");
  34. //sql.AppendFormat("update ce_erptradecell with(rowlock) set AfterSaleState=4,FinishAfterSaleTime=getdate() where AfterSaleState=3 and IsArbitrate=0 and DATEDIFF(hh,AfterSalePreTime,getdate())>=168;");
  35. //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;");
  36. //sql.AppendFormat("update CE_ErpTradeResponsible set VerifyState=1 where VerifyState=0 and IsArbitrate=0 and DATEDIFF(hh,createdTime,getdate())>=168;");
  37. //DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  38. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  39. sql = new StringBuilder();
  40. sql.AppendFormat("SELECT r.ID, r.tid, r.VerifyState, r.UserId, r.VerifyTime, ( CASE WHEN r.IsSup IS NULL THEN 0 ELSE r.IsSup END ) AS IsSup, ( CASE WHEN r.IsFlow IS NULL THEN 0 ELSE r.IsFlow END ) AS IsFlow 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;");
  41. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  42. foreach (DataRow dr in dt.Rows)
  43. {
  44. string state = dr["VerifyState"].ToString();
  45. string tid = dr["tid"].ToString();
  46. int userId = Convert.ToInt32(dr["UserId"]);
  47. int reasonId = Convert.ToInt32(dr["ID"]);
  48. int IsSup = Convert.ToInt32(dr["IsSup"]);
  49. int IsFlow = Convert.ToInt32(dr["IsFlow"]);
  50. if (IsSup == 0 && IsFlow == 0)
  51. {
  52. if (state == "0")//主管审核超时
  53. {
  54. CeErpTradeResponsible ceErpTradeResponsible = CeErpTradeResponsible.GetById(dr["ID"].ToString());
  55. if (ceErpTradeResponsible != null)
  56. {
  57. ceErpTradeResponsible.VerifyTime = DateTime.Now;
  58. ceErpTradeResponsible.VerifyState = 3;
  59. ceErpTradeResponsible.Update();
  60. LogHelper.AddAfterSaleLog(tid, reasonId, "主管审核超时", userId);
  61. LogHelper.addLog(tid, 0, "主管审核超时", 4, 4);
  62. }
  63. }
  64. if (state == "3")//责任人审核超时
  65. {
  66. CeErpTradeResponsible ceErpTradeResponsible = CeErpTradeResponsible.GetById(dr["ID"].ToString());
  67. if (ceErpTradeResponsible != null)
  68. {
  69. ceErpTradeResponsible.VerifyTime = DateTime.Now;
  70. ceErpTradeResponsible.VerifyState = 1;
  71. ceErpTradeResponsible.Update();
  72. LogHelper.AddAfterSaleLog(tid, reasonId, "责任人审核超时", userId);
  73. LogHelper.addLog(tid, 0, "责任人审核超时", 4, 4);
  74. CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ceErpTradeResponsible.tid);
  75. bool isAll = tradeResponsibleAll(entity);
  76. if (isAll)
  77. {
  78. entity.AfterSaleState = 4;
  79. entity.FinishAfterSaleTime = DateTime.Now;
  80. entity.AfterSaleSupplierState = 1;
  81. ApiVo apiVo = new ApiVo();
  82. apiVo.orderNumber = entity.ctid;
  83. apiVo.actionName = "afterOver";
  84. designHelper.API_WorkCore(apiVo); //afterOver
  85. entity.Update();
  86. }
  87. }
  88. }
  89. }
  90. else
  91. {
  92. if (IsSup == 0 && IsFlow == 1)
  93. {
  94. DateTime date = DateTime.Parse(dr["VerifyTime"].ToString());
  95. if (DateTime.Compare(DateTime.Now, date.AddHours(96)) > 0)
  96. {
  97. continue;
  98. }
  99. }
  100. if (state == "0")
  101. {
  102. CeErpTradeResponsible ceErpTradeResponsible = CeErpTradeResponsible.GetById(dr["ID"].ToString());
  103. if (ceErpTradeResponsible != null)
  104. {
  105. ceErpTradeResponsible.VerifyTime = DateTime.Now;
  106. ceErpTradeResponsible.VerifyState = 1;
  107. ceErpTradeResponsible.Update();
  108. CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ceErpTradeResponsible.tid);
  109. bool isAll = tradeResponsibleAll(entity);
  110. if (isAll)
  111. {
  112. entity.AfterSaleState = 4;
  113. entity.FinishAfterSaleTime = DateTime.Now;
  114. if (entity.AfterSaleResSupId > 0)
  115. {
  116. entity.AfterSaleSupplierState = 1;
  117. }
  118. entity.Update();
  119. ApiVo apiVo = new ApiVo();
  120. apiVo.orderNumber = entity.ctid;
  121. apiVo.actionName = "afterOver";
  122. designHelper.API_WorkCore(apiVo); //afterOver
  123. }
  124. CeErpSukuraData.createInfo(entity.ctid, 8);
  125. LogHelper.addLog(tid, 0, "审核超时,自动完成售后", 4, 4);
  126. }
  127. }
  128. }
  129. }
  130. }
  131. public static void tradeSaleState(CeErpTradeCell ceErpTradeCell)
  132. {
  133. string sql = "select * from ce_erptraderesponsible where tid='" + ceErpTradeCell.ctid + "' and VerifyState != -1";
  134. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql).Tables[0];
  135. CeErpTradeAfterSaleExtend ceErpTradeAfterSaleExtend = CeErpTradeAfterSaleExtend.getByTid(ceErpTradeCell.ctid);
  136. if (ceErpTradeAfterSaleExtend == null)
  137. {
  138. ceErpTradeAfterSaleExtend = new CeErpTradeAfterSaleExtend();
  139. ceErpTradeAfterSaleExtend.tid = ceErpTradeCell.ctid;
  140. ceErpTradeAfterSaleExtend.Create();
  141. }
  142. List<string> list = new List<string>();
  143. foreach (DataRow row in dt.Rows)
  144. {
  145. list.Add(row["VerifyState"].ToString());
  146. }
  147. ceErpTradeAfterSaleExtend.VerifyStates = String.Join(",", list);
  148. ceErpTradeAfterSaleExtend.Update();
  149. }
  150. public static bool tradeResponsibleAll(CeErpTradeCell ceErpTradeCell)
  151. {
  152. //判断是否全部处理完成
  153. string sql = "select * from ce_erptraderesponsible where tid='" + ceErpTradeCell.ctid + "' and VerifyState != -1";
  154. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql).Tables[0];
  155. bool isAll = true;
  156. if (dt.Rows.Count > 0 && dt.Rows.Count == 1)
  157. {
  158. }
  159. else if (dt.Rows.Count > 1)
  160. {
  161. foreach (DataRow row in dt.Rows)
  162. {
  163. if (row["VerifyState"].ToString() != "1")
  164. {
  165. isAll = false;
  166. break;
  167. }
  168. }
  169. }
  170. return isAll;
  171. }
  172. public static string getSupplierNameById(int sid)
  173. {
  174. CeErpSupplier sup = CeErpSupplier.Get(sid);
  175. if (sup != null)
  176. {
  177. return sup.ComName;
  178. }
  179. else
  180. {
  181. return "";
  182. }
  183. }
  184. public static void aftersaleSend(string ctid, string cpCode, string curUseWayBillCode)
  185. {
  186. if (ctid.IndexOf("S_") > -1)
  187. {
  188. try
  189. {
  190. string tradeCtid = ctid.Remove(0, 2);
  191. CeErpTradeAfterSaleExtend ceErpTradeAfterSaleExtend = CeErpTradeAfterSaleExtend.getByTid(tradeCtid);
  192. if (ceErpTradeAfterSaleExtend == null)
  193. {
  194. ceErpTradeAfterSaleExtend = new CeErpTradeAfterSaleExtend();
  195. ceErpTradeAfterSaleExtend.tid = tradeCtid;
  196. ceErpTradeAfterSaleExtend.ExpressNo = cpCode + "-" + curUseWayBillCode;
  197. ceErpTradeAfterSaleExtend.Create();
  198. }
  199. else
  200. {
  201. ceErpTradeAfterSaleExtend.ExpressNo = cpCode + "-" + curUseWayBillCode;
  202. ceErpTradeAfterSaleExtend.Update();
  203. }
  204. }
  205. catch (Exception ex)
  206. {
  207. }
  208. }
  209. }
  210. public static string getUserNameById(int sid)
  211. {
  212. CeErpUser sup = CeErpUser.Get(sid);
  213. if (sup != null)
  214. {
  215. return sup.Name;
  216. }
  217. else
  218. {
  219. return "";
  220. }
  221. }
  222. public static int getSupplierIDByName(string name)
  223. {
  224. StringBuilder sql2 = new StringBuilder();
  225. sql2.AppendFormat("select top 1 * from CE_ErpSupplier where ComName='{0}';", name);
  226. DataTable dt2 = DbHelper.DbConn.ExecuteDataset(sql2.ToString()).Tables[0];
  227. if (dt2.Rows.Count > 0)
  228. {
  229. return Convert.ToInt32(dt2.Rows[0]["ID"]);
  230. }
  231. return 0;
  232. }
  233. public static int autoDistributeToSupplier(CeErpTradeCell trade)
  234. {
  235. if (trade.seller_memo.IndexOf("电子稿") != -1) return 0;
  236. int count = 0;
  237. string sc = trade.ProductCount;
  238. count = handleProductCount(sc, true);
  239. //string needSc = System.Text.RegularExpressions.Regex.Replace(sc, @"[^0-9]+", "");
  240. //if (!int.TryParse(needSc, out count))
  241. //{
  242. // XLog.SaveLog(0, "autoDistributeToSupplier:获取数量[" + trade.ProductCount + "]转换出错");
  243. //}
  244. //老客户指派之前供应商
  245. if (trade.IsOldCustomer == 1 && trade.seller_memo.IndexOf("改稿") != -1)
  246. {
  247. CeErpTrade ceErpTrade = CeErpTrade.Get(trade.tid);
  248. if (ceErpTrade != null)
  249. {
  250. //用昵称找之前的订单
  251. string name = ceErpTrade.buyer_nick;
  252. StringBuilder CeErpTradeSql = new StringBuilder();
  253. CeErpTradeSql.AppendFormat("select top 1 * from ce_erptrade where buyer_nick='{0}' order by created desc;", name);
  254. DataSet data = DbHelper.DbConn.ExecuteDataset(CeErpTradeSql.ToString());
  255. DataTable datatable = data.Tables[0];
  256. if (datatable.Rows.Count > 0)
  257. {
  258. CeErpTradeCell oldOrder = CeErpTradeCell.GetByTid(datatable.Rows[0]["tid"].ToString());
  259. if (oldOrder != null)
  260. {
  261. CeErpSupplier ceErpSupplier = CeErpSupplier.Get(oldOrder.SupplierId);
  262. if (ceErpSupplier != null && ceErpSupplier.IsClose == 0)
  263. {
  264. return oldOrder.SupplierId;
  265. }
  266. }
  267. }
  268. }
  269. }
  270. if (trade.Craft.IndexOf("门挂卡") != -1)
  271. {
  272. return 7;// ljl
  273. }
  274. else if (trade.Craft.IndexOf("打印") != -1 || trade.Craft.IndexOf("专版") != -1)
  275. {
  276. return 10; //得力
  277. }
  278. else if (trade.Craft.IndexOf("打码") != -1 || trade.Craft.IndexOf("压点线") != -1)
  279. {
  280. if (count < 300)
  281. {
  282. return 10;
  283. }
  284. else
  285. return 25;
  286. }
  287. if (trade.seller_memo.Contains("金属标") && (trade.ShopId == 26 || trade.ShopId == 45))
  288. {
  289. return 9;
  290. }
  291. //if (trade.IsOldCustomer == 1)
  292. //{
  293. // StringBuilder oldsql = new StringBuilder();
  294. // oldsql.AppendFormat("select top 1 SupplierId from view_erptradecell where buyer_nick={0} and IsAutoDistribute=1 ;",trad, trade.ProductId);
  295. //}
  296. StringBuilder sql = new StringBuilder();
  297. sql.AppendFormat("select count(0) from ce_erpproduct where id={0} and IsAutoDistribute=1 ;", trade.ProductId);
  298. sql.AppendFormat("select top 1 * from ce_erptrade where tid='{0}';", trade.tid);
  299. DataSet oDs = DbHelper.DbConn.ExecuteDataset(sql.ToString());
  300. DataTable pDt = oDs.Tables[0];
  301. DataTable rDt = oDs.Tables[1];
  302. string material = trade.Material;
  303. material = material.Replace("铜板纸", "铜版纸");
  304. string crafts = trade.Craft;
  305. string supplierCrafts = trade.MakeSupplier;
  306. if (supplierCrafts == "")
  307. {
  308. supplierCrafts = "123123";
  309. }
  310. decimal size = getOrderSizeFromString(trade.ProductSize);
  311. if (pDt != null && pDt.Rows.Count > 0)
  312. {
  313. string receiver_state = "";
  314. if (rDt != null || rDt.Rows.Count > 0)
  315. {
  316. receiver_state = rDt.Rows[0]["receiver_state"].ToString();
  317. if (trade.IsOldCustomer == 1)
  318. {
  319. StringBuilder oldsql = new StringBuilder();
  320. 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);
  321. DataTable oldDt = DbHelper.DbConn.ExecuteDataset(oldsql.ToString()).Tables[0];
  322. if (oldDt.Rows.Count > 0)
  323. {
  324. CeErpSupplier ceErpSupplier = CeErpSupplier.Get(Convert.ToInt32(oldDt.Rows[0]["SupplierId"]));
  325. if (ceErpSupplier != null && ceErpSupplier.IsClose == 0)
  326. {
  327. return Convert.ToInt32(oldDt.Rows[0]["SupplierId"]);
  328. }
  329. }
  330. }
  331. }
  332. try
  333. {
  334. //CHARINDEX(','+'{0}'+',',','+ProductID+',')>0
  335. sql = new StringBuilder();
  336. 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);
  337. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  338. if (dt == null || dt.Rows.Count < 1) return 0;
  339. DataView dv = new DataView(dt);
  340. int topOneProductSupplier = Convert.ToInt32(dv[0]["SupplierID"]);
  341. if (receiver_state.Length > 0)
  342. {
  343. 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);
  344. if (dv.Count > 0)
  345. {
  346. return Convert.ToInt32(dv[0]["SupplierID"]);
  347. }
  348. }
  349. if (count > 0)
  350. {
  351. if (size > 0)
  352. {
  353. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1} and SizeL<={2} and SizeW>={2} ", material, count, size);
  354. if (dv.Count > 0)
  355. {
  356. return Convert.ToInt32(dv[0]["SupplierID"]);
  357. }
  358. }
  359. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1}", material, count);
  360. if (dv.Count > 0)
  361. {
  362. LogHelper.addLog(trade.ctid, 0, "筛选供应商:产品 材质 工艺 数量 符合!"); return Convert.ToInt32(dv[0]["SupplierID"]);
  363. }
  364. }
  365. if (size > 0)
  366. {
  367. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1} and SizeL<={2} and SizeW>={2}", material, count, size);
  368. if (dv.Count > 0)
  369. {
  370. return Convert.ToInt32(dv[0]["SupplierID"]);
  371. }
  372. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and SizeL<={1} and SizeW>={1}", material, size);
  373. if (dv.Count > 0)
  374. {
  375. return Convert.ToInt32(dv[0]["SupplierID"]);
  376. }
  377. }
  378. dv.RowFilter = string.Format("ProductCrafts like '%{0}%'", material);
  379. if (count > 0)
  380. {
  381. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and MinNum<={1} and MaxNum>={1}", material, count);
  382. if (dv.Count > 0)
  383. {
  384. return Convert.ToInt32(dv[0]["SupplierID"]);
  385. }
  386. dv.RowFilter = string.Format("MinNum<={0} and MaxNum>={0}", count);
  387. if (dv.Count > 0)
  388. {
  389. return Convert.ToInt32(dv[0]["SupplierID"]);
  390. }
  391. }
  392. if (size > 0)
  393. {
  394. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' and SizeL<={1} and SizeW>={1}", material, size);
  395. if (dv.Count > 0)
  396. {
  397. return Convert.ToInt32(dv[0]["SupplierID"]);
  398. }
  399. dv.RowFilter = string.Format(" SizeL<={0} and SizeW>={0}", size);
  400. if (dv.Count > 0)
  401. {
  402. return Convert.ToInt32(dv[0]["SupplierID"]);
  403. }
  404. }
  405. dv.RowFilter = string.Format("Crafts like '%{0}%' or Crafts like '%{1}%'", crafts, supplierCrafts);
  406. if (dv.Count > 0)
  407. {
  408. return Convert.ToInt32(dv[0]["SupplierID"]);
  409. }
  410. //产品 材质符合
  411. dv.RowFilter = string.Format("ProductCrafts like '%{0}%' ", material);
  412. if (dv.Count > 0)
  413. {
  414. return Convert.ToInt32(dv[0]["SupplierID"]);
  415. }
  416. else
  417. {
  418. return topOneProductSupplier;
  419. }
  420. }
  421. catch (Exception ex)
  422. {
  423. XLog.SaveLog(0, "commmonHelper:autoDistributeToSupplier" + ex.Message);
  424. }
  425. }
  426. return 0;
  427. }
  428. public static void setDeliveryUnusualOrder()
  429. {
  430. try
  431. {
  432. StringBuilder sql = new StringBuilder();
  433. 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);");
  434. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  435. List<string> tLst = new List<string>();
  436. if (dt.Rows.Count > 0)
  437. {
  438. foreach (DataRow dr in dt.Rows)
  439. {
  440. double hour = 0;
  441. string fptime = dr["FinishPlaceTime"].ToString();
  442. if (fptime.Length > 0)
  443. {
  444. hour = DateTime.Now.Subtract(Convert.ToDateTime(fptime)).TotalHours;
  445. }
  446. else
  447. continue;
  448. int useHour = 10000;
  449. StringBuilder sqlhour = new StringBuilder();
  450. 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());
  451. DataTable dthour = DbHelper.DbConn.ExecuteDataset(sqlhour.ToString()).Tables[0];
  452. if (dthour.Rows.Count > 0)
  453. {
  454. useHour = Convert.ToInt32(dthour.Rows[0]["fhTime"]);
  455. }
  456. else
  457. {
  458. sqlhour = new StringBuilder();
  459. sqlhour.AppendFormat("select top 1 * from CE_ErpProductHour where ProductID={0} and (CHARINDEX(Craft,'{1}')>0 or Craft='*');", dr["ProductId"].ToString(), dr["Craft"].ToString());
  460. dthour = DbHelper.DbConn.ExecuteDataset(sqlhour.ToString()).Tables[0];
  461. if (dthour.Rows.Count > 0)
  462. {
  463. useHour = Convert.ToInt32(dthour.Rows[0]["fhTime"]);
  464. }
  465. else
  466. {
  467. sqlhour = new StringBuilder();
  468. sqlhour.AppendFormat("select top 1 * from CE_ErpProductHour where ProductID={0};", dr["ProductId"].ToString());
  469. dthour = DbHelper.DbConn.ExecuteDataset(sqlhour.ToString()).Tables[0];
  470. if (dthour.Rows.Count > 0)
  471. {
  472. useHour = Convert.ToInt32(dthour.Rows[0]["fhTime"]);
  473. }
  474. }
  475. }
  476. if (hour > useHour)
  477. {
  478. tLst.Add("'" + dr["ctid"].ToString() + "'");
  479. }
  480. }
  481. }
  482. sql = new StringBuilder();
  483. 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 ;");
  484. dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  485. if (dt.Rows.Count > 0)
  486. {
  487. foreach (DataRow dr in dt.Rows)
  488. {
  489. double hour = 0;
  490. string fptime = dr["FinishPlaceTime"].ToString();
  491. string paytime = dr["pay_time"].ToString();
  492. DateTime dtPaytime = Convert.ToDateTime(paytime);
  493. if (fptime.Length > 0)
  494. {
  495. hour = DateTime.Now.Subtract(Convert.ToDateTime(paytime)).TotalHours;
  496. }
  497. else
  498. continue;
  499. DateTime nowtime = DateTime.Now;
  500. if (hour > 18)
  501. {
  502. tLst.Add("'" + dr["ctid"].ToString() + "'");
  503. }
  504. //if (hour > 72 && Convert.ToInt32(dr["ShopId"])==34)//公司自用
  505. //{
  506. // tLst.Add("'" + dr["ctid"].ToString() + "'");
  507. //}
  508. //else if (nowtime.Hour >= 17)
  509. //{
  510. // if((dtPaytime.Hour >= 14 && dtPaytime.Hour < 17) || (dtPaytime.Hour == 17 && dtPaytime.Minute < 40))
  511. // {
  512. // string sptime = nowtime.Year + "/" + nowtime.Month + "/" + nowtime.Day + " 17:40:00";
  513. // DateTime spDatetime = Convert.ToDateTime(sptime);
  514. // if (spDatetime.Subtract(Convert.ToDateTime(paytime)).TotalMinutes > 0)
  515. // {
  516. // tLst.Add("'" + dr["ctid"].ToString() + "'");
  517. // }
  518. // }
  519. //}
  520. //else if (nowtime.Hour >= 14)
  521. //{
  522. // if(dtPaytime.Hour >= 10 && dtPaytime.Hour < 14)
  523. // {
  524. // string sptime = nowtime.Year + "/" + nowtime.Month + "/" + nowtime.Day + " 14:00:00";
  525. // DateTime spDatetime = Convert.ToDateTime(sptime);
  526. // if (spDatetime.Subtract(Convert.ToDateTime(paytime)).TotalMinutes > 0)
  527. // {
  528. // tLst.Add("'" + dr["ctid"].ToString() + "'");
  529. // }
  530. // }
  531. //}
  532. //else if (nowtime.Hour >= 10)
  533. //{
  534. // if (dtPaytime.Hour >= 18 || dtPaytime.Hour < 10)
  535. // {
  536. // string sptime = nowtime.Year + "/" + nowtime.Month + "/" + nowtime.Day + " 10:00:00";
  537. // DateTime spDatetime = Convert.ToDateTime(sptime);
  538. // if (spDatetime.Subtract(Convert.ToDateTime(paytime)).TotalMinutes > 0)
  539. // {
  540. // tLst.Add("'" + dr["ctid"].ToString() + "'");
  541. // }
  542. // }
  543. //}
  544. }
  545. }
  546. if (tLst.Count > 0)
  547. {
  548. string needctids = string.Join(",", tLst.ToArray());
  549. StringBuilder updsql = new StringBuilder();
  550. //DateTime unusualTime = new DateTime();
  551. updsql.AppendFormat("update ce_erptradecell with(rowlock) set unusualTag=5,UnusualTime=getDate() where ctid in ({0});", needctids);
  552. DbHelper.DbConn.ExecuteNonQuery(updsql.ToString());
  553. }
  554. }
  555. catch (Exception ex)
  556. {
  557. XLog.SaveLog(0, "更新发货异常订单错误:" + ex.Message);
  558. }
  559. splitCell2AllPlaceOrder();
  560. }
  561. public static void splitCell2AllPlaceOrder()
  562. {
  563. //
  564. int spid = 0;
  565. try
  566. {
  567. StringBuilder sql = new StringBuilder();
  568. sql.AppendFormat("select * from CE_ErpTradeCell2 where DATEDIFF(DAY, FinishPlaceTime, GETDATE())<5 and MakeSupplier like '%,%';");
  569. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  570. List<string> idList = new List<string>();
  571. foreach (DataRow dr in dt.Rows)
  572. {
  573. string msup = dr["MakeSupplier"].ToString();
  574. string[] suplist = msup.Split(',');
  575. spid = Convert.ToInt32(dr["ID"]);
  576. foreach (string supItem in suplist)
  577. {
  578. StringBuilder newsql = new StringBuilder();
  579. newsql.AppendFormat(" insert into CE_ErpTradeCell2 ([ctid],[tid],[DesignUserId],[OrderState],[CustomerUserId],[IsUrgency],[IsRefund],[IsReturn],[IsNeedBill]," +
  580. "[SupplierId],[DeliveryAddress],[CallTimes],[NoteTimes],[OvertimeUserId],[UnusualTag],[UnusualCon],[ReturnReason],[MemoOpt],[AfterSaleTime],[AfterSaleUserId]," +
  581. "[AfterSaleReason],[PlaceUserId],[AfterSaleState],[AfterSaleMethod],[AfterSaleMemo],[AfterSaleResponsible],[AfterSalePreTime],[FinishAfterSaleTime],[DeductFee]," +
  582. "[RefundFee],[HandleTime],[IsHaveNewOrder],[ResponsibleUserId],[ptid],[IsPreDelivery],[IsSample],[seller_memo],[ProductId],[WaitDesignTime],[StartDesignTime]," +
  583. "[FinishDesignTime],[FinishPlaceTime],[FinishDeliveryTime],[DesignSelfMemo],[DesignPrice],[Material],[Craft],[ProductSize],[ProductCount],[UnusualTime],[IsAutoDispatch]," +
  584. "[IsVerifyToSupplier],[CustomerMemo],[payment],[OutSid],[AfterSalePayment],[ShopId],[SplitTag],[isAfterSaleOrder],[isDianziOrder],[LastBillCpCode],[LastBillWaybillCode]," +
  585. "[pay_time],[IsSF],[IsXianHuo],[ReturnTime],[OtherMemo],[AfterSaleBackReason],[CheckMemo],[IsOldCustomer],[IsSupplierRefund],[IsReadTag],[AfterSaleMemoType]," +
  586. "[UrgencyTime],[IsOffLineOrder],[PayProofImg],[wechatTag],[MakeSupplier]) select [ctid],[tid],[DesignUserId],[OrderState],[CustomerUserId],[IsUrgency],[IsRefund]," +
  587. "[IsReturn],[IsNeedBill],[SupplierId],[DeliveryAddress],[CallTimes],[NoteTimes],[OvertimeUserId],[UnusualTag],[UnusualCon],[ReturnReason],[MemoOpt],[AfterSaleTime]," +
  588. "[AfterSaleUserId],[AfterSaleReason],[PlaceUserId],[AfterSaleState],[AfterSaleMethod],[AfterSaleMemo],[AfterSaleResponsible],[AfterSalePreTime],[FinishAfterSaleTime]," +
  589. "[DeductFee],[RefundFee],[HandleTime],[IsHaveNewOrder],[ResponsibleUserId],[ptid],[IsPreDelivery],[IsSample],[seller_memo],[ProductId],[WaitDesignTime],[StartDesignTime]," +
  590. "[FinishDesignTime],[FinishPlaceTime],[FinishDeliveryTime],[DesignSelfMemo],[DesignPrice],[Material],[Craft],[ProductSize],[ProductCount],[UnusualTime],[IsAutoDispatch]," +
  591. "[IsVerifyToSupplier],[CustomerMemo],[payment],[OutSid],[AfterSalePayment],[ShopId],[SplitTag],[isAfterSaleOrder],[isDianziOrder],[LastBillCpCode],[LastBillWaybillCode]," +
  592. "[pay_time],[IsSF],[IsXianHuo],[ReturnTime],[OtherMemo],[AfterSaleBackReason],[CheckMemo],[IsOldCustomer],[IsSupplierRefund],[IsReadTag],[AfterSaleMemoType],[UrgencyTime]," +
  593. "[IsOffLineOrder],[PayProofImg],[wechatTag],'{1}' from CE_ErpTradeCell2 where ID={0}", Convert.ToInt32(dr["ID"]), supItem);
  594. DbHelper.DbConn.ExecuteNonQuery(newsql.ToString());
  595. }
  596. idList.Add(dr["ID"].ToString());
  597. }
  598. string idsstr = string.Join(",", idList.ToArray());
  599. sql.AppendFormat("delete from CE_ErpTradeCell2 where ID in ({0})", idsstr);
  600. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  601. }
  602. catch (Exception ex)
  603. {
  604. XLog.SaveLog(0, "拆分ce_erptradecell2表的制作车间出错:" + spid + ex.Message);
  605. }
  606. }
  607. public static void DoAutoDispatch(string conn)
  608. {
  609. if (webConfig.Dispatch_TimeList.Contains(DateTime.Now.ToString("HH:mm")))
  610. {
  611. WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "开始自动派单!"));
  612. SqlParameter[] sqlParameter ={
  613. new SqlParameter("@res", SqlDbType.VarChar, 50)};
  614. sqlParameter[0].Direction = ParameterDirection.Output;
  615. CeErpOpt.ExecuteNonQueryStore("sp_autodispatch", sqlParameter);
  616. string res = sqlParameter[0].Value.ToString();
  617. if (res == "派单完成") WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "结束自动派单!"));
  618. else WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "无法成功派单"));
  619. }
  620. //sp_autodispatch
  621. }
  622. public static void DoAutoDispatch2(string conn)
  623. {
  624. if (webConfig.Dispatch_TimeList.Contains(DateTime.Now.ToString("HH:mm")))
  625. {
  626. WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "开始自动派单!"));
  627. SqlConnection sqlCnt = new SqlConnection(conn);
  628. try
  629. {
  630. sqlCnt.Open();
  631. string sql = "select * from view_ErpTradeCell where OrderState = 2 and ProductId <> 0";
  632. SqlDataAdapter myDataAdapter = new SqlDataAdapter(sql, sqlCnt);
  633. DataSet myDataSet = new DataSet();
  634. myDataAdapter.Fill(myDataSet, "Trade");
  635. DataTable myTable = myDataSet.Tables[0];
  636. List<string> ids = new List<string>();
  637. foreach (DataRow Dr in myTable.Rows)
  638. {
  639. if (Convert.ToInt32(Dr["OrderState"]) > 2 || Convert.ToInt32(Dr["DesignUserId"]) > 0)
  640. {
  641. continue;
  642. }
  643. ids.Add(Dr["ctid"].ToString());
  644. CeErpShop nShop = CeErpShop.GetShopIdByName(Dr["seller_nick"].ToString());
  645. string shopId = "0";
  646. if (nShop != null)
  647. {
  648. shopId = nShop.ID.ToString();
  649. }
  650. string proId = Dr["ProductId"].ToString();
  651. string Amount = Dr["payment"].ToString();
  652. string ctid = Dr["ctid"].ToString();
  653. string ctids = "";
  654. if (ctid.IndexOf("C") != -1)
  655. {
  656. ctids = getSameTradeByTid(Dr["tid"].ToString());
  657. if (ctids.Length <= 0)
  658. {
  659. continue;
  660. }
  661. }
  662. else
  663. {
  664. ctids = "'" + ctid + "'";
  665. }
  666. sql = "select top 1 * from view_ErpUser " +
  667. "where PostCode = 'Designer' and " + //设计师
  668. "OnDuty = 1 and " + //上班状态
  669. "DayOrderReceive < DayOrderLimit and " + //当日接单数小于可接单数量上限
  670. "OrderAmountLimit >= " + Amount + " and " + //额度上限大于付款金额
  671. "CHARINDEX('," + shopId + ",',','+OrgShop+ ',')>0 and " + //部门关联店铺
  672. "CHARINDEX('," + shopId + ",',','+pemShop+ ',')>0 and " + //个人关联店铺
  673. "CHARINDEX('," + proId + ",',','+pemDesign+ ',')>0 " + //个人关联产品
  674. "order by DayOrderPer, PostLevel desc, Id";
  675. SqlDataAdapter userAdapter = new SqlDataAdapter(sql, sqlCnt);
  676. DataSet userSet = new DataSet();
  677. userAdapter.Fill(userSet, "user");
  678. DataTable userTable = userSet.Tables[0];
  679. //有满足条件的设计师
  680. if (userTable.Rows.Count > 0)
  681. {
  682. SqlCommand updCMD = sqlCnt.CreateCommand();
  683. try
  684. {
  685. updCMD.Transaction = sqlCnt.BeginTransaction();//开启事务
  686. //派单
  687. updCMD.CommandText = "update CE_ErpTradeCell set OrderState = 3, IsAutoDispatch = 1, WaitDesignTime = getdate(), DesignUserId = " + userTable.Rows[0]["ID"].ToString() + " where ctid in (" + ctids + ")";
  688. updCMD.ExecuteNonQuery();
  689. //更新日数量上限和可接单比例
  690. 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();
  691. updCMD.ExecuteNonQuery();
  692. //写订单日志
  693. updCMD.CommandText = "insert into CE_ErpTradeLog(tid,OrderState,UserId,OperateTime,Con) select ctid,OrderState,0,getdate(),'自动派单' from ce_erptradecell where ctid in(" + ctids + ")";
  694. updCMD.ExecuteNonQuery();
  695. updCMD.Transaction.Commit();//提交事务(真正的从数据库中修改了数据)
  696. }
  697. catch (Exception ee)
  698. {
  699. updCMD.Transaction.Rollback();
  700. }
  701. }
  702. }
  703. string sql1 = "select ctid from view_ErpTradeCell where orderstate=3 and DesignUserId = 2125 and ctid in ('" + string.Join(",", ids) + "');";
  704. /* string sql1 = "select ctid from view_ErpTradeCell where orderstate=3 and DesignUserId = 2125 ";*/
  705. DataTable dt1 = SqlHelper.ExecuteDataSet(sql1).Tables[0];
  706. foreach (DataRow dr1 in dt1.Rows)
  707. {
  708. apiDesign.API_GetPrintData_CreateOrder(CeErpTradeCell.GetByCtid(dr1["ctid"].ToString()));
  709. WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "开始派单" + dr1["ctid"].ToString() + "至设计系统!"));
  710. Thread.Sleep(1000); // 添加五秒延迟
  711. }
  712. WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), "结束自动派单!"));
  713. }
  714. catch (Exception ed)
  715. {
  716. WriteLog(string.Format("派单 | {0} | {1}", DateTime.Now.ToString(), ed.Message));
  717. }
  718. finally
  719. {
  720. if (sqlCnt.State == ConnectionState.Open)
  721. sqlCnt.Close();
  722. }
  723. }
  724. }
  725. public static string getSameTradeByTid(string tid)
  726. {
  727. StringBuilder sql = new StringBuilder();
  728. sql.AppendFormat("select ctid from view_ErpTradeCell where tid='{0}';", tid);
  729. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  730. if (dt.Rows.Count > 0)
  731. {
  732. string ctids = "";
  733. foreach (DataRow dr in dt.Rows)
  734. {
  735. ctids += "'";
  736. ctids += dr["ctid"].ToString();
  737. ctids += "'";
  738. ctids += ",";
  739. }
  740. ctids = ctids.Substring(0, ctids.Length - 1);
  741. return ctids;
  742. }
  743. else
  744. return "";
  745. }
  746. public static void WriteLog(string LogText)
  747. {
  748. string sDir = System.IO.Path.GetTempPath() + @"Log\" + DateTime.Now.ToString("yyyyMM");
  749. if (!Directory.Exists(sDir))
  750. Directory.CreateDirectory(sDir);
  751. using (StreamWriter sw = new StreamWriter(sDir + @"\Log_" + DateTime.Now.ToString("dd") + ".txt", true, Encoding.UTF8))
  752. {
  753. sw.Write(LogText + System.Environment.NewLine);
  754. }
  755. }
  756. public static void UpdateRelationOrder(string ctid)
  757. {
  758. if (ctid.Length <= 0) return;
  759. CeErpTradeCell.UpdateRelationOrder(ctid);
  760. //try
  761. //{
  762. // //父订单变化,更新补差价订单
  763. // //List<string> lw = new List<string>();
  764. // //lw.Add(string.Format("OrderState={0}", father.OrderState));
  765. // //lw.Add(string.Format("CustomerUserId={0}", father.CustomerUserId));
  766. // //lw.Add(string.Format("DesignUserId={0}", father.DesignUserId));
  767. // //lw.Add(string.Format("AfterSaleState={0}", father.AfterSaleState));
  768. // //lw.Add(string.Format("IsNeedBill={0}", father.IsNeedBill));
  769. // ////lw.Add(string.Format("IsUrgency={0}", father.IsUrgency == true ? 1 : 0));
  770. // //lw.Add(string.Format("IsRefund={0}", father.IsRefund));
  771. // //lw.Add(string.Format("WaitDesignTime='{0}'", father.WaitDesignTime.ToString()));
  772. // //lw.Add(string.Format("StartDesignTime='{0}'", father.StartDesignTime.ToString()));
  773. // //lw.Add(string.Format("FinishDesignTime='{0}'", father.FinishDesignTime.ToString()));
  774. // //lw.Add(string.Format("FinishPlaceTime='{0}'", father.FinishPlaceTime.ToString()));
  775. // //lw.Add(string.Format("FinishDeliveryTime='{0}'", father.FinishDeliveryTime.ToString()));
  776. // ////lw.Add(string.Format("IsReturn={0}", father.IsReturn));
  777. // //string sqlstr = string.Join(" , ", lw.ToArray());
  778. // //StringBuilder sql = new StringBuilder();
  779. // //sql.AppendFormat("update ce_erptradecell set " + sqlstr + " where ptid='{0}'", father.tid);
  780. // ////sql.AppendFormat("update view_erptrade set status={1} where ptid={0}", father.ctid, father.status);
  781. // //DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  782. // //StringBuilder sql = new StringBuilder();
  783. // //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,");
  784. // //sql.Append("AfterSaleState=b.AfterSaleState,IsNeedBill=b.IsNeedBill,IsRefund=b.IsRefund from ce_erptradecell,ce_erptradecell as b ");
  785. // //sql.AppendFormat("where ce_erptradecell.ptid =b.tid and ce_erptradecell.ptid='{0}'", tid);//='1827905618077154637'
  786. // //DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  787. // //SqlParameter[] sqlParameter ={
  788. // // new SqlParameter("@mainctids", SqlDbType.VarChar,100),
  789. // // new SqlParameter("@res", SqlDbType.VarChar, 4000)
  790. // //};
  791. // //sqlParameter[0].Value = ctid;
  792. // //sqlParameter[1].Direction = ParameterDirection.Output;
  793. // //DbHelper.DbConn.ExecuteNonQuery(CommandType.StoredProcedure, "sp_set_bucha", sqlParameter);
  794. //}
  795. //catch (Exception ex)
  796. //{
  797. // XLog.SaveLog(0, "commmonHelper:UpdateRelationOrder" + ex.Message);
  798. //}
  799. }
  800. public static void UpdateSameOrderToDesigner(CeErpTradeCell entity, int designId)
  801. {
  802. CeErpTrade trade = CeErpTrade.Get(entity.tid);
  803. if (trade != null)
  804. {
  805. StringBuilder sql = new StringBuilder();
  806. if (trade.type == "PDD" || trade.type == "JD")
  807. {
  808. 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);
  809. }
  810. else
  811. 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);
  812. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  813. }
  814. }
  815. public static void SetSameSupplierToOrder(CeErpTradeCell entity, int supId)
  816. {
  817. StringBuilder sql = new StringBuilder();
  818. sql.AppendFormat("update CE_ErpTradeCell with(rowlock) set SupplierId={0} where orderstate=5 and tid='{1}';", supId, entity.tid);
  819. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  820. }
  821. public static string MidStrEx(string sourse, string startstr, string endstr)
  822. {
  823. string result = string.Empty;
  824. int startindex, endindex;
  825. try
  826. {
  827. startindex = sourse.IndexOf(startstr);
  828. if (startindex == -1)
  829. return result;
  830. string tmpstr = sourse.Substring(startindex + startstr.Length);
  831. endindex = tmpstr.IndexOf(endstr);
  832. if (endindex == -1)
  833. return result;
  834. result = tmpstr.Remove(endindex);
  835. }
  836. catch (Exception ex)
  837. {
  838. Console.WriteLine("MidStrEx Err:" + ex.Message);
  839. }
  840. return result;
  841. }
  842. public static string KeepChinese(string str)
  843. {
  844. string chineseString = "";
  845. for (int i = 0; i < str.Length; i++)
  846. {
  847. if (str[i] >= 0x4E00 && str[i] <= 0x9FA5)
  848. {
  849. chineseString += str[i];
  850. }
  851. }
  852. return chineseString;
  853. }
  854. public static string GetD3ComCode(string code, string name)
  855. {
  856. string useStr = code;
  857. if (code.Length == 0)
  858. {
  859. useStr = name;
  860. }
  861. string sql = "select * from CE_ErpMailInfo";
  862. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  863. foreach (DataRow dr in dt.Rows)
  864. {
  865. if (dr["cpCode"].ToString().IndexOf(useStr) != -1)
  866. {
  867. return dr["cpCode"].ToString();
  868. }
  869. }
  870. //声明存储结果的字符串
  871. //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," +
  872. // "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," +
  873. // "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," +
  874. // "YUNDA-CAINIAO-JA,SF-CAINIAO-GDGZ,YUNDA-CAINIAO-GDFS,";
  875. //string[] codeList = codeStr.Split(',');
  876. ////将传入参数中的中文字符添加到结果字符串中
  877. //for (int i = 0; i < codeList.Length; i++)
  878. //{
  879. // if (codeList[i].IndexOf(useStr) != -1)
  880. // {
  881. // return codeList[i];
  882. // }
  883. //}
  884. //返回保留中文的处理结果
  885. return "";
  886. }
  887. public static int getRefundTagByState(string st, int isPart = 0)
  888. {
  889. int state = 0;
  890. if (st == "NO_REFUND" || st == "SELLER_REFUSE_BUYER" || st == "CLOSED" || st == "FAILED")
  891. {
  892. state = 0;
  893. }
  894. else if (st == "REFUNDING")
  895. {
  896. state = 1;
  897. }
  898. else if (st == "REFUNDED" || st == "SUCCESS")
  899. {
  900. state = 2;
  901. }
  902. else if (st == "PART_REFUNDED" || isPart == 1)
  903. {
  904. state = 3;
  905. }
  906. else if (st == "WAIT_BUYER_RETURN_GOODS")
  907. {
  908. state = 4;
  909. }
  910. else if (st == "REJECT_REFUNDED")
  911. {
  912. state = 5;
  913. }
  914. else if (st == "WAIT_SELLER_CONFIRM_GOODS")
  915. {
  916. state = 6;
  917. }
  918. return state;
  919. }
  920. public static string getRefundStringByState(string st)
  921. {
  922. string stateStr = "";
  923. if (st == "NOT_SHIPPED")
  924. {
  925. stateStr = "待发货";
  926. }
  927. else if (st == "PART_SHIPPED")
  928. {
  929. stateStr = "部分发货";
  930. }
  931. else if (st == "SHIPPED")
  932. {
  933. stateStr = "已发货";
  934. }
  935. else if (st == "COMPLETE")
  936. {
  937. stateStr = "已完成";
  938. }
  939. else if (st == "CLOSE")
  940. {
  941. stateStr = "已关闭";
  942. }
  943. else if (st == "REFUNDED")
  944. {
  945. stateStr = "退款成功";
  946. }
  947. else if (st == "PART_REFUNDED")
  948. {
  949. stateStr = "部分退款";
  950. }
  951. else if (st == "WAIT_BUYER_RETURN_GOODS")
  952. {
  953. stateStr = "等待买家退货";
  954. }
  955. else if (st == "REJECT_REFUNDED")
  956. {
  957. stateStr = "拒绝退货";
  958. }
  959. else if (st == "WAIT_SELLER_CONFIRM_GOODS")
  960. {
  961. stateStr = "等待卖家确认收货";
  962. }
  963. else if (st == "SELLER_REFUSE_BUYER")
  964. {
  965. stateStr = "卖家拒绝退款";
  966. }
  967. else if (st == "SUCCESS")
  968. {
  969. stateStr = "退款成功";
  970. }
  971. else if (st == "CLOSED")
  972. {
  973. stateStr = "退款关闭";
  974. }
  975. else if (st == "FAILED")
  976. {
  977. stateStr = "退款失败";
  978. }
  979. return stateStr;
  980. }
  981. public static void UpdateRefundOrderState(string tid, int rstate)
  982. {
  983. StringBuilder sql = new StringBuilder();
  984. sql.AppendFormat("insert into S_BuChaJia(ctid,addtime,dotype,refundState) values('{0}',getdate(),'refund',{1}); ", tid, rstate);
  985. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  986. }
  987. public static void checkBillResult(int billId)
  988. {
  989. CeErpBill entiy = CeErpBill.Get(billId);
  990. if (entiy != null)
  991. {
  992. try
  993. {
  994. string[] billOrderList = entiy.billOrderId.Split(',');
  995. int iTag = 0;
  996. entiy.fplsh = "";
  997. entiy.fpdm = "";
  998. entiy.fphm = "";
  999. foreach (string billOrderId in billOrderList)
  1000. {
  1001. iTag++;
  1002. string res = taobaoHelper.get_invoicing(billId.ToString(), billOrderId);
  1003. int fcount = StrCount(res, "c_orderno");
  1004. if (res.IndexOf("success") != -1 && res.IndexOf("开票中") != -1)
  1005. {
  1006. StringBuilder sql = new StringBuilder();
  1007. sql.AppendFormat("insert into S_BuChaJia(ctid,addtime,dotype) values('{0}',getdate(),'billres'); ", billId.ToString());
  1008. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  1009. return;
  1010. }
  1011. else if (res.IndexOf("success") != -1 && (res.IndexOf("开票成功") != -1 || res.IndexOf("开票完成") != -1))
  1012. {
  1013. //res = GetUTF8String2(Encoding.UTF8.GetBytes(res));
  1014. try
  1015. {
  1016. Invoicing_get_response_Obj iObj = null;
  1017. iObj = JsonConvert.DeserializeObject<Invoicing_get_response_Obj>(res);
  1018. if (iObj != null)
  1019. {
  1020. if (fcount > 1)
  1021. {
  1022. entiy.state = 4; //红冲作废
  1023. }
  1024. else
  1025. entiy.state = 2; //开票完成
  1026. entiy.fplsh += iObj.list[0].c_fpqqlsh;
  1027. entiy.fpdm += iObj.list[0].c_fpdm;
  1028. entiy.fphm += iObj.list[0].c_fphm;
  1029. if (iTag < billOrderList.Length)
  1030. {
  1031. entiy.fplsh += ",";
  1032. entiy.fpdm += ",";
  1033. entiy.fphm += ",";
  1034. }
  1035. entiy.Update();
  1036. }
  1037. if (fcount <= 1)
  1038. {
  1039. StringBuilder sql = new StringBuilder();
  1040. sql.AppendFormat("update CE_ErpTradeCell WITH(ROWLOCK) set IsNeedBill=2 where tid='{0}';", entiy.tid);
  1041. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  1042. }
  1043. }
  1044. catch (Exception ex)
  1045. {
  1046. StringBuilder sql = new StringBuilder();
  1047. sql.AppendFormat("insert into S_BuChaJia(ctid,addtime,dotype) values('{0}',getdate(),'billres'); ", billId.ToString());
  1048. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  1049. XLog.SaveLog(0, "查看开票结果,更新状态失败" + ex.Message + res);
  1050. }
  1051. return;
  1052. }
  1053. else
  1054. {
  1055. string redError = "";
  1056. if (fcount > 1)
  1057. {
  1058. redError = "红冲失败";
  1059. }
  1060. int eidx = res.IndexOf("c_resultmsg");
  1061. string emsg = KeepChinese(res.Substring(eidx, res.Length - eidx));
  1062. //开票失败
  1063. entiy.state = 5;
  1064. entiy.failerror = entiy.failerror + (iTag + "&" + redError + emsg + "|");
  1065. entiy.Update();
  1066. return;
  1067. }
  1068. }
  1069. }
  1070. catch (Exception ex)
  1071. {
  1072. XLog.SaveLog(0, "buchajia查看开票结果错误," + ex.Message);
  1073. }
  1074. }
  1075. }
  1076. public static void insertToBuchaForDelivery(string Maintid, string posCode, string comCode, string outSid)
  1077. {
  1078. if (Maintid.Length <= 0) return;
  1079. try
  1080. {
  1081. StringBuilder sql = new StringBuilder();
  1082. 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);
  1083. DbHelper.DbConn.ExecuteNonQuery(sql.ToString());
  1084. //}
  1085. }
  1086. catch (Exception ex)
  1087. {
  1088. XLog.SaveLog(0, "commhelper,insertToBuchaForDelivery,insert" + ex.Message);
  1089. //}
  1090. }
  1091. }
  1092. public static void setBuChaDelivery(string tid, string posCode, string comCode, string outSid)
  1093. {
  1094. outSid = outSid.Trim();
  1095. posCode = posCode.Trim();
  1096. comCode = comCode.Trim();
  1097. CeErpTrade mainEn = CeErpTrade.Get(tid);
  1098. if (mainEn != null)
  1099. {
  1100. if (mainEn.status == "SHIPPED" || mainEn.status == "PART_SHIPPED" || mainEn.status == "COMPLETE" || mainEn.status == "CLOSE") //已发货的不处理直接返回面单
  1101. {
  1102. return;
  1103. //不处理
  1104. }
  1105. string apires = apiHelper.API_LogisticsDummySend(tid, posCode);
  1106. if (apires.IndexOf("发货成功") == -1)
  1107. {
  1108. XLog.SaveLog(0, "补差价单虚拟发货失败," + tid + "," + posCode + "," + apires);
  1109. string wures = apiHelper.API_LogisticsOnlineSend(tid, posCode, comCode, outSid);
  1110. if (wures.IndexOf("发货成功") == -1)
  1111. {
  1112. XLog.SaveLog(0, "补差价单实物发货失败," + tid + "," + posCode + "," + wures);
  1113. return;
  1114. }
  1115. else
  1116. {
  1117. LogHelper.addLog(tid, 0, "补差价发货-" + comCode + "-" + outSid);
  1118. }
  1119. return;
  1120. }
  1121. else
  1122. {
  1123. LogHelper.addLog(tid, 0, "补差价发货-" + comCode + "-" + outSid);
  1124. }
  1125. }
  1126. }
  1127. public static int StrCount(string str, string constr)
  1128. {
  1129. return System.Text.RegularExpressions.Regex.Matches(str, constr).Count;
  1130. }
  1131. public static void saveErpDesignerGather()
  1132. {
  1133. string date1 = DateTime.Now.AddDays(-1).ToString();
  1134. string date2 = DateTime.Now.AddDays(-1).ToString();
  1135. //string date1 = DateTime.Now.ToString();
  1136. //string date2 = DateTime.Now.ToString();
  1137. StringBuilder sql = new StringBuilder();
  1138. 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);
  1139. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  1140. foreach (DataRow dr in dt.Rows)
  1141. {
  1142. SqlParameter[] sqlParameter ={
  1143. new SqlParameter("@sDisDate", SqlDbType.DateTime, 20),
  1144. new SqlParameter("@eDisDate", SqlDbType.DateTime, 20),
  1145. new SqlParameter("@designid", SqlDbType.Int, 4)
  1146. };
  1147. sqlParameter[0].Value = date1;
  1148. sqlParameter[1].Value = date2;
  1149. sqlParameter[2].Value = Convert.ToInt32(dr["ID"]);
  1150. //CeErpTradeCell.ExecuteNonQueryStore("sp_getdesigngather", sqlParameter);
  1151. DbHelper.DbConn.ExecuteNonQuery(CommandType.StoredProcedure, "sp_savedesigngather", sqlParameter);
  1152. }
  1153. new_Designer_Rate(date1);
  1154. }
  1155. public static void new_Designer_Rate(String date1)
  1156. {
  1157. /*String date1 = DateTime.Now.ToString();*/
  1158. /* if (date1 ==null) {
  1159. date1 = DateTime.Now.ToString();
  1160. }*/
  1161. DateTime currentDate = DateTime.Parse(date1);
  1162. // 获取指定日期的开始时间
  1163. DateTime startTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 0, 0, 0);//日
  1164. // 获取指定日期的结束时间(即下一天的开始时间,减去1秒)
  1165. DateTime endTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 23, 59, 59).AddSeconds(-1);//日
  1166. DateTime now = DateTime.Now; // 获取当前日期和时间
  1167. DateTime dateOnly = now.Date; // 限制日期为年月日
  1168. StringBuilder sql = new StringBuilder();
  1169. CeErpDesignerFinishRateNew.Del(startTime.ToString("yyyy-MM-dd HH:mm:ss"));
  1170. 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"));
  1171. DataTable dt = DbHelper.DbConn.ExecuteDataset(sql.ToString()).Tables[0];
  1172. foreach (DataRow dr in dt.Rows)
  1173. {
  1174. CeErpDesignerFinishRateNew ceErpDesignerFinishRateNew = new CeErpDesignerFinishRateNew();
  1175. if (!Convert.IsDBNull(dr["DesignUserId"]))
  1176. {
  1177. ceErpDesignerFinishRateNew.did = Convert.ToInt32(dr["DesignUserId"] == null ? 0 : dr["DesignUserId"]);
  1178. }
  1179. if (!Convert.IsDBNull(dr["OrgID"]))
  1180. {
  1181. ceErpDesignerFinishRateNew.orgid = Convert.ToInt32(dr["OrgID"] == null ? 0 : dr["OrgID"]);
  1182. }
  1183. if (!Convert.IsDBNull(dr["DesignerName"]))
  1184. {
  1185. ceErpDesignerFinishRateNew.name = dr["DesignerName"].ToString() == null ? "" : dr["DesignerName"].ToString();
  1186. }
  1187. if (!Convert.IsDBNull(dr["Amount"]))
  1188. {
  1189. ceErpDesignerFinishRateNew.Amount = dr["Amount"].ToString() == null ? "" : dr["Amount"].ToString();
  1190. }
  1191. if (!Convert.IsDBNull(dr["AllOrder"]))
  1192. {
  1193. ceErpDesignerFinishRateNew.AllOrder = Convert.ToInt32(dr["AllOrder"] == null ? 0 : dr["AllOrder"]);
  1194. }
  1195. if (!Convert.IsDBNull(dr["FinalizationRate"]))
  1196. {
  1197. ceErpDesignerFinishRateNew.FinalizationRate = Convert.ToInt32(dr["FinalizationRate"] == null ? 0 : dr["FinalizationRate"]);
  1198. }
  1199. if (!Convert.IsDBNull(dr["afterSaleSum"]))
  1200. {
  1201. ceErpDesignerFinishRateNew.afterSaleSum = Convert.ToInt32(dr["afterSaleSum"] == null ? 0 : dr["afterSaleSum"]);
  1202. }
  1203. if (!Convert.IsDBNull(dr["resolutionSum"]))
  1204. {
  1205. ceErpDesignerFinishRateNew.resolutionSum = Convert.ToInt32(dr["resolutionSum"] == null ? 0 : dr["resolutionSum"]);
  1206. }
  1207. if (!Convert.IsDBNull(dr["splitSum"]))
  1208. {
  1209. ceErpDesignerFinishRateNew.splitSum = Convert.ToInt32(dr["splitSum"] == null ? 0 : dr["splitSum"]);
  1210. }
  1211. if (!Convert.IsDBNull(dr["splitSum2"]))
  1212. {
  1213. ceErpDesignerFinishRateNew.csplitum = Convert.ToInt32(dr["splitSum2"] == null ? 0 : dr["splitSum2"]);
  1214. }
  1215. if (!Convert.IsDBNull(dr["FinalizationRate2"]))
  1216. {
  1217. ceErpDesignerFinishRateNew.FinalizationRate2 = Convert.ToInt32(dr["FinalizationRate2"] == null ? 0 : dr["FinalizationRate2"]);
  1218. }
  1219. if (!Convert.IsDBNull(dr["AllOrder"]) && !Convert.IsDBNull(dr["FinalizationRate"]) && !Convert.IsDBNull(dr["splitSum2"]) && !Convert.IsDBNull(dr["splitSum"]))
  1220. {
  1221. try
  1222. {
  1223. int num1 = Convert.ToInt32(dr["FinalizationRate"]) + Convert.ToInt32(dr["splitSum"]);
  1224. int num2 = Convert.ToInt32(dr["AllOrder"]) + Convert.ToInt32(dr["splitSum2"]);
  1225. if (num2 != 0)
  1226. {
  1227. double result = (double)num1 / num2;
  1228. if (double.IsNaN(result))
  1229. {
  1230. result = 0;
  1231. }
  1232. double roundedResult = Math.Round(result, 4);
  1233. ceErpDesignerFinishRateNew.onFinalizationRate = roundedResult.ToString();
  1234. int num3 = Convert.ToInt32(dr["refund"]);
  1235. double result2 = (double)num3 / num2;
  1236. if (double.IsNaN(result2))
  1237. {
  1238. result2 = 0;
  1239. }
  1240. double roundedResult2 = Math.Round(result2, 4);
  1241. ceErpDesignerFinishRateNew.onRefund = roundedResult2.ToString();
  1242. }
  1243. else
  1244. {
  1245. ceErpDesignerFinishRateNew.onFinalizationRate = "0.0000";
  1246. ceErpDesignerFinishRateNew.onRefund = "0.0000";
  1247. }
  1248. }
  1249. catch (Exception ex)
  1250. {
  1251. ceErpDesignerFinishRateNew.onFinalizationRate = "0";
  1252. }
  1253. }
  1254. ceErpDesignerFinishRateNew.ctime = startTime;
  1255. ceErpDesignerFinishRateNew.Createtime = now;
  1256. if (!Convert.IsDBNull(dr["refund"]))
  1257. {
  1258. ceErpDesignerFinishRateNew.refund = Convert.ToInt32(dr["refund"] == null ? 0 : dr["refund"]);
  1259. }
  1260. ceErpDesignerFinishRateNew.Create();
  1261. }
  1262. }
  1263. public static DateTime FirstDayOfMonth(DateTime datetime)
  1264. {
  1265. return datetime.AddDays(1 - datetime.Day);
  1266. }
  1267. public static DateTime LastDayOfMonth(DateTime datetime)
  1268. {
  1269. return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
  1270. }
  1271. public static DateTime GetDateTimeWeekFirstDaySun(DateTime dateTime)
  1272. {
  1273. DateTime firstWeekDay = DateTime.Now;
  1274. try
  1275. {
  1276. //得到是星期几,然后从当前日期减去相应天数
  1277. int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
  1278. int daydiff = (-1) * weeknow;
  1279. firstWeekDay = dateTime.AddDays(daydiff);
  1280. }
  1281. catch { }
  1282. return firstWeekDay;
  1283. }
  1284. public static DateTime GetDateTimeWeekFirstDayMon(DateTime dateTime)
  1285. {
  1286. DateTime firstWeekDay = DateTime.Now;
  1287. try
  1288. {
  1289. int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
  1290. //星期一为第一天,weeknow等于0时,要向前推6天。
  1291. weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
  1292. int daydiff = (-1) * weeknow;
  1293. firstWeekDay = dateTime.AddDays(daydiff);
  1294. }
  1295. catch { }
  1296. return firstWeekDay;
  1297. }
  1298. public static DateTime GetDateTimeWeekLastDaySat(DateTime dateTime)
  1299. {
  1300. DateTime lastWeekDay = DateTime.Now;
  1301. try
  1302. {
  1303. int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
  1304. int daydiff = (7 - weeknow) - 1;
  1305. lastWeekDay = dateTime.AddDays(daydiff);
  1306. }
  1307. catch { }
  1308. return lastWeekDay;
  1309. }
  1310. public static DateTime GetDateTimeWeekLastDaySun(DateTime dateTime)
  1311. {
  1312. DateTime lastWeekDay = DateTime.Now;
  1313. try
  1314. {
  1315. int weeknow = Convert.ToInt32(dateTime.DayOfWeek);
  1316. weeknow = (weeknow == 0 ? 7 : weeknow);
  1317. int daydiff = (7 - weeknow);
  1318. lastWeekDay = dateTime.AddDays(daydiff);
  1319. }
  1320. catch { }
  1321. return lastWeekDay;
  1322. }
  1323. public static void updateOrderStateForShipped(string ctid, int ost, string stateType)
  1324. {
  1325. try
  1326. {
  1327. CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ctid);
  1328. if (entity != null)
  1329. {
  1330. if (entity.isAfterSaleOrder == 1) return;
  1331. if (stateType == "updatestate_complete")
  1332. {
  1333. if (entity.IsPreDelivery == 1) return;
  1334. entity.OrderState = 8;
  1335. entity.Update();
  1336. if (entity.ProductId == 9 || entity.ProductId == 17 || entity.ProductId == 20 || entity.ProductId == 29 || entity.ProductId == 30)//卡片、手提袋价格自动核算
  1337. {
  1338. CeErpDesignerBill.updateDesignerBill(entity.ctid, entity.ProductId);
  1339. LogHelper.addDesignerBillLog(entity.ctid, 0, "自动核算设计费", "系统", 1);
  1340. }
  1341. else if (entity.ProductId == 22)
  1342. {
  1343. CeErpDesignerBill.updateBill(entity.ctid, entity.ProductId, entity.seller_memo);
  1344. LogHelper.addDesignerBillLog(entity.ctid, 0, "自动核算设计费", "系统", 1);
  1345. }
  1346. }
  1347. else if (stateType == "updatestate_shipped")
  1348. {
  1349. if (entity.IsPreDelivery == 1) return;
  1350. entity.OrderState = 7;
  1351. entity.Update();
  1352. }
  1353. else if (stateType == "updatestate_close")
  1354. {
  1355. entity.OrderState = 9;
  1356. entity.Update();
  1357. }
  1358. }
  1359. else
  1360. {
  1361. StringBuilder sql = new StringBuilder();
  1362. sql.AppendFormat("insert into S_BuChaJia(ctid,orderState,dotype,addtime) values('{0}',{1},'{2}',getdate());", ctid, ost, stateType);
  1363. CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  1364. }
  1365. }
  1366. catch (Exception ex)
  1367. {
  1368. XLog.SaveLog(0, "updateOrderStateForShipped函数出错," + ctid + "," + ex.Message);
  1369. StringBuilder sql = new StringBuilder();
  1370. sql.AppendFormat("insert into S_BuChaJia(ctid,orderState,dotype,addtime) values('{0}',{1},'{2}',getdate());", ctid, ost, stateType);
  1371. CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  1372. }
  1373. }
  1374. public static string changeCountFromChiness(string countStr)
  1375. {
  1376. try
  1377. {
  1378. return handleProductCount(countStr).ToString();
  1379. }
  1380. catch (Exception ex)
  1381. {
  1382. return countStr;
  1383. }
  1384. }
  1385. public static int getIntCountFromString(string fstr)
  1386. {
  1387. try
  1388. {
  1389. string str = fstr;
  1390. string r = @"[0-9]+";
  1391. Regex reg = new Regex(r, RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromSeconds(2));//2秒后超时
  1392. MatchCollection mc = reg.Matches(str);//设定要查找的字符串
  1393. int count = 0;
  1394. foreach (Match m in mc)
  1395. {
  1396. string s = m.Groups[0].Value;
  1397. int cc = Convert.ToInt32(s);
  1398. if (count == 0)
  1399. {
  1400. count = cc;
  1401. }
  1402. else
  1403. {
  1404. count = count * cc;
  1405. }
  1406. }
  1407. return count;
  1408. }
  1409. catch (Exception ex)
  1410. {
  1411. return 0;
  1412. }
  1413. }
  1414. public static int getPlaceProductCount(string count_str)
  1415. {
  1416. count_str = count_str.Trim();
  1417. string[] count_list = count_str.Split(',');
  1418. int count = 0;
  1419. foreach (string item in count_list)
  1420. {
  1421. int tem_count = getSingleIntCountFromString(item);
  1422. if (tem_count > count)
  1423. {
  1424. count = tem_count;
  1425. }
  1426. }
  1427. return count;
  1428. }
  1429. public static int getSingleIntCountFromString(string fstr)
  1430. {
  1431. try
  1432. {
  1433. string str = fstr;
  1434. string r = @"[0-9]+";
  1435. Regex reg = new Regex(r, RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromSeconds(2));//2秒后超时
  1436. MatchCollection mc = reg.Matches(str);//设定要查找的字符串
  1437. if (mc.Count <= 0) return 0;
  1438. if (mc.Count == 1)
  1439. {
  1440. string s = mc[0].Groups[0].Value;
  1441. int cc = Convert.ToInt32(s);
  1442. return cc;
  1443. }
  1444. else if (mc.Count > 1)
  1445. {
  1446. string s = mc[1].Groups[0].Value;
  1447. int cc = Convert.ToInt32(s);
  1448. return cc;
  1449. }
  1450. //foreach (Match m in mc)
  1451. //{
  1452. // string s = m.Groups[0].Value;
  1453. // int cc = Convert.ToInt32(s);
  1454. // if (count == 0)
  1455. // {
  1456. // count = cc;
  1457. // }
  1458. // else
  1459. // {
  1460. // count = count * cc;
  1461. // }
  1462. //}
  1463. return 0;
  1464. }
  1465. catch (Exception ex)
  1466. {
  1467. return 0;
  1468. }
  1469. }
  1470. public static int handleProductCount(string pCount, bool isSingle = false)
  1471. {
  1472. string cstr = pCount;
  1473. if (cstr.IndexOf("百万") != -1)
  1474. {
  1475. cstr = cstr.Replace("百万", "000000");
  1476. }
  1477. else if (cstr.IndexOf("十万") != -1)
  1478. {
  1479. cstr = cstr.Replace("十万", "00000");
  1480. }
  1481. else if (cstr.IndexOf("万") != -1)
  1482. {
  1483. cstr = cstr.Replace("万", "0000");
  1484. }
  1485. else if (cstr.IndexOf("千") != -1)
  1486. {
  1487. cstr = cstr.Replace("千", "000");
  1488. }
  1489. else if (cstr.IndexOf("百") != -1)
  1490. {
  1491. cstr = cstr.Replace("百", "00");
  1492. }
  1493. else if (cstr.IndexOf("十") != -1)
  1494. {
  1495. cstr = cstr.Replace("十", "0");
  1496. }
  1497. int rCount = 0;
  1498. if (isSingle) rCount = getSingleIntCountFromString(cstr);
  1499. else rCount = getIntCountFromString(cstr);
  1500. return rCount;
  1501. }
  1502. public static decimal getOrderSizeFromString(string size)
  1503. {
  1504. string rsize = size.Replace("mm", "");
  1505. string[] sizeList = rsize.Split('x');
  1506. if (sizeList.Length != 2) return 0;
  1507. try
  1508. {
  1509. decimal mianji = Convert.ToDecimal(sizeList[0]) * Convert.ToDecimal(sizeList[1]);
  1510. return mianji;
  1511. }
  1512. catch (Exception ex)
  1513. {
  1514. return 0;
  1515. }
  1516. return 0;
  1517. }
  1518. public static string getDateFromString(string fstr)
  1519. {
  1520. try
  1521. {
  1522. string str = fstr;
  1523. string r = @"[0-9]+";
  1524. Regex reg = new Regex(r, RegexOptions.IgnoreCase | RegexOptions.Singleline, TimeSpan.FromSeconds(2));//2秒后超时
  1525. MatchCollection mc = reg.Matches(str);//设定要查找的字符串
  1526. if (mc.Count < 3) return "";
  1527. int tag = 0;
  1528. string datestr = "";
  1529. foreach (Match m in mc)
  1530. {
  1531. string s = m.Groups[0].Value;
  1532. datestr += s;
  1533. if (tag < 2) { datestr += "-"; }
  1534. else break;
  1535. tag++;
  1536. }
  1537. DateTime dd = Convert.ToDateTime(datestr);
  1538. return datestr;
  1539. }
  1540. catch (Exception ex)
  1541. {
  1542. return "";
  1543. }
  1544. }
  1545. public static void DeleteOriginalOrderIfIsSplitOrder(string tid, string splitTag)
  1546. {
  1547. if (splitTag.Length > 0)
  1548. {
  1549. CeErpTradeCell.DelByCtid(tid);
  1550. }
  1551. }
  1552. public static void setOrderDummyDelivery(string tid)
  1553. {
  1554. try
  1555. {
  1556. CeErpTrade trade = CeErpTrade.Get(tid);
  1557. if (trade != null)
  1558. {
  1559. string xuniapires = apiHelper.API_LogisticsDummySend(tid, trade.posCode);
  1560. if (xuniapires.IndexOf("成功") != -1)
  1561. {
  1562. LogHelper.addLog(tid, 0, "电子稿自动发货");
  1563. return;
  1564. }
  1565. else if (xuniapires.IndexOf("失败") != -1)
  1566. {
  1567. string chiness = KeepChinese(xuniapires);
  1568. XLog.SaveLog(0, "setOrderDummyDelivery虚拟发货失败," + tid + "," + chiness);
  1569. return;
  1570. }
  1571. }
  1572. }
  1573. catch (Exception ex)
  1574. {
  1575. XLog.SaveLog(0, "setOrderDummyDelivery虚拟发货出错," + tid + "," + ex.Message);
  1576. return;
  1577. }
  1578. }
  1579. public static designApiResponseVo checkOrderListDesignInfo(string tid)
  1580. {
  1581. if (string.IsNullOrEmpty(tid))
  1582. {
  1583. return new designApiResponseVo(-1, "无订单信息");
  1584. }
  1585. string info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}'", tid);
  1586. DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
  1587. string check_info = "无订单信息";
  1588. if (data.Rows.Count > 0)
  1589. {
  1590. bool need_send = false;
  1591. bool has_design = false;
  1592. foreach (DataRow row in data.Rows)
  1593. {
  1594. CeErpTradeCell cell = CeErpTradeCell.GetByCtid(row["ctid"].ToString());
  1595. if (cell != null)
  1596. {
  1597. if (cell.DesignUserId == 0 || cell.DispatchSort == 2)
  1598. {
  1599. designApiResponseVo result = checkOrderDesignInfo(cell, "");
  1600. check_info = result.msg;
  1601. if (result.code == 200)
  1602. {
  1603. need_send = true;
  1604. has_design = false;
  1605. }
  1606. }
  1607. else
  1608. {
  1609. has_design = true;
  1610. }
  1611. }
  1612. }
  1613. if (need_send && !has_design)
  1614. {
  1615. return new designApiResponseVo(200, "");
  1616. }
  1617. }
  1618. return new designApiResponseVo(-1, check_info);
  1619. }
  1620. public static designApiResponseVo checkOrderDesignInfo(CeErpTradeCell ceErpTradeCell, string post = "")
  1621. {
  1622. if (ceErpTradeCell.DispatchSort == 2)
  1623. {
  1624. return new designApiResponseVo(200, "");
  1625. }
  1626. if (ceErpTradeCell.ProductId == 0)
  1627. {
  1628. return new designApiResponseVo(-1, "订单无品类");
  1629. }
  1630. if (ceErpTradeCell.ProductId == 1797 && ceErpTradeCell.seller_memo.Contains("手绘"))
  1631. {
  1632. return new designApiResponseVo(200, "");
  1633. }
  1634. if (ceErpTradeCell.isDianziOrder == 1)
  1635. {
  1636. return new designApiResponseVo(200, "");
  1637. }
  1638. if ((post != "SysAdmin" && post != "Summarize"))
  1639. {
  1640. if (ceErpTradeCell.DesignUserId != 0 && ceErpTradeCell.DispatchSort != 2)
  1641. {
  1642. return new designApiResponseVo(-1, "已有设计师无法指派");
  1643. }
  1644. string info_sql = string.Format("SELECT count(*) as total FROM [dbo].[Ce_ErpDesignInfo] WHERE type = 1 and tarId = 3542 and shopId = {0}", ceErpTradeCell.ShopId);
  1645. DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
  1646. int a = Convert.ToInt32(data.Rows[0]["total"]);
  1647. bool drop = false;
  1648. if (DateTime.Now.Hour >= 17 && DateTime.Now.Hour <= 7 && ceErpTradeCell.ProductId == 29 && (ceErpTradeCell.ShopId == 14 || ceErpTradeCell.ShopId == 56))
  1649. {
  1650. drop = false;
  1651. }
  1652. if (!drop)
  1653. {
  1654. CeErpDesignInfo ceErpDesignInfo = CeErpDesignInfo.GetByShopDesign(3542, ceErpTradeCell.ShopId, ceErpTradeCell.ProductId);
  1655. if (ceErpDesignInfo == null)
  1656. {
  1657. return new designApiResponseVo(-1, "该店铺无该技能权限");
  1658. }
  1659. }
  1660. //卡片五款
  1661. if (ceErpTradeCell.ProductId == 29 && ceErpTradeCell.ShopId > 0)
  1662. {
  1663. bool num_bool = true;
  1664. bool size_bool = false;
  1665. int min_num = 2;
  1666. int num = 0;
  1667. if (a < 15)//限制不是全品的店铺限制
  1668. {
  1669. /*if (ceErpTradeCell.payment >= 500)
  1670. {
  1671. return new designApiResponseVo(-1, "订单价格超出");
  1672. }*/
  1673. string pattern = @"\b(\d{1,5}[x\*]\d{1,5}(mm|cm))\b";
  1674. string memo = ceErpTradeCell.seller_memo.Replace("MM", "mm").Replace("CM", "cm");
  1675. Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(2));//2秒后超时
  1676. MatchCollection matches = reg.Matches(memo);//设定要查找的字符串
  1677. string size = "";
  1678. double min_width = 90;
  1679. double min_height = 90;
  1680. double width = 0;
  1681. double height = 0;
  1682. try
  1683. {
  1684. num = matches.Count;
  1685. foreach (System.Text.RegularExpressions.Match match in matches)
  1686. {
  1687. if (match.Success)
  1688. {
  1689. size = match.Groups[0].Value;
  1690. if (size.Contains("cm"))
  1691. {
  1692. size = size.Replace("cm", "");
  1693. string[] size_list = size.Split('x');
  1694. if (size_list.Length > 1)
  1695. {
  1696. width = Convert.ToDouble(size_list[0]) * 10;
  1697. height = Convert.ToDouble(size_list[1]) * 10;
  1698. }
  1699. }
  1700. else if (size.Contains("mm"))
  1701. {
  1702. size = size.Replace("mm", "");
  1703. string[] size_list = size.Split('x');
  1704. if (size_list.Length > 1)
  1705. {
  1706. width = Convert.ToDouble(size_list[0]);
  1707. height = Convert.ToDouble(size_list[1]);
  1708. }
  1709. }
  1710. if (width >= min_width && height >= min_height && height >= min_width && width >= min_height)
  1711. {
  1712. size_bool = true;
  1713. break;
  1714. }
  1715. else
  1716. {
  1717. size_bool = false;
  1718. }
  1719. }
  1720. }
  1721. }
  1722. catch (Exception ex)
  1723. {
  1724. }
  1725. if (ceErpTradeCell.seller_memo.Contains("刮刮"))
  1726. {
  1727. num = Math.Max(num - 1, 1);
  1728. }
  1729. pattern = @"(\d+)款";
  1730. matches = Regex.Matches(ceErpTradeCell.seller_memo, pattern);
  1731. try
  1732. {
  1733. num = Math.Max(num - matches.Count, 0);
  1734. foreach (System.Text.RegularExpressions.Match match in matches)
  1735. {
  1736. if (match.Success)
  1737. {
  1738. num += Convert.ToInt32(match.Groups[1].Value);
  1739. break;
  1740. }
  1741. }
  1742. }
  1743. catch (Exception ex)
  1744. {
  1745. }
  1746. //2款不进
  1747. if (num < min_num)
  1748. {
  1749. num_bool = false;
  1750. }
  1751. if (!num_bool && !size_bool)
  1752. {
  1753. return new designApiResponseVo(-1, "尺寸小于80x80或款数小于2");
  1754. }
  1755. }
  1756. }
  1757. }
  1758. return new designApiResponseVo(200, "");
  1759. }
  1760. public static void sendCytAfterSale(CeErpTradeCell entity)
  1761. {
  1762. try
  1763. {
  1764. CeErpTradeAfterSaleExtend ceErpTradeAfterSaleExtend = CeErpTradeAfterSaleExtend.getByTid(entity.ctid);
  1765. string after = "";
  1766. if (entity != null && entity.AfterSaleReason.Contains("质量问题"))
  1767. {
  1768. after = "质量问题";
  1769. }
  1770. else if (entity != null && entity.AfterSaleReason.Contains("发货问题"))
  1771. {
  1772. after = "没收到货";
  1773. }
  1774. else
  1775. {
  1776. after = "其他问题";
  1777. }
  1778. string refund_type = "退款退货";
  1779. if (entity.supRefundType != null && entity.supRefundType == "重印" && (after == "质量问题" || after == "其他问题"))
  1780. {
  1781. refund_type = "补印";
  1782. }
  1783. JObject jsonObject12 = new JObject
  1784. {
  1785. { "Userid", "77886" },
  1786. //{ "pwd", "lt666888" },
  1787. { "LTOrderId", entity.ctid },
  1788. { "RefundType", refund_type },
  1789. { "ReprintReasons", after },
  1790. { "ReasonsImgUrls", entity.AfterSaleSupplierImg },
  1791. { "ReasonRemarks", ceErpTradeAfterSaleExtend.supplierResponsible }
  1792. };
  1793. /**JObject jsonObject12 = new JObject
  1794. {
  1795. { "Userid", "10095" },
  1796. { "pwd", "test123456" },
  1797. { "LTOrderId", "test123456" },
  1798. { "RefundType", "退款退货" },
  1799. { "ReprintReasons", "其他问题" },
  1800. { "ReasonRemarks", "测试" }
  1801. };**/
  1802. string response1 = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/ApplyOrderRefund", jsonObject12.ToString());
  1803. JObject jsonObjects1 = JObject.Parse(response1);
  1804. string msg = (string)jsonObjects1["msg"];
  1805. LogHelper.addLog(entity.ctid, 0, "CYT售后单推送:" + msg);
  1806. }
  1807. catch (Exception ex)
  1808. {
  1809. LogHelper.addLog(entity.ctid, 0, "CYT售后单推送:" + ex.ToString());
  1810. }
  1811. }
  1812. public static void getCytPrice(CeErpTradeCell entity)
  1813. {
  1814. try
  1815. {
  1816. CeErpProduct cp = CeErpProduct.GetById(entity.ProductId);
  1817. double price = 0;
  1818. if (cp == null)
  1819. {
  1820. JObject jsonObject12 = new JObject
  1821. {
  1822. { "UserId", "77886" },
  1823. { "Pwd", "lt666888" },
  1824. { "Filename", entity.seller_memo }
  1825. };
  1826. string response1 = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/LTBaojia", jsonObject12.ToString());
  1827. JObject jsonObjects1 = JObject.Parse(response1);
  1828. string ms1g = (string)jsonObjects1["msg"];
  1829. if (ms1g == "报价成功")
  1830. {
  1831. JObject jsonObject1 = (JObject)jsonObjects1["data"];
  1832. string data = (string)jsonObject1["price"];
  1833. 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 + "');";
  1834. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  1835. price = Convert.ToDouble(data);
  1836. }
  1837. else
  1838. {
  1839. 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 + "');";
  1840. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  1841. return;
  1842. }
  1843. }
  1844. String[] beizhu = entity.seller_memo.Split('-');
  1845. String chanp = "";
  1846. if (beizhu.Length > 1)
  1847. {
  1848. chanp = "(" + entity.ctid + ")-" + entity.ProductSize + "-" + entity.ProductCount + "-" + entity.Material + cp.PSupType + entity.Craft + "-备注:" + beizhu[1];
  1849. }
  1850. else
  1851. {
  1852. chanp = "(" + entity.ctid + ")-" + entity.ProductSize + "-" + entity.ProductCount + "-" + entity.Material + cp.PSupType + entity.Craft;
  1853. }
  1854. JObject jsonObject = new JObject
  1855. {
  1856. { "UserId", "77886" },
  1857. { "Pwd", "lt666888" },
  1858. { "Filename", chanp }
  1859. };
  1860. string response = HttpPost("http://www.kiy.cn/m-mobile/autobaojia/LTBaojia", jsonObject.ToString());
  1861. JObject jsonObjects = JObject.Parse(response);
  1862. string msg = (string)jsonObjects["msg"];
  1863. if (msg == "报价成功")
  1864. {
  1865. JObject jsonObject1 = (JObject)jsonObjects["data"];
  1866. string data = (string)jsonObject1["price"];
  1867. 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 + "');";
  1868. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  1869. price = Convert.ToDouble(data);
  1870. }
  1871. else
  1872. {
  1873. 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 + "');";
  1874. CeErpTradeCell.ExecuteNonQuery(sql_pay.ToString());
  1875. return;
  1876. }
  1877. if (price > 0)
  1878. {
  1879. CeErpTradeCellExtend ceErpTradeCellExtend = CeErpTradeCellExtend.getByTid(entity.ctid);
  1880. if (ceErpTradeCellExtend == null)
  1881. {
  1882. ceErpTradeCellExtend = new CeErpTradeCellExtend();
  1883. ceErpTradeCellExtend.ctid = entity.ctid;
  1884. ceErpTradeCellExtend.payment_cyt = price;
  1885. ceErpTradeCellExtend.Create();
  1886. }
  1887. else
  1888. {
  1889. ceErpTradeCellExtend.payment_cyt = price;
  1890. ceErpTradeCellExtend.Update();
  1891. }
  1892. }
  1893. }
  1894. catch (Exception ex)
  1895. {
  1896. }
  1897. return;
  1898. }
  1899. /// <summary>
  1900. /// 更新设计信息
  1901. /// </summary>
  1902. /// <param name="ceErpTradeCell"></param>
  1903. public static void updateDataTradeCellDesignInfo(string ctid)
  1904. {
  1905. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  1906. if (ceErpTradeCell == null)
  1907. {
  1908. return;
  1909. }
  1910. string info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}'", ceErpTradeCell.tid);
  1911. DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
  1912. foreach (DataRow row in data.Rows)
  1913. {
  1914. ceErpTradeCell = CeErpTradeCell.GetByCtid(row["ctid"].ToString());
  1915. if (ceErpTradeCell == null)
  1916. {
  1917. continue;
  1918. }
  1919. Dictionary<string, string> map = new Dictionary<string, string>();
  1920. if (ceErpTradeCell.DesignUserId > 0)
  1921. {
  1922. string design_sql = string.Format("SELECT * FROM [dbo].[view_ErpUser] WHERE ID = {0}", ceErpTradeCell.DesignUserId);
  1923. DataTable design_dt = DbHelper.DbConn.ExecuteDataset(design_sql).Tables[0];
  1924. if (design_dt != null && design_dt.Rows.Count > 0)
  1925. {
  1926. map.Add("ShortText1717743889973", design_dt.Rows[0]["Name"].ToString());
  1927. map.Add("ShortText1717743889516", design_dt.Rows[0]["OrgName"].ToString());
  1928. if (!string.IsNullOrEmpty(design_dt.Rows[0]["OrgID"].ToString()))
  1929. {
  1930. int orgId = Convert.ToInt32(design_dt.Rows[0]["OrgID"]);
  1931. if (orgId > 0)
  1932. {
  1933. 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"]);
  1934. DataTable mDesign_dt = DbHelper.DbConn.ExecuteDataset(mDesign_sql).Tables[0];
  1935. if (mDesign_dt != null && mDesign_dt.Rows.Count > 0)
  1936. {
  1937. map.Add("ShortText1717743890850", mDesign_dt.Rows[0]["Name"].ToString());
  1938. }
  1939. }
  1940. }
  1941. }
  1942. map.Add("Date1717743893776", ceErpTradeCell.WaitDesignTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  1943. map.Add("ShortText1717743882604", ((OrderState)ceErpTradeCell.OrderState).ToString());
  1944. }
  1945. dataHelper.updateErpTradeCell(map, ctid);
  1946. }
  1947. }
  1948. /// <summary>
  1949. /// 下单更新
  1950. /// </summary>
  1951. /// <param name="ceErpTradeCell"></param>
  1952. public static void updateDataTradeCellPlaceInfo(string ctid)
  1953. {
  1954. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  1955. if (ceErpTradeCell == null)
  1956. {
  1957. return;
  1958. }
  1959. Dictionary<string, string> map = new Dictionary<string, string>();
  1960. if (ceErpTradeCell.OrderState >= 6 && ceErpTradeCell.SupplierId > 0)
  1961. {
  1962. map.Add("Date1717743895362", ceErpTradeCell.FinishDesignTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  1963. map.Add("Date1717744246168", ceErpTradeCell.FinishPlaceTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  1964. string supplierId = dataHelper.getSupplerDataInfo(ceErpTradeCell.SupplierId.ToString());
  1965. map.Add("RelevanceForm1718100412422", supplierId);
  1966. CeErpTradeCellExtend ceErpTradeCellExtend = CeErpTradeCellExtend.getByTid(ceErpTradeCell.ctid);
  1967. if (ceErpTradeCellExtend != null)
  1968. {
  1969. map.Add("Number1718099884613", ceErpTradeCellExtend.payment_cyt.ToString());
  1970. }
  1971. map.Add("ShortText1717743882604", ((OrderState)ceErpTradeCell.OrderState).ToString());
  1972. }
  1973. dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
  1974. }
  1975. /// <summary>
  1976. /// 发货更新
  1977. /// </summary>
  1978. /// <param name="ceErpTradeCell"></param>
  1979. public static void updateDataTradeCellDeliveInfo(string ctid)
  1980. {
  1981. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  1982. if (ceErpTradeCell == null)
  1983. {
  1984. return;
  1985. }
  1986. string info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}'", ceErpTradeCell.tid);
  1987. DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
  1988. foreach (DataRow row in data.Rows)
  1989. {
  1990. ceErpTradeCell = CeErpTradeCell.GetByCtid(row["ctid"].ToString());
  1991. if (ceErpTradeCell == null)
  1992. {
  1993. continue;
  1994. }
  1995. Dictionary<string, string> map = new Dictionary<string, string>();
  1996. if (ceErpTradeCell.OrderState >= 7 && ceErpTradeCell.SupplierId > 0)
  1997. {
  1998. map.Add("Date1717744254301", ceErpTradeCell.FinishDeliveryTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  1999. map.Add("ShortText1717744255441", ceErpTradeCell.OutSid);
  2000. map.Add("ShortText1717743882604", ((OrderState)ceErpTradeCell.OrderState).ToString());
  2001. }
  2002. dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
  2003. }
  2004. }
  2005. /// <summary>
  2006. /// 打回
  2007. /// </summary>
  2008. /// <param name="ceErpTradeCell"></param>
  2009. public static void updateDataTradeCellBackInfo(string ctid)
  2010. {
  2011. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  2012. if (ceErpTradeCell == null)
  2013. {
  2014. return;
  2015. }
  2016. Dictionary<string, string> map = new Dictionary<string, string>();
  2017. map.Add("Date1717745436357", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  2018. map.Add("ShortText1717745435559", "是");
  2019. map.Add("ShortText1717745481283", ceErpTradeCell.ReturnReason);
  2020. map.Add("ShortText1717743882604", ((OrderState)ceErpTradeCell.OrderState).ToString());
  2021. dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
  2022. }
  2023. /// <summary>
  2024. /// 查货
  2025. /// </summary>
  2026. /// <param name="ceErpTradeCell"></param>
  2027. public static void updateDataTradeCellCheckGoodInfo(string ctid)
  2028. {
  2029. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  2030. if (ceErpTradeCell == null)
  2031. {
  2032. return;
  2033. }
  2034. Dictionary<string, string> map = new Dictionary<string, string>();
  2035. map.Add("Date1717745495718", ceErpTradeCell.CheckOrderTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  2036. map.Add("ShortText1717745492918", "是");
  2037. map.Add("ShortText1717745497837", ceErpTradeCell.CheckMemo);
  2038. map.Add("ShortText1717745499141", ceErpTradeCell.UnusualCon);
  2039. dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
  2040. }
  2041. /// <summary>
  2042. /// 加急
  2043. /// </summary>
  2044. /// <param name="ceErpTradeCell"></param>
  2045. public static void updateDataTradeCellUrgentInfo(string ctid)
  2046. {
  2047. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  2048. if (ceErpTradeCell == null)
  2049. {
  2050. return;
  2051. }
  2052. Dictionary<string, string> map = new Dictionary<string, string>();
  2053. map.Add("Date1717745535736", ceErpTradeCell.UrgencyTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  2054. map.Add("ShortText1717745533062", "是");
  2055. dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
  2056. }
  2057. /// <summary>
  2058. /// 售后
  2059. /// </summary>
  2060. /// <param name="ceErpTradeCell"></param>
  2061. public static void updateDataTradeCellAfterSaleInfo(string ctid)
  2062. {
  2063. CeErpTradeCell ceErpTradeCell = CeErpTradeCell.GetByCtid(ctid);
  2064. if (ceErpTradeCell == null)
  2065. {
  2066. return;
  2067. }
  2068. Dictionary<string, string> map = new Dictionary<string, string>();
  2069. map.Add("ShortText1717745540758", "是");
  2070. map.Add("Date1717745544245", ceErpTradeCell.AfterSaleTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  2071. if (ceErpTradeCell.AfterSaleResSupId > 0)
  2072. {
  2073. CeErpUser user = CeErpUser.Get(ceErpTradeCell.AfterSaleResSupId);
  2074. if (user != null)
  2075. {
  2076. map.Add("ShortText1717745541664", user.Name);
  2077. }
  2078. }
  2079. map.Add("Date1717745545841", ceErpTradeCell.FinishAfterSaleTime?.ToString("yyyy-MM-dd HH:mm:ss"));
  2080. if (!string.IsNullOrEmpty(ceErpTradeCell.AfterSaleReason))
  2081. {
  2082. string[] list = ceErpTradeCell.AfterSaleReason.Split('|');
  2083. for (int i = 0; i < list.Length; i++)
  2084. {
  2085. if (i == 0)
  2086. {
  2087. map.Add("ShortText1717745548220", list[i]);
  2088. }
  2089. if (i == 1)
  2090. {
  2091. map.Add("ShortText1717745549835", list[i]);
  2092. }
  2093. if (i == 2)
  2094. {
  2095. map.Add("ShortText1717745550687", list[i]);
  2096. }
  2097. }
  2098. }
  2099. if (!string.IsNullOrEmpty(ceErpTradeCell.ResponsibleUserId))
  2100. {
  2101. string[] list = ceErpTradeCell.ResponsibleUserId.Split(',');
  2102. for (int i = 0; i < list.Length; i++)
  2103. {
  2104. string[] user = list[i].Split('_');
  2105. if (user.Length > 0)
  2106. {
  2107. if (user[1] == "g")
  2108. {
  2109. CeErpSupplier ceErpSupplier = CeErpSupplier.Get(user[0]);
  2110. if (i == 0)
  2111. {
  2112. map.Add("ShortText1717745553842", list[i]);
  2113. map.Add("ShortText1717745554626", "");
  2114. }
  2115. if (i == 1)
  2116. {
  2117. map.Add("ShortText1717811042513", list[i]);
  2118. map.Add("ShortText1717811049407", "");
  2119. }
  2120. }
  2121. else if (user[1] == "w")
  2122. {
  2123. if (i == 0)
  2124. {
  2125. map.Add("ShortText1717745553842", "物流问题");
  2126. map.Add("ShortText1717745554626", "");
  2127. }
  2128. if (i == 1)
  2129. {
  2130. map.Add("ShortText1717811042513", "物流问题");
  2131. map.Add("ShortText1717811049407", "");
  2132. }
  2133. }
  2134. else
  2135. {
  2136. string customer_sql = string.Format("SELECT * FROM [dbo].[view_ErpUser] WHERE ID = {0}", ceErpTradeCell.CustomerUserId);
  2137. DataTable customer_dt = DbHelper.DbConn.ExecuteDataset(customer_sql).Tables[0];
  2138. if (customer_dt.Rows.Count > 0)
  2139. {
  2140. if (i == 0)
  2141. {
  2142. map.Add("ShortText1717745553842", customer_dt.Rows[0]["Name"].ToString());
  2143. map.Add("ShortText1717745554626", customer_dt.Rows[0]["OrgName"].ToString());
  2144. }
  2145. if (i == 1)
  2146. {
  2147. map.Add("ShortText1717811042513", customer_dt.Rows[0]["Name"].ToString());
  2148. map.Add("ShortText1717811049407", customer_dt.Rows[0]["OrgName"].ToString());
  2149. }
  2150. }
  2151. }
  2152. }
  2153. }
  2154. }
  2155. map.Add("number1717745810151", ceErpTradeCell.RefundFee.ToString());
  2156. CeErpTradeAfterSaleExtend ceErpTradeAfterSaleExtend = CeErpTradeAfterSaleExtend.getByTid(ceErpTradeCell.ctid);
  2157. if (ceErpTradeAfterSaleExtend != null && !string.IsNullOrEmpty(ceErpTradeAfterSaleExtend.RefundFees))
  2158. {
  2159. string[] list = ceErpTradeAfterSaleExtend.RefundFees.Split(',');
  2160. for (int i = 0; i < list.Length; i++)
  2161. {
  2162. if (i == 0)
  2163. {
  2164. map.Add("Number1717745564936", list[i]);
  2165. }
  2166. if (i == 1)
  2167. {
  2168. map.Add("Number1717745565580", list[i]);
  2169. }
  2170. }
  2171. }
  2172. map.Add("ShortText1717745580986", ceErpTradeCell.AfterSaleSupplierState == 1 ? "认可" : "不认可");
  2173. map.Add("ShortText1717745582613", ceErpTradeCell.AfterSaleSupplierMemo);
  2174. map.Add("ShortText1717745583256", ceErpTradeCell.AfterSaleMethod);
  2175. map.Add("ShortText1717745583810", ceErpTradeCell.AfterSaleMemo);
  2176. dataHelper.updateErpTradeCell(map, ceErpTradeCell.ctid);
  2177. }
  2178. /// <summary>
  2179. /// 退款
  2180. /// </summary>
  2181. /// <param name="content"></param>
  2182. public static void updateDataTradeCellRefundInfo(Api_tmc_refund_info_Obj.Content content)
  2183. {
  2184. Dictionary<string, string> map = new Dictionary<string, string>();
  2185. map.Add("Date1717745588048", StampToDateTime(content.createTime).ToString("yyyy-MM-dd HH:mm:ss"));
  2186. map.Add("ShortText1717745585444", "是");
  2187. map.Add("Number1717743148189", content.refundFee);
  2188. map.Add("ShortText1717745591810", content.reason);
  2189. map.Add("ShortText1717745592639", content.desc);
  2190. string tid = content.refOid;
  2191. string info_sql = string.Format("SELECT ctid FROM [dbo].[CE_ErpTradeCell] WHERE tid ='{0}'", tid);
  2192. DataTable data = DbHelper.DbConn.ExecuteDataset(info_sql).Tables[0];
  2193. foreach (DataRow row in data.Rows)
  2194. {
  2195. dataHelper.updateErpTradeCell(map, row["ctid"].ToString());
  2196. }
  2197. }
  2198. /// <summary>
  2199. /// 返现
  2200. /// </summary>
  2201. /// <param name="entity"></param>
  2202. /// <param name="cash"></param>
  2203. public static void updateDataTradeCellCashInfo(CeErpTradeCell entity, CeErpReturnCash cash)
  2204. {
  2205. Dictionary<string, string> map = new Dictionary<string, string>();
  2206. map.Add("ShortText1717745601056", "是");
  2207. map.Add("ShortText1717745602313", cash.rtype);
  2208. map.Add("Number1717745604245", cash.payment.ToString());
  2209. map.Add("ShortText1717745607208", cash.con);
  2210. dataHelper.updateErpTradeCell(map, entity.ctid);
  2211. }
  2212. /// <summary>
  2213. /// 推购
  2214. /// </summary>
  2215. /// <param name="entity"></param>
  2216. public static void updateDataTradeCellStayInfo(CeErpTradeCell entity)
  2217. {
  2218. Dictionary<string, string> map = new Dictionary<string, string>();
  2219. map.Add("ShortText1717745608381", "是");
  2220. dataHelper.updateErpTradeCell(map, entity.ctid);
  2221. }
  2222. public static DateTime StampToDateTime(string timeStamp)
  2223. {
  2224. DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  2225. long lTime = long.Parse(timeStamp + "0000");
  2226. TimeSpan toNow = new TimeSpan(lTime);
  2227. return dateTimeStart.Add(toNow);
  2228. }
  2229. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  2230. {
  2231. return true; //总是接受
  2232. }
  2233. public static string HttpPost(string url, string param = null)
  2234. {
  2235. HttpWebRequest request;
  2236. //如果是发送HTTPS请求
  2237. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  2238. {
  2239. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  2240. request = WebRequest.Create(url) as HttpWebRequest;
  2241. request.ProtocolVersion = HttpVersion.Version10;
  2242. }
  2243. else
  2244. {
  2245. request = WebRequest.Create(url) as HttpWebRequest;
  2246. }
  2247. request.Method = "POST";
  2248. request.ContentType = "application/json";
  2249. request.Accept = "*/*";
  2250. request.Timeout = 60000;
  2251. request.AllowAutoRedirect = false;
  2252. StreamWriter requestStream = null;
  2253. WebResponse response = null;
  2254. string responseStr = null;
  2255. try
  2256. {
  2257. requestStream = new StreamWriter(request.GetRequestStream());
  2258. requestStream.Write(param);
  2259. requestStream.Close();
  2260. response = request.GetResponse();
  2261. if (response != null)
  2262. {
  2263. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  2264. responseStr = reader.ReadToEnd();
  2265. reader.Close();
  2266. }
  2267. }
  2268. catch (Exception ex)
  2269. {
  2270. return ex.Message;
  2271. }
  2272. finally
  2273. {
  2274. request = null;
  2275. requestStream = null;
  2276. response = null;
  2277. }
  2278. return responseStr;
  2279. }
  2280. }
  2281. }