Exemple #1
0
        public static void SendEmails()
        {
            var myLock = new object();

            lock (myLock)
            {
                try
                {
                    using (var repository = new TradelrRepository())
                    {
                        bool haveChanges = false;
                        var  mails       = repository.GetMails();
                        foreach (var mail in mails.ToList())
                        {
                            Email.Email.SendMail(mail, true, false);
                            repository.DeleteMail(mail);
                            haveChanges = true;
                        }
                        if (haveChanges)
                        {
                            repository.Save("SendEmails");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Syslog.Write(ex);
                }
            }
        }
Exemple #2
0
        private void AddAuctionItem()
        {
            var call = service.AddItem(ebay_site);

            // insert into database
            using (var repository = new TradelrRepository())
            {
                var product = repository.GetProduct(ProductId);
                product.ebay_product = ebayProduct;

                product.ebay_product.ebayid    = call.ItemID;
                product.ebay_product.siteid    = ebay_site.ToString();
                product.ebay_product.startTime = call.Item.ListingDetails.StartTime;
                product.ebay_product.endTime   = call.Item.ListingDetails.EndTime;
                product.ebay_product.isActive  = true;

                foreach (FeeType fee in call.FeeList)
                {
                    if (fee.Name == "ListingFee")
                    {
                        product.ebay_product.listingFees = Currency.symbol + fee.Fee.Value.ToString("n" + Currency.decimalCount);
                    }
                }

                repository.Save("AddEbayItem");
            }
        }
Exemple #3
0
        public void AddItem()
        {
            var response = service.CreateListing(new CreateListingRequest(item));

            if (response.CreateListingResult.Success)
            {
                // insert into database
                using (var repository = new TradelrRepository())
                {
                    var product = repository.GetProduct(ProductId);
                    product.trademe_product = trademeproduct;

                    product.trademe_product.listingid = response.CreateListingResult.ListingId;
                    product.trademe_product.startTime = DateTime.UtcNow;
                    product.trademe_product.endTime   = DateTime.UtcNow.AddDays(trademeproduct.duration);
                    product.trademe_product.isActive  = true;

                    repository.Save("Trademe.AddItem");
                }
            }
            else
            {
                Syslog.Write(response.CreateListingResult.Description);
            }
        }
Exemple #4
0
        public ActionResult Ebay(string username, string sid)
        {
            using (var repository = new TradelrRepository())
            {
                var odb = repository.GetOAuthToken(sid, OAuthTokenType.EBAY);

                if (odb == null)
                {
                    throw new Exception("Could not locate ebay token entry");
                }

                try
                {
                    var ebayservice = new EbayService();
                    var token       = ebayservice.GetToken(odb.token_key);

                    odb.token_key    = token;
                    odb.token_secret = "";
                    odb.guid         = username;
                    odb.authorised   = true;
                    odb.expires      = ebayservice.TokenExpires;
                    repository.Save();

                    // sync with ebay
                    var ebay = new NetworksEbay(odb.MASTERsubdomain.id);
                    new Thread(() => ebay.StartSynchronisation(false)).Start();
                }
                catch (Exception ex)
                {
                    Syslog.Write(ex);
                }

                return(Redirect(odb.MASTERsubdomain.ToHostName().ToDomainUrl("/dashboard/networks#ebay")));
            }
        }
        public static void PollGoogleBase()
        {
            var myLock = new object();

            lock (myLock)
            {
                var date = DateTime.UtcNow;
                using (var repository = new TradelrRepository())
                {
                    // check for expired items
                    foreach (var sd in repository.GetSubDomains())
                    {
                        var products =
                            repository.GetProducts(sd.id).Where(x => x.gbase.HasValue);

                        foreach (var p in products)
                        {
                            var gb = new GoogleBaseExporter(sd.id, sd.ToHostName());
                            if (date > p.gbase_product.expirydate)
                            {
                                gb.InitValues(p);
#if !DEBUG
                                IEnumerable <Photo> productPhotos = repository.GetImages(PhotoType.PRODUCT, p.id).ToModel(Imgsize.LARGE);
                                gb.AddProductImages(productPhotos);
#endif
                                gb.AddToGoogleBase();

                                // delete old entry
                                gb.DeleteFromGoogleBase(p.gbase_product.externalid);

                                // update gbase entry
                                p.gbase_product.externalid   = gb.entry.Id.AbsoluteUri;
                                p.gbase_product.expirydate   = gb.entry.ExpirationDate;
                                p.gbase_product.externallink = NetworksGbase.URLFromEntry(gb.entry);
                            }
                            else
                            {
                                // get status
                                if (gb.GetFromGoogleBase(p.gbase_product.externalid))
                                {
                                    p.gbase_product.expirydate = gb.entry.ExpirationDate;

                                    if (gb.entry.IsDraft)
                                    {
                                        p.gbase_product.flags |= (int)InventoryItemFlag.DRAFT;
                                    }
                                    else
                                    {
                                        p.gbase_product.flags &= ~(int)InventoryItemFlag.DRAFT;
                                    }
                                }
                            }
                        }
                    }

                    repository.Save("PollGoogleBase");
                }
            }
        }
Exemple #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="photoids">tradelr photo id</param>
        /// <returns>trademe photo id</returns>
        private IEnumerable <int> UploadPhotos(IEnumerable <string> photoids)
        {
            var       ids     = photoids.Select(long.Parse);
            const int timeout = 10000; // 10 seconds
            var       cts     = new CancellationTokenSource();
            var       tasks   = new List <Task>();

            var results = new List <int>();

            var photoservice = new PhotoService(key, secret);

            using (var t = new Timer(_ => cts.Cancel(), null, timeout, -1))
            {
                foreach (var photoid in ids)
                {
                    var task = Task.Factory.StartNew(() =>
                    {
                        using (var repository = new TradelrRepository())
                        {
                            var image = repository.GetProductImage(photoid);
                            if (image != null)
                            {
                                if (image.trademephotoid.HasValue)
                                {
                                    results.Add(image.trademephotoid.Value);
                                }
                                else
                                {
                                    // we need to upload photo
                                    var photoreq = new PhotoUploadRequest
                                    {
                                        FileName        = Path.GetFileName(image.url),
                                        FileType        = Path.GetExtension(image.url).Substring(1),
                                        IsWaterMarked   = true,
                                        IsUsernameAdded = true,
                                        PhotoData       = Img.ConvertToBase64String(GeneralConstants.APP_ROOT_DIR + image.url)
                                    };

                                    photoreq.GenerateSignature();

                                    var resp = photoservice.AddPhoto(new AddPhotoRequest(photoreq));
                                    if (resp.AddPhotoResult.Status == PhotoStatus.Success)
                                    {
                                        results.Add(resp.AddPhotoResult.PhotoId);
                                        image.trademephotoid = resp.AddPhotoResult.PhotoId;
                                        repository.Save();
                                    }
                                }
                            }
                        }
                    }, cts.Token);
                    tasks.Add(task);
                }
            }
            Task.WaitAll(tasks.ToArray());

            return(results.ToArray());
        }
Exemple #7
0
        public static image ReadAndSaveFromUrl(this string url, long subdomainid, long ownerid, long contextid, PhotoType type)
        {
            var         req  = WebRequest.Create(url);
            WebResponse resp = null;

            try
            {
                resp = req.GetResponse();
            }
            catch (Exception ex)
            {
                Syslog.Write(ex);
            }

            if (resp == null)
            {
                return(null);
            }
            try
            {
                var image = new image();
                using (var repository = new TradelrRepository())
                {
                    var sd        = repository.GetSubDomain(subdomainid);
                    var extension = url.ToImageFormat().ToStringExtension();
                    var filename  = BuildFilename(ownerid, extension);
                    var handler   = new FileHandler(filename, UploadFileType.IMAGE, sd.uniqueid);

                    image.imageType = type.ToString();
                    image.subdomain = subdomainid;
                    image.contextID = contextid;
                    image.url       = handler.Save(resp.GetResponseStream());

                    repository.AddImage(image);
                    switch (type)
                    {
                    case PhotoType.PROFILE:
                        var usr = repository.GetUserById(ownerid);
                        if (usr != null)
                        {
                            usr.profilePhoto = image.id;
                        }
                        repository.Save("ReadAndSaveFromUrl:Profile");
                        break;

                    default:
                        break;
                    }
                }
                return(image);
            }
            catch (Exception ex)
            {
                Syslog.Write(ex);
                return(null);
            }
        }
Exemple #8
0
        private bool saveToken(OAuthTokenType tokenType, string oauth_token, string oauth_verifier)
        {
            using (var repository = new TradelrRepository())
            {
                // oauth_token here would match request token saved in db
                // normally access token is different from request token
                var odb = repository.GetOAuthToken(oauth_token, tokenType);
                if (odb == null)
                {
                    return(false);
                }

                accountHostName = odb.MASTERsubdomain.ToHostName();

                OAuthClient client = null;
                switch (tokenType)
                {
                case OAuthTokenType.YAHOO:
                    client = new OAuthClient(tokenType,
                                             OAuthClient.OAUTH_YAHOO_CONSUMER_KEY,
                                             OAuthClient.OAUTH_YAHOO_CONSUMER_SECRET,
                                             odb.token_key,
                                             odb.token_secret,
                                             oauth_verifier);
                    break;

                case OAuthTokenType.TRADEME:
                    client = new OAuthClient(tokenType, OAuthClient.OAUTH_TRADEME_CONSUMER_KEY,
                                             OAuthClient.OAUTH_TRADEME_CONSUMER_SECRET,
                                             odb.token_key,
                                             odb.token_secret,
                                             oauth_verifier,
                                             "HMAC-SHA1",
                                             "MyTradeMeRead,MyTradeMeWrite");
                    break;

                default:
                    break;
                }

                if (client == null ||
                    !client.GetAccessToken())
                {
                    return(false);
                }

                odb.token_key    = client.oauth_token;
                odb.token_secret = client.oauth_secret;
                odb.guid         = client.guid;
                odb.authorised   = true;
                repository.Save();
            }
            return(true);
        }
Exemple #9
0
        public void ClearSynchronisation()
        {
            using (var repository = new TradelrRepository())
            {
                repository.DeleteOAuthToken(subdomainid, OAuthTokenType.EBAY);

                // delete inventory location
                repository.DeleteInventoryLocation(Networks.LOCATIONNAME_EBAY, subdomainid);
                repository.Save();
            }
        }
 public void UpdateProductGbaseID(string gbaseid)
 {
     using (var repository = new TradelrRepository())
     {
         var p = repository.GetProduct(ProductId);
         if (p != null)
         {
             p.gbaseID = gbaseid;
             repository.Save();
         }
     }
 }
Exemple #11
0
        public static product_image ReadAndSaveProductImageFromUrl(this string url, long subdomainid, long ownerid, long?productid)
        {
            var         req  = WebRequest.Create(url);
            WebResponse resp = null;

            try
            {
                resp = req.GetResponse();
            }
            catch (Exception ex)
            {
                Syslog.Write(ex);
            }

            if (resp == null)
            {
                return(null);
            }
            try
            {
                var image = new product_image();
                using (var repository = new TradelrRepository())
                {
                    var sd        = repository.GetSubDomain(subdomainid);
                    var extension = url.ToImageFormat().ToStringExtension();
                    var filename  = BuildFilename(ownerid, extension);

                    var handler = new FileHandler(filename, UploadFileType.IMAGE, sd.uniqueid);

                    image.productid   = productid;
                    image.subdomainid = subdomainid;
                    image.url         = handler.Save(resp.GetResponseStream());

                    if (productid.HasValue)
                    {
                        repository.AddProductImage(image);
                        var product = repository.GetProduct(productid.Value, subdomainid);
                        if (product != null && !product.thumb.HasValue)
                        {
                            product.thumb = image.id;
                        }
                        repository.Save("ReadAndSaveProductImageFromUrl");
                    }
                }
                return(image);
            }
            catch (Exception ex)
            {
                Syslog.Write(ex);
                return(null);
            }
        }
        public ActionResult Single(long?id, string title, bool isJson = false)
        {
            if (!id.HasValue)
            {
                return(Content(CreatePageMissingTemplate().Render()));
            }
            // if store disabled then hide the product
            if (!IsStoreEnabled && !sessionid.HasValue)
            {
                return(RedirectToAction("Index", "login"));
            }

            LiquidTemplate template;

            using (var repo = new TradelrRepository())
            {
                repo.SetIsolationToNoLock();
                var p = repo.GetProduct(id.Value, subdomainid.Value);

                if (p == null)
                {
                    return(Content(CreatePageMissingTemplate().Render()));
                }
                var liquidmodel = p.ToLiquidModel(sessionid, "");

                if (isJson)
                {
                    return(Json(liquidmodel, JsonRequestBehavior.AllowGet));
                }

                if (p.hits.HasValue)
                {
                    p.hits += 1;
                }
                else
                {
                    p.hits = 1;
                }
                repo.Save();

                template = CreateLiquidTemplate("product", p.title);

                // opengraph
                var opengraph = MASTERdomain.organisation.ToOpenGraph(p, null);
                template.AddHeaderContent(this.RenderViewToString("~/Views/store/liquid/defaultHeader.ascx", opengraph));
                template.InitContentTemplate("templates/product.liquid");
                template.AddParameters("product", liquidmodel);
            }
            return(Content(template.Render()));
        }
Exemple #13
0
        public void UpdateEbayItem(string itemid)
        {
            // todo: get fields which were deletedd
            // http://developer.ebay.com/DevZone/xml/docs/Reference/ebay/ReviseItem.html#Request.DeletedField
            service.ReviseItem(itemid, Enumerable.Empty <string>(), ebay_site);

            // insert into database
            using (var repository = new TradelrRepository())
            {
                var product = repository.GetProduct(ProductId);
                product.ebay_product        = ebayProduct;
                product.ebay_product.ebayid = itemid;

                repository.Save("Ebay.UpdateEbayItem");
            }
        }
 public void UpdateID(int postid)
 {
     Debug.Assert(ProductId != 0);
     using (var repository = new TradelrRepository())
     {
         var w = repository.GetProduct(ProductId).wordpressPosts;
         if (w == null)
         {
             w = new wordpressPost();
             repository.AddWordpressPost(w);
         }
         w.productid = ProductId;
         w.postid    = postid;
         repository.Save();
     }
 }
        public string AddToGoogleBase()
        {
            UpdateEntry();
            // try insert
            string gbaseId = "";
            bool hasError = false;
            try
            {
                entry = service.Insert(feed, entry);
                gbaseId = entry.Id.AbsoluteUri;
            }
            catch (WebException ex)
            {
                var resp = ex.Response;
                hasError = true;
                if (resp != null)
                {
                    using (var sr = new StreamReader(resp.GetResponseStream()))
                    {
                        var err = sr.ReadToEnd();
                        Syslog.Write(string.Concat("ADD: ", err, " ", hostName, " ", ProductId));
                    }
                }
            }
            catch (Exception ex)
            {
                Syslog.Write(ex);
                Syslog.Write(string.Concat("ADD: ", ex.Message, " ", hostName, " ", ProductId));
                hasError = true;
            }

            if (hasError && ownerid.HasValue)
            {
                using (var repository = new TradelrRepository())
                {
                    repository.AddActivity(ownerid.Value,
                                   new ActivityMessage(ProductId, ownerid,
                                               ActivityMessageType.AUTOPOST_GBASE_FAIL,
                                               string.Format("<a href='{0}'>{1}</a>", producturl, productname)),
                                               subdomainid);
                    repository.Save(); 
                }
                
            }

            return gbaseId;
        }
Exemple #16
0
        public void UpdateID(string postid)
        {
            Debug.Assert(ProductId != 0);

            using (var repository = new TradelrRepository())
            {
                var t = repository.GetProduct(ProductId).tumblrPosts;
                if (t == null)
                {
                    t = new tumblrPost();
                    repository.AddTumblrPost(t);
                }
                t.productid = ProductId;
                t.postid    = postid;
                repository.Save();
            }
        }
        public int?PostEntry()
        {
            Debug.Assert(post != null);
            bool hasError = false;
            int? postid   = null;

            try
            {
#if DEBUG
                postid = wrapper.NewPost(post, false);
#else
                postid = wrapper.NewPost(post, true);
#endif
            }
            catch (WebException ex)
            {
                var resp = ex.Response;
                if (resp != null)
                {
                    using (var sr = new StreamReader(resp.GetResponseStream()))
                    {
                        var err = sr.ReadToEnd();
                        hasError = true;
                        Syslog.Write(string.Concat("Wordpress Post: ", err, " ", hostName, " ", postid));
                    }
                }
            }
            catch (Exception ex)
            {
                hasError = true;
                Syslog.Write(string.Concat("Wordpress Post: ", ex.Message, " ", hostName, " ", postid));
            }
            if (hasError)
            {
                using (var repository = new TradelrRepository())
                {
                    repository.AddActivity(ownerid.Value,
                                           new ActivityMessage(ProductId, ownerid,
                                                               ActivityMessageType.AUTOPOST_WORDPRESS_FAIL,
                                                               string.Format("<a href='{0}'>{1}</a>", producturl, productname)),
                                           subdomainid);
                    repository.Save();
                }
            }
            return(postid);
        }
        public bool UpdateToGoogleBase()
        {
            bool hasError = false;
            try
            {
                var atomid = service.Update(entry).Id.AbsoluteUri;
                if (AtomID != atomid)
                {
                    Syslog.Write(string.Format("Inserted GBASE not equal, productid {0} :{1} {2}", ProductId, AtomID, atomid));
                }
            }
            catch(WebException ex)
            {
                var resp = ex.Response;
                hasError = true;
                if (resp != null)
                {
                    using (var sr = new StreamReader(resp.GetResponseStream()))
                    {
                        var err = sr.ReadToEnd();
                        Syslog.Write(string.Format("Update err: {0}, hostname: {1}", err, hostName));
                    }
                }
            }
            catch (Exception ex)
            {
                Syslog.Write(ex);
                hasError = true;
            }

            if (hasError && ownerid.HasValue)
            {
                using (var repository = new TradelrRepository())
                {
                    repository.AddActivity(ownerid.Value,
                                   new ActivityMessage(ProductId, ownerid,
                                               ActivityMessageType.AUTOPOST_GBASE_FAIL,
                                               string.Format("<a href='{0}'>{1}</a>", producturl, productname)),
                                               subdomainid);
                    repository.Save();
                }
                
                return false;
            }
            return true;
        }
        public void GetBlogEntry(product p, int postid)
        {
            bool hasError = false;

            try
            {
                post = wrapper.GetPost(postid);
            }
            catch (WebException ex)
            {
                var resp = ex.Response;
                if (resp != null)
                {
                    using (var sr = new StreamReader(resp.GetResponseStream()))
                    {
                        var err = sr.ReadToEnd();

                        Syslog.Write(string.Concat("Wordpress Get entry: ", err, " ", hostName, " "));
                    }
                }
                hasError = true;
            }
            catch (Exception ex)
            {
                hasError = true;
                Syslog.Write(string.Concat("Wordpress Get entry: ", ex.Message, " ", hostName, " "));
            }

            if (hasError)
            {
                using (var repository = new TradelrRepository())
                {
                    repository.AddActivity(ownerid.Value,
                                           new ActivityMessage(ProductId, ownerid,
                                                               ActivityMessageType.AUTOPOST_WORDPRESS_FAIL,
                                                               string.Format("<a href='{0}'>{1}</a>", producturl, productname)),
                                           subdomainid);
                    repository.Save();
                }
            }

            FillBlogEntry(p);
        }
Exemple #20
0
        public override void StartSynchronisation(bool?upload)
        {
            using (var repository = new TradelrRepository())
            {
                // create default shipping profile
                var sd = repository.GetSubDomain(subdomainid);

                if (sd == null)
                {
                    throw new ArgumentException("Cannot find domain for subdomainid " + subdomainid);
                }

                // create network location
                var inventoryLocation = new inventoryLocation
                {
                    name       = LOCATIONNAME_EBAY,
                    subdomain  = subdomainid,
                    lastUpdate = DateTime.UtcNow
                };
                repository.AddInventoryLocation(inventoryLocation, subdomainid);

                // add shipping profile if there's none
                foreach (var site in EbayService.SupportedSites)
                {
                    if (sd.ebay_shippingprofiles.Count(x => x.siteid == site.ToString()) != 0)
                    {
                        continue;
                    }

                    var shippingprofile = new ebay_shippingprofile
                    {
                        title  = "Default",
                        siteid = site.ToString()
                    };

                    sd.ebay_shippingprofiles.Add(shippingprofile);

                    repository.Save("ebay.StartSynchronisation");
                }
            }
        }
Exemple #21
0
        public static void PollForShipwireShippedStatus()
        {
            var myLock = new object();

            lock (myLock)
            {
                try
                {
                    using (var repository = new TradelrRepository())
                    {
                        bool haveChanges = ShipwirePollForShippedStatus(repository);
                        if (haveChanges)
                        {
                            repository.Save("PollForShipwireShippedStatus");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Syslog.Write(ex);
                }
            }
        }
Exemple #22
0
        public static void PollPaypalPaymentDetails()
        {
            var myLock = new object();

            lock (myLock)
            {
                try
                {
                    using (var repository = new TradelrRepository())
                    {
                        bool haveChanges = PaypalHandleBuyerPaidAndWeNeedToVerify(repository);
                        if (haveChanges)
                        {
                            repository.Save("PollPaypalPaymentDetails");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Syslog.Write(ex);
                }
            }
        }
Exemple #23
0
        private void Update()
        {
            if (string.IsNullOrEmpty(warehouse))
            {
                Syslog.Write(string.Format("Shipwire warehouse not specified: {0}", subdomainid));
                return;
            }
            service.CreateInventoryUpdate(warehouse);
            var resp = service.SubmitInventoryUpdate();

            if (resp != null)
            {
                // check for Error
                if (resp.Status == ShipwireService.StatusError && resp.ErrorMessage.ToLower().Contains("password"))
                {
                    // clear invalid credentials
                    using (var repository = new TradelrRepository())
                    {
                        var sd = repository.GetSubDomain(subdomainid);
                        if (sd != null)
                        {
                            sd.shipwireEmail    = "";
                            sd.shipwirePassword = "";
                            repository.Save();
                        }
                    }
                }

                // we want to create a location only if there are products
                if (resp.Products.Count != 0)
                {
                    Debug.WriteLine(string.Format("{0}: {1} products", warehouse, resp.Products.Count));
                    using (var repository = new TradelrRepository())
                    {
                        // if items not zero then we create inventory location if it does not already exist
                        var inventoryloc = new inventoryLocation
                        {
                            subdomain  = subdomainid,
                            name       = warehouse,
                            lastUpdate = DateTime.UtcNow
                        };
                        var locid = repository.AddInventoryLocation(inventoryloc, subdomainid);
                        // we go through each product
                        foreach (var product in resp.Products)
                        {
                            var variant = repository.GetProductVariant(product.code, subdomainid, ProductFlag.ARCHIVED);
                            // if product exist and not archived
                            if (variant != null)
                            {
                                Debug.WriteLine("Existing product: " + product.code);
                                // then we just update the inventorylocitem
                                var ilocitem =
                                    repository.GetInventoryLocationItems(locid, subdomainid).SingleOrDefault(x => x.variantid == variant.id);
                                if (ilocitem == null)
                                {
                                    // can be null from do these updates from Shipwire as we're doing on a per location basis
                                    // anyway create an entry
                                    ilocitem = new inventoryLocationItem
                                    {
                                        variantid  = variant.id,
                                        locationid = locid,
                                        lastUpdate = DateTime.UtcNow,
                                        available  = product.quantity
                                    };
                                    repository.AddInventoryLocationItem(ilocitem, subdomainid);
                                }
                                else
                                {
                                    // just update as this is a sync
                                    ilocitem.available  = product.quantity;
                                    ilocitem.lastUpdate = DateTime.UtcNow;
                                    repository.Save("InventoryUpdate Update");
                                }
                            }
                            else
                            {
                                Debug.WriteLine("New product: " + product.code);

                                // create new product
                                var productInfo = new ProductInfo();

                                // do product
                                var p = new product
                                {
                                    subdomainid = subdomainid,
                                    title       = product.code,
                                    details     = "",
                                    created     = DateTime.UtcNow
                                };
                                productInfo.p = p;
                                variant       = new product_variant();
                                variant.sku   = product.code;

                                // do inventory location item
                                var ilocitem = new inventoryLocationItem
                                {
                                    variantid  = variant.id,
                                    locationid = locid,
                                    lastUpdate = DateTime.UtcNow
                                };
                                var invWorker = new InventoryWorker(ilocitem, subdomainid, true, false); // assume not digital
                                invWorker.SetValues("Shipwire Update", product.quantity, null, null, null);
                                variant.inventoryLocationItems.Add(ilocitem);
                                productInfo.p.product_variants.Add(variant);

                                // finally add to db
                                repository.AddProduct(productInfo, subdomainid);
                            }
                        }
                    }
                }
                else
                {
                    //Syslog.Write(ErrorLevel.WARNING,string.Format("{0}: No products", warehouse));
                }
            }
            else
            {
                Syslog.Write("No response from warehouse " + warehouse);
            }
        }
Exemple #24
0
        private void SaveEbayOrders(OrderTypeCollection collection)
        {
            using (var repository = new TradelrRepository())
            {
                foreach (OrderType entry in collection)
                {
                    Transaction transaction;
                    // check if order already exists
                    var existingEbayOrder = repository.GetSubDomain(sd.id).ebay_orders.SingleOrDefault(x => x.orderid == entry.OrderID);

                    if (existingEbayOrder != null)
                    {
                        var order = existingEbayOrder.orders.Single();
                        transaction = new Transaction(order, repository, seller.id);

                        // update order status
                        existingEbayOrder.status = entry.OrderStatus.ToString();
                    }
                    else
                    {
                        // check if user already exists
                        var buyer = repository.GetUserByEbayID(entry.BuyerUserID);

                        if (buyer == null)
                        {
                            // get receiver and add to contact db
                            var userService = new UserService(token);

                            // get by itemid as invalid request seems to be returned when get by userid
                            var ebaybuyer = userService.GetUser(entry.BuyerUserID);

                            // we assume that same buyer for all transactions so we get the first email address
                            var buyeremail = entry.TransactionArray.ItemAt(0).Buyer.Email;

                            buyer = SaveEbayBuyer(ebaybuyer, buyeremail);
                        }

                        // add a shipping and billing address
                        if (entry.ShippingAddress != null)
                        {
                            var buyername = Utility.SplitFullName(entry.ShippingAddress.Name);
                            var handler   = new AddressHandler(buyer.organisation1, repository);
                            handler.SetShippingAndBillingAddresses(buyername[0],
                                                                   buyername[1],
                                                                   entry.ShippingAddress.CompanyName ?? "",
                                                                   entry.ShippingAddress.Street1 + "\r\n" + entry.ShippingAddress.Street2,
                                                                   entry.ShippingAddress.CityName,
                                                                   null,
                                                                   entry.ShippingAddress.PostalCode,
                                                                   entry.ShippingAddress.Phone,
                                                                   entry.ShippingAddress.Country.ToString().ToCountry().id,
                                                                   entry.ShippingAddress.StateOrProvince,
                                                                   entry.ShippingAddress.StateOrProvince,
                                                                   entry.ShippingAddress.StateOrProvince,
                                                                   buyername[0],
                                                                   buyername[1],
                                                                   entry.ShippingAddress.CompanyName ?? "",
                                                                   entry.ShippingAddress.Street1 + "\r\n" + entry.ShippingAddress.Street2,
                                                                   entry.ShippingAddress.CityName,
                                                                   null,
                                                                   entry.ShippingAddress.PostalCode,
                                                                   entry.ShippingAddress.Phone,
                                                                   entry.ShippingAddress.Country.ToString().ToCountry().id,
                                                                   entry.ShippingAddress.StateOrProvince,
                                                                   entry.ShippingAddress.StateOrProvince,
                                                                   entry.ShippingAddress.StateOrProvince,
                                                                   true);
                        }

                        // add normal order
                        transaction = new Transaction(sd, buyer, TransactionType.INVOICE, repository, seller.id);

                        transaction.CreateTransaction(repository.GetNewOrderNumber(sd.id, TransactionType.INVOICE),
                                                      entry.CreatedTime, "",
                                                      entry.AmountPaid.currencyID.ToString().ToCurrency().id);

                        // mark as sent
                        var tradelr_orderstatus = GetOrderStatus(entry.OrderStatus);
                        transaction.UpdateOrderStatus(tradelr_orderstatus);

                        // add ebay specific order information
                        var newEbayOrder = new ebay_order();
                        newEbayOrder.orderid     = entry.OrderID;
                        newEbayOrder.status      = entry.OrderStatus.ToString();
                        newEbayOrder.created     = entry.CreatedTime;
                        newEbayOrder.subdomainid = sd.id;
                        transaction.AddEbayOrderInformation(newEbayOrder);

                        foreach (eBay.Service.Core.Soap.TransactionType trans in entry.TransactionArray)
                        {
                            var ebay_itemid = trans.Item.ItemID;

                            // get product details
                            var itemservice = new ItemService(token);
                            var item        = itemservice.GetItem(ebay_itemid);

                            // add new product if necessary
                            var existingproduct = repository.GetProducts(sd.id).SingleOrDefault(x => x.ebayID.HasValue && x.ebay_product.ebayid == ebay_itemid);
                            if (existingproduct == null)
                            {
                                // add new product  (triggered when synchronisation is carried out the first time)
                                var newproduct = new Listing();
                                newproduct.Populate(item);
                                var importer = new ProductImport();
                                var pinfo    = importer.ImportEbay(newproduct, sd.id);

                                repository.AddProduct(pinfo, sd.id);
                                existingproduct = pinfo.p;
                            }
                            else
                            {
                                // if existing product is completed then we need to relist
                                if (entry.OrderStatus == OrderStatusCodeType.Completed ||
                                    entry.OrderStatus == OrderStatusCodeType.Shipped)
                                {
                                    // see if product listing is still active
                                    if (item.SellingStatus.ListingStatus == ListingStatusCodeType.Completed ||
                                        item.SellingStatus.ListingStatus == ListingStatusCodeType.Ended)
                                    {
                                        // set status to inactive
                                        existingproduct.ebay_product.isActive = false;

                                        // check if we should autorelist
                                        if (existingproduct.ebay_product.autorelist)
                                        {
                                            // check that product has enough stock
                                            if (existingproduct.HasStock(existingproduct.ebay_product.quantity))
                                            {
                                                var exporter =
                                                    new EbayExporter(
                                                        existingproduct.ebay_product.siteid.ToEnum <SiteCodeType>(),
                                                        sd.ToHostName(),
                                                        token,
                                                        sd);

                                                exporter.BuildItem(existingproduct.ebay_product);
                                            }
                                        }
                                    }
                                }
                            }

                            // add tradelr order item
                            var orderItem = new orderItem
                            {
                                description = item.Title,
                                variantid   = existingproduct.product_variants[0].id,
                                unitPrice   = (decimal)trans.TransactionPrice.Value,
                                quantity    = trans.QuantityPurchased
                            };

                            if (trans.Taxes != null)
                            {
                                orderItem.tax =
                                    (decimal)(trans.Taxes.TotalTaxAmount.Value / trans.TransactionPrice.Value);
                            }

                            transaction.AddOrderItem(orderItem, null);

                            // update inventory
                            transaction.UpdateInventoryItem(orderItem, trans.QuantityPurchased);

                            // add ebay order item
                            var ebayorderitem = new ebay_orderitem();
                            ebayorderitem.lineid = trans.OrderLineItemID;
                            newEbayOrder.ebay_orderitems.Add(ebayorderitem);
                        }

                        // update shipping
                        transaction.UpdateShippingCost(entry.ShippingServiceSelected.ShippingServiceCost.Value.ToString());
                        transaction.UpdateShippingMethod(entry.ShippingServiceSelected.ShippingService);

                        // update tax : ebay tax is the shipping tax which applies to the entire order total
                        // may or may not include shipping cost
                        if (entry.ShippingDetails.SalesTax != null)
                        {
                            transaction.UpdateOrderTax((decimal)entry.ShippingDetails.SalesTax.SalesTaxPercent,
                                                       entry.ShippingDetails.SalesTax.ShippingIncludedInTax);
                        }


                        transaction.UpdateTotal();
                        transaction.SaveNewTransaction(); ////////////////////// SAVE INVOICE
                    }

                    // the following applies to both new and existing order
                    var existingPayment = transaction.GetPayments().SingleOrDefault(x => x.reference == entry.OrderID);
                    if (existingPayment != null)
                    {
                        var newstatus = GetPaymentStatus(entry.CheckoutStatus.Status);
                        if (existingPayment.status != newstatus.ToString())
                        {
                            transaction.UpdatePaymentStatus(existingPayment, newstatus);
                        }
                    }
                    else
                    {
                        // if payment has been made then add payment
                        if (entry.CheckoutStatus.Status == CompleteStatusCodeType.Complete)
                        {
                            var p = new DBML.payment();
                            p.status     = GetPaymentStatus(entry.CheckoutStatus.Status).ToString();
                            p.method     = entry.CheckoutStatus.PaymentMethod.ToString();
                            p.created    = entry.CheckoutStatus.LastModifiedTime;
                            p.notes      = entry.BuyerCheckoutMessage;
                            p.paidAmount = (decimal)entry.AmountPaid.Value;
                            p.reference  = entry.OrderID;

                            transaction.AddPayment(p, false);
                        }
                    }

                    // if there is a shipped date, mark as ship if not already done so
                    if (transaction.GetOrderStatus() != OrderStatus.SHIPPED &&
                        entry.ShippedTimeSpecified)
                    {
                        transaction.UpdateOrderStatus(OrderStatus.SHIPPED);

                        if (entry.ShippingDetails.ShipmentTrackingDetails.Count != 0)
                        {
                            foreach (ShipmentTrackingDetailsType trackentry in entry.ShippingDetails.ShipmentTrackingDetails)
                            {
                                var comment = string.Format(OrderComment.ORDER_SHIP_STANDARD,
                                                            trackentry.ShippingCarrierUsed,
                                                            trackentry.ShipmentTrackingNumber);
                                transaction.AddComment(comment);
                            }
                        }
                        else
                        {
                            transaction.AddComment(OrderComment.ORDER_SHIP, created: entry.ShippedTime);
                        }
                    }
                    repository.Save();  // save per order
                }
            }
        }
Exemple #25
0
        public override void StartSynchronisation(bool?upload)
        {
            // pull items
            var gbase = new GoogleBaseExporter(subdomainid, hostName, sessionid);

            gbase.GetAllProducts();
            using (var repository = new TradelrRepository())
            {
                // create network location
                var inventoryLocation = new inventoryLocation
                {
                    name       = LOCATIONNAME_GBASE,
                    subdomain  = subdomainid,
                    lastUpdate = DateTime.UtcNow
                };
                locationid = repository.AddInventoryLocation(inventoryLocation, subdomainid);

                // init some settings
                locationid = repository.GetInventoryLocation(LOCATIONNAME_GBASE, subdomainid).id;
                currency   = repository.GetSubDomain(subdomainid).currency.ToCurrency();

                var products = repository.GetProducts(subdomainid);
                foreach (var entry in gbase.entries)
                {
                    ProductEntry entry1       = entry;
                    var          oldTypeEntry = products.SingleOrDefault(x => x.gbaseID == entry1.Id.AbsoluteUri);
                    if (oldTypeEntry != null)
                    {
                        // old type entry exists

                        // remove id
                        oldTypeEntry.gbaseID = null;

                        // create gbase entry, don't need to create a variant since one would already exist
                        oldTypeEntry.gbase_product = CreateGbaseInformationEntry(entry);
                    }
                    else
                    {
                        var newtypeEntry =
                            products.Where(x => x.gbase_product.externalid == entry1.Id.AbsoluteUri).Select(
                                x => x.gbase_product).SingleOrDefault();
                        if (newtypeEntry != null)
                        {
                            // new type entry exists
                            // update status
                            newtypeEntry.expirydate = entry.ExpirationDate;
                            if (entry.IsDraft)
                            {
                                newtypeEntry.flags |= (int)InventoryItemFlag.DRAFT;
                            }
                            else
                            {
                                newtypeEntry.flags &= ~(int)InventoryItemFlag.DRAFT;
                            }
                        }
                        else
                        {
                            // entry does not exist
                            // create and add entry to tradelr
                            var p = CreateProductFromEntry(entry);

                            // create variant
                            var variants = new List <product_variant>();

                            var variant = new product_variant()
                            {
                                sku =
                                    string.Concat("GBASE", entry.Id.AbsoluteUri.Substring(
                                                      entry.Id.AbsoluteUri.LastIndexOf('/') + 1))
                            };
                            variants.Add(variant);

                            // add gbase info
                            p.gbase_product = CreateGbaseInformationEntry(entry);
                            p.product_variants.AddRange(variants);
                            var pinfo = new ProductInfo()
                            {
                                p = p
                            };
                            repository.AddProduct(pinfo, subdomainid);

                            // images
                            foreach (var link in entry.AdditionalImageLinks)
                            {
                                var image = link.Value.ReadAndSaveProductImageFromUrl(subdomainid, sessionid, p.id);
                                p.thumb = image.id;
                            }
                        }
                    }
                }

                // upload to google base for each entry that does not have a special entry
                if (upload.HasValue && upload.Value)
                {
                    var newproducts =
                        repository.GetProducts(subdomainid).Where(
                            x => !x.gbase.HasValue && (x.flags & (int)ProductFlag.ARCHIVED) == 0);
                    foreach (var p in newproducts)
                    {
                        var gb = new GoogleBaseExporter(subdomainid, hostName, sessionid);
                        gb.InitValues(p);
#if !DEBUG
                        IEnumerable <Photo> productPhotos = repository.GetImages(PhotoType.PRODUCT, p.id).ToModel(Imgsize.LARGE);
                        gb.AddProductImages(productPhotos);
#endif
                        var worker = new GoogleBaseWorker(gb);
                        new Thread(worker.Post).Start();
                    }
                }

                // save
                repository.Save();
            }
        }
Exemple #26
0
        public void ipn(string txn_id, string custom, string mc_gross, string payment_status, string receiver_email)
        {
            //Per PayPal Order Management / Integration Guide Pg.25
            //we have to validate message by sending message back to paypal
            //Post back to either sandbox or live
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PaymentConstants.PaypalPostAddress);

            //Set values for the request back
            req.Method      = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] param      = Request.BinaryRead(Request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(param);

            strRequest       += "&cmd=_notify-validate";
            req.ContentLength = strRequest.Length;

            //for proxy
            //WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
            //req.Proxy = proxy;

            //Send the request to PayPal and get the response
            StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);

            streamOut.Write(strRequest);
            streamOut.Close();
            StreamReader streamIn    = new StreamReader(req.GetResponse().GetResponseStream());
            string       strResponse = streamIn.ReadToEnd();

            streamIn.Close();

            string response;

            Request.InputStream.Position = 0;
            using (var sr = new StreamReader(Request.InputStream))
            {
                response = sr.ReadToEnd();
            }
            var subdomainid = long.Parse(custom);

            try
            {
                if (strResponse == "VERIFIED")
                {
                    using (var repository = new TradelrRepository())
                    {
                        var sd = repository.GetSubDomain(subdomainid);
                        if (payment_status.ToLower() == "completed" && receiver_email == PaymentConstants.PaypalSubscribeEmail)
                        {
                            // payment verified
                            sd.accountTypeStatus    = (int)AccountPlanPaymentStatus.NONE;
                            sd.accountTransactionID = txn_id;
                            Syslog.Write(string.Concat("SUBSCRIBE:", subdomainid, ":oldplan:", sd.accountType, ":newplan:", sd.accountTypeNew));
                            if (sd.accountType != sd.accountTypeNew)
                            {
                                sd.accountType = sd.accountTypeNew;
                            }
                            else
                            {
                                Syslog.Write("Payment received for subdomain ID:" + subdomainid);
                            }
                            repository.Save();
                        }
                    }
                    Syslog.Write("VALID IPN:" + HttpUtility.HtmlEncode(response));
                }
                else
                {
                    if (strResponse == "INVALID")
                    {
                        Syslog.Write("INVALID IPN:" + HttpUtility.HtmlEncode(response));
                    }
                    else
                    {
                        Syslog.Write("UNKNOWN IPN:" + HttpUtility.HtmlEncode(response));
                    }
                }
            }
            catch (Exception ex)
            {
                Syslog.Write(ex);
                Syslog.Write(string.Format("Exception {0}: {1}", subdomainid, HttpUtility.HtmlEncode(response)));
            }
        }
Exemple #27
0
        public static void GenerateDefaultStructures(long subdomainid)
        {
            using (var repository = new TradelrRepository())
            {
                var mastersubdomain = repository.GetSubDomain(subdomainid);
                if (mastersubdomain == null)
                {
                    Syslog.Write("Can't generate liquid structures for domainid: " + subdomainid);
                    return;
                }

                if (mastersubdomain.theme != null)
                {
                    // already initialise, return
                    return;
                }

                // init default theme (SOLO)
                mastersubdomain.theme = new DBML.theme()
                {
                    created = DateTime.UtcNow,
                    title   = "Solo",
                    preset  = "",
                    url     = "/Content/templates/store/themes/solo/thumb.jpg"
                };

                // do liquid stuff
                var page_about = new page()
                {
                    name      = "About Us",
                    permalink = "about-us",
                    creator   = mastersubdomain.organisation.users.First().id,
                    updated   = DateTime.UtcNow,
                    settings  = (int)PageSettings.VISIBLE
                };

                using (var reader = File.OpenText(GeneralConstants.APP_ROOT_DIR + "Content/templates/store/aboutus.txt"))
                {
                    page_about.content = reader.ReadToEnd();
                }
                mastersubdomain.pages.Add(page_about);

                var linklist_mainmenu = new linklist()
                {
                    permalink = "main-menu",
                    permanent = true,
                    title     = "Main Menu"
                };
                mastersubdomain.linklists.Add(linklist_mainmenu);
                var link_home = new link
                {
                    title = "Home",
                    type  = (int)LinkType.FRONTPAGE,
                    url   = "/"
                };
                var link_catalog = new link()
                {
                    title = "Catalog",
                    type  = (int)LinkType.WEB,
                    url   = "/collections/all"
                };
                var link_about = new link()
                {
                    title = "About Us",
                    type  = (int)LinkType.PAGE,
                    url   = "/pages/about-us"
                };
                linklist_mainmenu.links.Add(link_home);
                linklist_mainmenu.links.Add(link_catalog);
                linklist_mainmenu.links.Add(link_about);

                var linklist_footer = new linklist()
                {
                    permalink = "footer",
                    permanent = true,
                    title     = "Footer"
                };
                mastersubdomain.linklists.Add(linklist_footer);

                var link_search = new link
                {
                    title = "Search",
                    type  = (int)LinkType.SEARCHPAGE,
                    url   = "/search"
                };
                linklist_footer.links.Add(link_search);
                linklist_footer.links.Add(link_about);

                // create default collection
                var collection = new product_collection()
                {
                    name      = "Frontpage",
                    permalink = "frontpage",
                    settings  = (int)(CollectionSettings.VISIBLE | CollectionSettings.PERMANENT)
                };
                mastersubdomain.product_collections.Add(collection);

                // finally save
                repository.Save();

                // copy theme files
                var handler = new ThemeHandler(mastersubdomain, false);
                new Thread(() =>
                {
                    var source =
                        new DirectoryInfo(GeneralConstants.APP_ROOT_DIR +
                                          "Content/templates/store/themes/solo");
                    handler.CopyThemeToUserThemeDirectory(source);
                }).Start();


                // copy mobile theme files
                var handler_mobile = new ThemeHandler(mastersubdomain, true);
                new Thread(() =>
                {
                    var source = handler.GetMobileThemeRepositorySourceDir();
                    handler_mobile.CopyThemeToUserThemeDirectory(source);
                }).Start();
            }
        }