Beispiel #1
0
        public ActionResult CloneModule(int id)
        {
            var newModule = new ContentModule();

            var moduleToClone = Context.ContentModules.First(x => x.ContentModuleId == id);

            newModule.CreateDate   = DateTime.Today;
            newModule.HTMLContent  = moduleToClone.HTMLContent;
            newModule.HTMLUnparsed = moduleToClone.HTMLUnparsed;
            newModule.JSContent    = moduleToClone.JSContent;

            newModule.CSSContent        = moduleToClone.CSSContent;
            newModule.SchemaEntryValues = moduleToClone.SchemaEntryValues;
            newModule.SchemaId          = moduleToClone.SchemaId;
            newModule.ModuleName        = "New Module";

            Context.ContentModules.Add(newModule);
            Context.SaveChanges();

            // Update the Display Name
            newModule.ModuleName = "New Module " + newModule.ContentModuleId;
            Context.SaveChanges();


            return(RedirectToAction("EditModule", "Modules", new { id = newModule.ContentModuleId }));
        }
Beispiel #2
0
        protected ContentModule SetContentModuleData(ContentModule entity, bool isBasic, DateTime?createDate)
        {
            var editedContent = new ContentModule
            {
                CreateDate            = createDate ?? DateTime.UtcNow,
                ModuleName            = entity.ModuleName,
                HTMLContent           = entity.HTMLContent,
                HTMLUnparsed          = entity.HTMLUnparsed,
                SchemaId              = entity.SchemaId,
                SchemaEntryValues     = entity.SchemaEntryValues,
                IsActive              = false,
                ParentContentModuleId = entity.ContentModuleId,
                DraftAuthorName       = UserUtils.CurrentMembershipUsername(),
                WasPublished          = createDate != null
            };

            // Basic Editors don't pass JS / CSS Content along
            if (!isBasic)
            {
                editedContent.JSContent  = entity.JSContent;
                editedContent.CSSContent = entity.CSSContent;
            }

            return(editedContent);
        }
        public JsonResult GetSchemaHtml(int schemaId, int moduleId, bool isPage = false)
        {
            var result = new JsonResult();

            string entryValues;

            var theSchema = Context.Schemas.FirstOrDefault(x => x.SchemaId == schemaId);

            if (isPage)
            {
                ContentPage thePage = Context.ContentPages.FirstOrDefault(x => x.ContentPageId == moduleId);
                entryValues = thePage.SchemaEntryValues;
            }
            else
            {
                ContentModule theModule = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == moduleId);
                entryValues = theModule.SchemaEntryValues;
            }

            if (theSchema != null)
            {
                result.Data = new { data = theSchema.JSONData, values = entryValues };
            }

            return(result);
        }
Beispiel #4
0
        public ExampleModule(ExampleNotificationService exampleNotificationService)
        {
            if (exampleNotificationService == null)
            {
                throw new ArgumentNullException("exampleNotificationService");
            }

            _ExampleNotificationService = exampleNotificationService;

            Get["/"] = x =>
            {
                return(ContentModule.GetEmbeddedResource("Nancy.LongPoll.Example.Index.html", Assembly.GetExecutingAssembly()));
            };

            Post["/Stop"] = x =>
            {
                _ExampleNotificationService.RunNotifications = false;

                return(null);
            };

            Post["/Start"] = x =>
            {
                _ExampleNotificationService.RunNotifications = true;

                return(null);
            };
        }
Beispiel #5
0
        /// <summary>
        /// ConfigureContainer is where you can register things directly
        /// with Autofac. This runs after ConfigureServices so the things
        /// here will override registrations made in ConfigureServices.
        /// Don't build the container; that gets done for you. If you
        /// need a reference to the container, you need to use the
        /// "Without ConfigureContainer" mechanism shown later.
        /// </summary>
        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder
            .RegisterInstance(_configuration)
            .AsImplementedInterfaces()
            .SingleInstance();

            builder
            .RegisterInstance(_hostingEnvironment)
            .AsImplementedInterfaces()
            .SingleInstance();

            var integrationsSection = _configuration.GetSection("Integrations");
            var integrations        = integrationsSection.Get <IntegrationsLocation>();
            var location            = integrations.Location;
            var filePath            = Path.Combine(_hostingEnvironment.ContentRootPath, location);

            var integrationsDictionary = JsonConvert
                                         .DeserializeObject <IntegrationsContainer>(File.ReadAllText(filePath));

            var contentModule = new ContentModule(integrationsDictionary);

            builder.RegisterModule(contentModule);

            var contextModule = new ContextModule(integrationsDictionary);

            builder.RegisterModule(contextModule);

            builder.RegisterModule <RoutesModule>();
            builder.RegisterModule <MvcHttpModule>();
            builder.RegisterModule <NewtonsoftJsonModule>();
        }
        public ActionResult CloneModule(int id)
        {
            var newModule = new ContentModule();

            var moduleToClone = Context.ContentModules.First(x => x.ContentModuleId == id);

            newModule.CreateDate = DateTime.Today;
            newModule.HTMLContent = moduleToClone.HTMLContent;
            newModule.HTMLUnparsed = moduleToClone.HTMLUnparsed;
            newModule.JSContent = moduleToClone.JSContent;

            newModule.CSSContent = moduleToClone.CSSContent;
            newModule.SchemaEntryValues = moduleToClone.SchemaEntryValues;
            newModule.SchemaId = moduleToClone.SchemaId;
            newModule.ModuleName = "New Module";

            Context.ContentModules.Add(newModule);
            Context.SaveChanges();

            // Update the Display Name
            newModule.ModuleName = "New Module " + newModule.ContentModuleId;
            Context.SaveChanges();

            return RedirectToAction("EditModule", "Modules", new { id = newModule.ContentModuleId });
        }
        public CommerceModule()
        {
            if (_Triggered == false)
            {
                // ensure that we have thank you page
                ContentModule.GetPage(this.SiteDatabase, "/__/commerce/thankyou", true);
                _Triggered = true;
            }

            // testing thankyou page by nancy white
            Get["/__/commerce/thankyou"] = this.HandleViewRequest("commerce-thankyoupage", (arg) =>
            {
                if (this.CurrentUser.HasClaim("admin") == false)
                {
                    return(new StandardModel(404));
                }

                var page = ContentModule.GetPage(this.SiteDatabase, "/__/commerce/thankyou", true);
                return(new StandardModel(this, page, JObject.FromObject(new SaleOrder()
                {
                    SaleOrderIdentifier = "SO20990909-999999",
                })));
            });


            Get["/__commerce/cart"] = this.HandleViewRequest("commerce-shoppingcart", (arg) =>
            {
                return(new StandardModel(this, "Checkout"));
            });

            // get the product
            Get["/__commerce/api/productstructure"] = this.HandleRequest(this.BuildProductStructure);

            // List User's address
            Get["/__commerce/api/addresses"] = this.HandleRequest(this.FindUserAddress);

            // Save User's address
            Post["/__commerce/api/address"] = this.HandleRequest(this.UpdateUserAddress);

            // Save User's cart
            Post["/__commerce/api/checkout"] = this.HandleRequest(this.Checkout);

            Get["/__commerce/saleorder/{so_id}/{form}"] = this.HandleViewRequest("commerce-print", this.HandleCommercePrint);

            Patch["/tables/SaleOrder/{id:int}"] = this.HandleRequest(this.HandleSalorderSaveRequest);

            Post["/__commerce/api/resolvevariation"] = this.HandleRequest(this.HandleVariationRequest);

            Get["/__commerce/banner"] = this.HandleRequest(this.HandleBannerRequest);

            Get["/__commerce/settings"] = this.HandleRequest((arg) =>
            {
                return(this.CurrentSite.commerce);
            });

            Post["/__commerce/api/checkpromotion"] = this.HandleRequest(this.HandlePromotionCheckRequest);
        }
