commonHelper.cs 144 KB

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