Exemple #1
0
        public static Shop ToLiquidModel(this MASTERsubdomain row)
        {
            var shop = new Shop
            {
                email             = row.organisation.users.First().email,
                name              = row.storeName,
                message           = row.organisation.motd,
                url               = row.ToHostName().ToDomainUrl(),
                permanent_domain  = string.Format("{0}.tradelr.com", row.name),
                products_count    = row.products.AsQueryable().IsActive().Count(),
                collections_count = row.product_collections.Where(x => (x.settings & (int)CollectionSettings.VISIBLE) != 0).Count(),
                payment_policy    = row.paymentTerms,
                refund_policy     = row.returnPolicy,
                fb_adminid        = row.organisation.users.First().FBID
            };

            var currency = row.currency.ToCurrency();

            shop.currency                = currency.code;
            shop.currency_symbol         = currency.symbol;
            shop.currency_decimal_places = currency.decimalCount;

            if (!string.IsNullOrEmpty(row.customDomain))
            {
                shop.domain = row.customDomain;
            }
            else
            {
                shop.domain = shop.permanent_domain;
            }

            return(shop);
        }
Exemple #2
0
        public void InitSalesAndProductsStatistics(ITradelrRepository repository, long subdomainid, long viewerid,
                                                   MASTERsubdomain sd)
        {
            var date     = DateTime.UtcNow;
            var currency = sd.currency.ToCurrency();
            // sales stats
            var invoices       = repository.GetOrders(subdomainid, TransactionType.INVOICE, viewerid, null, null, null, false);
            var invoices_month = invoices.Where(x => x.created.Month == date.Month);
            var invoices_year  = invoices.Where(x => x.created.Year == date.Year);

            numberOfSalesThisMonth       = invoices_month.Count();
            numberOfSalesThisYear        = invoices_year.Count();
            numberofSalesUnpaidThisMonth =
                invoices_month.Where(x => x.totalPaid != x.total + (x.shippingCost ?? 0)).Count();
            numberofSalesUnpaidThisYear = invoices_year.Where(x => x.totalPaid != x.total + (x.shippingCost ?? 0)).Count();
            salesThisMonth = string.Concat(currency.symbol,
                                           invoices_month.ToArray().Sum(x => x.total).ToString("n" + currency.decimalCount));
            salesThisYear = string.Concat(currency.symbol,
                                          invoices_year.ToArray().Sum(x => x.total).ToString("n" + currency.decimalCount));
            salesUnpaidThisMonth = string.Concat(currency.symbol,
                                                 invoices_month.Where(
                                                     x => x.totalPaid != x.total + (x.shippingCost ?? 0)).ToArray().Sum(
                                                     x => x.total + (x.shippingCost ?? 0) - x.totalPaid).ToString(
                                                     "n" + currency.decimalCount));
            salesUnpaidThisYear = string.Concat(currency.symbol,
                                                invoices_year.Where(
                                                    x => x.totalPaid != x.total + (x.shippingCost ?? 0)).ToArray().Sum(
                                                    x => x.total + (x.shippingCost ?? 0) - x.totalPaid).ToString(
                                                    "n" + currency.decimalCount));

            // product stats
            productTotal    = sd.total_products_mine;
            outOfStockTotal = sd.total_outofstock;
        }
Exemple #3
0
 public EbayExporter(SiteCodeType site, string hostname, string token, MASTERsubdomain sd) : this(hostname)
 {
     this.token     = token;
     service        = new ItemService(token);
     this.sd        = sd;
     this.ebay_site = site;
 }
Exemple #4
0
        // for fb
        public Account(ITradelrRepository repository, string email, string loginPage, AccountPlanType plan, string affiliate)
        {
            this.repository = repository;
            this.email      = email;
            this.loginPage  = loginPage;
            this.plan       = plan;
            this.affiliate  = affiliate;

            // create subdomain entry
            mastersubdomain = new MASTERsubdomain
            {
                flags                   = 0,
                name                    = loginPage,
                total_outofstock        = 0,
                total_contacts_public   = 0,
                total_contacts_private  = 0,
                total_contacts_staff    = 0,
                total_invoices_sent     = 0,
                total_invoices_received = 0,
                total_orders_sent       = 0,
                total_orders_received   = 0,
                total_products_mine     = 0,
                uniqueid                = Utility.GetRandomString(10),
                accountType             = plan.ToString(),
                accountTypeStatus       = (int)AccountPlanPaymentStatus.TRIAL,                 // start date for 30-day trial campaign
                trialExpiry             = DateTime.UtcNow.AddDays(30),
                affiliateID             = AffiliateUtil.GenerateAffiliateID()
            };
        }
Exemple #5
0
 // used for creation
 public Transaction(MASTERsubdomain senderDomain, user to, TransactionType transactionType, ITradelrRepository repository, long sessionid)
 {
     this.senderDomain    = senderDomain;
     receiver             = to;
     this.repository      = repository;
     this.transactionType = transactionType;
     caller_sessionid     = sessionid;
 }
Exemple #6
0
 public TrademeExporter(string hostname, string key, string secret, MASTERsubdomain sd)
     : this(hostname)
 {
     service     = new SellingService(key, secret);
     this.sd     = sd;
     this.key    = key;
     this.secret = secret;
 }