Beispiel #8
0
        public JsonResult ModifyModule(ContentModule entity)
        {
            var result = new JsonResult()
            {
                Data = new
                {
                    success = false,
                    message = "There as an error processing your request"
                }
            };

            if (String.IsNullOrEmpty(entity.ModuleName))
            {
                return(result);
            }

            var editedContent = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == entity.ContentModuleId);

            if (editedContent == null)
            {
                return(result);
            }

            if (editedContent.ParentContentModuleId.HasValue)
            {
                editedContent = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == editedContent.ParentContentModuleId.Value);
                if (editedContent == null)
                {
                    return(result);
                }
            }

            SaveDraft(editedContent, editedContent.CreateDate);

            editedContent.DraftAuthorName = UserUtils.CurrentMembershipUsername();
            editedContent.CreateDate      = DateTime.UtcNow;
            LoadContentFromUploadedModel(entity, editedContent);
            editedContent.IsActive = true;

            var success = Context.SaveChanges();

            if (success > 0)
            {
                CachedObjects.GetCacheContentModules(true);

                BookmarkUtil.UpdateTitle("/admin/modules/" + editedContent.ContentModuleId + "/", editedContent.ModuleName);
                result.Data = new
                {
                    success = true,
                    message = "Content saved successfully.",
                    date    = SystemTime.CurrentLocalTime.ToString("dd/MM/yyy @ h:mm tt")
                };
            }

            return(result);
        }
Beispiel #9
0
 private static void LoadContentFromUploadedModel(ContentModule entity, ContentModule editedContent)
 {
     editedContent.ModuleName        = ContentUtils.ScrubInput(entity.ModuleName);
     editedContent.HTMLContent       = entity.HTMLContent;
     editedContent.HTMLUnparsed      = entity.HTMLUnparsed;
     editedContent.JSContent         = entity.JSContent;
     editedContent.CSSContent        = entity.CSSContent;
     editedContent.SchemaId          = entity.SchemaId;
     editedContent.SchemaEntryValues = entity.SchemaEntryValues;
 }
        /// <summary>
        /// Find the content under given url
        /// </summary>
        /// <param name="url">Base Url </param>
        /// <param name="contentTemplate">Razor Template to render for each item of the output</param>
        public object ListRootContents(Func <dynamic, object> contentTemplate)
        {
            var list = ContentModule.GetRootPages(this.Context.GetSiteDatabase());

            foreach (var item in list)
            {
                var output = contentTemplate(item);
                this.WriteLiteral(output);
            }

            return(null);
        }
        public EditModuleViewModel(int id)
        {
            using (var context = new DataContext())
            {
                TheModule = context.ContentModules.FirstOrDefault(x => x.ContentModuleId == id);

                // Set Unparsed Html on Legacy Modules
                if (String.IsNullOrEmpty(TheModule.HTMLUnparsed) && !String.IsNullOrEmpty(TheModule.HTMLContent))
                {
                    TheModule.HTMLUnparsed = TheModule.HTMLContent;
                }

                Schemas = context.Schemas.ToList();
            }
        }
Beispiel #12
0
        public JsonResult SaveDraft(ContentModule entity, DateTime?publishDate)
        {
            var draft = SetContentModuleData(entity, false, publishDate);

            var originalModule = Context.ContentModules.First(module => module.ContentModuleId == entity.ContentModuleId);

            draft.ParentContentModuleId = originalModule.ParentContentModuleId ?? originalModule.ContentModuleId;

            Context.ContentModules.Add(draft);
            Context.SaveChanges();

            return(new JsonResult
            {
                Data = new { id = draft.ContentModuleId }
            });
        }
Beispiel #13
0
        public static void Setup()
        {
            Console.WriteLine("E3");
            Driver = GetWebDriver(ConfigurationSettings.AppSettings["browser"]);
            string baseUrl = ConfigurationSettings.AppSettings["baseUrl"];

            Console.WriteLine("E4");
            Driver.Manage().Window.Maximize();
            Driver.Navigate().GoToUrl(baseUrl);
            LoginModule        = new LoginModule(Driver);
            CompanyModule      = new CompanyModule(Driver);
            DashboardModule    = new DashboardModule(Driver);
            ArtistModule       = new ArtistModule(Driver);
            GroupModule        = new GroupModule(Driver);
            ContentModule      = new ContentModule(Driver);
            ElementPresentTest = new ElementPresentTest(Driver);
        }
