commonHelper.cs 174 KB

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