Exemple #7
0
 public void DeleteGoogleBaseSync(MASTERsubdomain sd)
 {
     if (sd.googleBase != null)
     {
         db.googleBases.DeleteOnSubmit(sd.googleBase);
         sd.googleBase = null;
         Save();
     }
 }
        public void GetInitialisedFeatures(MASTERsubdomain sd)
        {
            organisationDetailsConfigured = !string.IsNullOrEmpty(sd.organisation.name);

            var owner = sd.organisation.users.First();

            personalDetailsConfigured = !string.IsNullOrEmpty(owner.firstName) && !string.IsNullOrEmpty(owner.lastName);

            paymentMethodsConfigured = sd.paymentMethods.Count != 0;
        }
Exemple #9
0
        public static string ToPaymentLogos(this MASTERsubdomain value)
        {
            string logos = "";

            if (!string.IsNullOrEmpty(value.GetPaypalID()))
            {
                logos = paypalLogo;
            }
            return(logos);
        }
Exemple #10
0
        public LiquidTemplateBase(MASTERsubdomain sd, bool isMobile)
        {
            parameters = new Hash();
            values     = new Hash();

            handler   = new ThemeHandler(sd, isMobile);
            themepath = handler.GetThemeUrl();

            AddFilterValues("asset_url", themepath);
            AddFilterValues("theme_version", isMobile? sd.theme.theme_mobile_version:sd.theme.theme_version);
        }
Exemple #11
0
 public LinkLists(MASTERsubdomain sd)
 {
     all = sd.linklists.Select(x => new LinkList(x.title, x.permalink)
     {
         links = x.links.Select(y => new Link()
         {
             title = y.title,
             url   = y.url,
             type  = ((LinkType)y.type).ToLinkType()
         })
     });
 }
Exemple #12
0
 public Collection(string name, string handle, MASTERsubdomain sd)
 {
     title       = name;
     this.handle = handle;
     url         = "/collections/" + handle;
     all_tags    = sd.tags.OrderBy(x => x.name).GroupBy(x => x.handle).Select(y => new TitleUrl()
     {
         is_link = true,
         title   = y.First().name,
         url     = y.First().handle
     });
 }
Exemple #13
0
 public static List <SettingsColumn> ToSyncModel(this MASTERsubdomain v, CFlag flag)
 {
     return(new List <SettingsColumn>
     {
         new SettingsColumn
         {
             cflag = flag,
             id = v.id,
             currency = v.organisation.MASTERsubdomain.currency.ToCurrencySymbol(),
             flags = v.flags,
             serverid = v.id                 // required so we don't keep creating more rows in offlne db
         }
     });
 }
Exemple #14
0
        public ThemeHandler(MASTERsubdomain sd, bool isMobile)
        {
            IsMobile = isMobile;
            this.sd  = sd;

            SelectedThemeName = sd.theme.title;

            if (isMobile)
            {
                DestRelativePath = string.Format("{0}/{1}/mobile_theme", THEMES_PATH, sd.uniqueid);
            }
            else
            {
                DestRelativePath = string.Format("{0}/{1}/theme", THEMES_PATH, sd.uniqueid);
            }
            ThemeLocationPath = string.Format("{0}/{1}", GeneralConstants.APP_ROOT_DIR, DestRelativePath);
        }
Exemple #15
0
 public static SubdomainStats ToSubdomainStats(this MASTERsubdomain value)
 {
     return(new SubdomainStats()
     {
         products_mine = value.total_products_mine,
         contacts_private = value.total_contacts_private,
         contacts_public = value.total_contacts_public,
         contacts_staff = value.total_contacts_staff,
         orders_received = value.total_orders_received,
         orders_sent = value.total_orders_sent,
         invoices_received = value.total_invoices_received,
         invoices_sent = value.total_invoices_sent,
         total_outofstock = value.total_outofstock,
         total_contacts = value.total_contacts_private + value.total_contacts_public + value.total_contacts_staff,
         total_invoices = value.total_invoices_received + value.total_invoices_sent,
         total_orders = value.total_orders_received + value.total_orders_sent
     });
 }
Exemple #16
0
        public static IEnumerable <SelectListItem> ToShippingProfiles(this MASTERsubdomain domain, long?selected = null)
        {
            if (selected.HasValue)
            {
                return(domain.shippingProfiles.OrderBy(x => x.title).Select(x => new SelectListItem()
                {
                    Value = x.id.ToString(),
                    Text = x.title,
                    Selected = x.id == selected.Value
                }));
            }

            return(domain.shippingProfiles.OrderBy(x => x.title).Select(x => new SelectListItem()
            {
                Value = x.id.ToString(),
                Text = x.title,
                Selected = x.permanent
            }));
        }