Beispiel #14
0
        public ActionResult NewContentModule(string schemaId, string editContentHeading)
        {
            // Create a new Content Module to be passed to the edit content action

            ContentModule module = GetDefaultContentModule();

            // If a schema was passed in, we will want to assign that schema id to the newly created module
            // We will also want to copy over html from an existing module that uses that html. That way the user has a consistent editor.
            int iSchemaId = !string.IsNullOrEmpty(schemaId) ? Int32.Parse(schemaId) : 0;

            if (iSchemaId > 0)
            {
                module.SchemaId = iSchemaId;

                var moduleToCloneFrom = Context.ContentModules.FirstOrDefault(x => x.SchemaId == iSchemaId);
                if (moduleToCloneFrom != null)
                {
                    module.HTMLContent  = moduleToCloneFrom.HTMLContent;
                    module.HTMLUnparsed = moduleToCloneFrom.HTMLUnparsed;
                    module.JSContent    = moduleToCloneFrom.JSContent;
                    module.CSSContent   = moduleToCloneFrom.CSSContent;
                }
            }

            Context.ContentModules.Add(module);
            Context.SaveChanges();

            // Update the module name
            var moduleId = module.ContentModuleId;

            module.ModuleName      = "Module " + moduleId;
            module.DraftAuthorName = UserUtils.CurrentMembershipUsername();

            Context.SaveChanges();

            CachedObjects.GetCacheContentModules(true);

            object routeParameters = new { id = moduleId };

            if (!String.IsNullOrEmpty(editContentHeading))
            {
                routeParameters = new { id = moduleId, editContentHeading };
            }

            return(RedirectToAction("EditModule", "Modules", routeParameters));
        }
        /// <summary>
        /// Find the content under given url
        /// </summary>
        /// <param name="url">Base Url </param>
        /// <param name="contentTemplate">Razor Template to render for each item of the output</param>
        public object ListChildContents(string url, Func <IContent, object> contentTemplate, int levels = 0)
        {
#if DEBUG
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }
#endif
            var list = ContentModule.GetChildPages(this.Database, url, levels);

            foreach (var item in list)
            {
                var output = contentTemplate(item);
                this.WriteLiteral(output);
            }

            return(null);
        }
Beispiel #16
0
        private StandardModel HandlePaySbuyPostback(dynamic arg)
        {
            JObject         postback        = JObject.FromObject(this.Request.Form.ToDictionary());
            PaySbuyPostback paysbuyPostback = postback.ToObject <PaySbuyPostback>();

            // Since before 02 Dec, 2015. Paysbuy had been sending SO with prefix 00.
            var soId = paysbuyPostback.result.Substring(2);
            var code = paysbuyPostback.result.Substring(0, 2);

            var log = PaymentLog.FromContext(this.Context);

            log.PaymentSource       = PaymentMethod.PaySbuy;
            log.Amount              = paysbuyPostback.amt;
            log.Fee                 = paysbuyPostback.fee;
            log.SaleOrderIdentifier = soId;
            log.IsErrorCode         = code != "00";
            log.ResponseCode        = code;
            log.IsPaymentSuccess    = false;

            var      paymentDateString = log.FormResponse.Value <string>("payment_date");
            DateTime paymentDate;

            if (!log.IsErrorCode)
            {
                paymentDate = DateTime.ParseExact(paymentDateString, "d/M/yyyy H:m:s", new CultureInfo("th-TH"));
            }
            else
            {
                paymentDate = DateTime.Now;
            }

            CommerceModule.HandlePayment(this.SiteDatabase, log, paymentDate);

            var page = ContentModule.GetPage(this.SiteDatabase, "/__/commerce/thankyou", true);

            var so = this.SiteDatabase.Query <SaleOrder>().Where(s => s.SaleOrderIdentifier == soId).FirstOrDefault();

            return(new StandardModel(this, page, JObject.FromObject(new
            {
                SaleOrderIdentification = soId,
                Log = log,
                IsSplitPayment = so.Status == PaymentStatus.Deposit || so.PaymentStatus == PaymentStatus.Deposit
            })));
        }
Beispiel #17
0
        public ActionResult NewContentModule()
        {
            int ModuleId = 0;

            // Create a new Content Page to be passed to the edit content action

            ContentModule module = GetDefaultContentModule();

            Context.ContentModules.Add(module);
            Context.SaveChanges();

            // Update the page title / permalink with the new id we now have
            ModuleId               = module.ContentModuleId;
            module.ModuleName      = "Module " + ModuleId;
            module.DraftAuthorName = UserUtils.CurrentMembershipUsername();

            Context.SaveChanges();

            return(RedirectToAction("EditModule", "Modules", new { id = ModuleId }));
        }
Beispiel #18
0
        public EditModuleViewModel(int id)
        {
            Heading = "Edit Module";
            EditURL = "editmodule";

            TheModule = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == id);

            if (TheModule == null)
            {
                return;
            }

            BookmarkTitle = TheModule.ModuleName;
            // Set Unparsed Html on Legacy Modules
            if (String.IsNullOrEmpty(TheModule.HTMLUnparsed) && !String.IsNullOrEmpty(TheModule.HTMLContent))
            {
                TheModule.HTMLUnparsed = TheModule.HTMLContent;
            }

            var newerVersion = Context.ContentModules.Where(x => (x.ParentContentModuleId == id || x.ContentModuleId == id) &&
                                                            x.CreateDate > TheModule.CreateDate &&
                                                            x.ContentModuleId != TheModule.ContentModuleId).OrderByDescending(x => x.CreateDate).FirstOrDefault();

            if (newerVersion != null)
            {
                NewerVersionId = newerVersion.ContentModuleId;
            }

            var parentId = TheModule.ParentContentModuleId ?? TheModule.ContentModuleId;

            Revisions = Context.ContentModules.Where(x => x.ParentContentModuleId == parentId || x.ContentModuleId == parentId).OrderByDescending(x => x.CreateDate).ToList().Select(rev => new RevisionViewModel
            {
                Date         = rev.CreateDate,
                ContentId    = rev.ContentModuleId,
                AuthorName   = rev.DraftAuthorName,
                WasPublished = rev.WasPublished
            }).ToList();
            Schemas = Context.Schemas.ToList();
        }
        public EditModuleViewModel(int id)
        {
            Heading = "Edit Module";
            EditURL = "editmodule";

            TheModule = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == id);

            if (TheModule == null)
            {
                return;
            }

            BookmarkTitle = TheModule.ModuleName;
            // Set Unparsed Html on Legacy Modules
            if (String.IsNullOrEmpty(TheModule.HTMLUnparsed) && !String.IsNullOrEmpty(TheModule.HTMLContent))
            {
                TheModule.HTMLUnparsed = TheModule.HTMLContent;
            }

            var newerVersion = Context.ContentModules.Where(x => (x.ParentContentModuleId == id || x.ContentModuleId == id)
                && x.CreateDate > TheModule.CreateDate
                && x.ContentModuleId != TheModule.ContentModuleId).OrderByDescending(x => x.CreateDate).FirstOrDefault();

            if (newerVersion != null)
            {
                NewerVersionId = newerVersion.ContentModuleId;
            }

            var parentId = TheModule.ParentContentModuleId ?? TheModule.ContentModuleId;

            Revisions = Context.ContentModules.Where(x => x.ParentContentModuleId == parentId || x.ContentModuleId == parentId).OrderByDescending(x => x.CreateDate).ToList().Select(rev => new RevisionViewModel
            {
                Date = rev.CreateDate,
                ContentId = rev.ContentModuleId,
                AuthorName = rev.DraftAuthorName,
                WasPublished = rev.WasPublished
            }).ToList();
            Schemas = Context.Schemas.ToList();
        }
        public TestBulkRequestsModule()
        {
            Get["/TestBulkRequests/{file}"] = x =>
            {
                return(ContentModule.GetEmbeddedResource("Nancy.LongPoll.Test." + x.file, typeof(TestBulkRequestsModule).Assembly));
            };

            Get["/TestBulkRequests/StopTest"] = x =>
            {
                BulkRequestsTest.StopTest = true;

                return("");
            };

            Get["/TestBulkRequests/StopWait"] = x =>
            {
                BulkRequestsTest.StopWait = true;

                return("");
            };

            Get["/TestBulkRequests/Wait"] = x =>
            {
                Interlocked.Increment(ref _Counter);

                while (!BulkRequestsTest.StopWait)
                {
                    Thread.Sleep(1000);
                }

                return("");
            };

            Get["/TestBulkRequests/RequestsCount"] = x =>
            {
                return(_Counter.ToString());
            };
        }
