예제 #1
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);
        }
예제 #2
0
        /// <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();
        }
예제 #3
0
        /// <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();
        }
예제 #4
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()));
        }
예제 #5
0
        /// <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);
        }