Exemple #17
0
        protected void InitValues(product p, decimal exchange_rate, MASTERsubdomain sd = null)
        {
            productname = p.title;
            subdomainid = p.subdomainid;
            producturl  = p.ToProductUrl();

            Title       = p.title;
            Description = p.details;
            ProductId   = p.id;
            Condition   = "New";
            if (p.sellingPrice.HasValue)
            {
                SellingPrice = (p.specialPrice ?? p.sellingPrice).Value * exchange_rate;
            }

            if (p.sellingPrice.HasValue)
            {
                SellingPrice = p.tax.HasValue
                                           ? (p.sellingPrice.Value * (p.tax.Value / 100 + 1))
                                           : p.sellingPrice.Value;

                if (p.specialPrice.HasValue)
                {
                    // if has special price then original (strike-through) + special price
                    SpecialPrice = p.tax.HasValue
                                           ? (p.specialPrice.Value * (p.tax.Value / 100 + 1))
                                           : p.specialPrice.Value;
                }
            }

            if (sd == null)
            {
                sd = p.MASTERsubdomain;
            }

            Currency      = sd.currency.ToCurrency();
            PaymentNotes  = sd.paymentTerms;
            hostName      = sd.ToHostName();
            LocationState = sd.organisation.state;
            Country       = sd.organisation.country.ToCountry();
        }
 public void Initialise(MASTERsubdomain msd, bool excludePaypal)
 {
     foreach (var row in msd.paymentMethods)
     {
         if (row.method == PaymentMethod.Paypal.ToString())
         {
             if (excludePaypal)
             {
                 continue;
             }
             if (!string.IsNullOrEmpty(msd.GetPaypalID()))
             {
                 Add(PaymentMethod.Paypal.ToString(), "paypal");
             }
         }
         else
         {
             Add(row.method == PaymentMethod.Other.ToString() ? row.name : row.method.ToEnum <PaymentMethod>().ToDescriptionString(),
                 row.id.ToString());
         }
     }
 }
Exemple #19
0
        public bool CalculateShippingCost(IQueryable <product_variant> products, MASTERsubdomain sender, user receiver)
        {
            var shippingProfiles = products.Select(x => x.product.shippingProfile);
            var shippingAddress  = receiver.organisation1.address1;

            if (shippingProfiles.UseShipwire())
            {
                var aes             = new AESCrypt();
                var shipwireService = new ShipwireService(sender.shipwireEmail,
                                                          aes.Decrypt(sender.shipwirePassword, sender.id.ToString()));
                var address = new AddressInfo(string.Format("{0} {1}", shippingAddress.first_name, shippingAddress.last_name), shippingAddress.street_address,
                                              shippingAddress.city, shippingAddress.state,
                                              Country.GetCountry(shippingAddress.country.Value).name,
                                              shippingAddress.postcode, "", receiver.email);

                var shipwireOrder = new Order(address);
                foreach (var entry in products)
                {
                    var quantity = items.Single(x => x.id == entry.id).quantity;
                    var item     = new OrderItem
                    {
                        Sku      = entry.sku,
                        Quantity = quantity
                    };
                    shipwireOrder.AddItem(item);
                }

                shipwireService.CreateRateRequest(shipwireOrder);

                var rateResponse = shipwireService.SubmitRateRequest();
                var quote        = rateResponse.GetCost(shippingMethod);

                if (quote == null)
                {
                    // failed to obtain shipping cost
                    return(false);
                }
                if (currencyCode != "USD")
                {
                    shippingCost = CurrencyConverter.Instance.Convert("USD", currencyCode, quote.value);
                }
                else
                {
                    shippingCost = quote.value;
                }

                shipwireShippingName = rateResponse.GetShippingServiceName(shippingMethod);
            }
            else
            {
                IQueryable <shippingRule> rules = null;
                var statename = shippingAddress.state;
                var countryid = shippingAddress.country.Value;
                if (!string.IsNullOrEmpty(statename))
                {
                    // try get state match
                    rules =
                        shippingProfiles.SelectMany(x => x.shippingRules).Where(
                            x => x.state == statename && x.country == countryid);
                    // if none try get state-other match
                    if (!rules.Any())
                    {
                        rules =
                            shippingProfiles.SelectMany(x => x.shippingRules).Where(
                                x => x.state == "" && x.country == countryid);
                    }
                }

                if (rules == null || !rules.Any())
                {
                    rules = shippingProfiles.SelectMany(x => x.shippingRules).Where(x => x.country == countryid);
                    if (!rules.Any())
                    {
                        // look for any
                        rules = shippingProfiles.SelectMany(x => x.shippingRules).Where(x => !x.country.HasValue);
                    }
                }

                // what type of rule
                var rule = rules.FirstOrDefault();
                if (rule != null)
                {
                    var ruletype = (RuleType)rule.ruletype;
                    switch (ruletype)
                    {
                    case RuleType.PRICE:
                        decimal orderprice = 0;
                        foreach (var p in products)
                        {
                            var quantity = items.Single(x => x.id == p.id).quantity;
                            var price    = p.product.ToUserPrice(receiver.id);
                            if (price.HasValue)
                            {
                                orderprice += (price.Value * quantity);
                            }
                        }
                        if (orderprice != 0)
                        {
                            var matchedRule =
                                rules.Where(x => x.matchvalue < orderprice && x.name == shippingMethod).
                                OrderByDescending(x => x.matchvalue).
                                FirstOrDefault();
                            if (matchedRule == null)
                            {
                                return(false);
                            }
                            shippingCost = matchedRule.cost;
                        }
                        break;

                    case RuleType.WEIGHT:
                        decimal weight          = 0;
                        var     serializer      = new JavaScriptSerializer();
                        var     incompletecount = products.Count(x => x.product.dimensions == null);
                        if (incompletecount == 0)
                        {
                            foreach (var p in products)
                            {
                                var dimension = serializer.Deserialize <Dimension>(p.product.dimensions);
                                var quantity  = items.Single(x => x.id == p.id).quantity;
                                Debug.Assert(dimension != null && quantity != 0);
                                if (dimension.weight == 0)
                                {
                                    return(false);
                                }
                                weight += (dimension.weight * quantity);
                            }

                            // only match if weight has been entered
                            if (weight != 0)
                            {
                                var matchedRule = rules.Where(x => x.matchvalue < weight && x.name == shippingMethod).OrderByDescending(x => x.matchvalue).FirstOrDefault();
                                if (matchedRule == null)
                                {
                                    return(false);
                                }
                                shippingCost = matchedRule.cost;
                            }
                            else
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            return(false);
                        }
                        break;

                    default:
                        throw new NotImplementedException();
                    }
                }
                else
                {
                    // unable to find matching rule
                    return(false);
                }
            }
            return(true);
        }
