commonHelper.cs 177 KB

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