Beispiel #21
0
 public void SMK08_VerifyContentCreation_Video_FixedCountdown_Artist_Preview()
 {
     TestGroupName = GetType().Name;
     TestName      = TestContext.TestName;
     CreateFolders(TestGroupName, TestName);
     try
     {
         type        = "Fixed Countdown";
         level       = "3";
         media       = "Video";
         pathcontent = datapath + "\\Video.au3";
         pathpreview = datapath + "\\Image.au3";
         owner       = "Artist";
         var tmp = File.ReadAllText(@datapath + "\\path.txt");
         DashboardModule.NavigateToDashboard(TestGroupName, TestName);
         ContentModule.VerifyAddContent(type, level, media, pathcontent, pathpreview, owner, tmp, TestGroupName, TestName);
     }
     catch (Exception e)
     {
         _verificationErrors.Append(e.Message);
         Assert.Fail(e.Message);
     }
 }
Beispiel #22
0
 public void SMK09_VerifyContentCreation_Image_DurationCountdown_Group()
 {
     TestGroupName = GetType().Name;
     TestName      = TestContext.TestName;
     CreateFolders(TestGroupName, TestName);
     try
     {
         type        = "Duration Countdown";
         level       = "4";
         media       = "Image";
         pathcontent = datapath + "\\Image.au3";
         pathpreview = "";
         owner       = "Group";
         var tmp = File.ReadAllText(@datapath + "\\path.txt");
         DashboardModule.NavigateToDashboard(TestGroupName, TestName);
         ContentModule.VerifyAddContent(type, level, media, pathcontent, pathpreview, owner, tmp, TestGroupName, TestName);
         LoginModule.Logout(TestGroupName, TestName);
     }
     catch (Exception e)
     {
         _verificationErrors.Append(e.Message);
         Assert.Fail(e.Message);
     }
 }
        protected ContentModule SetContentModuleData(ContentModule entity, bool isBasic, DateTime? createDate)
        {
            var editedContent = new ContentModule
            {
                CreateDate = createDate ?? DateTime.UtcNow,
                ModuleName = entity.ModuleName,
                HTMLContent = entity.HTMLContent,
                HTMLUnparsed = entity.HTMLUnparsed,
                SchemaId = entity.SchemaId,
                SchemaEntryValues = entity.SchemaEntryValues,
                IsActive = false,
                ParentContentModuleId = entity.ContentModuleId,
                DraftAuthorName = UserUtils.CurrentMembershipUsername(),
                WasPublished = createDate != null
            };

            // Basic Editors don't pass JS / CSS Content along
            if (!isBasic)
            {
                editedContent.JSContent = entity.JSContent;
                editedContent.CSSContent = entity.CSSContent;
            }

            return editedContent;

        }
 private static void LoadContentFromUploadedModel(ContentModule entity, ContentModule editedContent)
 {
     editedContent.ModuleName = ContentUtils.ScrubInput(entity.ModuleName);
     editedContent.HTMLContent = entity.HTMLContent;
     editedContent.HTMLUnparsed = entity.HTMLUnparsed;
     editedContent.JSContent = entity.JSContent;
     editedContent.CSSContent = entity.CSSContent;
     editedContent.SchemaId = entity.SchemaId;
     editedContent.SchemaEntryValues = entity.SchemaEntryValues;
 }
        public JsonResult ModifyModule(ContentModule entity)
        {
            var result = new JsonResult()
            {
                Data = new
                {
                    success = false,
                    message = "There as an error processing your request"
                }
            };

            if (String.IsNullOrEmpty(entity.ModuleName))
            {
                return result;
            }

            var editedContent = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == entity.ContentModuleId);

            if (editedContent == null)
            {
                return result;
            }

            if (editedContent.ParentContentModuleId.HasValue)
            {
                editedContent = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == editedContent.ParentContentModuleId.Value);
                if (editedContent == null)
                {
                    return result;
                }
            }

            SaveDraft(editedContent, editedContent.CreateDate);

            editedContent.DraftAuthorName = UserUtils.CurrentMembershipUsername();
            editedContent.CreateDate = DateTime.UtcNow;
            LoadContentFromUploadedModel(entity, editedContent);
            editedContent.IsActive = true;

            var success = Context.SaveChanges();

            if (success > 0)
            {
                CachedObjects.GetCacheContentModules(true);

                BookmarkUtil.UpdateTitle("/admin/modules/" + editedContent.ContentModuleId + "/", editedContent.ModuleName);
                result.Data = new
                {
                    success = true,
                    message = "Content saved successfully.",
                    date = SystemTime.CurrentLocalTime.ToString("dd/MM/yyy @ h:mm tt")
                };
            }

            return result;
        }
        public JsonResult SaveDraft(ContentModule entity, DateTime? publishDate)
        {
            var draft = SetContentModuleData(entity, false, publishDate);

            var originalModule = Context.ContentModules.First(module => module.ContentModuleId == entity.ContentModuleId);
            draft.ParentContentModuleId = originalModule.ParentContentModuleId ?? originalModule.ContentModuleId;

            Context.ContentModules.Add(draft);
            Context.SaveChanges();

            return new JsonResult
            {
                Data = new { id = draft.ContentModuleId }
            };
        }
        public JsonResult ModifyModule(ContentModule entity)
        {
            var result = new JsonResult();

            if (!String.IsNullOrEmpty(entity.ModuleName))
            {
                using (var context = new DataContext())
                {
                    ContentModule editedContent = context.ContentModules.FirstOrDefault(x => x.ContentModuleId == entity.ContentModuleId);
                    if (editedContent != null)
                    {
                        editedContent.ModuleName = scrubInput(entity.ModuleName);
                        editedContent.HTMLContent = entity.HTMLContent;
                        editedContent.HTMLUnparsed = entity.HTMLUnparsed;
                        editedContent.JSContent = entity.JSContent;
                        editedContent.CSSContent = entity.CSSContent;
                        editedContent.SchemaId = entity.SchemaId;
                        editedContent.SchemaEntryValues = entity.SchemaEntryValues;

                        context.SaveChanges();
                    }
                }
            }
            return result;
        }
Beispiel #28
0
 private void _RegisterModules()
 {
     Profile = new ProfileModule(this);
     Sale    = new SaleModule(this);
     Content = new ContentModule(this);
 }
Beispiel #29
0
        public JsonResult ModifyModule(ContentModule entity)
        {
            var result = new JsonResult()
            {
                Data = new
                {
                    success = false,
                    message = "There as an error processing your request"
                }
            };

            var success = 0;

            if (String.IsNullOrEmpty(entity.ModuleName))
            {
                return(result);
            }

            var editedContent = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == entity.ContentModuleId);

            if (editedContent == null)
            {
                return(result);
            }

            if (editedContent.ParentContentModuleId.HasValue)
            {
                editedContent = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == editedContent.ParentContentModuleId.Value);
                if (editedContent == null)
                {
                    return(result);
                }
            }

            SaveDraft(editedContent, editedContent.CreateDate);

            editedContent.DraftAuthorName   = UserUtils.CurrentMembershipUsername();
            editedContent.CreateDate        = DateTime.UtcNow;
            editedContent.ModuleName        = ContentUtils.ScrubInput(entity.ModuleName);
            editedContent.HTMLContent       = entity.HTMLContent;
            editedContent.HTMLUnparsed      = entity.HTMLUnparsed;
            editedContent.JSContent         = entity.JSContent;
            editedContent.CSSContent        = entity.CSSContent;
            editedContent.SchemaId          = entity.SchemaId;
            editedContent.SchemaEntryValues = entity.SchemaEntryValues;
            editedContent.IsActive          = true;

            success = Context.SaveChanges();

            if (success > 0)
            {
                BookmarkUtil.UpdateTitle("/admin/modules/" + editedContent.ContentModuleId + "/", editedContent.ModuleName);
                result.Data = new
                {
                    success = true,
                    message = "Content saved successfully.",
                    date    = editedContent.CreateDate.Value.ToString("dd/MM/yyy @ h:mm tt")
                };
            }

            return(result);
        }