Exemple #20
0
 public Pages(MASTERsubdomain sd)
 {
     all = sd.pages.Select(x => new Page(x));
 }
Exemple #21
0
        public static IEnumerable <ShippingRule> ToShippingMethods(this List <CheckoutItem> checkoutItems,
                                                                   MASTERsubdomain sender, organisation receiver, shippingProfile[] shippingProfiles)
        {
            IEnumerable <ShippingRule> shippingMethods = Enumerable.Empty <ShippingRule>();

            if (shippingProfiles.Count() != 0 &&
                receiver.address1 != null &&
                receiver.address1.country.HasValue)
            {
                // try get shipping rates)
                var shippingAddress = receiver.address1;
                if (shippingProfiles.UseShipwire())
                {
                    var aes             = new AESCrypt();
                    var shipwireService = new ShipwireService(sender.shipwireEmail,
                                                              aes.Decrypt(sender.shipwirePassword, sender.id.ToString()));

                    var address =
                        new AddressInfo(string.Format("{0} {1}", shippingAddress.first_name, shippingAddress.last_name),
                                        shippingAddress.street_address,
                                        shippingAddress.city, shippingAddress.state,
                                        Country.GetCountry(shippingAddress.country.Value).name,
                                        shippingAddress.postcode, "", "");

                    var shipwireOrder = new Order(address);
                    foreach (var entry in checkoutItems)
                    {
                        var item = new Shipwire.order.OrderItem
                        {
                            Sku      = entry.SKU,
                            Quantity = entry.quantity
                        };
                        shipwireOrder.AddItem(item);
                    }

                    shipwireService.CreateRateRequest(shipwireOrder);

                    var rateResponse = shipwireService.SubmitRateRequest();
                    shippingMethods = rateResponse.ToModel(sender.organisation.MASTERsubdomain.currency.ToCurrency());
                }
                else
                {
                    shippingRule[] rules     = null;
                    var            statename = shippingAddress.state;
                    var            countryid = shippingAddress.country.Value;
                    if (!string.IsNullOrEmpty(statename))
                    {
                        // try get state match
                        rules =
                            shippingProfiles.SelectMany(x => x.shippingRules).Where(
                                x => x.state == statename && x.country == countryid).ToArray();
                        // if none try get state-other match
                        if (rules.Count() == 0)
                        {
                            rules =
                                shippingProfiles.SelectMany(x => x.shippingRules).Where(
                                    x => x.state == "" && x.country == countryid).ToArray();
                        }
                    }

                    if (rules == null || rules.Count() == 0)
                    {
                        rules = shippingProfiles.SelectMany(x => x.shippingRules).Where(x => x.country == countryid).ToArray();
                        if (rules.Count() == 0)
                        {
                            rules = shippingProfiles.SelectMany(x => x.shippingRules).Where(x => !x.country.HasValue).ToArray();
                        }
                    }

                    // what type of rule
                    var rule = rules.FirstOrDefault();
                    if (rule != null)
                    {
                        var ruletype = (RuleType)rule.ruletype;
                        switch (ruletype)
                        {
                        case RuleType.PRICE:
                            decimal orderprice = 0;
                            foreach (var item in checkoutItems)
                            {
                                var sellingprice = item.UnitPrice;
                                orderprice += (sellingprice * item.quantity);
                            }
                            if (orderprice != 0)
                            {
                                var keys =
                                    rules.Where(x => x.matchvalue < orderprice).GroupBy(x => x.name).Select(
                                        y => y.Key);
                                var matchedrules = new List <ShippingRule>();
                                foreach (var key in keys)
                                {
                                    var result =
                                        rules.Where(x => x.matchvalue < orderprice && x.name == key).
                                        OrderByDescending(x => x.matchvalue).FirstOrDefault();
                                    if (result != null)
                                    {
                                        matchedrules.Add(result.ToModel());
                                    }
                                }
                                shippingMethods = matchedrules;
                            }
                            break;

                        case RuleType.WEIGHT:
                            decimal weight = 0;

                            // only calculate weight if all items have weight dimensions
                            var incompletecount = checkoutItems.Where(x => x.dimension == null ||
                                                                      x.dimension.weight == 0).Count();
                            if (incompletecount == 0)
                            {
                                foreach (var item in checkoutItems)
                                {
                                    Debug.Assert(item.dimension != null && item.quantity != 0);
                                    weight += (item.dimension.weight * item.quantity);
                                }
                                // only match if weight has been entered
                                if (weight != 0)
                                {
                                    var keys =
                                        rules.Where(x => x.matchvalue < weight).GroupBy(x => x.name).Select(
                                            y => y.Key);
                                    var matchedrules = new List <ShippingRule>();
                                    foreach (var key in keys)
                                    {
                                        var result =
                                            rules.Where(x => x.matchvalue < weight && x.name == key).OrderByDescending(
                                                x => x.matchvalue).FirstOrDefault();
                                        if (result != null)
                                        {
                                            matchedrules.Add(result.ToModel());
                                        }
                                    }
                                    shippingMethods = matchedrules;
                                }
                            }
                            break;

                        default:
                            throw new NotImplementedException();
                        }
                    }
                }
            }
            return(shippingMethods);
        }
