Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 58.01 KB | None | 0 0
  1. using SmartaBusinessBuilder.Core.RepositoryInterfaces;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using System;
  5. using SmartaBusinessBuilder.Core.Helpers;
  6. using System.IO;
  7. using SmartaBusinessBuilder.Encryption;
  8. using SmartaBusinessBuilder.Core.Enums;
  9. using SmartaBusinessBuilder.Core.ExtensionMethods;
  10. using System.Web.Mvc;
  11. using SmartaBusinessBuilder.Core.Exceptions;
  12. using SmartaBusinessBuilder.Core.Dashboard;
  13. using SmartaBusinessBuilder.Core.DashboardInterfaces;
  14. using Microsoft.Practices.ServiceLocation;
  15. using SmartaBusinessBuilder.ApplicationServices;
  16. using SmartaBusinessBuilder.Core.ModelBinders;
  17.  
  18. namespace SmartaBusinessBuilder.Core.ViewModels
  19. {
  20.     public class AccountModel
  21.     {
  22.         #region Fields
  23.         #region Repository Fields
  24.         private readonly IAccountRepository _accountRepository;
  25.         private readonly IBundleRepository _bundleRepository;
  26.         private readonly ISmartaUserRepository _userRepository;
  27.         private readonly ISettingRepository _settingRepository;
  28.         private readonly IPackageOrderRepository _orderRepository;
  29.         private readonly ISmartaUserAccountSystemRepository _userAccountProductRepository;
  30.         private readonly IAccountStatusRepository _accountStatusRepository;
  31.         private readonly IEmailRepository _emailRepository;
  32.         private readonly IAddressRepository _addressRepository;
  33.         private readonly IProviderOutputRepository _outputRepository;
  34.         private readonly ISmartaUserAccountSystemRepository _userAccountSystemRepository;
  35.         private readonly IUserSystemPasswordRepository _userSystemPasswordRepository;
  36.         private readonly IAccountSystemPasswordRepository _accountSystemRepository;
  37.         private readonly ISystemRepository _systemRepository;
  38.         private readonly IAdminLoginRepository _adminLoginRepository;
  39.         #endregion
  40.  
  41.         private IAccounts _accounts;
  42.         private IDomain _domain;
  43.         private SmartaUser _user;
  44.         private int _selectedAccountId;
  45.         private SettingCollection _settingCollection;
  46.         private List<SmartaUserAccountSystem> _userSystems;
  47.         private IBusinessPlan _businessPlan;
  48.         private IWebsiteBuilder _website;
  49.         private ILegal _legal;
  50.         private IList<AdminLoginValue> _adminValues;
  51.         private IEmail _emailGateway;
  52.         #endregion
  53.  
  54.         #region Properties
  55.         public IList<SmartaUser> Users { get; private set; }
  56.         public OrderModel OrderModel { get; private set; }
  57.         public SettingCollection Setting
  58.         {
  59.             get
  60.             {
  61.                 if (_settingCollection == null)
  62.                     _settingCollection = new SettingCollection(_settingRepository.GetAll());
  63.  
  64.                 return _settingCollection;
  65.             }
  66.         }
  67.  
  68.         private List<SmartaUserAccountSystem> UserSystems { get; set; }
  69.  
  70.         private AdminLoginCollection BusinessPlanAdminValueCollection
  71.         {
  72.             get
  73.             {
  74.                 return new AdminLoginCollection(AdminValueCollection.Where(a => a.AdminLoginTypeId == AdminLoginType.BusinessPlan).ToList());
  75.             }
  76.         }
  77.  
  78.         private IWebsiteBuilder WebsiteBuilder
  79.         {
  80.             get
  81.             {
  82.                 if (_website == null)
  83.                     _website = ServiceLocator.Current.GetInstance<IWebsiteBuilder>("IWebsiteBuilder");
  84.  
  85.                 return _website;
  86.             }
  87.         }
  88.  
  89.         private AdminLoginCollection WebsiteAdminValueCollection
  90.         {
  91.             get
  92.             {
  93.                 return new AdminLoginCollection(AdminValueCollection.Where(a => a.AdminLoginTypeId == AdminLoginType.WebsiteBuilder).ToList());
  94.             }
  95.         }
  96.  
  97.         public string UniqueDomainName
  98.         {
  99.             get
  100.             {
  101.                 return SelectedAccount.Domains.First().FullName;
  102.             }
  103.         }
  104.  
  105.         public bool AllowDomainSelection
  106.         {
  107.             get
  108.             {
  109.                 return SelectedAccount.Domains.Where(d => d.DomainType.Id != (int)Enums.DomainType.Smarta).Count() > 1;
  110.             }
  111.         }
  112.  
  113.         public decimal Vat
  114.         {
  115.             get
  116.             {
  117.                 string vat = Setting.Get(SettingType.Vat);
  118.                 return decimal.Parse(vat);
  119.             }
  120.         }
  121.  
  122.         public Account SelectedAccount
  123.         {
  124.             get
  125.             {
  126.                 return _user.Accounts.First(a => a.Id == _selectedAccountId);
  127.             }
  128.  
  129.         }
  130.  
  131.         public Bundle CurrentBundle
  132.         {
  133.             get
  134.             {
  135.                 var order = SelectedAccount.Orders.Where(x => x.HasOrderLines).FirstOrDefault(o => o.OrderLines.Any(i => !i.Cancelled && i.IsBundle));
  136.                 var orderline = order.OrderLines.FirstOrDefault(i => i.IsBundle);
  137.  
  138.                 return orderline != null ? orderline.Bundle : null;
  139.             }
  140.         }
  141.  
  142.         public IEnumerable<Product> SelectedAddOns
  143.         {
  144.             get
  145.             {
  146.                 return SelectedAccount.AccountProducts.Where(ap => !CurrentBundle.IncludedProducts.Any(p => p.Id == ap.Product.Id)).Select(a => a.Product);
  147.             }
  148.         }
  149.  
  150.         public bool HasAddOns
  151.         {
  152.             get
  153.             {
  154.                 return SelectedAddOns != null && SelectedAddOns.Count() > 0;
  155.             }
  156.         }
  157.  
  158.         private IEnumerable<SmartaUserAccountSystem> SelectedUserSystems
  159.         {
  160.             get
  161.             {
  162.                 if (UserSystems != null)
  163.                 { return UserSystems.Where(u => u.SmartaUser.Id == SelectedUser.Id); }
  164.                 else
  165.                 { return new List<SmartaUserAccountSystem>(); }
  166.  
  167.             }
  168.         }
  169.  
  170.         public IEnumerable<Bundle> Bundles { get; set; }
  171.  
  172.         public IEnumerable<Bundle> AvailableBundles
  173.         {
  174.             get
  175.             {
  176.                 return Bundles.Where(b => b.Id != CurrentBundle.Id);
  177.             }
  178.         }
  179.  
  180.         public IEnumerable<Product> UnselectedAddOns
  181.         {
  182.             get
  183.             {
  184.                 return CurrentBundle.AddOns.Where(a => !SelectedAddOns.Any(s => s.Id == a.Id));
  185.             }
  186.         }
  187.  
  188.         public bool CanChangeBundle
  189.         {
  190.             get
  191.             {
  192.                 // We don't allow the user to downgrade so can only upgrade
  193.                 return CurrentBundle.Rank != Bundles.Max(b => b.Rank);
  194.             }
  195.         }
  196.  
  197.         public IList<SmartaUser> UsersOnAccount
  198.         {
  199.             get
  200.             {
  201.                 return SelectedAccount.Users;
  202.             }
  203.         }
  204.  
  205.         public UserDetails UserDetails { get; set; }
  206.  
  207.         public UserPermissions UserPermissions { get; set; }
  208.  
  209.         public IList<System> Systems { get; private set; }
  210.  
  211.         public bool HasEmailAccountsRemaining
  212.         {
  213.             get
  214.             {
  215.                 var acc = _accountRepository.Get(_selectedAccountId);
  216.                 var availableEmailAccounts = acc.AccountProducts.Where(p => p.Product.System.Id == (int)SmartaSystem.Email).Sum(x => x.Quantity);
  217.  
  218.                 var userAccountSystems = _userAccountSystemRepository.GetBySystemAndAccount(SmartaSystem.Email, _selectedAccountId);
  219.                 var distinctUserCount = userAccountSystems.Where(a => a.System.Id == (int)SmartaSystem.Email).Distinct((lhs, rhs) => lhs.SmartaUser.Id == rhs.SmartaUser.Id, hash => hash.SmartaUser.Id.GetHashCode()).Count();
  220.  
  221.                 return availableEmailAccounts > distinctUserCount;
  222.             }
  223.         }
  224.  
  225.         private AdminLoginCollection LegalAdminValueCollection
  226.         {
  227.             get
  228.             {
  229.                 return new AdminLoginCollection(AdminValueCollection.Where(a => a.AdminLoginTypeId == AdminLoginType.LegalDocument).ToList());
  230.             }
  231.         }
  232.  
  233.         private ILegal Legal
  234.         {
  235.             get
  236.             {
  237.                 if (_legal == null)
  238.                     _legal = ServiceLocator.Current.GetInstance<ILegal>("ILegal");
  239.  
  240.                 return _legal;
  241.             }
  242.         }
  243.  
  244.         private AdminLoginCollection AccountsAdminValueCollection
  245.         {
  246.             get
  247.             {
  248.                 return new AdminLoginCollection(AdminValueCollection.Where(a => a.AdminLoginTypeId == AdminLoginType.Accounts).ToList());
  249.             }
  250.         }
  251.  
  252.         public SmartaUser SelectedUser { get; private set; }
  253.        
  254.         public IEnumerable<Product> AddOns
  255.         {
  256.             get
  257.             {
  258.                 return CurrentBundle.AddOns;
  259.             }
  260.         }
  261.         #endregion
  262.  
  263.         #region Constructors
  264.         public AccountModel(IAccountRepository accountRepository, ISmartaUserRepository userRepository, IBundleRepository bundleRepository, ISettingRepository settingRepository, IPackageOrderRepository orderRepository, ISmartaUserAccountSystemRepository userAccountProductRepository, IAccountStatusRepository accounStatusRepository, IEmailRepository emailRepository, ISmartaUserAccountSystemRepository userAccountSystemRepository, ISystemRepository systemRepository)
  265.         {
  266.             _accountRepository = accountRepository;
  267.             _userRepository = userRepository;
  268.             _bundleRepository = bundleRepository;
  269.             _settingRepository = settingRepository;
  270.             _orderRepository = orderRepository;
  271.             _userAccountProductRepository = userAccountProductRepository;
  272.             _accountStatusRepository = accounStatusRepository;
  273.             _emailRepository = emailRepository;
  274.             _systemRepository = systemRepository;
  275.             _userAccountSystemRepository = userAccountSystemRepository;
  276.         }
  277.  
  278.         public AccountModel(IAccountRepository accountRepository, ISmartaUserRepository userRepository, IBundleRepository bundleRepository, ISettingRepository settingRepository, IPackageOrderRepository orderRepository, ISmartaUserAccountSystemRepository userAccountProductRepository, IAccountStatusRepository accounStatusRepository, IEmailRepository emailRepository, SmartaUser user, int accountId, ISystemRepository systemRepository, ISmartaUserAccountSystemRepository userAccountSystemRepository, IAddressRepository addressRepository, IAccounts accounts, IDomain domain, IBusinessPlan businessPlan, IProviderOutputRepository outputRepository, IUserSystemPasswordRepository userSystemPasswordRepository, IAccountSystemPasswordRepository accountSystemRepository, IAdminLoginRepository adminLoginRepository)
  279.         {
  280.             _outputRepository = outputRepository;
  281.             _accountRepository = accountRepository;
  282.             _userRepository = userRepository;
  283.             _bundleRepository = bundleRepository;
  284.             _settingRepository = settingRepository;
  285.             _orderRepository = orderRepository;
  286.             _userAccountProductRepository = userAccountProductRepository;
  287.             _accountStatusRepository = accounStatusRepository;
  288.             _emailRepository = emailRepository;
  289.             _systemRepository = systemRepository;
  290.             _userAccountSystemRepository = userAccountSystemRepository;
  291.             _addressRepository = addressRepository;
  292.             _userSystemPasswordRepository = userSystemPasswordRepository;
  293.             _accountSystemRepository = accountSystemRepository;
  294.             _adminLoginRepository = adminLoginRepository;
  295.  
  296.             _accounts = accounts;
  297.             _businessPlan = businessPlan;
  298.             _domain = domain;
  299.             _user = user;
  300.  
  301.             _selectedAccountId = accountId;
  302.  
  303.             Bundles = _bundleRepository.GetAll();
  304.  
  305.             OrderModel = new OrderModel(_settingRepository, _userRepository, _userAccountProductRepository, _accountStatusRepository);
  306.            
  307.             UserDetails = new UserDetails();
  308.             SelectedUser = new SmartaUser();
  309.            
  310.             GetData();
  311.             UserPermissions = new UserPermissions(Systems, HasEmailAccountsRemaining);
  312.         }
  313.         #endregion
  314.  
  315.         #region Properties
  316.         #region Current Monthly Payment properties
  317.         public decimal CurrentMonthlyPayment
  318.         {
  319.             get
  320.             {
  321.                 var products = SelectedAccount.Orders.Sum(o => o.OrderLines.Where(l => !l.IsBundle && !l.Cancelled && l.Product.ProductPaymentTypeId == (int)Enums.PaymentType.Monthly).Sum(i => i.Quantity * i.Price));
  322.                 var bundle = SelectedAccount.Orders.Select(o => o.OrderLines.First(l => l.IsBundle && !l.Cancelled).Bundle.Price).First();
  323.  
  324.                 return products + bundle;
  325.             }
  326.         }
  327.  
  328.         public string CurrentMonthlyPaymentDisplay
  329.         {
  330.             get
  331.             {
  332.                 return CurrentMonthlyPayment.ToString("#0.00");
  333.             }
  334.         }
  335.  
  336.         public string CurrentMonthlyPaymentVat
  337.         {
  338.             get
  339.             {
  340.                 return (CurrentMonthlyPayment * (Vat / 100)).ToString("#0.00");
  341.             }
  342.         }
  343.  
  344.         public string CurrentMonthlyPaymentTotal
  345.         {
  346.             get
  347.             {
  348.                 return (CurrentMonthlyPayment * (1 + (Vat / 100))).ToString("#0.00");
  349.             }
  350.         }
  351.         #endregion
  352.  
  353.         #region Additional License Costs
  354.         public string AdditionalLicenseMonthlyCost
  355.         {
  356.             get
  357.             {
  358.                 return GetAdditionalLicenseCost(true).ToString("0.00");
  359.             }
  360.         }
  361.  
  362.         public string AdditionalLicenseCost
  363.         {
  364.             get
  365.             {
  366.                 return GetAdditionalLicenseCost(false).ToString("0.00");
  367.             }
  368.         }
  369.  
  370.         public string TotalAdditionalLicenseCost
  371.         {
  372.             get
  373.             {
  374.                 return GetTotalAdditionalLicenseCost().ToString("0.00");
  375.             }
  376.         }        
  377.         #endregion
  378.  
  379.         #region Additional Add On Cost
  380.         public string AdditionalAddOnCost
  381.         {
  382.             get
  383.             {
  384.                 return GetAdditionalAddOnCost(false).ToString("0.00");
  385.             }
  386.         }
  387.  
  388.         public string AdditionalAddOnMonthlyCost
  389.         {
  390.             get
  391.             {
  392.                 return GetAdditionalAddOnCost(true).ToString("0.00");
  393.             }
  394.         }
  395.  
  396.         public string TotalAdditionalAddOnMonthlyCost
  397.         {
  398.             get
  399.             {
  400.                 return GetTotalAdditionalAddOnCost().ToString("0.00");
  401.             }
  402.         }        
  403.         #endregion
  404.  
  405.         #region New Monthly Payment properties
  406.         public decimal NewMonthlyPayment
  407.         {
  408.             get
  409.             {
  410.                 return OrderModel.TotalMonthlyCost + CurrentMonthlyPayment;
  411.             }
  412.         }
  413.  
  414.         public string NewMonthlyPaymentDisplay
  415.         {
  416.             get
  417.             {
  418.                 return NewMonthlyPayment.ToString("#0.00");
  419.             }
  420.         }
  421.  
  422.         public string NewMonthlyPaymentVat
  423.         {
  424.             get
  425.             {
  426.                 return (NewMonthlyPayment * (Vat / 100)).ToString("#0.00");
  427.             }
  428.         }
  429.  
  430.         public string NewMonthlyPaymentTotal
  431.         {
  432.             get
  433.             {
  434.                 return (NewMonthlyPayment * (1 + (Vat / 100))).ToString("#0.00");
  435.             }
  436.         }
  437.  
  438.         public string OneOffCosts
  439.         {
  440.             get
  441.             {
  442.                 return (GetTotalAdditionalAddOnCost() + GetTotalAdditionalLicenseCost()).ToString("0.00");
  443.             }
  444.         }
  445.  
  446.         public string Cost
  447.         {
  448.             get
  449.             {
  450.                 return ((GetTotalAdditionalAddOnCost() + GetTotalAdditionalLicenseCost()) + ((GetTotalAdditionalAddOnCost() + GetTotalAdditionalLicenseCost()) * (Vat/100))).ToString("0.00");
  451.             }
  452.         }
  453.  
  454.         public string VatCost
  455.         {
  456.             get
  457.             {
  458.                 return ((GetTotalAdditionalAddOnCost() + GetTotalAdditionalLicenseCost()) * (Vat/100)).ToString("0.00");
  459.             }
  460.         }
  461.         #endregion
  462.         #endregion
  463.  
  464.         #region Methods
  465.         #region Public Methods
  466.         public string BundleChange(int rank)
  467.         {
  468.             return rank < CurrentBundle.Rank ? "Downgrade" : "Upgrade";
  469.         }
  470.  
  471.         public void CancelAccount()
  472.         {
  473.             // TODO : Need to control the cancellation of the account.
  474.             CancelUserLevelAccess();
  475.  
  476.             // TODO : Get the account passwords (not user passwords) for account level provisioned providers. Cancel each of these...
  477.             CancelAccountLevelAccess();
  478.  
  479.             // If the user has purchased a domain through Smarta then we need to effectively transfer the ownership. Here we should send them an email with their login details to enom to
  480.             // maintain their domain. The domain will be moved to a magic folder whereby it will not be renewed automatically.
  481.             CancelDomains();
  482.  
  483.             // TODO : We have a hardcoded value for commid here. Need to put this somewhere...
  484.             DataPoster.Post(SmartaBusinessBuilderSettings.Settings.RentSoftUrlCancellation, string.Format("userid={0}&accountid={1}&commid=67", _user.Id, _selectedAccountId));
  485.  
  486.             var user = _userRepository.Get(_user.Id);
  487.             user.Accounts.First(a => a.Id == _selectedAccountId).AccountStatus = new AccountStatus((int)Enums.AccountStatus.Cancelled);
  488.             _userRepository.SaveOrUpdate(user);
  489.             _userRepository.DbContext.CommitChanges();
  490.  
  491.             // Send Cancellation email
  492.             CreateCancellationEmail();
  493.         }
  494.  
  495.         public void GetUser(int id)
  496.         {
  497.             SelectedUser = _userRepository.Get(id);
  498.         }
  499.  
  500.         public string BundleChange()
  501.         {
  502.             int rank = OrderModel.Order.OrderLines.First(o => o.IsBundle).Bundle.Rank;
  503.             return BundleChange(rank);
  504.         }
  505.  
  506.         public string OrderQuantity(int productId)
  507.         {
  508.             return OrderModel.OrderQuantityDisplay(productId);
  509.         }
  510.  
  511.         public bool IsProductSelected(int id)
  512.         {
  513.             return OrderModel.IsProductSelected(id);
  514.         }
  515.  
  516.         public bool CanAddProduct(int productId, int quantity)
  517.         {
  518.             var product = CurrentBundle.BundleProducts.First(p => p.Product.Id == productId);
  519.             if (!product.CanAdd)
  520.                 return false;
  521.  
  522.             int? max = product.MaximumAllowed;
  523.             return !max.HasValue || quantity < max.Value;
  524.         }
  525.  
  526.         public bool CanAddProduct(int productId)
  527.         {
  528.             if (OrderModel == null || OrderModel.Order == null || !OrderModel.Order.HasOrderLines)
  529.                 return true;
  530.  
  531.             int cnt = OrderModel.Order.OrderLines.Count(o => !o.IsBundle && o.Product.Id == productId);
  532.             return CanAddProduct(productId, cnt);
  533.         }
  534.  
  535.         public void RemoveProduct(int id)
  536.         {
  537.             OrderModel.RemoveProduct(id);
  538.         }
  539.  
  540.         public void AddProduct(int id)
  541.         {
  542.             OrderModel.AddOrder(CurrentBundle.AllProducts.First(p => p.Id == id));
  543.         }
  544.  
  545.         public void DeleteAddOn(int id)
  546.         {
  547.             if (OrderModel.IsProductSelected(id))
  548.                 OrderModel.RemoveProduct(id);
  549.             else
  550.                 OrderModel.AddNegativeOrder(CurrentBundle.AllProducts.First(p => p.Id == id));
  551.         }
  552.  
  553.         /// <summary>
  554.         /// Need to store the orders - new and cancelled orders as well as the AccountProducts
  555.         /// </summary>
  556.         public void Save()
  557.         {
  558.             var orders = _orderRepository.GetAllForAccount(_selectedAccountId);
  559.             var user = _userRepository.Get(_user.Id);
  560.             var account = user.Accounts.First(a => a.Id == _selectedAccountId);
  561.  
  562.             // Has user changed Bundle?
  563.             if (OrderModel.Order.OrderLines.Any(ol => ol.IsBundle)
  564.                 && account.Orders.Select(o => o.OrderLines.First(l => l.IsBundle).Bundle.Id).First() != OrderModel.Order.OrderLines.First(ol => ol.IsBundle).Bundle.Id)
  565.             {
  566.                 // Cancel the current bundle order line so we can then add the additional one later
  567.                 var bundleOrder = orders.First(o => o.OrderLines.Any(l => l.IsBundle));
  568.                 bundleOrder.OrderLines.First(l => l.IsBundle).Cancelled = true;
  569.  
  570.                 // Remove products from previous bundle and add products for new bundle.
  571.                 foreach (var product in bundleOrder.OrderLines.First(l => l.IsBundle).Bundle.IncludedProducts)
  572.                 {
  573.                     account.DeleteProduct(product.Id);
  574.                 }
  575.  
  576.                 // Add products from new bundle
  577.                 foreach (var product in OrderModel.Order.OrderLines.First(l => l.IsBundle).Bundle.IncludedProducts)
  578.                 {
  579.                     var quantity = OrderModel.Order.OrderLines.First(l => l.IsBundle).Bundle.GetIncludedProductCount(product.Id);
  580.                     account.AddProduct(product, quantity);
  581.                 }
  582.             }
  583.  
  584.             // Delete Add Ons removed
  585.             OrderModel.Order.OrderLines.Where(o => !o.IsBundle).Where(o => o.Cancelled).ToList().ForEach(o => account.DeleteProduct(o.ProductId));
  586.             OrderModel.Order.OrderLines.Where(o => !o.IsBundle).Where(o => !o.Cancelled && o.Quantity > 0).ToList().ForEach(o => account.AddProduct(CurrentBundle.AllProducts.First(p => p.Id == o.ProductId), o.Quantity));
  587.             OrderModel.Order.OrderLines.Where(o => !o.IsBundle).Where(o => !o.Cancelled && o.Quantity < 0).ToList().ForEach(o => account.DeleteProduct(o.ProductId));
  588.             account.AddOrder(OrderModel.Order);
  589.  
  590.             using (_orderRepository.DbContext.BeginTransaction())
  591.             {
  592.                 try
  593.                 {
  594.                     foreach (var order in orders)
  595.                     {
  596.                         order.Account = account;
  597.                         _orderRepository.SaveOrUpdate(order);
  598.                         _orderRepository.DbContext.CommitChanges();
  599.                     }
  600.  
  601.                     _userRepository.SaveOrUpdate(user);
  602.                     _userRepository.DbContext.CommitChanges();
  603.  
  604.                     _orderRepository.DbContext.CommitTransaction();
  605.                 }
  606.                 catch
  607.                 {
  608.                     _orderRepository.DbContext.RollbackTransaction();
  609.                     throw;
  610.                 }
  611.             }
  612.         }
  613.  
  614.         public int QuantityBought(int productId)
  615.         {
  616.             var quantityPreviouslyAdded = 0;
  617.  
  618.             var _selectedAccount = SelectedAccount;
  619.             var existingLines = _selectedAccount.Orders.SelectMany(o => o.OrderLines.Where(ol => !ol.IsBundle && ol.ProductId == productId));
  620.  
  621.             if (existingLines != null && existingLines.Count() > 0)
  622.                 quantityPreviouslyAdded = existingLines.First(ol => ol.ProductId == productId).Quantity;
  623.  
  624.             var linesNewlyAdded = OrderModel.IsOrderEmpty ? null : OrderModel.Order.OrderLines.FirstOrDefault(l => !l.IsBundle && l.ProductId == productId);
  625.             var quantityNewlyAdded = linesNewlyAdded != null ? linesNewlyAdded.Quantity : 0;
  626.  
  627.             return quantityPreviouslyAdded + quantityNewlyAdded;
  628.         }
  629.  
  630.         public bool MultipleAccountsIncluded(int productId, int bundleId)
  631.         {
  632.             return AccountsIncluded(productId, bundleId) > 1;
  633.         }
  634.  
  635.         public int AccountsIncluded(int productId)
  636.         {
  637.             return AccountsIncluded(productId, CurrentBundle.Id);
  638.         }
  639.  
  640.         public int AccountsIncluded(int productId, int bundleId)
  641.         {
  642.             return Bundles.First(b => b.Id == bundleId).BundleProducts.First(p => p.Product.Id == productId).NumberIncluded;
  643.         }
  644.  
  645.         public int AccountsAvailable(int productId)
  646.         {
  647.             var currentOnAccount = SelectedAccount.AccountProducts.Where(a => a.Product.Id == productId).Sum(p => p.Quantity);
  648.             var newlyAdded = OrderModel.OrderQuantity(productId);
  649.  
  650.             return currentOnAccount + newlyAdded;
  651.         }
  652.        
  653.         public bool IsValidBundle(int bundleId)
  654.         {
  655.             return Bundles.Any(b => b.Id == bundleId);
  656.         }
  657.  
  658.         public int InviteUser(string name, string surname, string existingEmail, string baseUrl, string emailAlias, string domain)
  659.         {
  660.             SmartaUser user;
  661.             using (_userSystemPasswordRepository.DbContext.BeginTransaction())
  662.             {
  663.                 try
  664.                 {
  665.                     var userToken = Guid.NewGuid();
  666.                     var pin = new PasswordGenerator().GeneratePin();
  667.  
  668.                     var acc = _accountRepository.Get(_selectedAccountId);
  669.  
  670.                     var dom = domain ?? UniqueDomainName;
  671.                     // Send activation email containing link to user
  672.                     CreateInvitationEmail(name, surname, existingEmail, userToken, baseUrl, emailAlias, dom, pin);
  673.  
  674.                     user = CreateUser(name, surname, existingEmail, userToken, acc, pin);
  675.  
  676.                     // Add user to system to the created user's selected account and Create username/password for their email account
  677.                     var login = CreateUserSystemLogin(user, acc, existingEmail, dom, emailAlias);
  678.  
  679.                     // TODO : This needs to be done on the Join - so when the user actually logs on. Other accounts should also be created then too
  680.                    // if (!CreateEmailAccount(name, surname, login.Username, login.Password, emailAlias, domain ?? UniqueDomainName))
  681.                        // throw new ApiException("Unable to create email account", "Order");
  682.  
  683.                     // Set password for user to access SBB
  684.                     _userSystemPasswordRepository.DbContext.CommitTransaction();
  685.                 }
  686.                 catch
  687.                 {
  688.                     _userSystemPasswordRepository.DbContext.RollbackTransaction();
  689.                     throw;
  690.                 }
  691.             }
  692.  
  693.             return user.Id;
  694.         }
  695.  
  696.         public bool SaveUserAccess(UserAccess userAccess, int userId)
  697.         {
  698.             var acc = _accountRepository.Get(_selectedAccountId);
  699.             var usr = _userRepository.Get(userId);
  700.  
  701.             bool cancelEmailAccount = false;
  702.  
  703.                     IEnumerable<SmartaUserAccountSystem> removed;
  704.  
  705.                     // Delete those that have been removed first
  706.                     if (userAccess.HasSystemRoles)
  707.                         removed = UserPermissions.SelectedUserSystems.Where(u => !userAccess.SystemRoles.Any(s => s.SystemId == u.System.Id) || userAccess.SystemRoles.Any(s => s.SystemId == u.System.Id && s.RoleId != u.SystemRoleId));
  708.                     else
  709.                         removed = SelectedUserSystems;
  710.  
  711.                     if (removed != null && removed.Count() > 0)
  712.                     {
  713.                         foreach (var system in removed)
  714.                         {
  715.                             if (system.System.Id == (int)SmartaSystem.Email)
  716.                                 cancelEmailAccount = true;
  717.  
  718.                             _userAccountSystemRepository.Delete(system);
  719.                             _userAccountSystemRepository.DbContext.CommitChanges();
  720.                         }
  721.                     }
  722.  
  723.                     if (userAccess.HasSystemRoles)
  724.                     {
  725.                         foreach (var system in userAccess.SystemRoles)
  726.                         {
  727.                             // Do we need to add this one or is it already there with the same role if appropriate?
  728.                             if (UserPermissions.SelectedUserSystems.Any(u => u.System.Id == system.SystemId && u.SystemRoleId == system.RoleId))
  729.                                 continue;
  730.  
  731.                             var sys = _systemRepository.Get(system.SystemId);
  732.  
  733.                             var suas = new SmartaUserAccountSystem(acc, sys);
  734.                             suas.SmartaUser = usr;
  735.                             suas.SystemRoleId = system.RoleId;
  736.  
  737.                             _userAccountSystemRepository.SaveOrUpdate(suas);
  738.                             _userAccountSystemRepository.DbContext.CommitChanges();
  739.                         }
  740.                     }
  741.  
  742.                     // Refresh the data for the next screen
  743.                     _userSystems = _userAccountSystemRepository.GetByAccount(_selectedAccountId);
  744.  
  745.                     if (cancelEmailAccount)
  746.                         CancelEmailAccount(SelectedUser);
  747.  
  748.                     return userAccess.HasSystemRoles && userAccess.SystemRoles.Any(s => s.SystemId == (int)SmartaSystem.Email) && !_userSystems.Where(s => s.SmartaUser.Id == SelectedUser.Id).Any(s => s.System.Id == (int)SmartaSystem.Email);
  749.             }
  750.        
  751.         public void Upgrade(int bundleId)
  752.         {
  753.             // Cancel previous bundle order line item
  754.             OrderModel.AddOrder(Bundles.First(b => b.Id == bundleId));
  755.         }
  756.  
  757.         // TODO : If downgrading email accounts from, say, 6 to 4, and all accounts have been assigned (or in this instance there aren't 2 accounts unassigned) then we need to make the user choose whose account to cancel. Supply with list of email address (and details) and let them choose from there
  758.         public void Downgrade(int bundleId)
  759.         {
  760.             // Cancel previous bundle order line item
  761.             OrderModel.AddOrder(Bundles.First(b => b.Id == bundleId));
  762.         }
  763.  
  764.         public void ProcessAccountCancellation(int SelectedAccountId)
  765.         {
  766.             // TODO : Complete account cancellation process
  767.         }
  768.  
  769.         public bool CancellationChargeRequired(int selectedAccountId)
  770.         {
  771.             // TODO : This time should be put into a configurable component somewhere. 6 months is hard coded - not good!!!
  772.             return _user.Accounts.First(a => a.Id == selectedAccountId).CreatedAt > new DateTime(DateTime.Now.Subtract(new DateTime(0, 6, 0)).Ticks);
  773.         }
  774.  
  775.         public SmartaUser GetUser(int id, int accountId)
  776.         {
  777.             _user = _userRepository.Get(id);
  778.             _selectedAccountId = accountId;
  779.  
  780.             return _user;
  781.         }
  782.  
  783.         public void GetUserDetailsAndPermissions(int id)
  784.         {
  785.             //TODO: UI Caters for one Address Database caters for multiple what is required here?
  786.             if (id != 0)
  787.             {
  788.                 UserDetails.Address = _addressRepository.GetByUserAccount(id, _selectedAccountId).First();
  789.                 UserDetails.User = _userRepository.Get(id);
  790.                 UserPermissions = new UserPermissions(Systems, _userSystems, id, HasEmailAccountsRemaining);
  791.  
  792.  
  793.  
  794.             }
  795.             else
  796.             {
  797.                 UserDetails = new UserDetails();
  798.                 UserPermissions = new UserPermissions(Systems, HasEmailAccountsRemaining);
  799.             }
  800.         }
  801.  
  802.         public List<ValidationError> ValidateAddress(Address address)
  803.         {
  804.             var errors = new List<ValidationError>();
  805.  
  806.             if (String.IsNullOrEmpty(address.AddressName) && String.IsNullOrEmpty(address.Number))
  807.                 errors.Add(new ValidationError("AddressName", "Please enter a housename or number"));
  808.  
  809.             return errors;
  810.         }
  811.  
  812.         public SmartaUser SaveUser(SmartaUser user, Address address)
  813.         {
  814.             using (_userRepository.DbContext.BeginTransaction())
  815.             {
  816.                 user.Pin = new PasswordGenerator().Generate().Substring(0, 5);
  817.                 user.Token = Guid.NewGuid();
  818.                 user.Password = PasswordEncryption.Encrypt(new PasswordGenerator().Generate());
  819.  
  820.                 if (user.UserStatus == null)
  821.                     user.UserStatus = new UserStatus((int)Enums.UserStatus.Active);
  822.  
  823.                 CreateUser(user);
  824.  
  825.                 address.AccountId = _selectedAccountId;
  826.                 address.CreatedBy = _user.Id;
  827.                 address.SmartaUserId = user.Id;
  828.                 address.ModifiedBy = _user.Id;
  829.  
  830.                 _addressRepository.SaveOrUpdate(address);
  831.                 _addressRepository.DbContext.CommitChanges();
  832.  
  833.                 _userRepository.DbContext.CommitTransaction();
  834.             }
  835.  
  836.             return user;
  837.         }
  838.  
  839.         public SmartaUser SaveUser(SmartaUser user, Address address, UserAccess userAccess)
  840.         {
  841.             //Check If in Edit mode
  842.             if (UserDetails.User.Id != 0)
  843.             {
  844.                 SmartaUser currentSmarterUser = _userRepository.Get(UserDetails.User.Id);
  845.                 Address currentAddress = _addressRepository.GetByUserAccount(UserDetails.User.Id, SelectedAccount.Id).First();
  846.  
  847.                 currentSmarterUser.Forename = user.Forename;
  848.                 currentSmarterUser.Surname = user.Surname;
  849.                 currentSmarterUser.EmailAddress = user.EmailAddress;
  850.  
  851.                 currentAddress.Number = address.Number;
  852.                 currentAddress.AddressName = address.AddressName;
  853.                 currentAddress.AddressLine1 = address.AddressLine1;
  854.                 currentAddress.AddressLine2 = address.AddressLine2;
  855.                 currentAddress.AddressLine3 = address.AddressLine3;
  856.                 currentAddress.Town = address.Town;
  857.                 currentAddress.County = address.County;
  858.                 currentAddress.Postcode = address.Postcode;
  859.                 currentAddress.Country = address.Country;
  860.  
  861.                 user = currentSmarterUser;
  862.                 address = currentAddress;
  863.  
  864.            
  865.             }
  866.             else
  867.             {
  868.                 user.Pin = new PasswordGenerator().Generate().Substring(0, 5);
  869.                 user.Token = Guid.NewGuid();
  870.                 user.Password = PasswordEncryption.Encrypt(new PasswordGenerator().Generate());
  871.             }
  872.              
  873.  
  874.             using (_userRepository.DbContext.BeginTransaction())
  875.             {
  876.                
  877.                 if (user.UserStatus == null)
  878.                     user.UserStatus = new UserStatus((int)Enums.UserStatus.Active);
  879.  
  880.                 CreateUser(user);
  881.  
  882.                 address.AccountId = _selectedAccountId;
  883.                 address.CreatedBy = _user.Id;
  884.                 address.SmartaUserId = user.Id;
  885.                 address.ModifiedBy = _user.Id;
  886.  
  887.                 _addressRepository.SaveOrUpdate(address);
  888.                 _addressRepository.DbContext.CommitChanges();
  889.  
  890.                 //Save User Access Here
  891.                 GetUser(user.Id);
  892.                 SaveUserAccess(userAccess, user.Id);
  893.  
  894.                 _userRepository.DbContext.CommitTransaction();
  895.             }
  896.  
  897.             return user;
  898.        
  899.     }
  900.         public List<ValidationError> Validate(string name, string surname, string existingEmail, string emailAlias, string selectDomainName)
  901.         {
  902.             var errors = new List<ValidationError>();
  903.  
  904.             if (string.IsNullOrEmpty(name))
  905.                 errors.Add(new ValidationError("Name", "Name is required"));
  906.  
  907.             if (string.IsNullOrEmpty(surname))
  908.                 errors.Add(new ValidationError("Surname", "Surname is required"));
  909.  
  910.             if (string.IsNullOrEmpty(existingEmail))
  911.                 errors.Add(new ValidationError("ExistingEmail", "Existing email is required"));
  912.  
  913.             if (string.IsNullOrEmpty(emailAlias))
  914.                 errors.Add(new ValidationError("EmailAlias", "Email alias is required"));
  915.  
  916.             if (AllowDomainSelection && string.IsNullOrEmpty(selectDomainName))
  917.                 errors.Add(new ValidationError("SelectDomainName", "Please select domain to use"));
  918.  
  919.             if (!EmailAddressAvailable(emailAlias, selectDomainName))
  920.                 errors.Add(new ValidationError("EmailAlias", "That alias has already been taken. Please enter another"));
  921.  
  922.             return errors;
  923.         }
  924.  
  925.         public List<ValidationError> ValidateEmailAccount(string domain, string emailAlias)
  926.         {
  927.             var errors = new List<ValidationError>();
  928.  
  929.             if (string.IsNullOrEmpty(emailAlias))
  930.                 errors.Add(new ValidationError("EmailAlias", "Alias is required"));
  931.  
  932.             if (!EmailAddressAvailable(emailAlias, domain ?? UniqueDomainName))
  933.                 errors.Add(new ValidationError("EmailAlias", "That alias has already been taken. Please enter another"));
  934.  
  935.             return errors;
  936.         }
  937.  
  938.         public void CreateEmailAccount(string domain, string emailAlias)
  939.         {
  940.             // Check to see whether the user is currently a user on the email system. If they are then we should add the domain and alias to the account rather than performing an order and creating the user
  941.             var login = _userSystemPasswordRepository.GetByUserAndProduct(_user.Id, _selectedAccountId, SmartaSystem.Email);
  942.  
  943.             if (login == null)
  944.             {
  945.                 login = CreateUserSystemLogin(_user, SelectedAccount, _user.EmailAddress, domain, emailAlias);
  946.                 CreateEmailAccount(_user.Forename, _user.Surname, login.Username, login.Password, emailAlias, domain);
  947.  
  948.                 // Do we need to update the MX record here
  949.                 if (SelectedAccount.Domains.First(d => d.FullName == domain).DomainType.Id != (int)Enums.DomainType.Smarta)
  950.                     UpdateMxRecordForDomain(domain);
  951.             }
  952.             else
  953.             {
  954.                 // Add domain to the login and create alias
  955.                 if (AddDomain(domain, login))
  956.                 {
  957.                     if (AddAlias(string.Format("{0}@{1}", emailAlias, domain), login))
  958.                     {
  959.                         // Update domain to set EmailSetup = true
  960.                         var account = _accountRepository.Get(_selectedAccountId);
  961.                         account.Domains.First(d => d.FullName == domain).EmailSetup = true;
  962.  
  963.                         _accountRepository.SaveOrUpdate(account);
  964.                         _accountRepository.DbContext.CommitChanges();
  965.                     }
  966.  
  967.                     // Update the MX Record
  968.                     if (!UpdateMxRecordForDomain(domain))
  969.                     {
  970.                         // TODO : Log unable to update MX record for domain. Should we send an email here or just log?
  971.                         Logger.Log.Warning(string.Format("Unable to update MX record for domain : {0}", domain));
  972.                     }
  973.                 }
  974.             }
  975.         }
  976.  
  977.         public string AddOnCost(int productId, decimal price)
  978.         {
  979.             int qty = 0;
  980.             var order = SelectedAccount.Orders.Where(x => x.HasOrderLines).Where(o => o.OrderLines.Any(i => !i.Cancelled && !i.IsBundle && i.ProductId == productId));
  981.  
  982.             if (order != null && order.Count() > 0)
  983.             {
  984.                 qty = order.Where(o => o.HasOrderLines).ToList().Sum(o => o.OrderLines.Where(l => l.ProductId == productId).Sum(ol => ol.Quantity));
  985.  
  986.                 //qty = order.OrderLines.Where(o => !o.IsBundle && !o.Cancelled && o.ProductId == productId).Sum(p => p.Quantity);
  987.             }
  988.  
  989.             // Add on current order as well
  990.             if (OrderModel.Order != null && OrderModel.Order.HasOrderLines)
  991.             {
  992.                 var orderline = OrderModel.Order.OrderLines.FirstOrDefault(p => !p.IsBundle && p.Product.Id == productId);
  993.                 if (orderline != null)
  994.                     qty += orderline.Quantity;
  995.             }
  996.  
  997.             return (qty * price).ToString("#0.00");
  998.         }
  999.  
  1000.         public int AccountsUsed(int systemId)
  1001.         {
  1002.             return _userSystems.Count(u => u.System.Id == systemId);
  1003.         }
  1004.         #endregion
  1005.  
  1006.         #region Private methods
  1007.         private void CancelAccountLevelAccess()
  1008.         {
  1009.             var accounts = _accountSystemRepository.GetByAccount(_selectedAccountId);
  1010.             foreach (var account in accounts)
  1011.             {
  1012.                 switch (account.SystemId)
  1013.                 {
  1014.                     case Enums.SmartaSystem.Email:
  1015.                         CancelEmailAccount(account.Username);
  1016.                         break;
  1017.                     case Enums.SmartaSystem.Website:
  1018.                         // Should we cancel each website within here or above? I think maybe above. The access to the Website builder is per account rather than per user so this shouldn't come up here but be dealt with separately
  1019.                         CancelWebsite(account.Username);
  1020.                         break;
  1021.                     case Enums.SmartaSystem.Accounts:
  1022.                         // Should we cancel within here or above? I think maybe above. The access to the Accounts is per account rather than per user so this shouldn't come up here but be dealt with separately
  1023.                         CancelAccounts(account.Username, account.Password);
  1024.                         break;
  1025.                     case Enums.SmartaSystem.BusinessPlan:
  1026.                         // Should we cancel within here or above? I think maybe above. How is the access to the business plan done? Do we create a single user on an account basis and have all other users that have this access use this login credentials
  1027.                         CancelBusinessPlan(account.Username, account.Password);
  1028.                         break;
  1029.                     case Enums.SmartaSystem.LegalDocuments:
  1030.                         CancelLegal(account.Username, account.Password);
  1031.                         break;
  1032.                     case Enums.SmartaSystem.WorldPay:
  1033.                         // TODO : Do we need to cancel World Pay
  1034.                         break;
  1035.                     case Enums.SmartaSystem.Domain:
  1036.                         // Need to cancel all domains relating to the account so done below
  1037.                         break;
  1038.                 }
  1039.             }
  1040.         }
  1041.  
  1042.         private void CancelUserLevelAccess()
  1043.         {
  1044.             var accounts = _userSystemPasswordRepository.GetByAccount(_selectedAccountId);
  1045.             foreach (var account in accounts)
  1046.             {
  1047.                 switch (account.SystemId)
  1048.                 {
  1049.                     case Enums.SmartaSystem.Email:
  1050.                         CancelEmailAccount(account.Username);
  1051.                         break;
  1052.                     case Enums.SmartaSystem.Website:
  1053.                         // Should we cancel each website within here or above? I think maybe above. The access to the Website builder is per account rather than per user so this shouldn't come up here but be dealt with separately
  1054.                         CancelWebsite(account.Username);
  1055.                         break;
  1056.                     case Enums.SmartaSystem.Accounts:
  1057.                         // Should we cancel within here or above? I think maybe above. The access to the Accounts is per account rather than per user so this shouldn't come up here but be dealt with separately
  1058.                         CancelAccounts(account.Username, account.Password);
  1059.                         break;
  1060.                     case Enums.SmartaSystem.BusinessPlan:
  1061.                         // Should we cancel within here or above? I think maybe above. How is the access to the business plan done? Do we create a single user on an account basis and have all other users that have this access use this login credentials
  1062.                         CancelBusinessPlan(account.Username, account.Password);
  1063.                         break;
  1064.                     case Enums.SmartaSystem.LegalDocuments:
  1065.                         CancelLegal(account.Username, account.Password);
  1066.                         break;
  1067.                     case Enums.SmartaSystem.WorldPay:
  1068.                         // TODO : Do we need to cancel World Pay
  1069.                         break;
  1070.                     case Enums.SmartaSystem.Domain:
  1071.                         // Need to cancel all domains relating to the account so done below
  1072.                         break;
  1073.                 }
  1074.             }
  1075.         }
  1076.  
  1077.         private void CreateCancellationEmail()
  1078.         {
  1079.             EmailContent emailContent = new EmailContent();
  1080.             emailContent.Name = string.Format("{0} {1}", _user.Forename, _user.Surname);
  1081.  
  1082.             Email mail = new Email();
  1083.             mail.Body = EmailBody.Create(Path.Combine(SmartaBusinessBuilderSettings.Settings.EmailTemplateFoilder, "AccountCancelled.xslt"), emailContent);
  1084.             mail.FromAddress = SmartaBusinessBuilderSettings.Settings.EmailFromAddress;
  1085.             mail.SubjectId = (int)EmailSubjectType.AccountCancelled;
  1086.             mail.ToAddress = _user.EmailAddress;
  1087.  
  1088.             _emailRepository.SaveOrUpdate(mail);
  1089.             _emailRepository.DbContext.CommitChanges();
  1090.         }
  1091.        
  1092.         private void GetData()
  1093.         {
  1094.             // TODO : Now, this currently displays ALL systems irrespective of whether the user has included the add-ons. What should happen here? This is a UI Decision as I can see 2 options and both are valid : 1-Only display those systems available to the user;2-Display all systems but have an N/A next to them. This allows the user to see what is available if they select the add-on. It enables the user to see the option and maybe be tempted to upgrade to include that...
  1095.             Systems = _systemRepository.GetAll();
  1096.             Users = _accountRepository.Get(_selectedAccountId).Users;
  1097.  
  1098.             _userSystems = _userAccountSystemRepository.GetByAccount(_selectedAccountId);
  1099.         }
  1100.  
  1101.         private bool AddDomain(string domain, UserSystemPassword login)
  1102.         {
  1103.             EmailRequest request = new EmailRequest();
  1104.             request.Domain = domain;
  1105.             request.User = login.Username;
  1106.  
  1107.             return EmailGateway.AddDomain(EmailAdminValueCollection, request).IsSuccessful;
  1108.         }
  1109.  
  1110.         private bool AddAlias(string alias, UserSystemPassword login)
  1111.         {
  1112.             EmailRequest request = new EmailRequest();
  1113.             request.Alias = alias;
  1114.             request.User = login.Username;
  1115.  
  1116.             return EmailGateway.AddAlias(EmailAdminValueCollection, request).IsSuccessful;
  1117.         }
  1118.  
  1119.         private IEmail EmailGateway
  1120.         {
  1121.             get
  1122.             {
  1123.                 if (_emailGateway == null)
  1124.                     _emailGateway = ServiceLocator.Current.GetInstance<IEmail>("IEmail");
  1125.  
  1126.                 return _emailGateway;
  1127.             }
  1128.         }
  1129.  
  1130.         private AdminLoginCollection EmailAdminValueCollection
  1131.         {
  1132.             get
  1133.             {
  1134.                 return new AdminLoginCollection(AdminValueCollection.Where(a => a.AdminLoginTypeId == AdminLoginType.Email).ToList());
  1135.             }
  1136.         }
  1137.  
  1138.         private IList<AdminLoginValue> AdminValueCollection
  1139.         {
  1140.             get
  1141.             {
  1142.                 if (_adminValues == null)
  1143.                     _adminValues = _adminLoginRepository.GetAll();
  1144.  
  1145.                 return _adminValues;
  1146.             }
  1147.         }
  1148.  
  1149.         private AdminLoginCollection DomainAdminValueCollection
  1150.         {
  1151.             get
  1152.             {
  1153.                 return new AdminLoginCollection(AdminValueCollection.Where(a => a.AdminLoginTypeId == AdminLoginType.DomainReseller).ToList());
  1154.             }
  1155.         }
  1156.  
  1157.         private bool UpdateMxRecordForDomain(string domain)
  1158.         {
  1159.             DomainRequest request = new DomainRequest();
  1160.             request.Domain = domain;
  1161.  
  1162.             var response = _domain.ParseDomain(request, DomainAdminValueCollection);
  1163.  
  1164.             request.Tld = response.Tld;
  1165.             request.Sld = response.Sld;
  1166.  
  1167.             return _domain.SetMxAddress(request, DomainAdminValueCollection).IsSuccessful;
  1168.         }
  1169.  
  1170.         private UserSystemPassword CreateUserSystemLogin(SmartaUser user, Account acc, string existingEmail, string domain, string alias)
  1171.         {
  1172.             var account = _accountRepository.Get(_selectedAccountId);
  1173.             user = _userRepository.Get(user.Id);
  1174.  
  1175.             if (account.Domains.Count == 1)
  1176.                 account.Domains.First().EmailSetup = true;
  1177.             else
  1178.                 account.Domains.First(d => d.FullName == domain).EmailSetup = true;
  1179.  
  1180.             account.AccountProducts.Where(ap => ap.Product.System.Id == (int)SmartaSystem.Email).ToList().ForEach(a => a.ProductStatus = new SystemStatus((int)ProductStatus.Active));
  1181.  
  1182.             string password = new PasswordGenerator().Generate();
  1183.             UserSystemPassword pwd = new UserSystemPassword();
  1184.             pwd.EncryptedPassword = PasswordEncryption.DEncrypt(password);
  1185.             pwd.SmartaUser = user;
  1186.             pwd.SystemId = SmartaSystem.Email;
  1187.             pwd.Username = string.Format("{0}@{1}", alias, domain);
  1188.             pwd.Account = account;
  1189.  
  1190.             _userSystemPasswordRepository.SaveOrUpdate(pwd);
  1191.             _userSystemPasswordRepository.DbContext.CommitChanges();
  1192.  
  1193.             return pwd;
  1194.         }
  1195.  
  1196.         private bool EmailAddressAvailable(string emailAlias, string domainName)
  1197.         {
  1198.             var response = EmailGateway.CheckAlias(EmailAdminValueCollection, new EmailRequest() { Alias = emailAlias, Domain = domainName });
  1199.             return response.IsSuccessful;
  1200.         }
  1201.  
  1202.         private SmartaUser CreateUser(SmartaUser user)
  1203.         {
  1204.             var acc = _accountRepository.Get(_selectedAccountId);
  1205.  
  1206.             // Products assigned to the Email System type available to the current logged on user. These need to be added to the new user
  1207.             var emailProducts = SelectedAccount.AccountProducts.Where(p => p.Product.System.Id == (int)SmartaSystem.Email).Select(ap => ap.Product.System);
  1208.  
  1209.  
  1210.             if (UserDetails.User.Id == 0)
  1211.             { user.AddAccount(acc); }
  1212.  
  1213.  
  1214.             UserAccountSystemCollection col = new UserAccountSystemCollection();
  1215.             col.AddSystem(acc, emailProducts);
  1216.  
  1217.  
  1218.  
  1219.             _userRepository.SaveOrUpdate(user);
  1220.             _userRepository.DbContext.CommitChanges();
  1221.  
  1222.             col.SmartaUser = user;
  1223.             var systems = col.SmartaUserAccountProducts.Distinct((lhs, rhs) => lhs.System.Id == rhs.System.Id, hash => hash.System.Id.GetHashCode());
  1224.             foreach (var suap in systems)
  1225.             {
  1226.                 _userAccountSystemRepository.SaveOrUpdate(suap);
  1227.                 _userAccountSystemRepository.DbContext.CommitChanges();
  1228.             }
  1229.  
  1230.             return user;
  1231.            
  1232.         }
  1233.  
  1234.         private bool CreateEmailAccount(string name, string surname, string username, string password, string emailAlias, string domain)
  1235.         {
  1236.             EmailRequest request = new EmailRequest();
  1237.             request.Firstname = name;
  1238.             request.Lastname = surname;
  1239.             request.User = username;
  1240.             request.EmailAddress = _user.EmailAddress;
  1241.             request.Password = password;
  1242.             request.AddAlias(emailAlias, domain);
  1243.             request.Domain = domain;
  1244.  
  1245.             var response = EmailGateway.Order(EmailAdminValueCollection, request);
  1246.             return response.IsSuccessful;
  1247.         }
  1248.  
  1249.         private void CancelEmailAccount(SmartaUser SelectedUser)
  1250.         {
  1251.             // Get the account logon for this user
  1252.             var userLogon = _userSystemPasswordRepository.GetByUserAndProduct(SelectedUser.Id, _selectedAccountId, SmartaSystem.Email);
  1253.             CancelEmailAccount(userLogon.Username);
  1254.         }
  1255.  
  1256.         private void CancelDomains()
  1257.         {
  1258.             // Only need to cancel those domains bought through SBB. If previoulsy owned then the user should have the details they require. If Smarta, then the domain is owned by smarta
  1259.             var domains = SelectedAccount.Domains.Where(d => d.DomainType.Id < (int)Enums.DomainType.Owned);
  1260.  
  1261.             foreach (var domain in domains)
  1262.             {
  1263.                 var request = new DomainRequest(domain.Name, domain.DomainType.Name);
  1264.                 var response = _domain.CancelDomain(request, DomainAdminValueCollection);
  1265.  
  1266.                 StoreProviderOutput("Cancel", SmartaSystem.Domain, response.ResponseText);
  1267.             }
  1268.         }
  1269.  
  1270.         private void CancelBusinessPlan(string username, string password)
  1271.         {
  1272.             // TODO : Control the cancellation of the Business Plan if required
  1273.             BusinessPlanRequest request = new BusinessPlanRequest();
  1274.             request.Username = username;
  1275.             request.Password = password;
  1276.  
  1277.             var response = _businessPlan.CancelAccount(BusinessPlanAdminValueCollection, request);
  1278.             StoreProviderOutput("Cancel", SmartaSystem.BusinessPlan, response.ResponseText);
  1279.         }
  1280.  
  1281.         private void CancelLegal(string username, string password)
  1282.         {
  1283.             LegalDocumentRequest request = new LegalDocumentRequest();
  1284.             request.ExternalUserId = username;
  1285.             request.ExternalUserPassword = password;
  1286.  
  1287.             var response = Legal.CancelAccount(LegalAdminValueCollection, request);
  1288.  
  1289.             StoreProviderOutput("Cancel", SmartaSystem.LegalDocuments, response.ResponseText);
  1290.         }
  1291.  
  1292.         private void CancelAccounts(string username, string password)
  1293.         {
  1294.             // TODO : Cancel Accounts package
  1295.             AccountRequest request = new AccountRequest();
  1296.             request.Username = username;
  1297.             request.Password = password;
  1298.  
  1299.             var response = _accounts.CancelAccount(AccountsAdminValueCollection, request);
  1300.             StoreProviderOutput("Cancel", SmartaSystem.Accounts, response.ResponseText);
  1301.         }
  1302.  
  1303.         private void CancelWebsite(string username)
  1304.         {
  1305.             WebsiteRequest request = new WebsiteRequest();
  1306.             request.Username = username;
  1307.  
  1308.             // Need to get the user id first to be able to cancel the account
  1309.             var response = WebsiteBuilder.GetAccountInfo(WebsiteAdminValueCollection, request);
  1310.             request.UserId = response.UserId;
  1311.  
  1312.             response = WebsiteBuilder.CancelAccount(WebsiteAdminValueCollection, request);
  1313.  
  1314.             StoreProviderOutput("Cancel", SmartaSystem.Website, response.ResponseText);
  1315.         }
  1316.  
  1317.         private void CancelEmailAccount(string username)
  1318.         {
  1319.             EmailRequest request = new EmailRequest();
  1320.             request.User = username;
  1321.  
  1322.             var response = EmailGateway.Terminate(EmailAdminValueCollection, request);
  1323.  
  1324.             StoreProviderOutput("Cancel", SmartaSystem.Email, response.ResponseText);
  1325.         }
  1326.  
  1327.         private void StoreProviderOutput(string apiCall, SmartaSystem smartaSystem, string response)
  1328.         {
  1329.             ProviderOutput output = new ProviderOutput();
  1330.             output.AccountId = _selectedAccountId;
  1331.             output.ApiCall = apiCall;
  1332.             output.SystemId = (int)smartaSystem;
  1333.             output.ProviderResponse = response;
  1334.  
  1335.             _outputRepository.SaveOrUpdate(output);
  1336.             _outputRepository.DbContext.CommitChanges();
  1337.         }
  1338.  
  1339.         private void CreateInvitationEmail(string name, string surname, string existingEmail, Guid userToken, string baseUrl, string emailAlias, string domain, string pin)
  1340.         {
  1341.             EmailContent emailContent = new EmailContent();
  1342.             emailContent.Name = string.Format("{0} {1}", name, surname);
  1343.             emailContent.Url = string.Format("{0}/Admin/Join/{1}", baseUrl, userToken.ToString());
  1344.             emailContent.Invitor = string.Format("{0} {1}", _user.Forename, _user.Surname);
  1345.             emailContent.EmailAddress = string.Format("{0}@{1}", emailAlias, domain);
  1346.             emailContent.Pin = pin;
  1347.  
  1348.             Email mail = new Email();
  1349.             mail.Body = EmailBody.Create(Path.Combine(SmartaBusinessBuilderSettings.Settings.EmailTemplateFoilder, "InvitationToEmailAccount.xslt"), emailContent);
  1350.             mail.FromAddress = SmartaBusinessBuilderSettings.Settings.EmailFromAddress;
  1351.             mail.SubjectId = (int)EmailSubjectType.Invite;
  1352.             mail.ToAddress = existingEmail;
  1353.  
  1354.             _emailRepository.SaveOrUpdate(mail);
  1355.             _emailRepository.DbContext.CommitChanges();
  1356.         }
  1357.  
  1358.         private SmartaUser CreateUser(string name, string surname, string existingEmail, Guid userToken, Account acc, string pin)
  1359.         {
  1360.             SmartaUser user = _userRepository.GetByEmailAddress(existingEmail);
  1361.             if (user == null)
  1362.             {
  1363.                 user = new SmartaUser();
  1364.                 user.Forename = name;
  1365.                 user.Surname = surname;
  1366.                 // This can be overwritten shortly, but create a password for now to prevent anybody being able to login with this userid
  1367.                 user.Password = PasswordEncryption.Encrypt(new PasswordGenerator().Generate());
  1368.                 user.EmailAddress = existingEmail;
  1369.  
  1370.                 user.UserStatus = new UserStatus((int)Enums.UserStatus.Invited);
  1371.             }
  1372.             user.Token = userToken;
  1373.             user.Pin = pin;
  1374.  
  1375.             return CreateUser(user);
  1376.         }
  1377.  
  1378.         private decimal GetAdditionalLicenseCost(bool monthlyCharge)
  1379.         {
  1380.             decimal price = SelectedAccount.Orders.Where(l => l.HasOrderLines).Sum(m => m.OrderLines.Where(n => !n.Cancelled && !n.IsBundle && CurrentBundle.IncludedProducts.Any(p => p.Id == n.ProductId) && (n.Product.IsMonthlyCharge == monthlyCharge)).Sum(q => q.Price * q.Quantity));
  1381.  
  1382.             // Add on current order as well
  1383.             if (OrderModel.Order != null && OrderModel.Order.HasOrderLines)
  1384.             {
  1385.                 var orderlines = OrderModel.Order.OrderLines.Where(p => !p.IsBundle);
  1386.                 if (orderlines != null && orderlines.Count() > 0)
  1387.                     price += orderlines.Where(p => (p.Product.IsMonthlyCharge == monthlyCharge) && CurrentBundle.IncludedProducts.Any(pr => pr.Id == p.ProductId)).Sum(l => l.Price * l.Quantity);
  1388.             }
  1389.  
  1390.             return price > 0 ? price : 0;
  1391.         }
  1392.  
  1393.         private decimal GetTotalAdditionalLicenseCost()
  1394.         {
  1395.             decimal price = 0;
  1396.  
  1397.             if (OrderModel.Order != null && OrderModel.Order.HasOrderLines)
  1398.             {
  1399.                 var orderlines = OrderModel.Order.OrderLines.Where(p => !p.IsBundle && (p.Quantity > 0 || p.Product.IsMonthlyCharge));
  1400.                 if (orderlines != null && orderlines.Count() > 0)
  1401.                     price += orderlines.Where(p => CurrentBundle.IncludedProducts.Any(pr => pr.Id == p.ProductId)).Sum(l => l.Price * l.Quantity);
  1402.             }
  1403.  
  1404.             return price > 0 ? price : 0;
  1405.         }
  1406.  
  1407.         private decimal GetAdditionalAddOnCost(bool monthlyCharge)
  1408.         {
  1409.             decimal price = SelectedAccount.Orders.Where(l => l.HasOrderLines).Sum(m => m.OrderLines.Where(n => !n.Cancelled && !n.IsBundle && CurrentBundle.AddOns.Any(p => p.Id == n.ProductId) && (n.Product.IsMonthlyCharge == monthlyCharge)).Sum(q => q.Price * q.Quantity));
  1410.  
  1411.             // Add on current order as well
  1412.             if (OrderModel.Order != null && OrderModel.Order.HasOrderLines)
  1413.             {
  1414.                 var orderlines = OrderModel.Order.OrderLines.Where(p => !p.IsBundle);
  1415.                 if (orderlines != null && orderlines.Count() > 0)
  1416.                     price += orderlines.Where(p => (p.Product.IsMonthlyCharge == monthlyCharge) && CurrentBundle.AddOns.Any(pr => pr.Id == p.ProductId)).Sum(l => l.Price * l.Quantity);
  1417.             }
  1418.  
  1419.             return price > 0 ? price : 0;
  1420.         }
  1421.  
  1422.         private decimal GetTotalAdditionalAddOnCost()
  1423.         {
  1424.             decimal price = 0;
  1425.  
  1426.             if (OrderModel.Order != null && OrderModel.Order.HasOrderLines)
  1427.             {
  1428.                 var orderlines = OrderModel.Order.OrderLines.Where(p => !p.IsBundle && (p.Quantity > 0 || p.Product.IsMonthlyCharge));
  1429.                 if (orderlines != null && orderlines.Count() > 0)
  1430.                     price += orderlines.Where(p => CurrentBundle.AddOns.Any(pr => pr.Id == p.ProductId)).Sum(l => l.Price * l.Quantity);
  1431.             }
  1432.  
  1433.             return price > 0 ? price : 0;
  1434.         }      
  1435.         #endregion
  1436.         #endregion
  1437.     }
  1438. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement