/// <summary> /// Add a tax category to a product /// </summary> /// <param name="productJo"></param> /// <param name="stock"></param> /// <remarks> /// Tax categories have to be created in Nop's admin panel /// Tax categories : Belgique 6, Belgique 12, Belgique 21 /// </remarks> /// <returns></returns> private bool AddTVA(JObject productJo, STOCK stock) { string resultTC = WebService.Get("TaxCategory"); JToken[] tvaValues = ParserJSon.ParseResultToJTokenList(resultTC); Dictionary <string, int> tcIds = tvaValues.ToDictionary(x => x["Name"].ToString().Split(' ').Last(), x => (int)x["Id"]); int taxId; tcIds.TryGetValue(stock.S_TAUX_TVA.ToString(), out taxId); if (taxId != 0) { if ((int)productJo["TaxCategoryId"] == 0) { productJo["TaxCategoryId"] = taxId; } else { productJo.Add("TaxCategoryId", taxId); } } else { Program.log(String.Format("Le taux de TVA {0} n'existe pas dans NopCommerce. ID du produit concerné : {1}. \nVeuillez contacter l'administrateur pour régler le problème.", stock.S_TAUX_TVA, stock.S_ID.TrimEnd())); return(false); } return(true); }
public override bool Sync() { //Get Stock From Mercator where "Vente En Ligne" is set using (SqlConnection connection = new SqlConnection(dataSettings.DataConnectionString)) { try { IDictionary <string, int> prodStockDico; connection.Open(); string whereClause = String.Format(StockSyncer.WHERE_CLAUSE, -1); prodStockDico = GetMercatorProductListWithDispoDatas(connection, whereClause, StockSyncer.JOIN_CLAUSE).ToList().ToDictionary(y => y.S_ID, y => y.S_DISPO); //Recupère les sku et leurs stocks respectifs JToken[] skuStocks = ParserJSon.ParseResultToJTokenList(WebService.Get(urlBuilder.Select("Sku", "Id", "StockQuantity").BuildQuery())); IDictionary <string, string> stocksToUpdateNop = skuStocks.ToDictionary(y => y["Sku"].ToString().TrimEnd(), y => (int)y["Id"] + "+" + (int)y["StockQuantity"]); int stockUpdateCount = 0; //Si stocks différents entre Mercator et site on update if (stocksToUpdateNop.Count > 0 && prodStockDico.Count > 0) { foreach (var s in prodStockDico) { string stockValue = s.Value.ToString(); if (stocksToUpdateNop.ContainsKey(s.Key)) { if (stockValue != stocksToUpdateNop[s.Key].Split('+').LastOrDefault()) { int pId = int.Parse(stocksToUpdateNop[s.Key].Split('+').FirstOrDefault()); //Console.WriteLine(s.Key + " updated"); JObject request = new JObject(); request.Add("StockQuantity", stockValue); WebService.Patch(urlBuilder.Id(pId).BuildQuery(), request.ToString()); stockUpdateCount++; } } } } Console.WriteLine(String.Format("Stocks de {0} produits mis à jour.", stockUpdateCount)); return(true); } catch (Exception e) { Program.log(e.Message); Program.log(e.StackTrace); return(false); } finally { if (connection != null) { connection.Close(); } } } }
/// <summary> /// Initiate a Product to be synced /// </summary> /// <param name="stock"></param> /// <param name="qteStock"></param> /// <param name="categories"></param> /// <param name="specopts"></param> /// <param name="context"></param> /// <param name="productId"></param> /// <returns>A Json object corresponding to a NopCommerce Product</returns> private JObject GetProduct(STOCK stock, IDictionary <string, int> categories, SqlConnection connection, IDictionary <String, int> specopts, int productId = 0) { JObject p = new JObject(); Product product = new Product(stock.S_MODELE.TrimEnd(), stock.S_MEMO.TrimEnd(), stock.S_CLE2.TrimEnd(), stock.S_CLE1.TrimEnd(), stock.S_DISPO, stock.S_PRIX_HT, condit: stock.S_CONDIT_V, mercatorId: stock.S_ID.TrimEnd(), modiftag: stock.S_MODIFTAG); p = ParserJSon.ParseStockToNopProduct(product, productId); //p = ParserJSon.ParseStockToNopProduct(stock, additionalShippingCharge, false, qteStock, productId); if (!AddTVA(p, stock)) { return(null); } p.Add(WebApiEntities.PRODUCT_CATEGORIES, MapCategory(stock, categories, productId)); p.Add(WebApiEntities.PRODUCT_PICTURES, pic.Sync(stock, OptionsMercator, productId)); try { p.Add(WebApiEntities.PRODUCT_SPEC_ATTS, MapSpecs(stock, specopts, productId)); }catch (KeyNotFoundException knfe) { Program.log(knfe.Message); Program.log(knfe.StackTrace); } //p.Add(WebServiceUrls.TIER_PRICES, MapTierPrices(stock, connection, productId)); //p.Add(WebServiceUrls.PRODUCT_FILES, MapFiles(stock, connection, productId)); //p.Add(WebServiceUrls.PRODUCT_ATTRIBUTE_MAPPINGS, syncTaxAndCondit(stock, productId)); return(p); }
public override bool Sync() { #region CAT_STCK types //Get all the cat stock types in app.config and sync them catStckTypes = new Dictionary <int, string>(); bool keepGoing = false; int i = 1; do { string value = OptionsMercator.GetOptionValue(String.Format(formatCatStckType, i))?.ToString(); keepGoing = !String.IsNullOrWhiteSpace(value); if (keepGoing) { catStckTypes.Add(i, value.TrimEnd()); } i++; } while (keepGoing); SyncCatStckTypes(catStckTypes); #endregion //Get Stock From Mercator where "Vente En Ligne" is setted using (SqlConnection connection = new SqlConnection(dataSettings.DataConnectionString)) { connection.Open(); //IEnumerable<CAT_STCK> catStckList = GetMercatorCATSTCK(connection); //Array of existing attSpecOp IDictionary <String, int> attSpecOp = GetAllNopSpecOpt(); List <int> specsToKeep = new List <int>(); //Sync options for every S_CAT{x}, x being the type id in catStckTypes foreach (var catStckTyp in catStckTypes) { try { int nopId = 0; var cstResult = ParserJSon.ParseResultToJTokenList(WebService.Get(urlBuilder.FilterEq("Name", catStckTyp.Value).BuildQuery())); if (cstResult.Length > 0) { nopId = (int)cstResult.First()["Id"]; SyncSpecAttOps(attSpecOp, specsToKeep, catStckTyp.Key, nopId); } } catch (Exception e) { Program.log(e); } } //Exclude scat that aren't in Mercator Delete(attSpecOp, specsToKeep); connection.Close(); } return(true); }
/// <summary> /// Go through every Product Picture for product with id=productId /// If does not exist we add it otherwise we save the PP Id /// </summary> /// <param name="image"></param> /// <param name="productId"></param> /// <param name="found"></param> /// <param name="pps"></param> /// <param name="ppsIds"></param> private void SyncPic(string image, JArray pictureLinks, int productId = 0) { if (String.IsNullOrWhiteSpace(image)) { return; } JObject json = new JObject(); try { Model.Picture pm = GetPicBase64(image); if (pm != null) { json = ParserJSon.GetPictureJson(pm.Base64, pm.ImageType, pm.Name); string result = WebService.Post(ENTITY, json); JObject newPicture = JObject.Parse(result); int picId = (int)newPicture["Id"]; JObject jsonResult = ParserJSon.getProductPictureJson(picId, productId); pictureLinks.Add(jsonResult); } return; } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine("Error parsing picture:" + json.ToString()); Program.log("Error parsing picture:" + json.ToString()); return; } }
/// <summary> /// Delete the products in Nop that are no longer suppose to be on it /// </summary> /// <param name="context"></param> /// <param name="productsMIdMtag"></param> /// <param name="reappro"></param> private void DeleteProducts(SqlConnection connection, List <ProductDatas> productsMIdMtag) { Console.WriteLine("Suppression produits..."); //First gather products that were created on the website and have no MercatorId string jsonNoSkus = WebService.Get(urlBuilder .Select("Id", "Sku", "Published") .FilterEq("Sku", null) .BuildQuery()); JToken[] productsNoSku = ParserJSon.ParseResultToJTokenList(jsonNoSkus); //Then, get the mercator products that are supposed to be on the website List <STOCK> prodList = new List <STOCK>(); prodList = GetMercatorProductsList(connection, JOIN_CLAUSE, ALL_STOCKS_WHERE_CLAUSE).ToList(); List <string> all_stocks_ids = new List <string>(); //get stocks (if "Vente en ligne" checked) all_stocks_ids = prodList.Select(x => x.S_ID.TrimEnd()).ToList(); //Get the products that are on NopCommerce List <int> existsInNop = productsMIdMtag.Where(x => all_stocks_ids.Any(y => y == x.MercatorId)).Select(z => z.Id).ToList(); //If some are on Nop but not in the prodList from Mercator, we mark them as deleted List <int> toEject = productsMIdMtag.Select(x => x.Id).Except(existsInNop).ToList(); //We also add the product that were created on the website (Tournesols products don't have any sku) toEject.AddRange(productsNoSku.Select(x => (int)x["Id"])); if (toEject.Count() > 0) { JObject unpublish = new JObject(); unpublish.Add("Deleted", true); JObject urlDeactivate = new JObject(); urlDeactivate.Add("IsActive", false); foreach (int id in toEject) { JObject urls = JObject.Parse(WebService.Get(new UrlBuilder("UrlRecord") .FilterEq("EntityId", id) .FilterEq("EntityName", ENTITY) .BuildQuery())); var urlsValues = urls["value"].ToArray(); if (urlsValues.Count() > 0) { WebService.Patch(new UrlBuilder("UrlRecord").Id((int)urlsValues[0]["Id"]).BuildQuery(), urlDeactivate.ToString()); } WebService.Patch(urlBuilder.Id(id).BuildQuery(), unpublish.ToString()); } } Console.WriteLine("Produits supprimés"); }
private void SyncCatStckTypes(Dictionary <int, string> catStckTypes) { //1. Get existings specification attributes //2. Check existences //2b (opt) Check if names has changed //3. Add or udpates //4. Delete if necessary JToken[] specAtts = ParserJSon.ParseResultToJTokenList(WebService.Get(ENTITY)); List <int> toKeep = new List <int>(); foreach (KeyValuePair <int, string> s in catStckTypes) { JToken j = null; if (specAtts.Length > 0) { j = specAtts[s.Key - 1]; } if (j == null) { //ADD CAT_STCK cs = new CAT_STCK(); cs.NOM = s.Value; cs.TYPE = s.Key; string result = WebService.Post(ENTITY, ParserJSon.ParseScatToSpecificationAttribute(cs).ToString()); //JToken[] resultJ = ParserJSon.ParseResultToJTokenList(result); JObject jsonResult = JObject.Parse(result); toKeep.Add((int)jsonResult["Id"]); string gaResult = WebService.Post(WebApiEntities.GENERIC_ATTRIBUTE, ParserJSon.GetGenericAttributeJSon((int)jsonResult["Id"], ENTITY, KEY_TYPE, cs.TYPE.ToString()).ToString()); Console.WriteLine("Cat Stock:" + cs.NOM + " inserted"); } else { if (j["Name"].ToString() != s.Value) { //Update JObject jo = new JObject(); jo.Add("Name", s.Value); //jo.Add("Type", s.Key); WebService.Patch(urlBuilder.Id((int)j["Id"]).BuildQuery(), jo.ToString()); } toKeep.Add((int)j["Id"]); } } IEnumerable <int> idsExisting = specAtts.Select(x => (int)x["Id"]); IEnumerable <int> toDelete = idsExisting.Except(toKeep); toDelete.ToList().ForEach(x => WebService.Delete(urlBuilder.Id(x).BuildQuery())); }
private void AddSpec(JArray ja, IDictionary <String, int> specopts, string scat, int number, int productId) { int value; if (!String.IsNullOrWhiteSpace(scat)) { if (!specopts.TryGetValue(scat + number, out value)) { throw new KeyNotFoundException("Key: " + scat + number + " not found in the dictionary"); } ja.Add(ParserJSon.getProductSpecificationAttributeJson(value, true, productId)); } }
public void SyncSpecAttOps(IDictionary <String, int> attSpecOp, List <int> specsToKeep, int catStockTypeId, int specAttId) { string sql = String.Format("SELECT nom,id_web, id FROM CAT_STCK WHERE TYPE = {0}", catStockTypeId, StockSyncer.JOIN_CLAUSE, StockSyncer.ALL_STOCKS_WHERE_CLAUSE); string sqlUpdateIdWeb = "UPDATE CAT_STCK SET ID_WEB = {0} WHERE ID = '{1}'"; List <string> catStocks = new List <string>(); SqlCommand sqlCommand = new SqlCommand(sql); try { DataTable dt = DBContextFactory.DBContext.Query(sqlCommand); foreach (DataRow dr in dt.Rows) { string scatVal = Convert.ToString(dr["nom"]).TrimEnd(); string scatId = Convert.ToString(dr["id"]).TrimEnd(); int scatIdWeb = Convert.ToInt32(dr["id_web"]); //Format to JSON JObject json = ParserJSon.ParseSCATToSpecificationAttributeOption(specAttId, scatVal); int specId = 0; if (!attSpecOp.Any(x => x.Value == scatIdWeb)) { //Send via POST (new ones) string result = WebService.Post(WebApiEntities.SPEC_ATT_OPT, json); JObject newValue = JObject.Parse(result); specId = (int)newValue["Id"]; //Update sqlUpdateIdWeb = String.Format(sqlUpdateIdWeb, specId, scatId); dbContext.NonQuery(sqlUpdateIdWeb); } else { //Exists; we keep the id specId = scatIdWeb; JObject nameUpdate = new JObject(); nameUpdate.Add("Name", scatVal); WebService.Patch(new UrlBuilder("SpecificationAttributeOption").Id(scatIdWeb).BuildQuery(), nameUpdate.ToString()); } //Store cat to keep specsToKeep.Add(specId); } } catch (Exception e) { Program.log(e); } }
/// <summary> /// /// </summary> /// <param name="stock"></param> /// <param name="context"></param> /// <param name="productId"></param> /// <returns></returns> //private JArray MapFiles(STOCK stock, SqlConnection connection, int productId = 0) //{ // JArray ja = new JArray(); // string location = FileConverter.REP_FILES_LOCATION + stock.S_ID.TrimEnd(); // //string[] dirs = Directory.GetFiles(location); // DirectoryInfo directorySelected = new DirectoryInfo(location); // foreach (FileInfo fileToCompress in directorySelected.GetFiles()) // { // string path = location + "\\" + fileToCompress.Name; // ja.Add(ParserJSon.GetProductFileJson(fileToCompress.Name, FileConverter.ConvertFileToB64(path), productId)); // //File.Delete(path); // } // return ja; //} /// <summary> /// ! Specifications have to be synchronized first (S_CAT) ! /// Map the Mercator's Stock's S_CAT with Nop's Products's Specs /// </summary> /// <param name="stock"></param> /// <param name="productId"></param> /// <param name="specopts"></param> private JArray MapSpecs(STOCK stock, IDictionary <String, int> specopts, int productId = 0) { JArray ja = new JArray(); string typesResult = WebService.Get(new UrlBuilder("GenericAttribute") .FilterEq("KeyGroup", "SpecificationAttribute") .FilterEq("Key", "Type") .BuildQuery()); JToken[] types = ParserJSon.ParseResultToJTokenList(typesResult); int type1 = types.Where(x => (int)x["Value"] == 1).Select(x => (int)x["EntityId"]).FirstOrDefault(); int type2 = types.Where(x => (int)x["Value"] == 2).Select(x => (int)x["EntityId"]).FirstOrDefault(); int type3 = types.Where(x => (int)x["Value"] == 3).Select(x => (int)x["EntityId"]).FirstOrDefault(); if (type1 != 0) { AddSpec(ja, specopts, stock.S_CAT1, type1, productId); } if (type2 != 0) { AddSpec(ja, specopts, stock.S_CAT2, type2, productId); } if (type3 != 0) { AddSpec(ja, specopts, stock.S_CAT3, type3, productId); } //JToken[] prod = ParserJSon.ParseResultToJTokenList(WebService.Get(String.Format(WebServiceUrls.GET_PRODUCT_BY_MERCATOR_ID,stock.S_ID.TrimEnd()))); JToken[] toDelete = ParserJSon.ParseResultToJTokenList(WebService.Get(new UrlBuilder("ProductSpecificationAttribute") .FilterEq("ProductId", productId) .BuildQuery())); //TODO: revoir delete //foreach (JToken j in toDelete) //{ // if ((int)j["SpecificationAttributeOptionId"] != value) // { // WebService.Delete(String.Format(WebServiceUrls.PRODUCT_SPEC_ATT_BY_ID, (int)j["Id"])); // WebService.Delete(String.Format(WebServiceUrls.SPEC_ATT_OPT_BY_ID, (int)j["SpecificationAttributeOptionId"])); // } //} return(ja); }
/// <summary> /// Check if the Mercator client's email already exists in NopCommerce /// If so, it throws an Exception /// </summary> /// <param name="c">Mercator Client</param> private void checkEmailExistence(CLI c) { string emailResult = WebService.Get(urlBuilder.FilterEq("Email", c.C_EMAIL.TrimEnd()).BuildQuery()); JToken[] emails = ParserJSon.ParseResultToJTokenList(emailResult); if (emails.Count() > 0) { JToken user = emails.First(); if (user["Deleted"].ToString() == "False") { string mercatorId = user["MercatorId"].ToString().TrimEnd(); if (mercatorId != c.C_ID.TrimEnd() && mercatorId != "") { throw new Exception("User with email : " + c.C_EMAIL.TrimEnd() + " already exists"); } } } }
/// <summary> /// Get existing url records /// </summary> /// <param name="rayons"></param> /// <returns></returns> //private static IDictionary<String, int> GetExistingUrlRecords(IEnumerable<Category> categories) //{ // Dictionary<String, int> existingIds = new Dictionary<string, int>(); // string json = WebService.Get(WebServiceUrls.GET_URL_RECORDS_ACTIVE_CATEGORIES); // JObject urls = JObject.Parse(json); // var values = urls["value"].ToArray(); // foreach(Category c in categories) // { // foreach(JToken v in values) // { // if(c.MercatorId == v["Slug"].ToString()) // { // //r.ID => urlRecordId // existingIds.Add(c.MercatorId, (int)v["Id"]); // //r.IDSlug =>catId // existingIds.Add(c.MercatorId + SLUG, (int)v["EntityId"]); // } // } // } // return existingIds; //} /// <summary> /// Get a mapping of Mercator's RFS IDs and Nop's CatIds /// </summary> /// <returns>A Dictionnary with RFS IDs as key and Nop Ids as values</returns> public static IDictionary <string, int> GetMapIdNopId() { Dictionary <string, int> map = new Dictionary <string, int>(); //Get the categories mercator Ids string json = WebService.Get(new UrlBuilder("GenericAttribute").And().FilterEq("KeyGroup", ENTITY).FilterEq("Key", "MercatorId").BuildQuery()); JToken[] gaValues = ParserJSon.ParseResultToJTokenList(json); //Get the categories mercator Ids of the active categories foreach (JToken v in gaValues) { //if(catsValues.Any(x=>(int)x["Id"] == (int)v["EntityId"])) map.Add(v["Value"].ToString(), (int)v["EntityId"]); } return(map); }
/// <summary> /// Update Nop's Customer datas from Mercator /// </summary> /// <param name="cli"></param> /// <param name="cl"></param> /// <param name="context"></param> private void updateNopClient(CLI cli, Customer cl, JToken GenericAttributeModiftag) { //Patch Customer JObject toPatch = new JObject(); if (cli.C_EMAIL.TrimEnd() != cl.Email) { CheckEmailExistence(cli); toPatch.Add("Username", cli.C_EMAIL.TrimEnd()); toPatch.Add("Email", cli.C_EMAIL.TrimEnd()); } WebService.Patch(urlBuilder.Id(cl.Id).BuildQuery(), toPatch.ToString()); //Tarif update //string crJson = WebService.Get(String.Format(WebServiceUrls.GET_CUSTOMER_AND_CR_BY_ID, cl.IdNop)); //JToken[] customer = ParserJSon.ParseResultToJTokenList(crJson); //var crs = customer.FirstOrDefault(); //var customerRoles = crs != null ? crs["CustomerRoles"].ToArray() : null; //syncTarCli(cli, context); //Update Tag toPatch = new JObject(); toPatch.Add("Value", cli.C_MODIFTAG.ToString()); WebService.Patch(String.Format(new UrlBuilder("GenericAttribute").Id((int)GenericAttributeModiftag["Id"]).BuildQuery()), toPatch.ToString()); if (cli.C_ADRESSE.TrimEnd() != cl.Address1.Street.TrimEnd() || cli.C_ADRESSE2.TrimEnd() != cl.Address1.Street2.TrimEnd()) { string addressJson = ParserJSon.ParseAddressToJson(cli, OptionsMercator).ToString(); string addressResult = WebService.Post(WebApiEntities.ADDRESS, addressJson); JObject newAddress = JObject.Parse(addressResult); int addressId = (int)newAddress["Id"]; //link address JObject linkCliToAddress = new JObject(); linkCliToAddress.Add("@odata.id", WebService.GetStoreAddress() + new UrlBuilder("Address").Id(addressId).BuildQuery()); WebService.Put(urlBuilder.BuildQueryRef(cli.C_ID_WEB, "Addresses"), linkCliToAddress); //link address as billing address //WebService.Put(String.Format(WebServiceUrls.LINK_CUSTOMER_TO_BILLING_ADDRESS, cli.C_ID_WEB.ToString()), linkCliToAddress); } }
//Used for products public static void addAclMapping(int entityId, string entityNameMapping, JArray ja) { //ADD ACL RECORD var allowedRoles = ConfigurationManager.AppSettings["CRRestrictedAccessAllowed"].Split(';'); JObject jo = new JObject(); foreach (String s in allowedRoles) { JObject ids = JObject.Parse(WebService.Get(wsCustomerRoleMapping + "?$filter=Name+eq+'" + s + "'&select=Id")); var idsValue = ids["value"].ToArray(); if (idsValue.Count() > 0) { foreach (JToken id in idsValue) { ja.Add(ParserJSon.parseNewAclToJson(entityId, entityNameMapping, int.Parse(id["Id"].ToString()))); } } } }
/// <summary> /// Check if the Mercator client's username (PILE+id) already exists in NopCommerce /// If so, it throws an Exception /// </summary> /// <param name="c">Mercator Client</param> private void checkUsernameExistence(CLI c) { string userNameResult = WebService.Get(urlBuilder.FilterEq("Username", c.C_ID.TrimEnd()).BuildQuery()); JToken[] usernames = ParserJSon.ParseResultToJTokenList(userNameResult); if (usernames.Count() > 0) { JToken user = usernames.First(); if (user["Deleted"].ToString() == "False") { string mercatorId = user["MercatorId"].ToString().TrimEnd(); if (mercatorId != c.C_ID.TrimEnd() && mercatorId != "") { throw new DuplicateNameException("User with username : "******" already exists"); } } } }
/// <summary> /// Add taxes to products (i.e product attributes) (e.g ecotaxe) /// </summary> /// <param name="stock"></param> /// <param name="productId"></param> //private static JArray syncTaxAndCondit(STOCK stock, int productId = 0) //{ // JArray ja = new JArray(); // JObject attributeMapping; // JArray attributeValues; // string productVAttributeId; // //Attributes // foreach (ARTLIENS a in stock.ARTLIENS) // { // if (a.VEN) // { // int attributeId = 0; // productVAttributeId = ""; // //Create attribute if it doesn't exist yet // JObject paO = JObject.Parse(WebService.Get(WebServiceUrls.PRODUCT_ATTRIBUTE + "?$filter=Name+eq+'" + a.STOCK1.S_MODELE.TrimEnd() + "'")); // var pa = paO["value"].ToArray(); // if (pa.Count() == 0) // { // string result = WebService.Post(WebServiceUrls.PRODUCT_ATTRIBUTE, ParserJSon.ParseTaxToProductAttribute(a.STOCK1.S_MODELE.TrimEnd())); // JObject idO = JObject.Parse(result); // attributeId = (int)idO["Id"]; // } // else // { // attributeId = (int)pa[0]["Id"]; // } // attributeMapping = ParserJSon.ParseArtLien1ToProductVariantAttribute(attributeId, productId); // //Add value to attribute // attributeValues = new JArray(); // //JObject pvavO = JObject.Parse(WebService.Get(WebServiceUrls.PRODUCT_VARIANT_ATTRIBUTE_VALUE + "?$filter=ProductAttributeMappingId+eq+" + productVAttributeId)); // //var pvav = pvavO["value"].ToArray(); // attributeValues.Add(ParserJSon.ParseArtLien1ToProductVariantAttributeValue(a.STOCK1.S_MODELE.TrimEnd(), a.STOCK1.S_PRIX_TI)); // attributeMapping.Add("ProductAttributeValues", attributeValues); // ja.Add(attributeMapping); // } // } // if (stock.S_CONDIT_V > 1) // { // attributeMapping = ParserJSon.ParseArtLien1ToProductVariantAttribute(1, productId); // attributeValues = new JArray(); // attributeValues.Add(ParserJSon.ParseArtLien1ToProductVariantAttributeValue(stock.S_CONDIT_V.ToString() + " PC", 0)); // attributeMapping.Add("ProductAttributeValues", attributeValues); // ja.Add(attributeMapping); // } // return ja; //} /// <summary> /// Map product to tier prices (Tarifs in Mercator) /// </summary> /// <param name="stock"></param> /// <param name="productId"></param> /// <param name="connection"></param> //private static JArray MapTierPrices(STOCK stock, SqlConnection connection, int productId) //{ // JArray array = new JArray(); // string json = WebService.Get("TierPrice?$filter=ProductId+eq+" + productId); // JToken[] valuesTP = ParserJSon.ParseResultToJTokenList(json); // List<String> tpToKeep = new List<String>(); // //Get existing customer roles // string jsonCR = WebService.Get("CustomerRole?$filter=IsSystemRole+eq+false"); // JToken[] valuesCR = ParserJSon.ParseResultToJTokenList(jsonCR); // //CustomerRoleID => Price in Nop // IDictionary<String, String> tpMap = new Dictionary<String, String>(); // foreach (JToken v in valuesTP) // { // tpMap.Add(v["CustomerRoleId"].ToString()+"KEY", v["Id"].ToString()); // tpMap.Add(v["CustomerRoleId"].ToString(), v["Price"].ToString()); // } // foreach (JToken v in valuesCR) // { // string tarId = v["SystemName"].ToString().Split('_').Last(); // double tarti = (double)connection.Entry(stock).Property("S_PRIXHT" + tarId).CurrentValue; // decimal remise = GetRemise(stock,connection,tarId); // string concernedPrice; // tpMap.TryGetValue(v["Id"].ToString(), out concernedPrice); // //If TierPrice contains customer role's id => Check if it's the same price // if (concernedPrice != null) // { // //Price have changed => Patch // if (tarti.ToString() != concernedPrice) // { // array.Add(ParserJSon.GetTierPriceJson((int)v["Id"], tarti, remise, productId)); // } // } // //If it's not in it, we add it // else // { // array.Add(ParserJSon.GetTierPriceJson((int)v["Id"], tarti, remise, productId)); // } // } // return array; // //DELETE DONE AUTOMATICALLY WHEN TARIF IS REMOVED //} /// <summary> /// Get remise by stock and tarif /// </summary> /// <param name="stock"></param> /// <param name="context"></param> /// <param name="tarId"></param> /// <returns></returns> //private static decimal GetRemise(STOCK stock, SqlConnection connection, string tarId) //{ // string scat2 = stock.S_CAT2; // var cats = from c in context.CAT_STCK // where c.NOM.TrimEnd() == scat2.TrimEnd() // select c; // if(cats.FirstOrDefault() != null) // { // CAT_STCK cs = cats.FirstOrDefault(); // object tarti = context.Entry(cs).Property("CAT" + tarId).CurrentValue; // return (decimal)(double)tarti; // } // return 0; //} /// <summary> /// Add a new entry in Nop Product_Category_Mapping Table /// </summary> private JArray MapCategory(STOCK stock, IDictionary <string, int> categories, int productId = 0) { string ray = stock.S_ID_RAYON.TrimEnd(); string fam = stock.S_ID_FAMIL.TrimEnd(); string ssfam = stock.S_ID_SSFAM.TrimEnd(); //Get CatId string rfsId = (ssfam == "") ? ((fam == "") ? ray : fam) : ssfam; int catId; bool catExists = categories.TryGetValue(rfsId, out catId); //If catID is empty, the rfs have not been syncrhonised. Sync it or do nothing ? if (catExists) { JArray cats = new JArray(); cats.Add(ParserJSon.getProductCategoryJson(catId, productId)); return(cats); } return(null); }
/// <summary> /// Check if the Mercator client's email already exists in NopCommerce /// If so, it throws an Exception /// </summary> /// <param name="c">Mercator Client</param> private void CheckEmailExistence(CLI c) { string emailResult = WebService.Get(urlBuilder.FilterEq("Email", c.C_EMAIL.TrimEnd()).BuildQuery()); JToken[] emails = ParserJSon.ParseResultToJTokenList(emailResult); if (emails.Count() > 0) { JToken user = emails.First(); if (user["Deleted"].ToString() == "False") { string mercatorIdResult = WebService.Get(String.Format(new UrlBuilder("GenericAttribute").And().FilterEq("KeyGroup", ENTITY).FilterEq("Key", KEY_MERCATORID).FilterEq("EntityId", (int)user["Id"]).BuildQuery())); JObject mercatorIdJObject = JObject.Parse(mercatorIdResult); string mercatorId = mercatorIdJObject["Value"]?.ToString(); if (mercatorId != c.C_ID.TrimEnd() && !String.IsNullOrWhiteSpace(mercatorId)) { throw new Exception("User with email : " + c.C_EMAIL.TrimEnd() + " already exists"); } } } }
/// <summary> /// Get all SpecAttributeOptions /// <String, String> => <Name+Type, Id> /// </summary> /// <returns>A Dictionnary of strings : Key = Name+TypeId, Value = specId</returns> public static Dictionary <string, int> GetAllNopSpecOpt() { Dictionary <string, int> nopSpecOpt = new Dictionary <string, int>(); string json = WebService.Get(WebApiEntities.SPEC_ATT_OPT); var values = ParserJSon.ParseResultToJTokenList(json); foreach (JToken v in values) { //Name+typeID, cause 2 equal names can be in 2 differents cat try { nopSpecOpt.Add(v["Name"].ToString() + v["SpecificationAttributeId"], (int)v["Id"]); } catch (Exception e) { Program.log(e.Message); Program.log(String.Format("Valeur déjà présente : {0}{1}", v["Name"].ToString(), v["SpecificationAttributeId"].ToString())); Program.log(e.StackTrace); } } return(nopSpecOpt); }
//Récupère les id mercator, les modiftag et les id des produits Nop private List <ProductDatas> GetProductMercatorDatas() { Dictionary <string, int> map = new Dictionary <string, int>(); string jsonPublishedIds = WebService.Get(new UrlBuilder(ENTITY).Select("Id", "Sku", "Published").BuildQuery()); JToken[] products = ParserJSon.ParseResultToJTokenList(jsonPublishedIds); string jsonModiftagIds = WebService.Get(new UrlBuilder("GenericAttribute") .FilterEq("KeyGroup", ENTITY) .FilterEq("Key", KEY_MODIFTAG) .BuildQuery()); JToken[] gaModiftagIdsValues = ParserJSon.ParseResultToJTokenList(jsonModiftagIds); if (gaModiftagIdsValues.Length == 0) { return(new List <ProductDatas>()); } var productsMIds = from p in products join merc in gaModiftagIdsValues on p["Id"] equals merc["EntityId"] into z from q in z.DefaultIfEmpty() select new { Id = p["Id"], Published = p["Published"], MercatorId = p["Sku"], Modiftag = q["Value"] }; var productsDatas = from p in productsMIds join modif in gaModiftagIdsValues on p.Id equals modif["EntityId"] into z from q in z.DefaultIfEmpty() select new ProductDatas { Id = (int)p.Id, Published = (bool)p.Published, MercatorId = p.MercatorId.ToString(), Modiftag = (int)q["Value"] }; //return map; return(productsDatas.ToList()); }
//Update every product url and sync new ones public override bool Sync() { using (SqlConnection connection = new SqlConnection(dataSettings.DataConnectionString)) { try { List <STOCK> prodList = new List <STOCK>(); connection.Open(); string whereClause = String.Format(StockSyncer.WHERE_CLAUSE, -1); prodList = GetMercatorProductListWithUrlDatas(connection, whereClause).ToList(); JToken[] products = ParserJSon.ParseResultToJTokenList(WebService.Get(new UrlBuilder("Product") .FilterEq("Published", true) .Select("Id", "MercatorId") .BuildQuery())); foreach (JToken j in products) { try { STOCK s = prodList.Where(x => x.S_ID.TrimEnd() == j["MercatorId"].ToString().TrimEnd()).FirstOrDefault(); if (s != null) { string newUrl = BuildProductUrl(s, connection); JToken[] urls = ParserJSon.ParseResultToJTokenList(WebService.Get(new UrlBuilder("UrlRecord") .FilterEq("EntityId", (int)j["Id"]) .FilterEq("EntityName", "Product") .BuildQuery())); if (urls.Length > 0) { int urlId = (int)urls.FirstOrDefault()["Id"]; JObject newUrlObject = new JObject(); newUrlObject.Add("Slug", newUrl); WebService.Patch(new UrlBuilder("UrlRecord").Id(urlId).BuildQuery(), newUrlObject.ToString()); } } } catch (Exception e) { Program.log(e.Message); Program.log(e.StackTrace); continue; } } return(true); } catch (Exception e) { return(false); } finally { if (connection != null) { connection.Close(); } } } }
/// <summary> /// Synchronize RFS with Nop's categories /// Sync E-Commerce first (access to everyone) /// Then Sync Restricted access /// </summary> /// <note>RFS to excludes are to add in appconfig file</note> /// <param name="niveau"></param> /// <returns></returns> private bool Sync(RFS.TYPE niveau) { //Get Rayons From Mercator using (SqlConnection connection = new SqlConnection(dataSettings.DataConnectionString)) { IEnumerable <Category> categories = new List <Category>(); //map mercator's ids with nop commerce's existing ids IDictionary <string, int> mapMIdNopId = GetMapIdNopId(); categories = GetRFSAsCategories(connection, mapMIdNopId, niveau); //ID Mercator (url) + id category //rayonID => urlRecordID //rayonID + "SLUG" => catID //var existingUrlRecordsSlugAndCatId = GetExistingUrlRecords(categories); List <int> categoriesToKeep = new List <int>(); //ADD/EDIT RAYONS foreach (Category category in categories) { try { //Format to JSON JObject json = ParserJSon.ParseRFSToNopCategory(category); int catId = 0; //ADD CATEGORY TO NOP if (mapMIdNopId.ContainsKey(category.MercatorId)) { try { catId = mapMIdNopId[category.MercatorId]; //Send via PATCH/PUT (existing ones) WebService.Patch(urlBuilder.Id(catId).BuildQuery(), json.ToString()); //Activate url (in case it was deactivated) JObject urlActivate = new JObject(); urlActivate.Add("IsActive", true); JObject urls = JObject.Parse(WebService.Get(new UrlBuilder("UrlRecord").And().FilterEq("EntityId", catId).FilterEq("EntityName", ENTITY).BuildQuery())); var urlsValues = urls["value"].ToArray(); if (urlsValues.Count() > 0) { WebService.Patch(new UrlBuilder("UrlRecord").Id((int)urlsValues[0]["Id"]).BuildQuery(), urlActivate.ToString()); } } catch (Exception e) { Program.log("Exception lors de la mise à jour de la categorie : " + category.Name.TrimEnd()); Program.log("NopId de la catégorie :" + catId); Program.log(e.Message); Program.log(e.StackTrace); } } else { //Send via POST (new ones) string result = WebService.Post(ENTITY, json.ToString()); JObject newCat = JObject.Parse(result); catId = (int)newCat["Id"]; //ADD URL RECORD JObject urlJson = ParserJSon.GetUrlRecordJson(ENTITY, catId, UrlsSyncer.BuildCategoryUrl(category)); WebService.Post(WebApiEntities.URL_RECORD, urlJson.ToString()); //ADD GENERIC ATTRIBUTE MERCATOR ID JObject genericAttributeJSon = ParserJSon.GetGenericAttributeJSon(catId, ENTITY, KEY_MERCATORID, category.MercatorId); WebService.Post(WebApiEntities.GENERIC_ATTRIBUTE, genericAttributeJSon.ToString()); Console.WriteLine(category.Name + " inserted"); } //Store cat to keep categoriesToKeep.Add(catId); } catch (Exception e) { Program.log(String.Format("Error syncing category : {0}.", category.Name)); Program.log(e.Message); Program.log(e.StackTrace); } } //Delete categories that aren't in Mercator List <int> existings = new List <int>(); List <JToken> values = niveau == RFS.TYPE.RAYON ? JObject.Parse(WebService.Get(urlBuilder.And().FilterEq("Published", true).FilterEq("ParentCategoryId", 0).BuildQuery()))["value"].ToList() : (niveau == RFS.TYPE.FAMILLE ? GetNopFamilles() : GetNopSousFamilles()); foreach (JToken v in values) { if (!(bool)v["Deleted"]) { existings.Add((int)v["Id"]); } } var toDelete = existings.Except(categoriesToKeep); toDelete = toDelete.ToList(); JObject deletedJson = new JObject(); deletedJson.Add("Deleted", true); JObject urlDeactivated = new JObject(); urlDeactivated.Add("IsActive", false); foreach (int i in toDelete) { //Deactivate the deleted category and delete corresponding urlRecord //Instead of published : false => Delete : false ou vraiment la supprimer ? //WebService.Patch(wsCategoryMapping + "(" + s + ")", "{\"Published\":false}"); JObject urls = JObject.Parse(WebService.Get(new UrlBuilder("UrlRecord").And().FilterEq("EntityId", i).FilterEq("EntityName", "Category").BuildQuery())); var urlsValues = urls["value"].ToArray(); //WebService.Patch("UrlRecord("+urlsValues[0]["Id"].ToString()+")","{\"IsActive\":false}"); if (urlsValues.Count() > 0) { Program.log(i + " deleted"); //deleteResult = WebService.Delete(String.Format(WebServiceUrls.URL_RECORD_ID, (int)urlsValues[0]["Id"])); WebService.Patch(new UrlBuilder("UrlRecord").Id((int)urlsValues[0]["Id"]).BuildQuery(), urlDeactivated.ToString()); } //deleteResult = WebService.Delete(String.Format(WebServiceUrls.CATEGORY_ID, i)); WebService.Patch(urlBuilder.Id(i).BuildQuery(), deletedJson.ToString()); } } return(true); }
public override bool Sync() { using (SqlConnection connection = new SqlConnection(dataSettings.DataConnectionString)) { try { connection.Open(); //Get clients (lastActivityDate comes with it) string nopClients = WebService.Get(urlBuilder.FilterNe("Email", null).FilterEq("IsSystemAccount", false).FilterEq("Active", true).Expand("Addresses").BuildQuery()); JToken[] clis = ParserJSon.ParseResultToJTokenList(nopClients); List <Customer> toSync = new List <Customer>(); foreach (JToken c in clis) { try { string mercatorIdResult = WebService.Get(new UrlBuilder("GenericAttribute").And().FilterEq("KeyGroup", ENTITY).FilterEq("Key", KEY_MERCATORID).FilterEq("EntityId", (int)c["Id"]).BuildQuery()); JToken[] mercatorIdToken = ParserJSon.ParseResultToJTokenList(mercatorIdResult); string mercatorId = mercatorIdToken.FirstOrDefault()?["Value"]?.ToString(); if ((DateTimeOffset)c["LastActivityDateUtc"] > DateTimeOffset.Now.AddHours(-12) || mercatorId == null) { string ordersByCliResult = WebService.Get(new UrlBuilder("Order") .FilterEq("CustomerId", c["Id"]) .BuildQuery()); JToken[] ordersTokens = ParserJSon.ParseResultToJTokenList(ordersByCliResult); if (ordersTokens.Length > 0) { var address = c["Addresses"].ToArray(); if (address.Length > 0) { //Prend la première adresse Address a = getAddressFromToken(address[0]); Customer cli = new Customer { Id = (int)c["Id"], Email = c["Email"].ToString(), Username = c["Username"].ToString(), Name = a.FirstName + " " + a.LastName, CreatedOnUtc = (DateTime)c["CreatedOnUtc"], MercatorId = mercatorId, Address1 = a, }; //Fetch Tva JToken[] tvaNumber = ParserJSon.ParseResultToJTokenList(WebService.Get(new UrlBuilder("GenericAttribute") .FilterEq("EntityId", (int)c["Id"]) .FilterEq("KeyGroup", ENTITY) .FilterEq("Key", KEY_VATNUMBER) .BuildQuery())); if (tvaNumber.Length > 0) { cli.Tva = tvaNumber.First()["Value"].ToString(); } toSync.Add(cli); } } } }catch (Exception e) { Program.log(e); } } foreach (Customer c in toSync) { try { //Check if has to be edited or added SigCli sigCli = new SigCli(); bool exists = sigCli.ReadWhere(String.Format("C_ID_WEB = '{0}'", c.Id)); string newMercatorId = ""; if (!exists) { sigCli = createMClient(c); newMercatorId = sigCli.GetField("C_ID").Value.ToString(); } else if ((bool)sigCli.GetField("C_FROM_WEB").Value) //On l'update s'il a été créé sur le site, pas s'il vient de Mercator { if (c.MercatorId == null) { newMercatorId = sigCli.GetField("C_ID").Value.ToString().TrimEnd(); c.MercatorId = newMercatorId; } updateMClient(c); } //Add the newly created mercator id to the nopCommerce customer if (!String.IsNullOrWhiteSpace(newMercatorId)) { JToken[] result = ParserJSon.ParseResultToJTokenList(WebService.Get(new UrlBuilder("GenericAttribute").And().FilterEq("KeyGroup", ENTITY).FilterEq("Key", KEY_MERCATORID).FilterEq("EntityId", c.Id).BuildQuery())); if (result.Length > 0) { if (result.FirstOrDefault()["Value"].ToString() != "") { Program.log(String.Format("Client {0} already has a MercatorId : {1}", c.Id, result[0]["Value"])); } } else { JObject mercatorIdGA = ParserJSon.GetGenericAttributeJSon(c.Id, ENTITY, KEY_MERCATORID, newMercatorId); WebService.Post(WebApiEntities.GENERIC_ATTRIBUTE, mercatorIdGA); } } } catch (Exception e) { Program.log(e); } } } catch (Exception e) { Program.log(e.Message); Program.log(e.StackTrace); return(false); } finally { connection.Close(); } } return(true); }
/// <summary> /// Send the products to the website by WS /// </summary> /// <param name="products"></param> /// <returns>False if an exception has been caught, true if products have been succesfully synced</returns> private void SendProducts(JArray products, bool publish = true, List <STOCK> stocks = null, SqlConnection connection = null) { JObject container = new JObject(); string addedProductsResult = ""; JObject addedProductsResultO = new JObject(); try { //Add the products to the JSON container.Add("products", products); ParserJSon.checkJson(container.ToString()); //Post everything Console.WriteLine("Envoi des produits"); addedProductsResult = WebService.Post(urlBuilder.BuildQueryFct("AddProducts"), container.ToString()); addedProductsResultO = JObject.Parse(addedProductsResult); Console.WriteLine("Produits synchros"); if (publish) { Console.WriteLine("Ajouts URLS && Generic Attributes"); JArray urlList = new JArray(); JArray genericAttributeList = new JArray(); foreach (var j in addedProductsResultO) { STOCK s = stocks.Where(x => x.S_ID.TrimEnd() == j.Value.ToString()).FirstOrDefault(); string url = UrlsSyncer.BuildProductUrl(s, connection); JObject urlJSon = ParserJSon.GetUrlRecordJson(ENTITY, Int32.Parse(j.Key), url); JObject genericAttribute = ParserJSon.GetGenericAttributeJSon(Int32.Parse(j.Key), ENTITY, KEY_MODIFTAG, s.S_MODIFTAG.ToString()); urlList.Add(urlJSon); genericAttributeList.Add(genericAttribute); } JObject urlContainer = new JObject(); JObject gaContainer = new JObject(); urlContainer.Add("urls", urlList); gaContainer.Add("genericAttributes", genericAttributeList); WebService.Post(new UrlBuilder("UrlRecord").BuildQueryFct("AddUrlRecords"), urlContainer.ToString()); WebService.Post(new UrlBuilder("GenericAttribute").BuildQueryFct("AddGenericAttributes"), gaContainer.ToString()); Console.WriteLine("URLS et GA ajoutés"); } } catch (Exception e) { Program.log("Erreur lors de l'envoi des produits"); Program.log(e.Message); Program.log(e.StackTrace); Program.log("These products have failed syncing : "); foreach (JObject jo in products) { Program.WriteLine(jo["Name"].ToString()); Program.log(jo.ToString(), false); } } products.Clear(); }
/// <summary> /// Sync Clients from Mercator to Nop /// </summary> /// <returns></returns> public override bool Sync() { using (SqlConnection connection = new SqlConnection(dataSettings.DataConnectionString)) { try { connection.Open(); //TODO Get clients to be registered => DEFINIR CONDITION List <CLI> mclis = GetMercatorClientsList(connection, WHERE_CLAUSE); //List<CLI> mclis = mClients.Select(x => x.Cli).ToList(); string nopClient = ""; IEnumerable <JToken> clis = null; foreach (CLI c in mclis) { try { if (c.C_ID_WEB != 0) //a déjà été synchro : vérifie si on doit modifier quelque chose { //Get the customer addresses for the given customer Id if it is not deleted nopClient = WebService.Get(urlBuilder .Id(c.C_ID_WEB) .FilterEq("Deleted", false) .Expand("Addresses") .BuildQuery()); clis = ParserJSon.ParseResultToJTokenList(nopClient); if (clis.Count() > 0) { JToken client = clis.FirstOrDefault(); string modiftagResult = WebService.Get(new UrlBuilder("GenericAttribute").And().FilterEq("KeyGroup", ENTITY).FilterEq("Key", KEY_MODIFTAG).FilterEq("EntityId", (int)client["Id"]).BuildQuery()); JToken[] modiftagJtokens = ParserJSon.ParseResultToJTokenList(modiftagResult); string modiftagS = modiftagJtokens.FirstOrDefault()?["Value"]?.ToString(); decimal modiftag = Decimal.Parse(modiftagS); if (modiftag < c.C_MODIFTAG) { var address = client["Addresses"].ToArray(); if (address.Count() > 0) { Address a = GetAddressFromToken(address.Last()); Customer customer = new Customer(c.C_ID, client["Email"].ToString(), client["Username"].ToString(), c.C_NOM.TrimEnd(), (DateTime)client["CreatedOnUtc"], (int)client["Id"], a); customer.Tva = c.C_NUM_TVA?.TrimEnd(); customer.PasswordSalt = client["PasswordSalt"].ToString(); customer.Password = client["Password"].ToString(); updateNopClient(c, customer, modiftagJtokens.First()); } } } else { //Doesn't exist or has been deleted } } else { createNopClient(c); } }catch (Exception e) { Program.log(e); } } } catch (Exception e) { Program.log(e); return(false); } finally { connection.Close(); } return(true); } }
public override bool Sync() { //Get orders placed since last sync (based on Order's id) from Nop using Web Service using (Main Mercator = new Main(directory, null, ConfigurationManager.AppSettings["MercatorLogin"], ConfigurationManager.AppSettings["MercatorMdp"])) { //@"\\serveur\dossier_mercator" using (SqlConnection connection = new SqlConnection(dataSettings.DataConnectionString)) { try { connection.Open(); if (Mercator != null) { MercatorApi.Api.IsWeb = true; string jsonCommandes = ""; jsonCommandes = WebService.Get(new UrlBuilder("GenericAttribute").And().FilterEq("KeyGroup", ENTITY).FilterEq("Key", KEY_SYNCED).FilterEq("Value", "0").BuildQuery()); //jsonCommandes = WebService.Get(WebServiceUrls.ORDER_UNSYNCED); JToken[] commandes = ParserJSon.ParseResultToJTokenList(jsonCommandes); if (commandes.Length == 0) { Program.WriteLine("Pas de nouvelles commandes"); } foreach (JToken co in commandes) { try { string orderResult = WebService.Get(urlBuilder .Id((int)co["EntityId"]) .Expand("OrderItems") .BuildQuery()); //JToken[] orderToken = ParserJSon.ParseResultToJTokenList(orderResult); JObject order = JObject.Parse(orderResult); //if (order.FirstOrDefault() != null) //{ // JToken c = orderToken.FirstOrDefault(); if (((int)order["PaymentStatusId"] == 30 || (int)order["PaymentStatusId"] == 20) || (order["PaymentMethodSystemName"].ToString() == "Payments.CheckMoneyOrder")) { JObject syncMarker = new JObject(); List <int> syncedOrderIds = new List <int>(); var items = (order["OrderItems"]).ToArray(); int id = int.Parse(order["CustomerId"].ToString()); //Get web client SigCli sigCli = new SigCli(); bool exists = sigCli.ReadWhere(String.Format("C_ID_WEB = '{0}'", id)); if (!exists) { Program.log("Commande n°" + order["Id"].ToString() + " non synchronisée car le client " + id + " n'a pas été trouvé dans Mercator."); } else { //Get the journal in which the order has to be placed using (BillingEngine be = BillingEngine.InitNew(Billing.TypeVAEnum.V, 3, journal)) { be.ApplyCustomerSupplier(sigCli.GetField("C_ID").Value.ToString()); if (be.PIEDS != null) { be.PIEDS["DATE"] = DateTime.Parse(order["CreatedOnUtc"].ToString()); } else { throw new Exception("An error occured - please check that the journal exists"); } foreach (JToken i in items) { //Get product ids by SKU (Nop's SKU = S_CLE_1) JObject o = JObject.Parse(WebService.Get(new UrlBuilder("Product").Id((int)i["ProductId"]).Select("Sku").BuildQuery())); string sku = o["Sku"].ToString(); int index = be.AppendLine(); //get from db stock using cle_1 then Add ID be.InsertItem(sku, index, 1); //Use price/vat used when the order was placed : might have been some changes in Mercator since then be.LIGNES.Rows[index]["Q"] = i["Quantity"].Value <Double>() /** condit*/; be.LIGNES.Rows[index]["PU"] = i["UnitPriceExclTax"].Value <Decimal>(); /* * (1 + (i["Remise"].Value<Decimal>() / 100));*/ } //Shipping tax //TODO: faire un doc avec les étapes de l'installation + vérifications à faire //TODO: Verif: Présence d'un article frais de livraison dans le Mercator cible if (Double.Parse(order["OrderShippingInclTax"].ToString()) > 0) { string fraislivraisonId = OptionsMercator.GetOptionValue("NOP_LIV_ID").ToString(); SigStock sigStock = new SigStock(); bool fraisLivFound = sigStock.ReadWhere(String.Format("S_CLE1 = '{0}'", fraislivraisonId)); if (fraisLivFound) { int n = be.AppendLine(); be.InsertItem(sigStock.GetField("S_ID").Value.ToString(), n, 1); be.LIGNES.Rows[n]["PU"] = Double.Parse(order["OrderShippingInclTax"].ToString()) / 1.21; be.LIGNES.Rows[n]["TAUX_TVA"] = 21; } } //CODE PROMO SUR TOTAL COMMANDE //TODO:CODE PROMO - UNCOMMENT IF NECESSARY //if (Double.Parse(c["OrderDiscount"].ToString()) > 0) //{ // string codepromocommandecle1 = ConfigurationManager.AppSettings["CODEPROMOCOMMANDE"]; // SigStock sigStock = new SigStock(); // bool codePromoFound = sigStock.ReadWhere(String.Format("S_CLE1 = '{0}'", codepromocommandecle1)); // if (codePromoFound) // { // int n = be.AppendLine(); // be.InsertItem(sigStock.GetField("S_ID").Value.ToString().S_ID.TrimEnd(), n, 1); // be.LIGNES.Rows[n]["PU"] = (Double.Parse(c["OrderDiscount"].ToString())) * -1; // be.LIGNES.Rows[n]["TAUX_TVA"] = 0; // } //} be.UpdateAmounts(); #region payments //Check if order is paid : c["PaymentStatusId"] -> 10 pending, 30 paid if (order["PaymentStatusId"].ToString() == "10") { switch (order["PaymentMethodSystemName"].ToString()) { case PaymentMethods.NOP_VIREMENT: be.PIEDS["TYP_PAIEM1"] = PaymentMethods.M_VIREMENT; break; case PaymentMethods.NOP_PAYPAL: be.PIEDS["TYP_PAIEM1"] = PaymentMethods.M_PAYPAL; break; default: be.PIEDS["TYP_PAIEM1"] = PaymentMethods.M_VIREMENT; break; } } else if (order["PaymentStatusId"].ToString() == "30") { double tot = Convert.ToDouble(be.PIEDS["TOT_TTC_DV"].ToString()); switch (order["PaymentMethodSystemName"].ToString()) { case PaymentMethods.NOP_VIREMENT: be.PIEDS["TYP_PAIEM1"] = PaymentMethods.M_VIREMENT; break; case PaymentMethods.NOP_PAYPAL: be.PIEDS["TYP_PAIEM1"] = PaymentMethods.M_PAYPAL; break; default: be.PIEDS["TYP_PAIEM1"] = PaymentMethods.M_VIREMENT; break; } //be.PIEDS["TYP_PAIEM1"] = 10; be.PIEDS["TOT_PAIEM1"] = tot; be.PIEDS["NET_DV"] = tot; be.PIEDS["NET_FB"] = tot; } #endregion #region shipment if (order["PickUpInStore"].ToString() == "True") { be.AppendLine(); int nAdresse = be.AppendLine(); be.LIGNES.Rows[nAdresse]["DESIGNATIO"] = "Retrait en magasin"; } else { Address billingA = AddressConverter.ParseJsonToAddress(WebService.Get(new UrlBuilder("Address").Id((int)order["BillingAddressId"]).BuildQuery())); Address shippingA = AddressConverter.ParseJsonToAddress(WebService.Get(new UrlBuilder("Address").Id((int)order["ShippingAddressId"]).BuildQuery())); if (!billingA.Equals(shippingA)) { //be.ApplyCliLiv("ID_CLI_LIV"); be.AppendLine(); int nAdresse = be.AppendLine(); be.LIGNES.Rows[nAdresse]["DESIGNATIO"] = "Adresse de livraison: "; int nN = be.AppendLine(); be.LIGNES.Rows[nN]["DESIGNATIO"] = shippingA.FirstName + " " + shippingA.LastName; int nA = be.AppendLine(); be.LIGNES.Rows[nA]["DESIGNATIO"] = shippingA.Street; int nP = be.AppendLine(); be.LIGNES.Rows[nP]["DESIGNATIO"] = shippingA.ZipPostalCode; int nV = be.AppendLine(); be.LIGNES.Rows[nV]["DESIGNATIO"] = String.Format("{0}, {1}", shippingA.City, shippingA.Country); int nPh = be.AppendLine(); be.LIGNES.Rows[nPh]["DESIGNATIO"] = shippingA.PhoneNumber; //TODO: Mode de livraison UPS + suppléments } } #endregion #region CheckoutAttributes //Récupère les attributs de commandes associés à la commande et les affiches dans les lignes_v //if (order["CheckoutAttributeDescription"].ToString() != "" && order["CheckoutAttributeDescription"].ToString() != "null") //{ // Dictionary<string, string> attributes = extractAttributes(order["CheckoutAttributesXml"].ToString()); // if (attributes.ContainsKey(ATTRIBUT_COMM)) // { // if (attributes[ATTRIBUT_COMM] != "") // { // be.AppendLine(); // int n = be.AppendLine(); // be.LIGNES.Rows[n]["DESIGNATIO"] = "Commentaires: "; // string[] commLines = attributes[ATTRIBUT_COMM].Split(new string[] { "\r" }, StringSplitOptions.None); // foreach (string s in commLines) // { // int nLine = be.AppendLine(); // be.LIGNES.Rows[nLine]["DESIGNATIO"] = s; // } // } // } //} #endregion be.PIEDS["ID_WEB"] = order["Id"].ToString(); be.PIEDS["REFERENCE"] = REF_WEB; if (be.Save()) { be.Close(); syncMarker.Add("Value", "1"); //WebService.Patch(String.Format(WebServiceUrls.ORDER_ID, (int)c["Id"]), syncMarker.ToString()); WebService.Patch(String.Format(new UrlBuilder("GenericAttribute").Id((int)co["Id"]).BuildQuery()), syncMarker.ToString()); } else { //Erreur return(false); } } //} } } } catch (Exception e) { Program.log(e.Message); Program.log(e.StackTrace); return(false); } } //****** UPDATE STATUS ********// Program.WriteLine("Updating Nop Order status..."); string ordersUncomplete = WebService.Get(urlBuilder.FilterEq("OrderStatusId", 20).BuildQuery()); JToken[] orders = ParserJSon.ParseResultToJTokenList(ordersUncomplete); if (orders.Count() > 0) { foreach (JToken o in orders) { int oId = (int)o["Id"]; PiedsV piedsV = new PiedsV(); bool exists = piedsV.Read(oId, "ID_WEB"); if (exists) { JObject patch = new JObject(); patch.Add("OrderStatusId", 30); if (Convert.ToInt32(piedsV.GetField("TYPE").Value) == 2) { patch.Add("PaymentStatusId", 30); patch.Add("ShippingStatusId", 30); } else if (Convert.ToInt32(piedsV.GetField("TYPE").Value) == 1) { patch.Add("OrderStatusId", 30); patch.Add("PaymentStatusId", 30); patch.Add("ShippingStatusId", 40); } WebService.Patch(urlBuilder.Id(oId).BuildQuery(), patch.ToString()); } } } Program.WriteLine("Updated"); } } catch (Exception e) { Program.log(e.Message); Program.log(e.StackTrace); } finally { connection.Close(); } } //context.SaveChanges(); return(true); } }
/// <summary> /// Create a new Customer in NopCommerce from a Mercator CLI /// </summary> /// <param name="c"></param> /// <param name="context"></param> private void createNopClient(CLI c) { //Check if email/username already exists CheckEmailExistence(c); //checkUsernameExistence(c); //Generation random password, or use C_ID? //string password = PasswordManagement.CreatePassword(); string password = c.C_ID; //Add address string addressResult = WebService.Post(WebApiEntities.ADDRESS, ParserJSon.ParseAddressToJson(c, OptionsMercator).ToString()); JObject newAddress = JObject.Parse(addressResult); int addressId = (int)newAddress["Id"]; string clientJson = ParserJSon.ParseClientToJson(c.C_EMAIL.TrimEnd(), DateTimeOffset.Now, password, /*mercatorPrefix+*/ c.C_ID.TrimEnd(), c.C_MODIFTAG).ToString(); string clientResult = WebService.Post(ENTITY, clientJson); JObject newCli = JObject.Parse(clientResult); int id = (int)newCli["Id"]; c.C_ID_WEB = id; //Add TVA Number (if not_empty) //VatNumberStatudId : 10 = empty, 20 = valid if (!String.IsNullOrWhiteSpace(c.C_NUM_TVA)) { List <JObject> entries = ParserJSon.ParseClientCompanyToJson(id, c.C_NUM_TVA.TrimEnd(), c.C_NOM.TrimEnd()); foreach (JObject e in entries) { WebService.Post(WebApiEntities.GENERIC_ATTRIBUTE, e.ToString()); } } JObject linkCliToAddress = new JObject(); linkCliToAddress.Add("@odata.id", WebService.GetStoreAddress() + new UrlBuilder("Address").Id(addressId).BuildQuery()); //link address WebService.Put(urlBuilder.BuildQueryRef(c.C_ID_WEB, "Addresses"), linkCliToAddress.ToString()); //link address as billing address //WebService.Put(String.Format(WebServiceUrls.LINK_CUSTOMER_TO_BILLING_ADDRESS, c.C_ID_WEB.ToString()), linkCliToAddress.ToString()); //link role //3 = Registered (so that he can connect) JObject linkCliToCR = new JObject(); linkCliToCR.Add("@odata.id", WebService.GetStoreAddress() + new UrlBuilder("CustomerRole").Id(3).BuildQuery()); WebService.Put(urlBuilder.BuildQueryRef(c.C_ID_WEB, "CustomerRoles"), linkCliToCR.ToString()); JObject genericAttributeMercatorId = ParserJSon.GetGenericAttributeJSon(id, ENTITY, KEY_MERCATORID, c.C_ID); WebService.Post(WebApiEntities.GENERIC_ATTRIBUTE, genericAttributeMercatorId); JObject genericAttributeModiftagId = ParserJSon.GetGenericAttributeJSon(id, ENTITY, KEY_MODIFTAG, c.C_MODIFTAG.ToString()); WebService.Post(WebApiEntities.GENERIC_ATTRIBUTE, genericAttributeModiftagId); //From Mercator, tarif indiqué dans fiche article //string roleIdResult = WebService.Get(String.Format(WebServiceUrls.CUSTOMER_ROLE_BY_SYSTEM_NAME, WebServiceUrls.TARIF_ + c.C_TARIF)); //JToken[] roleId = ParserJSon.ParseResultToJTokenList(roleIdResult); //linkCliToCR = "{\"@odata.id\":\"" + ConfigurationManager.AppSettings["storeAddress"] + String.Format(WebServiceUrls.CUSTOMER_ROLE_ID, roleId.FirstOrDefault()["Id"].ToString()) + "\"}"; //WebService.Put(String.Format(WebServiceUrls.LINK_CUSTOMER_TO_CR_WS, c.C_ID_WEB.ToString()), linkCliToCR); SigCli sigCli = new SigCli(); sigCli.Read(c.C_ID); sigCli.SetValueForField("C_ID_WEB", c.C_ID_WEB); sigCli.Update(); //context.SaveChanges(); }