Exemple #22
0
 public Blogs(MASTERsubdomain sd)
 {
     all = sd.blogs.Select(x => new Blog(x));
 }
Exemple #23
0
        public ActionResult NewAccount(string code, string id, string identifier, PageType pagetype)
        {
            var client = new OAuthFacebook(GeneralConstants.FACEBOOK_API_KEY, GeneralConstants.FACEBOOK_API_SECRET,
                                           HttpUtility.UrlEncode(
                                               string.Format(
                                                   "{0}/newaccount/{1}?identifier={2}&pagetype={3}",
                                                   GeneralConstants.FACEBOOK_APP_URL, id, identifier, pagetype)),
                                           "read_stream,email,publish_stream,offline_access,manage_pages");

            // starting our authorisation process
            if (string.IsNullOrEmpty(code))
            {
                return(RedirectToAction("Redirect", new{ url = client.AuthorizationLinkGet() }));
            }

            if (!client.AccessTokenGet(code))
            {
                return(View("Error", new FacebookViewData {
                    errorMessage = "Unable to obtain permission", pageUrl = pagetype.ToReturnUrl(identifier)
                }));
            }

            // check subdomain is valid
            id = id.ToLower();

            // also check special domain list
            if (GeneralConstants.SUBDOMAIN_RESTRICTED.Contains(id))
            {
                return(View("Error", new FacebookViewData {
                    errorMessage = "Store address is not available", pageUrl = pagetype.ToReturnUrl(identifier)
                }));
            }

            var mastersubdomain = repository.GetSubDomains().Where(x => x.name == id).SingleOrDefault();

            if (mastersubdomain != null)
            {
                return(View("Error", new FacebookViewData {
                    errorMessage = "Store address is not available", pageUrl = pagetype.ToReturnUrl(identifier)
                }));
            }

            var facebook = new FacebookService(client.token);
            var fb_usr   = facebook.People.GetUser("me");

            if (fb_usr == null)
            {
                return(View("Error", new FacebookViewData {
                    errorMessage = "Unable to create account", pageUrl = pagetype.ToReturnUrl(identifier)
                }));
            }

            // verify that email has not been used to register another account
            if (repository.GetUserByEmail(fb_usr.email).Where(x => (x.role & (int)UserRole.CREATOR) != 0).SingleOrDefault() != null)
            {
                Syslog.Write(ErrorLevel.INFORMATION, "Facebook email address in use: " + fb_usr.email);
                return(View("Error", new FacebookViewData {
                    errorMessage = "Email address is already registered", pageUrl = pagetype.ToReturnUrl(identifier)
                }));
            }

            var usr = new user
            {
                role                 = (int)UserRole.ADMIN,
                viewid               = Crypto.Utility.GetRandomString(),
                permissions          = (int)UserPermission.ADMIN,
                FBID                 = fb_usr.id,
                email                = fb_usr.email ?? "",
                externalProfileUrl   = fb_usr.link,
                firstName            = fb_usr.first_name,
                lastName             = fb_usr.last_name,
                gender               = fb_usr.gender,
                externalProfilePhoto = string.Format("https://graph.facebook.com/{0}/picture?type=large", fb_usr.id)
            };

            // create subdomain entry
            mastersubdomain = new MASTERsubdomain
            {
                flags                   = 0,
                name                    = id,
                total_outofstock        = 0,
                total_contacts_public   = 0,
                total_contacts_private  = 0,
                total_contacts_staff    = 0,
                total_invoices_sent     = 0,
                total_invoices_received = 0,
                total_orders_sent       = 0,
                total_orders_received   = 0,
                total_products_mine     = 0,
                accountType             = AccountPlanType.ULTIMATE.ToString()
            };

            repository.AddMasterSubdomain(mastersubdomain);

            // create organisation first
            var org = new organisation
            {
                subdomain = mastersubdomain.id,
                name      = fb_usr.name
            };

            repository.AddOrganisation(org);
            usr.organisation = org.id;

            // CREATE DEFAULT STRUCTURES
            // add default inventory location
            var loc = new inventoryLocation
            {
                name       = GeneralConstants.INVENTORY_LOCATION_DEFAULT,
                subdomain  = mastersubdomain.id,
                lastUpdate = DateTime.UtcNow
            };

            repository.AddInventoryLocation(loc, mastersubdomain.id);

            // add default shipping profile
            var shippingProfile = new shippingProfile()
            {
                title       = "Default",
                type        = ShippingProfileType.FLATRATE.ToString(),
                subdomainid = mastersubdomain.id
            };

            repository.AddShippingProfile(shippingProfile);

            // update subdomain entry
            mastersubdomain.creator = org.id;

            // create facebookpage to link to subdomain
            var newEntry = new facebookPage {
                subdomainid = mastersubdomain.id, pageid = identifier
            };

            repository.AddFacebookPage(newEntry);


            try
            {
                // if user exist then we still need to verify email
                Random rnd = RandomNumberGenerator.Instance;
                usr.confirmationCode = rnd.Next();
                repository.AddUser(usr);

                // generate photo
                new Thread(() => usr.externalProfilePhoto.ReadAndSaveFromUrl(mastersubdomain.id, usr.id, usr.id, PhotoType.PROFILE)).Start();

                // add access token
                var oauthdb = new oauth_token
                {
                    token_key    = client.token,
                    token_secret = "",
                    type         = OAuthTokenType.FACEBOOK.ToString(),
                    subdomainid  = mastersubdomain.id,
                    appid        = usr.id.ToString(),
                    authorised   = true
                };
                repository.AddOAuthToken(oauthdb);

                // obtain any other account tokens
                var accounts = facebook.Account.GetAccountTokens("me");
                if (accounts != null && accounts.data != null)
                {
                    foreach (var account in accounts.data)
                    {
                        if (account.name != null)
                        {
                            var ftoken = new facebook_token
                            {
                                pageid      = account.id,
                                subdomainid = mastersubdomain.id,
                                accesstoken = account.access_token,
                                name        = account.name
                            };
                            repository.AddUpdateFacebookToken(ftoken);
                        }
                    }
                }
                repository.Save();

                // send confirmation email
                var viewdata = new ViewDataDictionary()
                {
                    { "host", id.ToSubdomainUrl() },
                    { "confirmCode", usr.confirmationCode },
                    { "email", usr.email }
                };
                EmailHelper.SendEmailNow(EmailViewType.ACCOUNT_CONFIRMATION, viewdata, "New Account Details and Email Verification Link",
                                         usr.email, usr.ToFullName(), usr.id);
            }
            catch (Exception ex)
            {
                Syslog.Write(ex);
                return(View("Error", new FacebookViewData {
                    errorMessage = "Unable to create account", pageUrl = pagetype.ToReturnUrl(identifier)
                }));
            }

            return(RedirectToAction("Redirect", new { url = pagetype.ToReturnUrl(identifier) }));
        }