Beispiel #30
0
        public CommerceModule()
        {
            if (_Triggered == false)
            {
                // ensure that we have thank you page
                ContentModule.GetPage(this.SiteDatabase, "/__/commerce/thankyou", true);
                _Triggered = true;
            }

            // testing thankyou page by nancy white
            Get["/__/commerce/thankyou"] = this.HandleViewRequest("commerce-thankyoupage", (arg) =>
            {
                if (this.CurrentUser.HasClaim("admin") == false)
                {
                    return(new StandardModel(404));
                }

                var page = ContentModule.GetPage(this.SiteDatabase, "/__/commerce/thankyou", true);
                return(new StandardModel(this, page, JObject.FromObject(new SaleOrder()
                {
                    SaleOrderIdentifier = "SO20990909-999999",
                })));
            });


            Get["/__commerce/cart"] = this.HandleViewRequest("commerce-shoppingcart", (arg) =>
            {
                return(new StandardModel(this, "Checkout"));
            });

            // get the product
            Get["/__commerce/api/productstructure"] = this.HandleRequest(this.BuildProductStructure);

            // List User's address
            Get["/__commerce/api/addresses"] = this.HandleRequest(this.FindUserAddress);

            // Save User's address
            Post["/__commerce/api/address"] = this.HandleRequest(this.UpdateUserAddress);

            // Save User's cart
            Post["/__commerce/api/checkout"] = this.HandleRequest(this.Checkout);

            Get["/__commerce/saleorder/{so_id}/{form}"] = this.HandleViewRequest("commerce-print", (arg) =>
            {
                int soId     = 0;
                var id       = (string)arg.so_id;
                SaleOrder so = null;
                if (int.TryParse(id, out soId))
                {
                    so = this.SiteDatabase.GetById <SaleOrder>(soId);
                }
                else
                {
                    so = this.SiteDatabase.Query <SaleOrder>()
                         .Where(row => row.SaleOrderIdentifier == id)
                         .FirstOrDefault();
                }

                if (arg.form == "receipt" && !this.CurrentUser.HasClaim("admin"))
                {
                    if (so.PaymentStatus != PaymentStatus.PaymentReceived)
                    {
                        return(new StandardModel(400));
                    }
                }

                if (so == null)
                {
                    return(new StandardModel(404));;
                }

                var receipts = this.SiteDatabase.Query <Receipt>()
                               .Where(r => r.SaleOrderId == so.Id)
                               .ToList();

                Receipt receipt;

                if (this.Request.Query.index == null && receipts.Count == 1)
                {
                    receipt = receipts.FirstOrDefault();
                }
                else if (this.Request.Query.index == null && receipts.Count > 1)
                {
                    receipt = new Receipt()
                    {
                        Identifier = "Specify Index"
                    };
                }
                else
                {
                    receipt = receipts
                              .Skip(this.Request.Query.index == null ? 0 : (int)this.Request.Query.index)
                              .FirstOrDefault();
                }

                if (receipt == null)
                {
                    receipt = new Receipt()
                    {
                        Identifier = so.ReceiptIdentifier
                    };
                }

                var paymentlogs = this.SiteDatabase.Query <PaymentLog>()
                                  .Where(p => p.SaleOrderIdentifier == so.SaleOrderIdentifier && p.IsErrorCode == false)
                                  .OrderBy(log => log.PaymentDate)
                                  .ToList();

                var totalPaid = paymentlogs.Sum(log => log.Amount);

                var paymentDetail = new
                {
                    TransactionLog      = paymentlogs,
                    PaymentRemaining    = so.TotalAmount - totalPaid,
                    TotalPaid           = totalPaid,
                    SplitedPaymentIndex = this.Request.Query.index == null ? -1 : (int)this.Request.Query.index
                };

                var dummyPage = new Page()
                {
                    Title        = arg.form + " for " + so.SaleOrderIdentifier,
                    ContentParts = JObject.FromObject(new
                    {
                        Type = (string)arg.form
                    })
                };

                return(new StandardModel(this, dummyPage, new { SaleOrder = so, PaymentDetail = paymentDetail, Receipt = receipt }));
            });

            Patch["/tables/SaleOrder/{id:int}"] = this.HandleRequest(this.HandleSalorderSaveRequest);

            Post["/__commerce/api/resolvevariation"] = this.HandleRequest(this.HandleVariationRequest);

            Get["/__commerce/banner"] = this.HandleRequest(this.HandleBannerRequest);

            Get["/__commerce/settings"] = this.HandleRequest((arg) =>
            {
                return(this.CurrentSite.commerce);
            });

            Post["/__commerce/api/checkpromotion"] = this.HandleRequest(this.HandlePromotionCheckRequest);
        }
        public AffiliateModule()
        {
            AffiliateModule.TemplatePath = Path.Combine(RootPath, "Site", "Views", "EmailTemplates");

            Post["/__affiliate/apply"] = HandleRequest((arg) =>
            {
                if (this.CurrentUser.IsAnonymous)
                {
                    return(400);
                }

                var reg       = AffiliateModule.ApplyAffiliate(this.SiteDatabase, this.CurrentUser.Id);
                var regresult = JObject.FromObject(reg);

                var body = arg.body.Value;
                if (body.sharedCoupon != null)
                {
                    var discountCode = (string)body.sharedCoupon.CouponCode;

                    lock (BaseModule.GetLockObject("SharedCouponCheck-" + reg.Id))
                    {
                        // prevent dubplicates
                        var existing = this.SiteDatabase.Query <AffiliateRewardsClaim>()
                                       .Where(c => c.DiscountCode == discountCode && c.AffiliateRegistrationId == reg.Id)
                                       .FirstOrDefault();

                        if (existing == null)
                        {
                            var toCopy = this.SiteDatabase.GetById <AffiliateRewardsClaim>((int)body.sharedCoupon.CouponId);

                            toCopy.Id = 0;
                            toCopy.AffiliateRegistrationId = reg.Id;
                            toCopy.AffiliateCode           = reg.AffiliateCode;
                            toCopy.NcbUserId      = this.CurrentUser.Id;
                            toCopy.RewardsName    = "shared from ID:" + body.sharedCoupon.AffiliateId;
                            toCopy.IsShareEnabled = false;

                            this.SiteDatabase.UpsertRecord(toCopy);

                            regresult.Add("CouponSaved", true);
                        }
                    }
                }

                if (body.sharedReward != null)
                {
                    lock (BaseModule.GetLockObject("SharedRewardCheck-" + reg.Id))
                    {
                        var result = AffiliateReward.ClaimReward(this.SiteDatabase, (int)body.sharedReward.Id, reg.Id);
                        if (result != null)
                        {
                            regresult.Add("RewardClaimed", true);
                        }
                    }
                }

                return(regresult);
            });

            Post["/__affiliate/requestpayment"] = HandleRequest((arg) =>
            {
                if (CurrentUser.IsAnonymous)
                {
                    return(400);
                }

                var registration = SiteDatabase.Query <AffiliateRegistration>()
                                   .Where(t => t.NcbUserId == CurrentUser.Id).FirstOrDefault();

                if (registration == null)
                {
                    return(400);
                }

                var pendingPayment = SiteDatabase.Query <AffiliateTransaction>()
                                     .Where(t => t.AffiliateCode == registration.AffiliateCode && t.IsCommissionPaid == false && t.IsPendingApprove == false)
                                     .ToList();


                // using alternate rate
                SiteDatabase.Transaction(() =>
                {
                    foreach (var item in pendingPayment)
                    {
                        item.IsPendingApprove = true;
                        SiteDatabase.UpsertRecord(item);
                    }
                });

                return(200);
            });

            Post["/__affiliate/claimrewards"] = HandleRequest((arg) =>
            {
                dynamic param = (arg.body.Value as JObject);
                if (param.Id == null)
                {
                    return(400);
                }

                var registration = AffiliateModule.ApplyAffiliate(this.SiteDatabase, this.CurrentUser.Id);

                var result = AffiliateReward.ClaimReward(this.SiteDatabase, (int)param.Id, registration.Id);
                if (result == null)
                {
                    return(403);
                }

                return(result);
            });

            Post["/__affiliate/addtosaleorder"] = HandleRequest((arg) =>
            {
                if (CurrentUser.IsAnonymous)
                {
                    return(400);
                }

                var requestBody             = (arg.body.Value as JObject);
                var saleOrderId             = requestBody.Value <int>("saleOrderId");
                var affiliateRewardsClaimId = requestBody.Value <int>("arcId");

                if (saleOrderId != 0 && affiliateRewardsClaimId != 0)
                {
                    var aRC = SiteDatabase.GetById <AffiliateRewardsClaim>(affiliateRewardsClaimId);

                    if (aRC.IncludedInSaleOrderId != 0 || aRC.DiscountCode != null)
                    {
                        return(403);
                    }

                    aRC.IncludedInSaleOrderId = saleOrderId;
                    SiteDatabase.UpsertRecord(aRC);

                    return(new
                    {
                        AffiliateRewardsClaim = aRC
                    });
                }


                return(403);
            });

            Post["/__affiliate/updateprofile"] = HandleRequest((arg) =>
            {
                var requestBody = arg.body.Value;

                if (requestBody.Profile == null && requestBody.Registration == null)
                {
                    return(400);
                }

                // Impersonation in effect
                int userId = this.CurrentUser.Id;
                if (userId != (int)requestBody.UserId)
                {
                    if (userId == 1)
                    {
                        userId = (int)requestBody.UserId;
                    }
                    else
                    {
                        return(400); // user that is not 1 cannot save with impersonation
                    }
                }

                if (requestBody.Profile != null)
                {
                    UserManager.Current.UpdateProfile(this.SiteDatabase, userId, requestBody.Profile);
                }

                if (requestBody.Registration != null)
                {
                    AffiliateRegistration registration = SiteDatabase.Query <AffiliateRegistration>()
                                                         .Where(t => t.NcbUserId == CurrentUser.Id).FirstOrDefault();

                    registration.AffiliateName    = requestBody.Registration.AffiliateName;
                    registration.AffiliateMessage = requestBody.Registration.AffiliateMessage;
                    SiteDatabase.UpsertRecord(registration);

                    MemoryCache.Default.Remove("AffiliateReg-" + registration.AffiliateCode);
                }

                MemoryCache.Default.Remove("dashboard-" + CurrentUser.Id);


                return(200);
            });

            Get["/" + AFFILIATE_PROGRAM_NAME + "/dashboard"] = HandleRequest((arg) =>
            {
                if (this.CurrentUser.IsAnonymous)
                {
                    return(this.Response.AsRedirect("/" + AFFILIATE_PROGRAM_NAME));
                }

                var id = this.CurrentUser.Id;
                AffiliateRegistration registration = null;

                if (this.CurrentUser.HasClaim("admin") && Request.Query.code != null) // admin impersonate anyone
                {
                    var code     = (string)Request.Query.code;
                    registration = SiteDatabase.Query <AffiliateRegistration>()
                                   .Where(t => t.AffiliateCode == code).FirstOrDefault();

                    if (registration == null)
                    {
                        return(404); // wrong code
                    }
                }
                else if (this.CurrentUser.HasClaim("admin") && Request.Query.so != null)
                {
                    var soId = (int)Request.Query.so;
                    var so   = SiteDatabase.GetById <SaleOrder>(soId);

                    if (so.NcbUserId == 0)
                    {
                        return(404); // user cannot view squad51 because they was not registered
                    }

                    registration = SiteDatabase.Query <AffiliateRegistration>()
                                   .Where(t => t.NcbUserId == so.NcbUserId).FirstOrDefault();

                    // automatically apply owner of given so
                    if (registration == null &&
                        (so.PaymentStatus == PaymentStatus.PaymentReceived ||
                         so.PaymentStatus == PaymentStatus.Deposit))
                    {
                        registration = AffiliateModule.ApplyAffiliate(this.SiteDatabase, so.NcbUserId);
                    }
                }
                else
                {
                    if (id != 0)
                    {
                        registration = SiteDatabase.Query <AffiliateRegistration>()
                                       .Where(t => t.NcbUserId == id).FirstOrDefault();
                    }
                }

                if (registration == null)
                {
                    if (id != 0) // some known user but we still can't get their registration
                    {
                        // no registration - try to see whether this user already a customer
                        var saleOrder = this.SiteDatabase.Query <SaleOrder>()
                                        .Where(so => so.NcbUserId == id &&
                                               (so.PaymentStatus == PaymentStatus.Deposit ||
                                                so.PaymentStatus == PaymentStatus.PaymentReceived))
                                        .FirstOrDefault();

                        // already customer - auto register them
                        if (saleOrder != null)
                        {
                            registration = AffiliateModule.ApplyAffiliate(this.SiteDatabase, id);
                            return(this.AffiliateDashboard(registration, arg));
                        }
                    }

                    // redirect back to application page
                    return(this.Response.AsRedirect("/" + AFFILIATE_PROGRAM_NAME));
                }


                return(this.AffiliateDashboard(registration, arg));
            });

            Get["/" + AFFILIATE_PROGRAM_NAME] = HandleRequest((arg) =>
            {
                var id = this.CurrentUser.Id;

                AffiliateRegistration registration = SiteDatabase.Query <AffiliateRegistration>()
                                                     .Where(t => t.NcbUserId == id).FirstOrDefault();

                var content = ContentModule.GetPage(SiteDatabase, "/__affiliate", true);
                return(View["affiliate-apply", new StandardModel(this, content, new
                {
                    Registration = registration
                })]);
            });

            Get["/__affiliate/profileimage/{id}"] = this.HandleRequest(arg =>
            {
                var response         = new Response();
                response.ContentType = "image/jpeg";
                response.Contents    = (output) =>
                {
                    WebClient client = new WebClient();
                    var data         = client.DownloadData("https://graph.facebook.com/" + (string)arg.id + "/picture?type=large");
                    output.Write(data, 0, data.Length);
                };
                return(response);
            });

            Get["/__affiliate/getsharedcoupon"] = this.HandleRequest((arg) =>
            {
                if (this.Request.Cookies.ContainsKey("coupon"))
                {
                    var id     = this.Request.Cookies["coupon"];
                    var coupon = this.SiteDatabase.GetById <AffiliateRewardsClaim>(int.Parse(id));

                    if (coupon != null)
                    {
                        if (coupon.IsShareEnabled == false)
                        {
                            return(404);
                        }

                        var couponProduct = this.SiteDatabase.GetById <Product>(coupon.ProductId);
                        if (couponProduct.Url.Contains("/archive/"))
                        {
                            return(new {
                                IsValid = false
                            });
                        }

                        var reg = this.SiteDatabase.GetById <AffiliateRegistration>(coupon.AffiliateRegistrationId);

                        return(new
                        {
                            AffiliateId = reg.Id,
                            AffiliateName = reg.AffiliateName,
                            AffiliateRewardsId = coupon.AffiliateRewardsId,
                            CouponId = coupon.Id,
                            CouponCode = coupon.DiscountCode,
                            CouponAttributes = coupon.CouponAttributes
                        });
                    }
                }

                return(404);
            });

            Get["/__affiliate/getreward"] = this.HandleRequest((arg) =>
            {
                if (this.Request.Cookies.ContainsKey("reward"))
                {
                    var id     = this.Request.Cookies["reward"];
                    var reward = this.SiteDatabase.GetById <AffiliateReward>(int.Parse(id));

                    if (reward != null)
                    {
                        if (reward.IsDirectClaim == false)
                        {
                            return(404);
                        }

                        if (reward.IsRewardsClaimable == false)
                        {
                            return(new
                            {
                                IsValid = false
                            });
                        }

                        return(reward);
                    }
                }

                return(404);
            });

            Get["/__affiliate/myrewards"] = this.HandleRequest((arg) =>
            {
                if (this.CurrentUser.IsAnonymous)
                {
                    return(401);
                }

                return(this.SiteDatabase.Query <AffiliateRewardsClaim>()
                       .Where(c => c.NcbUserId == this.CurrentUser.Id)
                       .AsEnumerable());
            });
        }
        private dynamic AffiliateDashboard(AffiliateRegistration registration, dynamic arg)
        {
            dynamic affiliateFacts = MemoryCache.Default["affiliatefacts"];

            if (affiliateFacts == null)
            {
                affiliateFacts = new
                {
                    Total       = this.SiteDatabase.Query <AffiliateRegistration>().Count(),
                    TotalActive = this.SiteDatabase.Query("SELECT Distinct AffiliateCode FROM AffiliateTransaction", new { Count = 0 }).Count(),
                    PayoutStats = this.SiteDatabase.Query("SELECT Count(Id) as Count, Avg(CommissionAmount) as Avg, Sum(CommissionAmount) as Sum FROM AffiliateTransaction", new { Count = 0, Avg = 0.0M, Sum = 0.0M }).FirstOrDefault(),
                };
                MemoryCache.Default.Add("affiliatefacts", affiliateFacts, DateTimeOffset.Now.AddHours(1));
            }

            var content = ContentModule.GetPage(SiteDatabase, "/__affiliate", true);

            var standardModel = new StandardModel(200);

            standardModel.Content = content;

            if (registration != null)
            {
                var     key           = "dashboard-" + registration.NcbUserId;
                dynamic dashboardData = MemoryCache.Default[key];

                if (Request.Query.code != null)
                {
                    dashboardData = null; // this is impersonation by user 1 - refresh all data

                    MemoryCache.Default.Remove(key);
                    MemoryCache.Default.Remove("AffiliateReg-" + registration.AffiliateCode);
                }

                if (dashboardData == null)
                {
                    var user       = this.SiteDatabase.GetById <NcbUser>(registration.NcbUserId);
                    var saleOrders = this.SiteDatabase.Query <SaleOrder>()
                                     .Where(so => so.NcbUserId == registration.NcbUserId)
                                     .ToList();

                    var activeSaleOrder = (from so in saleOrders
                                           where so.PaymentStatus == PaymentStatus.Credit ||
                                           so.PaymentStatus == PaymentStatus.Deposit ||
                                           so.PaymentStatus == PaymentStatus.PaymentReceived
                                           select so).FirstOrDefault();

                    if (activeSaleOrder != null)
                    {
                        // figure out delivery date
                        activeSaleOrder.FindShipoutAndDeliveryDate(this.SiteDatabase);
                    }

                    Func <SaleOrder, SaleOrder> reduce = (so) =>
                    {
                        var thinCustomer = new
                        {
                            FirstName = (string)so.Customer.FirstName,
                            LastName  = (string)so.Customer.LastName
                        };

                        return(new SaleOrder()
                        {
                            __createdAt = so.__createdAt,
                            SaleOrderIdentifier = so.SaleOrderIdentifier,
                            Status = so.Status,
                            PaymentStatus = so.PaymentStatus,
                            Customer = thinCustomer
                        });
                    };

                    var stat = AffiliateReward.GetRewardStats(this.SiteDatabase, registration);
                    Func <AffiliateReward, JObject> addCanClaim = (rew) =>
                    {
                        var canClaim = AffiliateReward.CanClaim(this.SiteDatabase, rew, registration, stat);
                        var toReturn = JObject.FromObject(rew);

                        toReturn.Add("canClaim", canClaim);

                        return(toReturn);
                    };

                    Func <AffiliateReward, bool> postProcess = (rew) =>
                    {
                        if (rew.IsRewardsClaimable)
                        {
                            return(true);
                        }

                        if (rew.ActiveUntil.HasValue)
                        {
                            if (DateTime.Now.Subtract(rew.ActiveUntil.Value).TotalDays > 7)
                            {
                                return(false); // skip rewards older than 1 week
                            }

                            return(true); // show that they have missed this rewards
                        }

                        if (rew.TotalQuota > 0) // with quota, see created date
                        {
                            if (DateTime.Now.Subtract(rew.__createdAt).TotalDays > 7)
                            {
                                return(false); // dont show old rewards
                            }

                            return(true);
                        }

                        return(true);
                    };

                    AffiliateRegistration refererReg;
                    refererReg = this.SiteDatabase.Query <AffiliateRegistration>()
                                 .Where(reg => reg.AffiliateCode == registration.RefererAffiliateCode)
                                 .FirstOrDefault();

                    if (refererReg != null)
                    {
                        var refererUser = this.SiteDatabase.GetById <NcbUser>(refererReg.NcbUserId);
                        refererReg.AdditionalData = new
                        {
                            Id = refererUser.Profile.id
                        };
                    }

                    dashboardData = new
                    {
                        Referer = refererReg,

                        Registration = registration,

                        Code = registration.AffiliateCode,

                        RelatedOrders = this.SiteDatabase.Query <SaleOrder>()
                                        .Where(so => so.AffiliateCode == registration.AffiliateCode)
                                        .AsEnumerable()
                                        .Select(s => reduce(s)).ToList(),

                        AffiliateTransaction = this.SiteDatabase.Query("SELECT * FROM AffiliateTransaction WHERE AffiliateCode=?",
                                                                       new AffiliateTransaction(),
                                                                       new object[] { registration.AffiliateCode }).ToList(),

                        Profile = user.Profile,

                        SaleOrders = this.SiteDatabase.Query <SaleOrder>()
                                     .Where(so => so.NcbUserId == registration.NcbUserId)
                                     .AsEnumerable()
                                     .Select(s => reduce(s)).ToList(),

                        ActiveSaleOrder = activeSaleOrder,

                        /* Stats */

                        SubscribeAll = SiteDatabase.QueryAsDynamic("SELECT COUNT(Id) As Count FROM AffiliateRegistration WHERE RefererAffiliateCode=?",
                                                                   new { Count = 0 },
                                                                   new object[] { registration.AffiliateCode }).First().Count,

                        ShareClicks = SiteDatabase.QueryAsDynamic("SELECT COUNT(Id) As Count, Url FROM AffiliateShareClick WHERE AffiliateRegistrationId=? GROUP By Url",
                                                                  new { Count = 0, Url = "" },
                                                                  new object[] { registration.Id }),

                        Downline = AffiliateModule.DiscoverDownLine(this.SiteDatabase, registration.AffiliateCode),

                        Rewards = this.SiteDatabase.Query <AffiliateReward>().AsEnumerable()
                                  .Where(rew => rew.IsActive == true)
                                  .AsEnumerable()
                                  .Where(rew => postProcess(rew))
                                  .Select(rew => addCanClaim(rew)),

                        RewardsStat = stat,

                        ClaimedRewards = this.SiteDatabase.Query <AffiliateRewardsClaim>()
                                         .Where(c => c.NcbUserId == registration.NcbUserId)
                                         .AsEnumerable(),

                        AffiliateFacts = affiliateFacts
                    };

#if !DEBUG
                    MemoryCache.Default.Add(key, dashboardData, DateTimeOffset.Now.AddMinutes(10));
#endif
                    UpdatePageView(registration);
                }

                standardModel.Data = JObject.FromObject(dashboardData);
            }


            return(View["affiliate-dashboard", standardModel]);
        }