using System;
using System.Linq;
using System.Web.Mvc;
using Organization.Project.Common;
using Organization.Project.Common.Authentication;
using Organization.Project.Common.Bll;
using Organization.Project.Common.Bll.Objects;
using Organization.Project.Common.Configuration;
using Organization.Project.Common.Enums.Bll;
using Organization.Project.Common.Enums.UI;
using Organization.Project.Web.Authentication;
using Organization.Project.Web.Extensions;
using Organization.Project.Web.Helpers;
using Organization.Project.Web.Models;
using Organization.Project.Web.Models.BuyStuff;
using Organization.Project.Web.ViewData;
namespace Organization.Project.Web.Controllers
{
///
/// Controller for buy stuff operations
///
public class BuyStuffController : BaseController
{
#region User Defined Variables
private readonly ICreditsManager creditsManager;
private readonly IReferenceBookManager referenceBookManager;
private readonly IErrorLogManager errorLog;
#endregion
#region Constructors
///
/// Constructor
///
/// authentication instance
/// account manager instance
/// shopping cart instance
/// configuration instance
/// credits manager instance
/// error log manager
/// reference book manager instance
public BuyStuffController(IAuthentication auth, IAccountManager authManager, IProjectCart cart, IProjectConfiguration config, ICreditsManager creditsManager, IErrorLogManager errorLogManager, IReferenceBookManager referenceBookManager)
: base(auth, authManager, cart, config)
{
this.creditsManager = creditsManager;
this.errorLog = errorLogManager;
this.referenceBookManager = referenceBookManager;
}
#endregion
#region Public Methods
///
/// Gets basic BuyStuff view
///
/// BuyStuff page
[ForceNoCache]
public ActionResult Index(string loadAction)
{
var items = Cart.GetItems(CurrentUser, 0, Constants.BuyStuffPageSize);
var model = CreateBuyStuffViewData(Cart.GetItemsCost(CurrentUser), items, 0);
return View(model);
}
///
/// Gets cart items list view (control)
///
/// cart items current page
/// cart items partial view
[ProjectAuthorize]
public ActionResult GetCartItemsView(int page)
{
var items = Cart.GetItems(CurrentUser, page * Constants.BuyStuffPageSize, Constants.BuyStuffPageSize);
int pagesCount = GetPagesCount(items.Total, Constants.BuyStuffPageSize);
// if no items on page (deleted last item on page) show last page
if (page >= pagesCount)
{
page = pagesCount - 1;
items = Cart.GetItems(CurrentUser, page * Constants.BuyStuffPageSize, Constants.BuyStuffPageSize);
}
return PartialView("Cart/CartItemsList", CreateBuyStuffViewData(Cart.GetItemsCost(CurrentUser), items, page));
}
///
/// Gets bought items list view (control)
///
/// bought items partial view
[ProjectAuthorize]
public ActionResult GetBoughtItemsView()
{
return PartialView("Cart/BoughtItemsList", CreateBoughtStuffListModel());
}
///
/// Downloads chitchat or application (add to cart and redirect to BuyStuff)
///
/// chitchat or application id
/// true if item is application
/// redirect to page with user's cart
[AcceptVerbs(HttpVerbs.Post), ProjectAuthorize]
public ActionResult DownloadItem(int id, bool isApplication)
{
try
{
Cart.AddItem(CurrentUser, id, !isApplication);
return Json(new { isSuccessful = true });
}
catch (Exception e)
{
errorLog.LogException(CurrentUser, HttpContext.Request.UserHostAddress, HttpContext.Request.UserAgent, e);
return Json( new { isSuccessful = false, message = "InvalidOperation" });
}
}
///
/// Adds content items to user's cart
///
/// chitchat or application id
/// true if item is application
/// json data
[AcceptVerbs(HttpVerbs.Post), ProjectAuthorize]
public ActionResult AddItemToCart(int id, bool isApplication)
{
try
{
Cart.AddItem(this.CurrentUser, id, !isApplication);
return Json(new { isSuccessful = true, totalCount = Cart.GetItemsCount(this.CurrentUser) });
}
catch (Exception e)
{
errorLog.LogException(CurrentUser, HttpContext.Request.UserHostAddress, HttpContext.Request.UserAgent, e);
return Json(new { isSuccessful = false, message = "InvalidOperation" });
}
}
///
/// Removes content items from user's cart
///
/// chitchat or application id
/// true if item is application
/// json data
[AcceptVerbs(HttpVerbs.Post), ProjectAuthorize]
public ActionResult DeleteItemFromCart(int id, bool isApplication)
{
try
{
if (isApplication)
Cart.DeleteApplication(this.CurrentUser, id);
else
Cart.DeleteChitchat(this.CurrentUser, id);
return Json(new { isSuccessful = true, totalCount = Cart.GetItemsCount(this.CurrentUser) });
}
catch (Exception e)
{
errorLog.LogException(CurrentUser, HttpContext.Request.UserHostAddress, HttpContext.Request.UserAgent, e);
return Json(new { isSuccessful = false, message = "InvalidOperation" });
}
}
///
/// Deletes item (chitchat or application) from cart
///
/// cart item id
/// current page number
/// List of cart items view + total items count
[AcceptVerbs(HttpVerbs.Post), ProjectAuthorize]
public ActionResult DeleteCartItem(int id, int page)
{
try
{
Cart.DeleteItem(CurrentUser, id);
return Json(new { isSuccessful = true, cartItemsView = ((PartialViewResult)GetCartItemsView(page)).GenerateMarkup(ControllerContext), totalCount = Cart.GetItemsCount(this.CurrentUser) }, "text/html");
}
catch (Exception e)
{
errorLog.LogException(CurrentUser, HttpContext.Request.UserHostAddress, HttpContext.Request.UserAgent, e);
return Json(new { isSuccessful = false, message = "InvalidOperation" });
}
}
///
/// Clears all the items from the cart
///
/// current page number
/// List of cart items view
[AcceptVerbs(HttpVerbs.Post), ProjectAuthorize]
public ActionResult ClearCart(int page)
{
try
{
Cart.Clear(CurrentUser);
return Json(new { isSuccessful = true, cartItemsView = ((PartialViewResult)GetCartItemsView(page)).GenerateMarkup(ControllerContext), totalCount = Cart.GetItemsCount(this.CurrentUser) }, "text/html");
}
catch (Exception e)
{
errorLog.LogException(CurrentUser, HttpContext.Request.UserHostAddress, HttpContext.Request.UserAgent, e);
return Json(new { isSuccessful = false, message = "InvalidOperation" });
}
}
///
/// Buys all the items from the cart
///
/// List of bought items
[AcceptVerbs(HttpVerbs.Post), ProjectAuthorize]
public ActionResult BuyItems()
{
JsonViewData viewData;
try
{
BuyStuffTransactionResult res = creditsManager.BuyStuff(CurrentUser, Cart);
if (res == BuyStuffTransactionResult.Ok)
viewData = new JsonViewData { isSuccessful = true, message = res.ToString() };
else
viewData = new JsonViewData { isSuccessful = false, message = res.ToString() };
}
catch (Exception e)
{
errorLog.LogException(CurrentUser, HttpContext.Request.UserHostAddress, HttpContext.Request.UserAgent, e);
viewData = new JsonViewData { isSuccessful = false, message = e.Message };
}
return Json(viewData);
}
///
/// Gets number of items in the user's cart
///
/// json data
public ActionResult GetItemsCount()
{
return Json(new { isSuccessful = true, totalCount = Cart.GetItemsCount(this.CurrentUser) });
}
#endregion
#region Private Methods
///
/// Creates Buy Stuff page viewdata
///
/// cost of all items in cart
/// paged list of items in cart
/// current pager page
/// Buy stuff viewdata instance
protected BuyStuffViewData CreateBuyStuffViewData(int totalCost, PagedResult> selectedItems, int currentPage)
{
var data = CreateViewData(ProjectWebPage.BuyStuff);
data.MyCredits = this.Auth.IsAuthenticated ? this.CurrentUser.TotalCredits : 0;
data.TotalCost = totalCost;
data.SelectedStuff = CreateCartItemsModel(selectedItems);
data.ListTotalPages = GetPagesCount(selectedItems.Total, Constants.BuyStuffPageSize);
data.ListCurrentPage = currentPage;
data.User = CurrentUser;
data.PaymentCompleteModel = BuyCreditsHelper.CreateModel(this.CurrentUser, this.Request,
ProjectWebPage.BuyStuff);
return data;
}
///
/// Creates Bought stuff list model
///
/// Bought stuff list model
protected BoughtStuffListModel CreateBoughtStuffListModel()
{
return new BoughtStuffListModel()
{
BoughtChitchats = Cart.RecentlyDownloadedChitchats,
BoughtApplications = Cart.RecentlyDownloadedApplications.Select(app => new ApplicationModel
{
Application = app,
CategoryPath = referenceBookManager.GetAppCategoriesImagePath(u => Url.Content(u), app.AppCategoryImpl),
})
.ToList()
};
}
///
/// Creates cart items model
///
/// paged list of items in cart
///
protected PagedResult CreateCartItemsModel(PagedResult> items)
{
return new PagedResult(
items.Total,
items.Result.Select(i => i.IsApplication
? new CartItemModel(i.CartItemId, new ApplicationModel
{ Application = i.Application,
CategoryPath = referenceBookManager.GetAppCategoriesImagePath(u => Url.Content(u), i.Application.AppCategoryImpl),
}, i.IsAlreadyPurchased)
: new CartItemModel(i.CartItemId, new ChitchatModel { Chitchat = i.Chitchat }, i.IsAlreadyPurchased)).ToArray());
}
#endregion
}
}