Exemple #24
0
 public LiquidTemplate(MASTERsubdomain sd, bool isMobile) : base(sd, isMobile)
 {
     registers    = new Hash();
     head_content = new StringBuilder();
 }
Exemple #25
0
 public EbayWorker(MASTERsubdomain sd, string token)
 {
     this.sd    = sd;
     this.token = token;
     seller     = sd.organisation.users.First();
 }
Exemple #26
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            accountHostname = Request.Headers["Host"];
            #if DEBUG
            if (accountHostname == "local")
            {
                filterContext.Result = new RedirectResult(GeneralConstants.HTTP_HOST + Request.Url.PathAndQuery);
                return;
            }
            #else
            if (accountHostname == null || accountHostname == "tradelr.com" || accountHostname == "98.126.29.28")
            {
                filterContext.Result = new RedirectResult(GeneralConstants.HTTP_HOST + Request.Url.PathAndQuery);
                return;
            }
            #endif
            ////////////////////// subdomain check ///////////////////////////////
            #if DEBUG
            if (accountHostname.EndsWith("localhost"))
            #else
            if (accountHostname.EndsWith("tradelr.com"))
            #endif
            {
                ////////////// handles case for subdomains
                string[] host = accountHostname.Split('.');
                string hostSegment = "";

                // not on a subdomain
                if (!Utility.IsOnSubdomain(host, out hostSegment))
                {
                    return;
                }

                MASTERdomain = db.GetSubDomain(hostSegment);

                // ensure that incoming host name matches x.tradelr.com.
                // this is to handle www.x.tradelr.com returning www.tradelr.com
                if (MASTERdomain != null)
                {
            #if DEBUG
                    var validHost = string.Format("{0}.localhost", hostSegment);
            #else
                    var validHost = string.Format("{0}.tradelr.com", hostSegment);
            #endif
                    if (validHost != accountHostname)
                    {
                        filterContext.Result = new RedirectResult(string.Format("{0}://{1}", Request.Url.Scheme, validHost));
                        return;
                    }
                }
            }
            else
            {
                ////////////////// handles case for custom subdomains
                MASTERdomain = db.GetCustomHostname(accountHostname);
            }

            if (MASTERdomain == null)
            {
                // subdomain does not exist
                filterContext.RequestContext.HttpContext.Response.StatusCode = HttpStatusCode.NotFound.ToInt();
                filterContext.Result = new RedirectResult(GeneralConstants.HTTP_HOST);
                return;
            }

            /////////// SUBDOMAIN EXISTS
            accountLimits = MASTERdomain.accountType.ToEnum<AccountPlanType>().ToAccountLimit();
            accountSubdomainName = MASTERdomain.name;
            subdomainid = MASTERdomain.id;
            stats = MASTERdomain.ToSubdomainStats();
            IsStoreEnabled = MASTERdomain.IsStoreEnabled();
            baseviewmodel.storeEnabled = IsStoreEnabled;
            subdomainFlags = (SubdomainFlags) MASTERdomain.flags;

            if ((MASTERdomain.flags & (int)SubdomainFlags.OFFLINE_ENABLED) != 0)
            {
                var browsertype = Request.Browser.Type.ToLower();
                if (browsertype.Contains("safari") || browsertype.Contains("chrome"))
                {
                    baseviewmodel.manifestFile = "manifest=\"/manifest\"";
                }
            }
            baseviewmodel.orgName = MASTERdomain.organisation.name;
            baseviewmodel.shopUrl = accountHostname;

            /////////////////////// session check ///////////////////////////////
            token = Request.RequestContext.HttpContext.Items["token"] as TradelrSecurityToken;

            if (token == null)
            {
                GetAuthCookie();
            }

            if (token != null)
            {
                Request.RequestContext.HttpContext.Items["token"] = token;
                sessionid = token.UserID;
                var usr = db.GetUserById(sessionid.Value, subdomainid.Value);
                if (usr != null)
                {
                    baseviewmodel.notifications = usr.ToNotification(MASTERdomain.trialExpired).ToJson();

                }

                role = token.UserRole.ToEnum<UserRole>();
                baseviewmodel.role = role;

                permission = token.Permission.ToEnum<UserPermission>();
                baseviewmodel.permission = permission;
            }

            base.OnActionExecuting(filterContext);
        }
