Beispiel #1
0
        /// <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);
        }
Beispiel #2
0
        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();
                    }
                }
            }
        }
Beispiel #3
0
        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);
        }
Beispiel #4
0
        /// <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");
        }
Beispiel #5
0
        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()));
        }
Beispiel #6
0
        /// <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);
        }
Beispiel #7
0
        /// <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");
                    }
                }
            }
        }
Beispiel #8
0
        /// <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);
        }
Beispiel #9
0
        /// <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");
                    }
                }
            }
        }
Beispiel #10
0
        /// <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");
                    }
                }
            }
        }
Beispiel #11
0
        /// <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);
        }
Beispiel #12
0
        //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());
        }
Beispiel #13
0
        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);
        }
Beispiel #14
0
        /// <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);
            }
        }
Beispiel #16
0
        //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();
                    }
                }
            }
        }