Exemple #27
0
 public Collections(MASTERsubdomain sd, long?viewerid)
 {
     all =
         sd.product_collections.Select(
             x => new Collection(x, null, viewerid));
 }
Exemple #28
0
        public void ReIndex()
        {
            writerInUse = true;
            using (var repository = new TradelrRepository())
            {
                // get subdomains
                var subdomains = repository.GetSubDomains();
                foreach (var subdomain in subdomains)
                {
                    // index contacts
                    writer = CreateWriter(LuceneIndexType.CONTACTS, subdomain.name);
                    if (writer != null)
                    {
                        var contacts = repository.GetAllContacts(subdomain.id);
                        foreach (var contact in contacts)
                        {
                            try
                            {
                                var action = new ContactItem(contact);
                                var doc    = IndexContact(action);
                                writer.AddDocument(doc);
                            }
                            catch (Exception ex)
                            {
                                Syslog.Write(ex);
                            }
                        }
                        writer.Optimize();
                        CloseWriter();
                    }

                    // index products
                    writer = CreateWriter(LuceneIndexType.PRODUCTS, subdomain.name);
                    if (writer != null)
                    {
                        var products = repository.GetProducts(subdomain.id);
                        foreach (var product in products)
                        {
                            try
                            {
                                var action = new ProductItem(product);
                                var doc    = IndexProduct(action);
                                writer.AddDocument(doc);
                            }
                            catch (Exception ex)
                            {
                                Syslog.Write(ex);
                            }
                        }

                        writer.Optimize();
                        CloseWriter();
                    }


                    // orders
                    writer = CreateWriter(LuceneIndexType.TRANSACTION, subdomain.name);
                    if (writer != null)
                    {
                        MASTERsubdomain subdomain1 = subdomain;
                        var             orders     = repository.GetOrders().Where(x => x.user1.organisation1.subdomain == subdomain1.id);
                        foreach (var order in orders)
                        {
                            try
                            {
                                var acttion = new TransactionItem(order);
                                var doc     = IndexTransaction(acttion);
                                writer.AddDocument(doc);
                            }
                            catch (Exception ex)
                            {
                                Syslog.Write("Lucene index error: order ID =" + order.id);
                                Syslog.Write(ex);
                            }
                        }

                        writer.Optimize();
                        CloseWriter();
                    }
                }
            }
            writerInUse = false;
        }
Exemple #29
0
        public EbayProductViewModel(ebay_product _ebayproduct, MASTERsubdomain sd, tradelrDataContext db)
        {
            categories     = new List <IEnumerable <SelectListItem> >();
            sitecategories = db.ebay_categories.Where(x => x.siteid == siteid.ToString());
            currency       = sd.currency.ToCurrency();

            if (_ebayproduct == null)
            {
                // new product
                this.ebayproduct = new ebay_product();
                siteid           = SiteCodeType.US;
                includeAddress   = true;
                quantity         = 1;
                conditions       = Enumerable.Empty <SelectListItem>();
                durations        = Enumerable.Empty <SelectListItem>();
                TypeList         = typeof(ListingType).ToSelectList(true, null, null, ListingType.FixedPriceItem.ToString());
            }
            else
            {
                // existing product
                ebayproduct    = _ebayproduct;
                siteid         = ebayproduct.siteid.ToEnum <SiteCodeType>();
                includeAddress = ebayproduct.includeAddress;
                isPosted       = true;
                isActive       = ebayproduct.isActive;
                quantity       = ebayproduct.quantity;

                var leafcategory = sitecategories.Single(x => x.categoryid == ebayproduct.categoryid);

                durations = leafcategory.ebay_listingdurations.Where(x => x.listingtypeid == ebayproduct.listingType)
                            .Select(x => new SelectListItem()
                {
                    Text = DurationNames.ContainsKey(x.duration)
                                                 ? DurationNames[x.duration]
                                                 : x.duration,
                    Value    = x.duration,
                    Selected = x.duration == ebayproduct.duration
                });
                conditions = leafcategory.ebay_conditions.Select(x => new SelectListItem()
                {
                    Text     = x.name,
                    Value    = x.value.ToString(),
                    Selected =
                        x.value == ebayproduct.condition
                });

                ListingID = ebayproduct.ebayid;

                // intervals
                if (ebayproduct.startTime.HasValue)
                {
                    StartDate = ebayproduct.startTime.Value.ToString(GeneralConstants.DATEFORMAT_INVOICE);
                }

                if (ebayproduct.endTime.HasValue)
                {
                    EndDate = ebayproduct.endTime.Value.ToString(GeneralConstants.DATEFORMAT_INVOICE);
                }

                // prices
                if (ebayproduct.startPrice.HasValue)
                {
                    StartPrice = ebayproduct.startPrice.Value.ToString("n" + currency.decimalCount);
                }
                if (ebayproduct.buynowPrice.HasValue)
                {
                    BuynowPrice = ebayproduct.buynowPrice.Value.ToString("n" + currency.decimalCount);
                }
                if (ebayproduct.reservePrice.HasValue)
                {
                    ReservePrice = ebayproduct.reservePrice.Value.ToString("n" + currency.decimalCount);
                }

                ViewLocation = ebayproduct.ToExternalLink();
                ListingFees  = ebayproduct.listingFees;

                TypeList = typeof(ListingType)
                           .ToSelectList(true, null, null,
                                         Listing.GetTradelrSupportedType(ebayproduct.listingType.ToEnum <ListingTypeCodeType>()).ToString());
            }

            dispatchTimes = db.ebay_dispatchtimes
                            .Where(x => x.siteid == siteid.ToString())
                            .OrderBy(x => x.dispatchTime)
                            .Select(x => new SelectListItem()
            {
                Text     = x.name,
                Value    = x.dispatchTime.ToString(),
                Selected = x.dispatchTime == ebayproduct.dispatchTime
            });

            shippingProfiles = sd.ebay_shippingprofiles
                               .Where(x => x.siteid == siteid.ToString())
                               .Select(x => new SelectListItem()
            {
                Text     = x.title,
                Value    = x.id.ToString(),
                Selected = x.id == ebayproduct.profileid
            });
        }
        public TrademeProductViewModel(trademe_product _trademeproduct, MASTERsubdomain sd, tradelrDataContext db)
        {
            categories     = new List <IEnumerable <SelectListItem> >();
            sitecategories = db.trademe_categories;
            currency       = sd.currency.ToCurrency();

            if (_trademeproduct == null)
            {
                // new product
                trademeproduct = new trademe_product();
                quantity       = 1;
                durations      = Enumerable.Empty <SelectListItem>();
                shippingCosts  = Enumerable.Empty <TrademeShippingCost>();
                freeShipping   = true;
            }
            else
            {
                // existing product
                trademeproduct     = _trademeproduct;
                isPosted           = true;
                isActive           = trademeproduct.isActive;
                isBrandNew         = trademeproduct.isnew;
                onlyAuthenticated  = trademeproduct.authenticatedOnly;
                isBold             = trademeproduct.isBold;
                isFeatured         = trademeproduct.isFeatured;
                isHomepageFeatured = trademeproduct.isHomepageFeatured;
                hasGallery         = trademeproduct.hasGallery;

                // shipping costs
                shippingCosts = trademeproduct.trademe_shippingcosts.ToModel();
                freeShipping  = !shippingCosts.Any();

                quantity = trademeproduct.quantity;

                var leafcategory = sitecategories.Single(x => x.id == trademeproduct.categoryid);

                durations = leafcategory.trademe_listingdurations.Where(x => x.categoryid == trademeproduct.categoryid)
                            .Select(x => new SelectListItem()
                {
                    Text     = x.duration == 1? (x.duration + " day"):(x.duration + " days"),
                    Value    = x.duration.ToString(),
                    Selected = x.duration == trademeproduct.duration
                });

                ListingID = trademeproduct.listingid;

                // intervals
                if (trademeproduct.startTime.HasValue)
                {
                    StartDate = trademeproduct.startTime.Value.ToString(GeneralConstants.DATEFORMAT_INVOICE);
                }

                if (trademeproduct.endTime.HasValue)
                {
                    EndDate = trademeproduct.endTime.Value.ToString(GeneralConstants.DATEFORMAT_INVOICE);
                }

                // prices
                StartPrice = trademeproduct.startPrice.ToString("n" + currency.decimalCount);

                if (trademeproduct.buynowPrice.HasValue)
                {
                    BuynowPrice = trademeproduct.buynowPrice.Value.ToString("n" + currency.decimalCount);
                }

                ReservePrice = trademeproduct.reservePrice.ToString("n" + currency.decimalCount);

                ViewLocation = trademeproduct.ToExternalLink();
                ListingFees  = trademeproduct.listingfees.HasValue? trademeproduct.listingfees.Value.ToString(): "";
            }
        }