move the scheduler to a windows service
This commit is contained in:
parent
97f09a5683
commit
5e414136b2
115 changed files with 587 additions and 166 deletions
|
@ -0,0 +1,135 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
|
||||
using ES = WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class CategoryController
|
||||
{
|
||||
#region Category routines
|
||||
|
||||
public static DataSet GetWholeCategoriesSet(int userId)
|
||||
{
|
||||
return EcommerceProvider.GetWholeCategoriesSet(
|
||||
ES.SecurityContext.User.UserId,
|
||||
userId
|
||||
);
|
||||
}
|
||||
|
||||
public static int GetCategoriesCount(int userId, int parentId)
|
||||
{
|
||||
return EcommerceProvider.GetCategoriesCount(
|
||||
ES.SecurityContext.User.UserId,
|
||||
userId,
|
||||
parentId
|
||||
);
|
||||
}
|
||||
|
||||
public static List<Category> GetCategoriesPaged(int userId, int parentId, int maximumRows, int startRowIndex)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<Category>(
|
||||
EcommerceProvider.GetCategoriesPaged(
|
||||
ES.SecurityContext.User.UserId,
|
||||
userId,
|
||||
parentId,
|
||||
maximumRows,
|
||||
startRowIndex
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public static int AddCategory(int userId, string categoryName, string categorySku, int parentId, string shortDescription, string fullDescription)
|
||||
{
|
||||
SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();
|
||||
//
|
||||
if (!result.Success)
|
||||
return result.ResultCode;
|
||||
//
|
||||
return EcommerceProvider.AddCategory(
|
||||
ES.SecurityContext.User.UserId,
|
||||
userId,
|
||||
categoryName,
|
||||
categorySku,
|
||||
parentId,
|
||||
shortDescription,
|
||||
fullDescription
|
||||
);
|
||||
}
|
||||
|
||||
public static Category GetCategory(int userId, int categoryId)
|
||||
{
|
||||
return ES.ObjectUtils.FillObjectFromDataReader<Category>(
|
||||
EcommerceProvider.GetCategory(
|
||||
ES.SecurityContext.User.UserId,
|
||||
userId,
|
||||
categoryId
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public static int UpdateCategory(int userId, int categoryId, string categoryName, string categorySku, int parentId, string shortDescription, string fullDescription)
|
||||
{
|
||||
SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();
|
||||
//
|
||||
if (!result.Success)
|
||||
return result.ResultCode;
|
||||
|
||||
return EcommerceProvider.UpdateCategory(
|
||||
ES.SecurityContext.User.UserId,
|
||||
userId,
|
||||
categoryId,
|
||||
categoryName,
|
||||
categorySku,
|
||||
parentId,
|
||||
shortDescription,
|
||||
fullDescription
|
||||
);
|
||||
}
|
||||
|
||||
public static int DeleteCategory(int userId, int categoryId)
|
||||
{
|
||||
SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();
|
||||
//
|
||||
if (!result.Success)
|
||||
return result.ResultCode;
|
||||
|
||||
return EcommerceProvider.DeleteCategory(
|
||||
ES.SecurityContext.User.UserId,
|
||||
userId,
|
||||
categoryId
|
||||
);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
|
@ -0,0 +1,218 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
|
||||
using ES = WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer.ContractSystem
|
||||
{
|
||||
public class ContractController
|
||||
{
|
||||
public static GenericResult AddContract(int resellerId, ContractAccount accountSettings)
|
||||
{
|
||||
try
|
||||
{
|
||||
ES.SecurityContext.SetThreadPrincipal(resellerId);
|
||||
//
|
||||
ES.TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.TASK_ADD_CONTRACT);
|
||||
//
|
||||
GenericResult result = new GenericResult();
|
||||
//
|
||||
int customerId = -1;
|
||||
int contractStatus = (int)ContractStatus.Pending;
|
||||
//
|
||||
if (accountSettings.PropertyExists(ContractAccount.CUSTOMER_ID))
|
||||
{
|
||||
customerId = accountSettings.GetProperty<int>(ContractAccount.CUSTOMER_ID);
|
||||
//
|
||||
contractStatus = (int)ContractStatus.Active;
|
||||
}
|
||||
|
||||
// Ensure customer not specified and then check requested username availability
|
||||
if (customerId == -1)
|
||||
{
|
||||
if (ES.UserController.UserExists(accountSettings[ContractAccount.USERNAME]))
|
||||
{
|
||||
result.Succeed = false;
|
||||
result.SetProperty("ResultCode", ES.BusinessErrorCodes.ERROR_USER_ALREADY_EXISTS);
|
||||
return result;
|
||||
}
|
||||
// EXIT
|
||||
}
|
||||
//
|
||||
string strNames = null;
|
||||
string strValues = null;
|
||||
//
|
||||
if (customerId == -1)
|
||||
{
|
||||
strNames = strValues = String.Empty;
|
||||
SecurityUtils.SerializeGenericProfile(ref strNames, ref strValues, accountSettings);
|
||||
}
|
||||
// emit the new contract
|
||||
string contractId = EcommerceProvider.AddContract(customerId, resellerId, accountSettings[ContractAccount.USERNAME],
|
||||
contractStatus, 0m, accountSettings[ContractAccount.FIRST_NAME], accountSettings[ContractAccount.LAST_NAME],
|
||||
accountSettings[ContractAccount.EMAIL], accountSettings[ContractAccount.COMPANY_NAME],
|
||||
strNames, strValues);
|
||||
//
|
||||
result.Succeed = true;
|
||||
result.SetProperty("ContractId", contractId);
|
||||
// Add contract object
|
||||
ES.TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT] = GetContract(contractId);
|
||||
//
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw ES.TaskManager.WriteError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ES.TaskManager.CompleteTask();
|
||||
}
|
||||
}
|
||||
|
||||
public static bool CheckCustomerContractExists()
|
||||
{
|
||||
return EcommerceProvider.CheckCustomerContractExists(ES.SecurityContext.User.UserId);
|
||||
}
|
||||
|
||||
public static GenericResult DeleteContract(string contractId)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void ImpersonateAsContractReseller(string contractId)
|
||||
{
|
||||
Contract contract = ContractSystem.ContractController.GetContract(contractId);
|
||||
// Impersonate
|
||||
ImpersonateAsContractReseller(contract);
|
||||
}
|
||||
|
||||
public static void ImpersonateAsContractReseller(Contract contractInfo)
|
||||
{
|
||||
// Impersonate
|
||||
ES.SecurityContext.SetThreadPrincipal(contractInfo.ResellerId);
|
||||
}
|
||||
|
||||
public static Contract GetCustomerContract(int customerId)
|
||||
{
|
||||
Contract contractInfo = ES.ObjectUtils.FillObjectFromDataReader<Contract>(
|
||||
EcommerceProvider.GetCustomerContract(customerId));
|
||||
//
|
||||
if (contractInfo == null)
|
||||
throw new Exception("Could not find customer contract.");
|
||||
//
|
||||
return contractInfo;
|
||||
}
|
||||
|
||||
public static Contract GetContract(string contractId)
|
||||
{
|
||||
Contract contractInfo = ES.ObjectUtils.FillObjectFromDataReader<Contract>(EcommerceProvider.GetContract(contractId));
|
||||
//
|
||||
if (contractInfo == null)
|
||||
throw new Exception("Could not find the contract specified. ContractID: " + contractId);
|
||||
//
|
||||
return contractInfo;
|
||||
}
|
||||
|
||||
public static int UpdateContract(string contractId, int customerId, string accountName,
|
||||
ContractStatus status, decimal balance, string firstName, string lastName, string email,
|
||||
string companyName, string propertyNames, string propertyValues)
|
||||
{
|
||||
return EcommerceProvider.UpdateContract(contractId, customerId, accountName, (int)status, balance,
|
||||
firstName, lastName, email, companyName, propertyNames, propertyValues);
|
||||
}
|
||||
|
||||
public static ContractAccount GetContractAccountSettings(string contractId)
|
||||
{
|
||||
return GetContractAccountSettings(contractId, false);
|
||||
}
|
||||
|
||||
public static ContractAccount GetContractAccountSettings(string contractId, bool internally)
|
||||
{
|
||||
//
|
||||
ContractAccount account = new ContractAccount();
|
||||
//
|
||||
IDataReader dr = null;
|
||||
//
|
||||
try
|
||||
{
|
||||
int customerId = -1;
|
||||
dr = EcommerceProvider.GetContract(contractId);
|
||||
//
|
||||
if (dr.Read())
|
||||
{
|
||||
string propertyNames = Convert.ToString(dr["PropertyNames"]);
|
||||
string propertyValues = Convert.ToString(dr["PropertyValues"]);
|
||||
if (dr["CustomerID"] != DBNull.Value)
|
||||
customerId = Convert.ToInt32(dr["CustomerID"]);
|
||||
else
|
||||
SecurityUtils.DeserializeGenericProfile(propertyNames, propertyValues, account);
|
||||
}
|
||||
//
|
||||
if (customerId > -1)
|
||||
{
|
||||
ES.UserInfo userInfo = (internally) ? ES.UserController.GetUserInternally(customerId) :
|
||||
ES.UserController.GetUser(customerId);
|
||||
//
|
||||
if (internally)
|
||||
account[ContractAccount.PASSWORD] = userInfo.Password;
|
||||
//
|
||||
account[ContractAccount.USERNAME] = userInfo.Username;
|
||||
account[ContractAccount.FIRST_NAME] = userInfo.FirstName;
|
||||
account[ContractAccount.LAST_NAME] = userInfo.LastName;
|
||||
account[ContractAccount.EMAIL] = userInfo.Email;
|
||||
account[ContractAccount.COMPANY_NAME] = userInfo.CompanyName;
|
||||
account[ContractAccount.COUNTRY] = userInfo.Country;
|
||||
account[ContractAccount.CITY] = userInfo.City;
|
||||
account[ContractAccount.ADDRESS] = userInfo.Address;
|
||||
account[ContractAccount.FAX_NUMBER] = userInfo.Fax;
|
||||
account[ContractAccount.INSTANT_MESSENGER] = userInfo.InstantMessenger;
|
||||
account[ContractAccount.PHONE_NUMBER] = userInfo.PrimaryPhone;
|
||||
account[ContractAccount.STATE] = userInfo.State;
|
||||
account[ContractAccount.ZIP] = userInfo.Zip;
|
||||
account[ContractAccount.MAIL_FORMAT] = userInfo.HtmlMail ? "HTML" : "PlainText";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw ex;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (dr != null)
|
||||
dr.Close();
|
||||
}
|
||||
//
|
||||
return account;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,591 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Configuration;
|
||||
using System.Xml;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Net;
|
||||
using System.Web;
|
||||
using System.Web.Caching;
|
||||
using System.Globalization;
|
||||
|
||||
using WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class SettingsHelper
|
||||
{
|
||||
public static string ConvertObjectSettings(string[][] settings)
|
||||
{
|
||||
XmlDocument doc = new XmlDocument();
|
||||
XmlElement root = doc.CreateElement("settings");
|
||||
|
||||
foreach (string[] pair in settings)
|
||||
{
|
||||
XmlElement s_item = doc.CreateElement("setting");
|
||||
s_item.SetAttribute("name", pair[0]);
|
||||
s_item.SetAttribute("value", pair[1]);
|
||||
root.AppendChild(s_item);
|
||||
}
|
||||
|
||||
return root.OuterXml;
|
||||
}
|
||||
|
||||
public static string ConvertObjectSettings(string[][] settings, string rootName, string childName)
|
||||
{
|
||||
XmlDocument doc = new XmlDocument();
|
||||
XmlElement root = doc.CreateElement(rootName);
|
||||
// exit
|
||||
if (settings == null)
|
||||
return root.OuterXml;
|
||||
// iterate
|
||||
foreach (string[] pair in settings)
|
||||
{
|
||||
XmlElement s_item = doc.CreateElement(childName);
|
||||
s_item.SetAttribute("name", pair[0]);
|
||||
s_item.SetAttribute("value", pair[1]);
|
||||
root.AppendChild(s_item);
|
||||
}
|
||||
//
|
||||
return root.OuterXml;
|
||||
}
|
||||
|
||||
public static string ConvertControlsBunch(string[][] bunch)
|
||||
{
|
||||
XmlDocument doc = new XmlDocument();
|
||||
XmlElement root = doc.CreateElement("Controls");
|
||||
|
||||
foreach (string[] pair in bunch)
|
||||
{
|
||||
XmlElement s_item = doc.CreateElement("Control");
|
||||
s_item.SetAttribute("Key", pair[0]);
|
||||
s_item.SetAttribute("Src", pair[1]);
|
||||
root.AppendChild(s_item);
|
||||
}
|
||||
|
||||
return root.OuterXml;
|
||||
}
|
||||
|
||||
public static KeyValueBunch FillSettingsBunch(IDataReader reader)
|
||||
{
|
||||
return FillSettingsBunch(
|
||||
reader,
|
||||
"SettingName",
|
||||
"SettingValue"
|
||||
);
|
||||
}
|
||||
|
||||
public static T FillSettingsBunch<T>(IDataReader reader, string keyNameColumn, string keyValueColumn)
|
||||
{
|
||||
Type type = typeof(T);
|
||||
|
||||
KeyValueBunch bunch = (KeyValueBunch)Activator.CreateInstance(type);
|
||||
|
||||
try
|
||||
{
|
||||
while (reader.Read())
|
||||
bunch[(String)reader[keyNameColumn]] = (String)reader[keyValueColumn];
|
||||
}
|
||||
catch
|
||||
{
|
||||
bunch = null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (reader != null)
|
||||
reader.Close();
|
||||
}
|
||||
|
||||
return (T)Convert.ChangeType(bunch, typeof(T));
|
||||
}
|
||||
|
||||
public static KeyValueBunch FillSettingsBunch(IDataReader reader,
|
||||
string keyNameColumn, string keyValueColumn)
|
||||
{
|
||||
KeyValueBunch bunch = null;
|
||||
|
||||
try
|
||||
{
|
||||
bunch = new KeyValueBunch();
|
||||
|
||||
while (reader.Read())
|
||||
bunch[(String)reader[keyNameColumn]] = (String)reader[keyValueColumn];
|
||||
}
|
||||
catch
|
||||
{
|
||||
bunch = null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (reader != null)
|
||||
reader.Close();
|
||||
}
|
||||
|
||||
return bunch;
|
||||
}
|
||||
|
||||
public static KeyValueBunch FillControlsBunch(IDataReader reader)
|
||||
{
|
||||
KeyValueBunch bunch = null;
|
||||
|
||||
try
|
||||
{
|
||||
bunch = new KeyValueBunch();
|
||||
|
||||
while (reader.Read())
|
||||
bunch[(String)reader["ControlKey"]] = (String)reader["ControlSrc"];
|
||||
}
|
||||
catch
|
||||
{
|
||||
bunch = null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (reader != null)
|
||||
reader.Close();
|
||||
}
|
||||
|
||||
return bunch;
|
||||
}
|
||||
|
||||
public static KeyValueBunch FillProperties(IDataReader reader)
|
||||
{
|
||||
KeyValueBunch settings = null;
|
||||
|
||||
try
|
||||
{
|
||||
settings = new KeyValueBunch();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
string name = (string)reader["PropertyName"];
|
||||
string value = (string)reader["PropertyValue"];
|
||||
//
|
||||
settings[name] = value;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
settings = null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (reader != null)
|
||||
reader.Close();
|
||||
}
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
public static KeyValueBunch FillSettings(IDataReader reader)
|
||||
{
|
||||
KeyValueBunch settings = null;
|
||||
|
||||
try
|
||||
{
|
||||
settings = new KeyValueBunch();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
settings[(string)reader["SettingName"]] = (string)reader["SettingValue"];
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
settings = null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (reader != null)
|
||||
reader.Close();
|
||||
}
|
||||
|
||||
return settings;
|
||||
}
|
||||
}
|
||||
|
||||
class Currency
|
||||
{
|
||||
public string ISOCode;
|
||||
public string Symbol;
|
||||
public decimal Rate;
|
||||
|
||||
public Currency()
|
||||
{
|
||||
}
|
||||
|
||||
public Currency(string isocode, string symbol, decimal rate)
|
||||
{
|
||||
this.ISOCode = isocode;
|
||||
this.Symbol = symbol;
|
||||
this.Rate = rate;
|
||||
}
|
||||
}
|
||||
|
||||
public class CurrenciesHelper
|
||||
{
|
||||
private const string ServiceUrl = "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml";
|
||||
public const string HttpCacheKey = "__Currencies";
|
||||
|
||||
private Dictionary<string, Currency> _currencies;
|
||||
|
||||
public CurrenciesHelper()
|
||||
{
|
||||
Initialize();
|
||||
}
|
||||
|
||||
public string[] GetSupportedCurrencies()
|
||||
{
|
||||
string[] array = new string[_currencies.Count];
|
||||
|
||||
_currencies.Keys.CopyTo(array, 0);
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
public string GetCurrencySymbol(string ISOCode)
|
||||
{
|
||||
ISOCode = ISOCode.ToUpper();
|
||||
|
||||
if (_currencies.ContainsKey(ISOCode))
|
||||
return _currencies[ISOCode].Symbol;
|
||||
|
||||
return ISOCode;
|
||||
}
|
||||
|
||||
public decimal GetCurrencyRate(string ISOCode)
|
||||
{
|
||||
ISOCode = ISOCode.ToUpper();
|
||||
|
||||
if (_currencies.ContainsKey(ISOCode))
|
||||
return _currencies[ISOCode].Rate;
|
||||
|
||||
return Decimal.Zero;
|
||||
}
|
||||
|
||||
private XmlDocument GetServiceResponse()
|
||||
{
|
||||
WebClient ecb = new WebClient();
|
||||
|
||||
try
|
||||
{
|
||||
TaskManager.StartTask("CURRENCY_HELPER", "LOAD_CURRENCIES_RATES");
|
||||
|
||||
XmlDocument xmlDoc = new XmlDocument();
|
||||
|
||||
xmlDoc.LoadXml(
|
||||
ecb.DownloadString(
|
||||
ServiceUrl
|
||||
)
|
||||
);
|
||||
|
||||
return xmlDoc;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TaskManager.WriteError(ex, "Failed to get response from www.ecb.int");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TaskManager.CompleteTask();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private Currency ConvertFromXml(XmlElement element, RegionInfo region)
|
||||
{
|
||||
string ISOCode = element.GetAttribute("currency");
|
||||
|
||||
Currency currency = new Currency();
|
||||
currency.Rate = Decimal.Parse(element.GetAttribute("rate"));
|
||||
currency.ISOCode = ISOCode;
|
||||
|
||||
if (region != null)
|
||||
currency.Symbol = region.CurrencySymbol;
|
||||
else
|
||||
currency.Symbol = ISOCode;
|
||||
|
||||
return currency;
|
||||
}
|
||||
|
||||
private void Initialize()
|
||||
{
|
||||
/*Cache cache = new Cache();
|
||||
_currencies = (Dictionary<string, Currency>)cache[HttpCacheKey];*/
|
||||
|
||||
if (_currencies == null)
|
||||
_currencies = LoadRatesFromService();
|
||||
}
|
||||
|
||||
private void OnCacheItem_Removed(string key, object value, CacheItemRemovedReason reason)
|
||||
{
|
||||
// if currencies rates were expired - renew them
|
||||
if (String.Compare(HttpCacheKey, key) == 0)
|
||||
_currencies = LoadRatesFromService();
|
||||
}
|
||||
|
||||
private Dictionary<string, Currency> LoadRatesFromService()
|
||||
{
|
||||
XmlDocument ecbXml = GetServiceResponse();
|
||||
|
||||
Dictionary<string, Currency> currencies = new Dictionary<string, Currency>();
|
||||
// add euro first
|
||||
currencies.Add("EUR", new Currency("EUR", "ˆ", 1));
|
||||
|
||||
if (ecbXml != null)
|
||||
{
|
||||
XmlNode cube = ecbXml.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Cube']/*[local-name()='Cube']");
|
||||
|
||||
if (cube != null)
|
||||
{
|
||||
CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
|
||||
|
||||
IEnumerator iterator = cultures.GetEnumerator();
|
||||
|
||||
// load symbols for currencies
|
||||
while (iterator.MoveNext() && cube.ChildNodes.Count > 0)
|
||||
{
|
||||
CultureInfo culture = (CultureInfo)iterator.Current;
|
||||
|
||||
RegionInfo region = new RegionInfo(culture.LCID);
|
||||
|
||||
string ISOCode = region.ISOCurrencySymbol;
|
||||
|
||||
// find currency by ISO code
|
||||
XmlElement element = (XmlElement)cube.SelectSingleNode(
|
||||
String.Format(
|
||||
"*[local-name()='Cube' and @currency='{0}']",
|
||||
ISOCode
|
||||
)
|
||||
);
|
||||
|
||||
if (element != null)
|
||||
{
|
||||
currencies.Add(ISOCode, ConvertFromXml(element, region));
|
||||
cube.RemoveChild(element);
|
||||
}
|
||||
}
|
||||
|
||||
// we still have an unrecognized currencies
|
||||
if (cube.ChildNodes.Count > 0)
|
||||
{
|
||||
foreach (XmlElement element in cube.ChildNodes)
|
||||
currencies.Add(element.GetAttribute("currency"), ConvertFromXml(element, null));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// calculate 12.00 time span
|
||||
DateTime expire = DateTime.Now.AddDays(1).Subtract(DateTime.Now.TimeOfDay);
|
||||
|
||||
// add currencies to the cache
|
||||
/*Cache cache = new Cache();
|
||||
cache.Add(
|
||||
HttpCacheKey,
|
||||
currencies,
|
||||
null,
|
||||
expire,
|
||||
Cache.NoSlidingExpiration,
|
||||
CacheItemPriority.Default,
|
||||
new CacheItemRemovedCallback(OnCacheItem_Removed)
|
||||
);*/
|
||||
|
||||
return currencies;
|
||||
}
|
||||
}
|
||||
|
||||
public class SecurityUtils
|
||||
{
|
||||
internal static void SerializeProfile(ref string propertyNames, ref string propertyValues,
|
||||
bool encrypt, CheckoutDetails profile)
|
||||
{
|
||||
// names
|
||||
StringBuilder namesBuilder = new StringBuilder();
|
||||
// string values
|
||||
StringBuilder valsBuilder = new StringBuilder();
|
||||
//
|
||||
string[] allKeys = profile.GetAllKeys();
|
||||
//
|
||||
foreach (string keyName in allKeys)
|
||||
{
|
||||
//
|
||||
int length = 0, position = 0;
|
||||
// get serialized property value
|
||||
string keyValue = profile[keyName];
|
||||
//
|
||||
if (String.IsNullOrEmpty(keyValue))
|
||||
{
|
||||
length = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
//
|
||||
length = keyValue.Length;
|
||||
//
|
||||
position = valsBuilder.Length;
|
||||
//
|
||||
valsBuilder.Append(keyValue);
|
||||
}
|
||||
//
|
||||
namesBuilder.Append(keyName + ":S:" + position.ToString(CultureInfo.InvariantCulture) + ":" + length.ToString(CultureInfo.InvariantCulture) + ":");
|
||||
}
|
||||
//
|
||||
propertyNames = (encrypt) ? CryptoUtils.Encrypt(namesBuilder.ToString()) : namesBuilder.ToString();
|
||||
//
|
||||
propertyValues = (encrypt) ? CryptoUtils.Encrypt(valsBuilder.ToString()) : valsBuilder.ToString();
|
||||
}
|
||||
|
||||
internal static void DeserializeProfile(string propertyNames, string propertyValues,
|
||||
bool encrypted, CheckoutDetails details)
|
||||
{
|
||||
// Input format:
|
||||
// PROPERTY_NAME:S:START_INDEX:PROP_VALUE_LENGTH
|
||||
//
|
||||
if ((propertyNames != null && propertyValues != null) && details != null)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
// decrypt
|
||||
propertyNames = (encrypted) ? CryptoUtils.Decrypt(propertyNames) : propertyNames;
|
||||
//
|
||||
propertyValues = (encrypted) ? CryptoUtils.Decrypt(propertyValues) : propertyValues;
|
||||
//
|
||||
string[] names = propertyNames.Split(':');
|
||||
// divide names length by 4 parts
|
||||
int count = names.Length / 4;
|
||||
// iterate through
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
// get property name
|
||||
string keyName = names[i * 4];
|
||||
//
|
||||
string keyValue = String.Empty;
|
||||
// calculate property value start index
|
||||
int startIndex = Int32.Parse(names[(i * 4) + 2], CultureInfo.InvariantCulture);
|
||||
// calculate property value length
|
||||
int length = Int32.Parse(names[(i * 4) + 3], CultureInfo.InvariantCulture);
|
||||
// ensure check property value not empty
|
||||
if (length != -1)
|
||||
{
|
||||
keyValue = propertyValues.Substring(startIndex, length);
|
||||
}
|
||||
//
|
||||
details[keyName] = keyValue;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static void SerializeGenericProfile(ref string propertyNames, ref string propertyValues, IKeyValueBunch source)
|
||||
{
|
||||
// names
|
||||
StringBuilder namesBuilder = new StringBuilder();
|
||||
// string values
|
||||
StringBuilder valsBuilder = new StringBuilder();
|
||||
//
|
||||
string[] allKeys = source.GetAllKeys();
|
||||
//
|
||||
foreach (string keyName in allKeys)
|
||||
{
|
||||
//
|
||||
int length = 0, position = 0;
|
||||
// get serialized property value
|
||||
string keyValue = source[keyName];
|
||||
//
|
||||
if (String.IsNullOrEmpty(keyValue))
|
||||
{
|
||||
length = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
//
|
||||
length = keyValue.Length;
|
||||
//
|
||||
position = valsBuilder.Length;
|
||||
//
|
||||
valsBuilder.Append(keyValue);
|
||||
}
|
||||
//
|
||||
namesBuilder.Append(keyName + ":S:" + position.ToString(CultureInfo.InvariantCulture) + ":" + length.ToString(CultureInfo.InvariantCulture) + ":");
|
||||
}
|
||||
//
|
||||
propertyNames = namesBuilder.ToString();
|
||||
//
|
||||
propertyValues = valsBuilder.ToString();
|
||||
}
|
||||
|
||||
internal static void DeserializeGenericProfile(string propertyNames, string propertyValues, IKeyValueBunch target)
|
||||
{
|
||||
// Input format:
|
||||
// PROPERTY_NAME:S:START_INDEX:PROP_VALUE_LENGTH
|
||||
//
|
||||
if ((propertyNames != null && propertyValues != null) && target != null)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
string[] names = propertyNames.Split(':');
|
||||
// divide names length by 4 parts
|
||||
int count = names.Length / 4;
|
||||
// iterate through
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
// get property name
|
||||
string keyName = names[i * 4];
|
||||
//
|
||||
string keyValue = String.Empty;
|
||||
// calculate property value start index
|
||||
int startIndex = Int32.Parse(names[(i * 4) + 2], CultureInfo.InvariantCulture);
|
||||
// calculate property value length
|
||||
int length = Int32.Parse(names[(i * 4) + 3], CultureInfo.InvariantCulture);
|
||||
// ensure check property value not empty
|
||||
if (length != -1)
|
||||
{
|
||||
keyValue = propertyValues.Substring(startIndex, length);
|
||||
}
|
||||
//
|
||||
target[keyName] = keyValue;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,375 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Xml;
|
||||
using System.Data;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.Web;
|
||||
using System.Web.Security;
|
||||
using System.Web.UI;
|
||||
using System.Web.UI.WebControls;
|
||||
using System.Web.UI.WebControls.WebParts;
|
||||
using System.Web.UI.HtmlControls;
|
||||
|
||||
using ES = WebsitePanel.EnterpriseServer;
|
||||
using System.Threading;
|
||||
using WebsitePanel.EnterpriseServer;
|
||||
using WebsitePanel.Templates;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class InvoiceController
|
||||
{
|
||||
private InvoiceController()
|
||||
{
|
||||
}
|
||||
|
||||
#region Ecommerce v2.1.0 routines
|
||||
|
||||
#region Helper methods
|
||||
|
||||
public static string BuildAddXmlForInvoiceItems(List<InvoiceItem> items)
|
||||
{
|
||||
XmlDocument xml = new XmlDocument();
|
||||
XmlElement root = xml.CreateElement("items");
|
||||
|
||||
foreach (InvoiceItem item in items)
|
||||
{
|
||||
XmlElement node = xml.CreateElement("item");
|
||||
|
||||
node.SetAttribute("serviceid", item.ServiceId.ToString());
|
||||
node.SetAttribute("itemname", item.ItemName);
|
||||
node.SetAttribute("typename", item.TypeName);
|
||||
node.SetAttribute("quantity", item.Quantity.ToString());
|
||||
node.SetAttribute("total", item.Total.ToString(CultureInfo.InvariantCulture));
|
||||
node.SetAttribute("subtotal", item.SubTotal.ToString(CultureInfo.InvariantCulture));
|
||||
node.SetAttribute("unitprice", item.UnitPrice.ToString(CultureInfo.InvariantCulture));
|
||||
|
||||
root.AppendChild(node);
|
||||
}
|
||||
|
||||
return root.OuterXml;
|
||||
}
|
||||
|
||||
public static List<InvoiceItem> CalculateInvoiceLinesForServices(List<int> services)
|
||||
{
|
||||
List<InvoiceItem> lines = new List<InvoiceItem>();
|
||||
|
||||
foreach (int serviceId in services)
|
||||
{
|
||||
ProductType svc_type = ServiceController.GetServiceItemType(serviceId);
|
||||
//
|
||||
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
|
||||
Type.GetType(svc_type.ProvisioningController));
|
||||
//
|
||||
InvoiceItem[] ilines = controller.CalculateInvoiceLines(serviceId);
|
||||
foreach (InvoiceItem iline in ilines)
|
||||
{
|
||||
iline.SubTotal = iline.UnitPrice * iline.Quantity;
|
||||
iline.Total = iline.SubTotal;
|
||||
}
|
||||
//
|
||||
lines.AddRange(ilines);
|
||||
}
|
||||
//
|
||||
return lines;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public static int VoidCustomerInvoice(int invoiceId)
|
||||
{
|
||||
SecurityResult result = StorehouseController.CheckAccountIsAdminOrReseller();
|
||||
if (!result.Success)
|
||||
return result.ResultCode;
|
||||
// void
|
||||
EcommerceProvider.VoidCustomerInvoice(ES.SecurityContext.User.UserId, invoiceId);
|
||||
//
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static Taxation GetCustomerTaxation(string contractId, string country, string state)
|
||||
{
|
||||
return ES.ObjectUtils.FillObjectFromDataReader<Taxation>(
|
||||
EcommerceProvider.GetCustomerTaxation(contractId, country, state));
|
||||
}
|
||||
|
||||
public static void CalculateInvoiceChargeAmounts(Taxation tax, List<InvoiceItem> items,
|
||||
out decimal totalAmount, out decimal subTotalAmount, out decimal taxAmount)
|
||||
{
|
||||
totalAmount = subTotalAmount = taxAmount = 0;
|
||||
// calculate all invoice items
|
||||
foreach (InvoiceItem item in items)
|
||||
subTotalAmount += item.SubTotal;
|
||||
//
|
||||
totalAmount = subTotalAmount;
|
||||
// tax applies
|
||||
if (tax != null)
|
||||
{
|
||||
switch (tax.Type)
|
||||
{
|
||||
case TaxationType.Fixed:
|
||||
taxAmount = tax.Amount;
|
||||
totalAmount += taxAmount;
|
||||
break;
|
||||
case TaxationType.Percentage:
|
||||
taxAmount = (subTotalAmount / 100) * tax.Amount;
|
||||
totalAmount += taxAmount;
|
||||
break;
|
||||
case TaxationType.TaxIncluded:
|
||||
taxAmount = totalAmount - totalAmount * 100 / (100M + tax.Amount);
|
||||
subTotalAmount -= taxAmount;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static int AddInvoice(string contractId, List<InvoiceItem> invoiceLines, KeyValueBunch extraArgs)
|
||||
{
|
||||
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(contractId);
|
||||
// read customer tax
|
||||
Taxation tax = GetCustomerTaxation(contractId, account[ContractAccount.COUNTRY], account[ContractAccount.STATE]);
|
||||
int taxationId = (tax == null) ? -1 : tax.TaxationId;
|
||||
|
||||
// Calculate invoice amounts
|
||||
decimal totalAmount = 0, subTotalAmount = 0, taxAmount = 0;
|
||||
CalculateInvoiceChargeAmounts(tax, invoiceLines, out totalAmount, out subTotalAmount, out taxAmount);
|
||||
|
||||
// align svcs suspend date
|
||||
int[] svcs = new int[invoiceLines.Count];
|
||||
for (int i = 0; i < invoiceLines.Count; i++)
|
||||
svcs[i] = invoiceLines[i].ServiceId;
|
||||
DateTime sdateAligned = ServiceController.GetSvcsSuspendDateAligned(svcs, DateTime.Now);
|
||||
//
|
||||
StoreSettings settings = StorehouseController.GetStoreSettings(ES.SecurityContext.User.UserId,
|
||||
StoreSettings.SYSTEM_SETTINGS);
|
||||
// get invoice grace period in days
|
||||
int gracePeriod = Common.Utils.Utils.ParseInt(settings["InvoiceGracePeriod"], 0);
|
||||
//
|
||||
if (gracePeriod < 0) gracePeriod = 0;
|
||||
//
|
||||
DateTime created = DateTime.Now;
|
||||
DateTime dueDate = sdateAligned.AddDays(gracePeriod);
|
||||
//
|
||||
return AddInvoice(contractId, created, dueDate, taxationId, totalAmount, subTotalAmount, taxAmount,
|
||||
invoiceLines, extraArgs);
|
||||
}
|
||||
|
||||
public static int AddInvoice(string contractId, DateTime created, DateTime dueDate,
|
||||
int taxationId, decimal totalAmount, decimal subTotalAmount, decimal taxAmount, List<InvoiceItem> invoiceLines, KeyValueBunch extraArgs)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
Contract contract = ContractSystem.ContractController.GetContract(contractId);
|
||||
//
|
||||
ES.TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.TASK_ADD_INVOICE);
|
||||
// build xml representation
|
||||
string invoiceLinesXml = BuildAddXmlForInvoiceItems(invoiceLines);
|
||||
// add invoice
|
||||
int result = EcommerceProvider.AddInvoice(contractId, created, dueDate,
|
||||
taxationId, totalAmount, subTotalAmount, taxAmount, invoiceLinesXml,
|
||||
StorehouseController.GetBaseCurrency(contract.ResellerId));
|
||||
|
||||
// check error
|
||||
if (result < 1)
|
||||
return result; // EXIT
|
||||
|
||||
// build invoice number
|
||||
Invoice invoice = GetCustomerInvoiceInternally(result);
|
||||
StoreSettings settings = StorehouseController.GetStoreSettings(contract.ResellerId, StoreSettings.SYSTEM_SETTINGS);
|
||||
if (!String.IsNullOrEmpty(settings["InvoiceNumberFormat"]))
|
||||
{
|
||||
Hashtable options = new Hashtable();
|
||||
options["ID"] = result;
|
||||
invoice.InvoiceNumber = StorehouseController.ApplyStringCustomFormat(
|
||||
settings["InvoiceNumberFormat"], options);
|
||||
}
|
||||
else
|
||||
{
|
||||
invoice.InvoiceNumber = result.ToString();
|
||||
}
|
||||
// update invoice
|
||||
InvoiceController.UpdateInvoice(invoice.InvoiceId, invoice.InvoiceNumber, invoice.DueDate,
|
||||
invoice.Total, invoice.SubTotal, invoice.TaxationId, invoice.TaxAmount, invoice.Currency);
|
||||
//
|
||||
ES.TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT] = contract;
|
||||
ES.TaskManager.TaskParameters[SystemTaskParams.PARAM_INVOICE] = invoice;
|
||||
ES.TaskManager.TaskParameters[SystemTaskParams.PARAM_INVOICE_LINES] = invoiceLines;
|
||||
ES.TaskManager.TaskParameters[SystemTaskParams.PARAM_EXTRA_ARGS] = extraArgs;
|
||||
//
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw ES.TaskManager.WriteError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ES.TaskManager.CompleteTask();
|
||||
}
|
||||
}
|
||||
|
||||
public static int UpdateInvoice(int invoiceId, string invoiceNumber, DateTime dueDate,
|
||||
decimal total, decimal subTotal, int taxationId, decimal taxAmount, string currency)
|
||||
{
|
||||
return EcommerceProvider.UpdateInvoice(ES.SecurityContext.User.UserId, invoiceId,
|
||||
invoiceNumber, dueDate, total, subTotal, taxationId, taxAmount, currency);
|
||||
}
|
||||
|
||||
public static Invoice GetCustomerInvoiceInternally(int invoiceId)
|
||||
{
|
||||
return ES.ObjectUtils.FillObjectFromDataReader<Invoice>(
|
||||
EcommerceProvider.GetCustomerInvoice(ES.SecurityContext.User.UserId, invoiceId));
|
||||
}
|
||||
|
||||
public static List<InvoiceItem> GetCustomerInvoiceItems(int invoiceId)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<InvoiceItem>(
|
||||
EcommerceProvider.GetCustomerInvoiceItems(ES.SecurityContext.User.UserId, invoiceId));
|
||||
}
|
||||
|
||||
public static string GetCustomerInvoiceFormattedInternally(int invoiceId, string cultureName)
|
||||
{
|
||||
Invoice invoice = GetCustomerInvoiceInternally(invoiceId);
|
||||
//
|
||||
return GetCustomerInvoiceFormattedInternally(invoice.ContractId, invoiceId, cultureName);
|
||||
}
|
||||
|
||||
internal static string GetCustomerInvoiceFormattedInternally(string contractId, int invoiceId, string cultureName)
|
||||
{
|
||||
Contract contract = ContractSystem.ContractController.GetContract(contractId);
|
||||
ContractAccount accountSettings = ContractSystem.ContractController.GetContractAccountSettings(contractId);
|
||||
//
|
||||
return GetCustomerInvoiceFormattedInternally(contract, invoiceId, accountSettings, cultureName);
|
||||
}
|
||||
|
||||
internal static string GetCustomerInvoiceFormattedInternally(Contract contract, int invoiceId, ContractAccount accountSettings, string cultureName)
|
||||
{
|
||||
//
|
||||
Invoice invoiceInfo = GetCustomerInvoiceInternally(invoiceId);
|
||||
// impersonate
|
||||
ES.SecurityContext.SetThreadPrincipal(contract.ResellerId);
|
||||
// load settings
|
||||
StoreSettings settings = StorehouseController.GetStoreSettings(contract.ResellerId, StoreSettings.NEW_INVOICE);
|
||||
//
|
||||
string templateBody = settings["HtmlBody"];
|
||||
//
|
||||
Taxation invoiceTax = StorehouseController.GetTaxation(contract.ResellerId, invoiceInfo.TaxationId);
|
||||
//
|
||||
List<InvoiceItem> invoiceLines = GetCustomerInvoiceItems(invoiceId);
|
||||
Dictionary<int, Service> invoiceServices = ServiceController.GetServicesDictionary(invoiceLines);
|
||||
//
|
||||
Template tm = new Template(templateBody);
|
||||
tm["Invoice"] = invoiceInfo;
|
||||
tm["InvoiceLines"] = invoiceLines;
|
||||
tm["InvoiceServices"] = invoiceServices;
|
||||
tm["Customer"] = accountSettings;
|
||||
tm["Tax"] = invoiceTax;
|
||||
|
||||
StringWriter writer = new StringWriter();
|
||||
try
|
||||
{
|
||||
// Preserve an original thread culture
|
||||
CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
|
||||
//
|
||||
if (!String.IsNullOrEmpty(cultureName))
|
||||
{
|
||||
try
|
||||
{
|
||||
CultureInfo formattingCulture = new CultureInfo(cultureName);
|
||||
// Empty currency symbol to supporty 3-letters ISO format
|
||||
// hardcorded in HTML templates
|
||||
formattingCulture.NumberFormat.CurrencySymbol = String.Empty;
|
||||
// Set formatting culture
|
||||
Thread.CurrentThread.CurrentCulture = formattingCulture;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TaskManager.WriteWarning("Wrong culture name has been provided. Culture name: {0}.", cultureName);
|
||||
TaskManager.WriteWarning(ex.StackTrace);
|
||||
TaskManager.WriteWarning(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// Process template
|
||||
tm.Evaluate(writer);
|
||||
templateBody = writer.ToString();
|
||||
|
||||
// Revert the original thread's culture back
|
||||
Thread.CurrentThread.CurrentCulture = originalCulture;
|
||||
}
|
||||
catch (ParserException ex)
|
||||
{
|
||||
return String.Format("Error in template (Line {0}, Column {1}): {2}",
|
||||
ex.Line, ex.Column, ex.Message);
|
||||
}
|
||||
|
||||
return templateBody;
|
||||
}
|
||||
|
||||
public static List<Invoice> GetUnpaidInvoices(int resellerId)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<Invoice>(
|
||||
EcommerceProvider.GetUnpaidInvoices(ES.SecurityContext.User.UserId, resellerId));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region New implementation
|
||||
|
||||
public static List<InvoiceItem> GetInvoicesItemsToActivate(int resellerId)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<InvoiceItem>(
|
||||
EcommerceProvider.GetInvoicesItemsToActivate(ES.SecurityContext.User.UserId, resellerId));
|
||||
}
|
||||
|
||||
public static List<InvoiceItem> GetInvoicesItemsOverdue(int resellerId, DateTime dueDate)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<InvoiceItem>(
|
||||
EcommerceProvider.GetInvoicesItemsOverdue(ES.SecurityContext.User.UserId, resellerId, dueDate));
|
||||
}
|
||||
|
||||
public static int SetInvoiceItemProcessed(int invoiceId, int itemId)
|
||||
{
|
||||
return EcommerceProvider.SetInvoiceItemProcessed(invoiceId, itemId);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Provisioning routines
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
|
@ -0,0 +1,172 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Configuration;
|
||||
using System.Web;
|
||||
using System.Web.Security;
|
||||
using System.Web.UI;
|
||||
|
||||
using ES = WebsitePanel.EnterpriseServer;
|
||||
using WebsitePanel.Templates;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class MiscController
|
||||
{
|
||||
private MiscController()
|
||||
{
|
||||
}
|
||||
|
||||
public static int SendNewInvoiceNotification(int invoiceId)
|
||||
{
|
||||
Invoice invoice = InvoiceController.GetCustomerInvoiceInternally(invoiceId);
|
||||
List<InvoiceItem> invoiceLines = InvoiceController.GetCustomerInvoiceItems(invoiceId);
|
||||
|
||||
return SendNewInvoiceNotification(invoice, invoiceLines, null);
|
||||
}
|
||||
|
||||
public static int SendNewInvoiceNotification(Invoice invoice)
|
||||
{
|
||||
List<InvoiceItem> invoiceLines = InvoiceController.GetCustomerInvoiceItems(invoice.InvoiceId);
|
||||
|
||||
return SendNewInvoiceNotification(invoice, invoiceLines, null);
|
||||
}
|
||||
|
||||
public static int SendNewInvoiceNotification(Invoice invoice, List<InvoiceItem> invoiceLines, KeyValueBunch extraArgs)
|
||||
{
|
||||
Contract contract = ContractSystem.ContractController.GetContract(invoice.ContractId);
|
||||
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(invoice.ContractId);
|
||||
Dictionary<int, Service> invoiceServices = ServiceController.GetServicesDictionary(invoiceLines);
|
||||
Hashtable items = new Hashtable();
|
||||
|
||||
items["Invoice"] = invoice;
|
||||
items["InvoiceLines"] = invoiceLines;
|
||||
items["InvoiceServices"] = invoiceServices;
|
||||
items["Tax"] = StorehouseController.GetTaxation(contract.ResellerId, invoice.TaxationId);
|
||||
items["Customer"] = account;
|
||||
items["IsEmail"] = "1";
|
||||
if (extraArgs != null)
|
||||
items["ExtraArgs"] = extraArgs;
|
||||
|
||||
return SendSystemNotification(StoreSettings.NEW_INVOICE, account, items, "HtmlBody", "TextBody");
|
||||
}
|
||||
|
||||
public static int SendServiceActivatedNotification(int serviceId)
|
||||
{
|
||||
Hashtable items = new Hashtable();
|
||||
//
|
||||
Service serviceInfo = ServiceController.GetService(serviceId);
|
||||
//
|
||||
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(serviceInfo.ContractId);
|
||||
|
||||
items["Service"] = serviceInfo;
|
||||
items["Customer"] = account;
|
||||
|
||||
return SendSystemNotification(StoreSettings.SERVICE_ACTIVATED, account, items, "HtmlBody", "TextBody");
|
||||
}
|
||||
|
||||
public static int SendServiceSuspendedNotification(int serviceId)
|
||||
{
|
||||
Hashtable items = new Hashtable();
|
||||
|
||||
Service serviceInfo = ServiceController.GetService(serviceId);
|
||||
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(serviceInfo.ContractId);
|
||||
|
||||
items["Service"] = serviceInfo;
|
||||
items["Customer"] = account;
|
||||
|
||||
return SendSystemNotification(StoreSettings.SERVICE_SUSPENDED, account, items, "HtmlBody", "TextBody");
|
||||
}
|
||||
|
||||
public static int SendServiceCanceledNotification(int serviceId)
|
||||
{
|
||||
Hashtable items = new Hashtable();
|
||||
|
||||
Service serviceInfo = ServiceController.GetService(serviceId);
|
||||
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(serviceInfo.ContractId);
|
||||
|
||||
items["Service"] = serviceInfo;
|
||||
items["Customer"] = account;
|
||||
|
||||
return SendSystemNotification(StoreSettings.SERVICE_CANCELLED, account, items, "HtmlBody", "TextBody");
|
||||
}
|
||||
|
||||
public static int SendPaymentReceivedNotification(CustomerPayment payment)
|
||||
{
|
||||
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(payment.ContractId);
|
||||
|
||||
Hashtable items = new Hashtable();
|
||||
items["Payment"] = payment;
|
||||
items["Customer"] = account;
|
||||
|
||||
return SendSystemNotification(StoreSettings.PAYMENT_RECEIVED, account, items, "HtmlBody", "TextBody");
|
||||
}
|
||||
|
||||
protected static int SendSystemNotification(string settingsName, ContractAccount recipient, Hashtable items,
|
||||
string htmlKeyName, string textKeyName)
|
||||
{
|
||||
// load e-mail template
|
||||
StoreSettings settings = StorehouseController.GetStoreSettings(ES.SecurityContext.User.UserId,
|
||||
settingsName);
|
||||
//
|
||||
bool htmlMail = (recipient[ContractAccount.MAIL_FORMAT] == "HTML");
|
||||
string email = recipient[ContractAccount.EMAIL];
|
||||
//
|
||||
string messageBody = htmlMail ? settings[htmlKeyName] : settings[textKeyName];
|
||||
|
||||
Template tmp = new Template(messageBody);
|
||||
|
||||
if (items != null)
|
||||
{
|
||||
foreach (string key in items.Keys)
|
||||
tmp[key] = items[key];
|
||||
}
|
||||
|
||||
StringWriter writer = new StringWriter();
|
||||
try
|
||||
{
|
||||
tmp.Evaluate(writer);
|
||||
}
|
||||
catch (ParserException ex)
|
||||
{
|
||||
writer.WriteLine(String.Format("Error in template (Line {0}, Column {1}): {2}",
|
||||
ex.Line, ex.Column, ex.Message));
|
||||
}
|
||||
// evaluate message body
|
||||
messageBody = writer.ToString();
|
||||
|
||||
return ES.MailHelper.SendMessage(settings["From"], email, settings["CC"], settings["Subject"],
|
||||
messageBody, htmlMail);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,165 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Configuration;
|
||||
using System.Xml;
|
||||
using System.Web;
|
||||
using System.Web.Security;
|
||||
using System.Web.UI;
|
||||
using System.Web.UI.WebControls;
|
||||
using System.Web.UI.WebControls.WebParts;
|
||||
using System.Web.UI.HtmlControls;
|
||||
|
||||
using ES = WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class PaymentGatewayController
|
||||
{
|
||||
public const string TASK_SOURCE = "PAYMENT_CONTROLLER";
|
||||
public const string CHECKOUT_TASK = "CHECKOUT";
|
||||
public const string GENERAL_FAILURE = "CHECKOUT_GENERAL_FAILURE";
|
||||
|
||||
private PaymentGatewayController()
|
||||
{
|
||||
}
|
||||
|
||||
#region Payment Gateway routines
|
||||
|
||||
/// <summary>
|
||||
/// Performs checkout operation
|
||||
/// </summary>
|
||||
/// <param name="spaceId">Space.</param>
|
||||
/// <param name="gatewayId">Gateway.</param>
|
||||
/// <param name="invoiceId">Invoice.</param>
|
||||
/// <param name="details">Array of parameters.</param>
|
||||
/// <returns>Checkout result object.</returns>
|
||||
public static CheckoutResult CheckOut(string contractId, int invoiceId, string methodName,
|
||||
CheckoutDetails details)
|
||||
{
|
||||
CheckoutResult result = new CheckoutResult();
|
||||
|
||||
try
|
||||
{
|
||||
Contract contractInfo = ContractSystem.ContractController.GetContract(contractId);
|
||||
// impersonate
|
||||
ContractSystem.ContractController.ImpersonateAsContractReseller(contractInfo);
|
||||
// TRACE
|
||||
ES.TaskManager.StartTask(TASK_SOURCE, CHECKOUT_TASK, methodName);
|
||||
ES.TaskManager.Write("Start accepting payment for invoice");
|
||||
ES.TaskManager.WriteParameter("ContractID", contractId);
|
||||
ES.TaskManager.WriteParameter("InvoiceID", invoiceId);
|
||||
|
||||
// get user details
|
||||
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(contractId);
|
||||
|
||||
// try to load plugin type and throw an exception if type not found
|
||||
IPaymentGatewayProvider provider = (IPaymentGatewayProvider)SystemPluginController.GetContractPaymentMethod(
|
||||
contractInfo, methodName);
|
||||
|
||||
// add invoice details
|
||||
Invoice invoice = InvoiceController.GetCustomerInvoiceInternally(invoiceId);
|
||||
|
||||
// append information for the provider
|
||||
details[CheckoutKeys.ContractNumber] = contractId;
|
||||
details[CheckoutKeys.Amount] = invoice.Total.ToString("0.00");
|
||||
details[CheckoutKeys.InvoiceNumber] = invoice.InvoiceNumber;
|
||||
details[CheckoutKeys.Currency] = invoice.Currency;
|
||||
|
||||
ES.TaskManager.Write("Submitting payment transaction");
|
||||
// call checkout routine
|
||||
TransactionResult pgResult = provider.SubmitPaymentTransaction(details);
|
||||
// log provider response
|
||||
SystemPluginController.LogContractPayment(contractInfo, methodName, pgResult.RawResponse);
|
||||
// ERROR
|
||||
if (!pgResult.Succeed)
|
||||
{
|
||||
result.Succeed = false;
|
||||
result.StatusCode = pgResult.StatusCode;
|
||||
//
|
||||
ES.TaskManager.WriteError("Transaction failed");
|
||||
ES.TaskManager.WriteParameter("StatusCode", result.StatusCode);
|
||||
ES.TaskManager.WriteParameter("RawResponse", pgResult.RawResponse);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
// OK
|
||||
ES.TaskManager.Write("Transaction is OK");
|
||||
|
||||
// check whether the transaction already exists
|
||||
CustomerPayment tran = StorehouseController.LookupForTransaction(pgResult.TransactionId);
|
||||
|
||||
// lookup for pending transaction
|
||||
if (tran == null)
|
||||
{
|
||||
// add payment record
|
||||
result.PaymentId = StorehouseController.AddCustomerPayment(contractId, invoice.InvoiceId,
|
||||
pgResult.TransactionId, invoice.Total, invoice.Currency, methodName,
|
||||
pgResult.TransactionStatus);
|
||||
// ERROR
|
||||
if (result.PaymentId < 1)
|
||||
{
|
||||
result.Succeed = false;
|
||||
result.StatusCode = result.PaymentId.ToString();
|
||||
//
|
||||
ES.TaskManager.WriteError("Could not add customer payment record to the db");
|
||||
ES.TaskManager.WriteParameter("ResultCode", result.StatusCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
}
|
||||
// if transaction is already submitted just update it's status
|
||||
if (tran != null)
|
||||
StorehouseController.UpdateTransactionStatus(tran.PaymentId, pgResult.TransactionStatus);
|
||||
// OK
|
||||
result.Succeed = true;
|
||||
// ensure user requests to persist his payment details for credit card
|
||||
if (details.Persistent && methodName == PaymentMethod.CREDIT_CARD)
|
||||
StorehouseController.SetPaymentProfile(contractId, details);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
result.Succeed = false;
|
||||
result.StatusCode = GENERAL_FAILURE;
|
||||
//
|
||||
ES.TaskManager.WriteError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ES.TaskManager.CompleteTask();
|
||||
}
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
|
@ -0,0 +1,543 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class DomainNameController : ServiceProvisioningBase, IServiceProvisioning
|
||||
{
|
||||
public const string SOURCE_NAME = "SPF_DOMAIN_NAME";
|
||||
|
||||
public static Dictionary<int, string> ApiErrorCodesMap;
|
||||
|
||||
static DomainNameController()
|
||||
{
|
||||
ApiErrorCodesMap = new Dictionary<int, string>();
|
||||
ApiErrorCodesMap.Add(BusinessErrorCodes.ERROR_DOMAIN_QUOTA_LIMIT, ERROR_DOMAIN_QUOTA_EXCEEDED);
|
||||
}
|
||||
|
||||
#region Trace Messages
|
||||
|
||||
public const string START_ACTIVATION_MSG = "Starting domain name activation";
|
||||
public const string START_SUSPENSION_MSG = "Starting domain name suspension";
|
||||
public const string START_CANCELLATION_MSG = "Starting domain name cancellation";
|
||||
public const string START_ROLLBACK_MSG = "Trying rollback operation";
|
||||
|
||||
public const string TLD_PROVISIONED_MSG = "Domain name has been provisioned";
|
||||
|
||||
#endregion
|
||||
|
||||
#region Error Messages
|
||||
|
||||
public const string ERROR_UPDATE_USR_SETTINGS_MSG = "Could not update user settings";
|
||||
public const string ERROR_ADD_INTERNAL_DOMAIN = "Could not add internal domain";
|
||||
public const string ERROR_DOMAIN_QUOTA_EXCEEDED = "Domain quota has been exceeded in the customer's hosting plan";
|
||||
public const string ERROR_ROLLBACK_DOM_MSG = "Could not rollback added internal domain";
|
||||
|
||||
#endregion
|
||||
|
||||
protected DomainNameSvc GetDomainNameSvc(int serviceId)
|
||||
{
|
||||
// assemble svc instance
|
||||
DomainNameSvc domainSvc = ObjectUtils.FillObjectFromDataReader<DomainNameSvc>(
|
||||
EcommerceProvider.GetDomainNameSvc(SecurityContext.User.UserId, serviceId));
|
||||
// deserialize svc properties
|
||||
SecurityUtils.DeserializeGenericProfile(domainSvc.PropertyNames, domainSvc.PropertyValues, domainSvc);
|
||||
// return result
|
||||
return domainSvc;
|
||||
}
|
||||
|
||||
protected InvoiceItem GetDomainSvcSetupFee(DomainNameSvc service)
|
||||
{
|
||||
InvoiceItem line = new InvoiceItem();
|
||||
|
||||
line.ItemName = service.ServiceName;
|
||||
line.Quantity = 1;
|
||||
line.UnitPrice = service.SetupFee;
|
||||
line.TypeName = "Setup Fee";
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
protected InvoiceItem GetDomainSvcFee(DomainNameSvc service)
|
||||
{
|
||||
InvoiceItem line = new InvoiceItem();
|
||||
|
||||
line.ItemName = service.ServiceName;
|
||||
line.ServiceId = service.ServiceId;
|
||||
line.Quantity = 1;
|
||||
line.UnitPrice = service.RecurringFee;
|
||||
// define line type
|
||||
if (service.Status != ServiceStatus.Ordered)
|
||||
{
|
||||
line.TypeName = "Recurring Fee";
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (service["SPF_ACTION"])
|
||||
{
|
||||
case DomainNameSvc.SPF_TRANSFER_ACTION:
|
||||
line.TypeName = String.Concat(Product.TOP_LEVEL_DOMAIN_NAME, " Transfer");
|
||||
break;
|
||||
case DomainNameSvc.SPF_REGISTER_ACTION:
|
||||
line.TypeName = String.Concat(Product.TOP_LEVEL_DOMAIN_NAME, " Registration");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
#region IServiceProvisioning Members
|
||||
|
||||
public ServiceHistoryRecord[] GetServiceHistory(int serviceId)
|
||||
{
|
||||
List<ServiceHistoryRecord> history = ObjectUtils.CreateListFromDataReader<ServiceHistoryRecord>(
|
||||
EcommerceProvider.GetDomainNameSvcHistory(SecurityContext.User.UserId, serviceId));
|
||||
//
|
||||
if (history != null)
|
||||
return history.ToArray();
|
||||
//
|
||||
return new ServiceHistoryRecord[] { };
|
||||
}
|
||||
|
||||
public InvoiceItem[] CalculateInvoiceLines(int serviceId)
|
||||
{
|
||||
List<InvoiceItem> lines = new List<InvoiceItem>();
|
||||
//
|
||||
DomainNameSvc domainSvc = GetDomainNameSvc(serviceId);
|
||||
//
|
||||
if (domainSvc["SPF_ACTION"] != DomainNameSvc.SPF_UPDATE_NS_ACTION)
|
||||
{
|
||||
// domain svc fee
|
||||
lines.Add(GetDomainSvcFee(domainSvc));
|
||||
// setup fee
|
||||
if (domainSvc.SetupFee > 0M && domainSvc.Status == ServiceStatus.Ordered)
|
||||
lines.Add(GetDomainSvcSetupFee(domainSvc));
|
||||
}
|
||||
//
|
||||
return lines.ToArray();
|
||||
}
|
||||
|
||||
public Service GetServiceInfo(int serviceId)
|
||||
{
|
||||
return GetDomainNameSvc(serviceId);
|
||||
}
|
||||
|
||||
public int UpdateServiceInfo(Service serviceInfo)
|
||||
{
|
||||
DomainNameSvc domainSvc = (DomainNameSvc)serviceInfo;
|
||||
// serialize props & values
|
||||
string propertyNames = null;
|
||||
string propertyValues = null;
|
||||
SecurityUtils.SerializeGenericProfile(ref propertyNames, ref propertyValues, domainSvc);
|
||||
// update svc
|
||||
return EcommerceProvider.UpdateDomainNameSvc(SecurityContext.User.UserId, domainSvc.ServiceId,
|
||||
domainSvc.ProductId, (int)domainSvc.Status, domainSvc.DomainId, domainSvc.Fqdn,
|
||||
propertyNames, propertyValues);
|
||||
}
|
||||
|
||||
public int AddServiceInfo(string contractId, string currency, OrderItem orderItem)
|
||||
{
|
||||
string propertyNames = null;
|
||||
string propertyValues = null;
|
||||
// deserialize
|
||||
SecurityUtils.SerializeGenericProfile(ref propertyNames, ref propertyValues, orderItem);
|
||||
//
|
||||
return EcommerceProvider.AddDomainNameSvc(contractId, orderItem.ParentSvcId,
|
||||
orderItem.ProductId, orderItem.ItemName, orderItem.BillingCycle, currency, propertyNames, propertyValues);
|
||||
}
|
||||
|
||||
public GenericSvcResult ActivateService(ProvisioningContext context)
|
||||
{
|
||||
GenericSvcResult result = new GenericSvcResult();
|
||||
|
||||
// remeber svc state
|
||||
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
|
||||
|
||||
// concretize service to be provisioned
|
||||
DomainNameSvc domainSvc = (DomainNameSvc)context.ServiceInfo;
|
||||
// concretize parent service
|
||||
HostingPackageSvc packageSvc = (HostingPackageSvc)context.ParentSvcInfo;
|
||||
|
||||
try
|
||||
{
|
||||
// LOG INFO
|
||||
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_ACTIVATE);
|
||||
TaskManager.WriteParameter(CONTRACT_PARAM, domainSvc.ContractId);
|
||||
TaskManager.WriteParameter(SVC_PARAM, domainSvc.ServiceName);
|
||||
TaskManager.WriteParameter(SVC_ID_PARAM, domainSvc.ServiceId);
|
||||
|
||||
// 0. Do security checks
|
||||
if (!CheckOperationClientPermissions(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
//
|
||||
if (!CheckOperationClientStatus(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
// error: hosting addon should have parent svc assigned
|
||||
if (packageSvc == null || packageSvc.PackageId == 0)
|
||||
{
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.Error = PARENT_SVC_NOT_FOUND_MSG;
|
||||
//
|
||||
result.ResultCode = EcommerceErrorCodes.ERROR_PARENT_SVC_NOT_FOUND;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(result.Error);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
// first of all - create internal domain in WebsitePanel
|
||||
if (domainSvc.Status == ServiceStatus.Ordered)
|
||||
{
|
||||
// create domain info object
|
||||
DomainInfo domain = ServerController.GetDomain(domainSvc.Fqdn);
|
||||
//
|
||||
if (domain != null)
|
||||
domainSvc.DomainId = domain.DomainId;
|
||||
//
|
||||
if (domain == null)
|
||||
{
|
||||
domain = new DomainInfo();
|
||||
domain.DomainName = domainSvc.Fqdn;
|
||||
domain.HostingAllowed = false;
|
||||
domain.PackageId = packageSvc.PackageId;
|
||||
// add internal domain
|
||||
domainSvc.DomainId = ServerController.AddDomain(domain);
|
||||
// check API result
|
||||
if (domainSvc.DomainId < 1)
|
||||
{
|
||||
// ASSEMBLE ERROR
|
||||
result.Succeed = false;
|
||||
// try to find corresponding error code->error message mapping
|
||||
if (ApiErrorCodesMap.ContainsKey(domainSvc.DomainId))
|
||||
result.Error = ApiErrorCodesMap[domainSvc.DomainId];
|
||||
else
|
||||
result.Error = ERROR_ADD_INTERNAL_DOMAIN;
|
||||
// copy result code
|
||||
result.ResultCode = domainSvc.DomainId;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(result.Error);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// update nameservers only
|
||||
if (domainSvc["SPF_ACTION"] == "UPDATE_NS")
|
||||
{
|
||||
// remove service here...
|
||||
ServiceController.DeleteCustomerService(domainSvc.ServiceId);
|
||||
//
|
||||
result.Succeed = true;
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
// load registrar wrapper
|
||||
IDomainRegistrar registrar = (IDomainRegistrar)SystemPluginController.GetSystemPluginInstance(
|
||||
domainSvc.ContractId, domainSvc.PluginId, true);
|
||||
|
||||
#region Commented operations
|
||||
// prepare consumer account information
|
||||
/*CommandParams cmdParams = PrepeareAccountParams(context.ConsumerInfo);
|
||||
// copy svc properties
|
||||
foreach (string keyName in domainSvc.GetAllKeys())
|
||||
cmdParams[keyName] = domainSvc[keyName];
|
||||
|
||||
// check registrar requires sub-account to be created
|
||||
if (registrar.SubAccountRequired)
|
||||
{
|
||||
// 1. Load user's settings
|
||||
UserSettings userSettings = LoadUserSettings(context.ConsumerInfo.UserId, registrar.PluginName);
|
||||
// 2. Ensure user has account on registrar's side
|
||||
if (userSettings.SettingsArray == null || userSettings.SettingsArray.Length == 0)
|
||||
{
|
||||
// 3. Check account exists
|
||||
bool exists = registrar.CheckSubAccountExists(context.ConsumerInfo.Username, context.ConsumerInfo.Email);
|
||||
//
|
||||
AccountResult accResult = null;
|
||||
//
|
||||
if (!exists)
|
||||
{
|
||||
// 4. Create user account
|
||||
accResult = registrar.CreateSubAccount(cmdParams);
|
||||
// copy keys & values
|
||||
foreach (string keyName in accResult.AllKeys)
|
||||
{
|
||||
userSettings[keyName] = accResult[keyName];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 4a. Get sub-account info
|
||||
accResult = registrar.GetSubAccount(context.ConsumerInfo.Username,
|
||||
context.ConsumerInfo.Email);
|
||||
//
|
||||
foreach (string keyName in accResult.AllKeys)
|
||||
userSettings[keyName] = accResult[keyName];
|
||||
}
|
||||
// 5. Update user settings
|
||||
int apiResult = UserController.UpdateUserSettings(userSettings);
|
||||
// check API result
|
||||
if (apiResult < 0)
|
||||
{
|
||||
// BUILD ERROR
|
||||
result.Error = ERROR_UPDATE_USR_SETTINGS_MSG;
|
||||
result.Succeed = false;
|
||||
result.ResultCode = apiResult;
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(result.Error);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// ROLLBACK
|
||||
RollbackOperation(domainSvc.DomainId);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
}
|
||||
// copy registrar-specific data
|
||||
foreach (string[] pair in userSettings.SettingsArray)
|
||||
{
|
||||
// copy 2
|
||||
cmdParams[pair[0]] = pair[1];
|
||||
}
|
||||
}*/
|
||||
#endregion
|
||||
|
||||
// load NS settings
|
||||
PackageSettings nsSettings = PackageController.GetPackageSettings(packageSvc.PackageId, PackageSettings.NAME_SERVERS);
|
||||
// build name servers array
|
||||
string[] nameServers = null;
|
||||
if (!String.IsNullOrEmpty(nsSettings[PackageSettings.NAME_SERVERS]))
|
||||
nameServers = nsSettings[PackageSettings.NAME_SERVERS].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
// register or renew domain
|
||||
if (domainSvc.Status == ServiceStatus.Ordered)
|
||||
// try to register domain
|
||||
registrar.RegisterDomain(domainSvc, context.ConsumerInfo, nameServers);
|
||||
else
|
||||
// try to renew domain
|
||||
registrar.RenewDomain(domainSvc, context.ConsumerInfo, nameServers);
|
||||
|
||||
// change svc status to active
|
||||
domainSvc.Status = ServiceStatus.Active;
|
||||
// update service info
|
||||
int updResult = UpdateServiceInfo(domainSvc);
|
||||
// check update result for errors
|
||||
if (updResult < 0)
|
||||
{
|
||||
// BUILD ERROR
|
||||
result.ResultCode = updResult;
|
||||
result.Succeed = false;
|
||||
result.Error = ERROR_SVC_UPDATE_MSG;
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(result.Error);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// ROLLBACK
|
||||
RollbackOperation(domainSvc.DomainId);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
//
|
||||
result.Succeed = true;
|
||||
//
|
||||
SetOutboundParameters(context);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ex);
|
||||
result.Succeed = false;
|
||||
// ROLLBACK
|
||||
RollbackOperation(result.ResultCode);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TaskManager.CompleteTask();
|
||||
}
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
public GenericSvcResult SuspendService(ProvisioningContext context)
|
||||
{
|
||||
GenericSvcResult result = new GenericSvcResult();
|
||||
//
|
||||
result.Succeed = true;
|
||||
//
|
||||
DomainNameSvc service = (DomainNameSvc)context.ServiceInfo;
|
||||
service.Status = ServiceStatus.Suspended;
|
||||
//
|
||||
UpdateServiceInfo(service);
|
||||
//
|
||||
SetOutboundParameters(context);
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
public GenericSvcResult CancelService(ProvisioningContext context)
|
||||
{
|
||||
GenericSvcResult result = new GenericSvcResult();
|
||||
//
|
||||
result.Succeed = true;
|
||||
//
|
||||
DomainNameSvc service = (DomainNameSvc)context.ServiceInfo;
|
||||
service.Status = ServiceStatus.Cancelled;
|
||||
//
|
||||
UpdateServiceInfo(service);
|
||||
//
|
||||
SetOutboundParameters(context);
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
public void LogServiceUsage(ProvisioningContext context)
|
||||
{
|
||||
// concretize svc to be provisioned
|
||||
DomainNameSvc domainSvc = (DomainNameSvc)context.ServiceInfo;
|
||||
//
|
||||
base.LogServiceUsage(context.ServiceInfo, domainSvc.SvcCycleId,
|
||||
domainSvc.BillingPeriod, domainSvc.PeriodLength);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private void RollbackOperation(int domainId)
|
||||
{
|
||||
if (domainId < 1)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
// restore
|
||||
DomainNameSvc domainSvc = (DomainNameSvc)RestoreObjectState(SERVICE_INFO);
|
||||
|
||||
int apiResult = 0;
|
||||
|
||||
switch (domainSvc.Status)
|
||||
{
|
||||
// Service
|
||||
case ServiceStatus.Ordered:
|
||||
apiResult = ServerController.DeleteDomain(domainId);
|
||||
break;
|
||||
}
|
||||
|
||||
// check API result
|
||||
if (apiResult < 0)
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_ROLLBACK_DOM_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, apiResult);
|
||||
}
|
||||
|
||||
// rollback service changes in EC metabase
|
||||
apiResult = UpdateServiceInfo(domainSvc);
|
||||
// check API result
|
||||
if (apiResult < 0)
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_ROLLBACK_SVC_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, apiResult);
|
||||
// EXIT
|
||||
return;
|
||||
}
|
||||
//
|
||||
TaskManager.Write(ROLLBACK_SUCCEED_MSG);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TaskManager.WriteError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads user's plugin-specific settings
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="pluginName"></param>
|
||||
/// <returns></returns>
|
||||
private UserSettings LoadUserSettings(int userId, string pluginName)
|
||||
{
|
||||
// build settings name
|
||||
string settingsName = pluginName + "Settings";
|
||||
// load user settings
|
||||
UserSettings settings = UserController.GetUserSettings(userId, settingsName);
|
||||
// set settings name
|
||||
settings.SettingsName = settingsName;
|
||||
//
|
||||
return settings;
|
||||
}
|
||||
|
||||
private CommandParams PrepeareAccountParams(UserInfo userInfo)
|
||||
{
|
||||
CommandParams args = new CommandParams();
|
||||
|
||||
args[CommandParams.USERNAME] = userInfo.Username;
|
||||
args[CommandParams.PASSWORD] = userInfo.Password;
|
||||
args[CommandParams.FIRST_NAME] = userInfo.FirstName;
|
||||
args[CommandParams.LAST_NAME] = userInfo.LastName;
|
||||
args[CommandParams.EMAIL] = userInfo.Email;
|
||||
args[CommandParams.ADDRESS] = userInfo.Address;
|
||||
args[CommandParams.CITY] = userInfo.City;
|
||||
args[CommandParams.STATE] = userInfo.State;
|
||||
args[CommandParams.COUNTRY] = userInfo.Country;
|
||||
args[CommandParams.ZIP] = userInfo.Zip;
|
||||
args[CommandParams.PHONE] = userInfo.PrimaryPhone;
|
||||
args[CommandParams.FAX] = userInfo.Fax;
|
||||
|
||||
return args;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,673 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class HostingAddonController : ServiceProvisioningBase, IServiceProvisioning
|
||||
{
|
||||
public const string SOURCE_NAME = "SPF_HOSTING_ADDN";
|
||||
|
||||
#region Trace Messages
|
||||
|
||||
public const string START_ACTIVATION_MSG = "Starting addon activation";
|
||||
public const string START_SUSPENSION_MSG = "Starting addon suspension";
|
||||
public const string START_CANCELLATION_MSG = "Starting addon cancellation";
|
||||
public const string START_ROLLBACK_MSG = "Trying rollback operation";
|
||||
|
||||
public const string ADDON_PROVISIONED_MSG = "Addon has been provisioned";
|
||||
|
||||
#endregion
|
||||
|
||||
#region Error Messages
|
||||
|
||||
public const string ERROR_CREATE_ADDON_MSG = "Could not create hosting addon";
|
||||
|
||||
public const string ERROR_ACTIVATE_ADDON_MSG = "Could not activate hosting addon";
|
||||
public const string ERROR_SUSPEND_ADDON_MSG = "Could not suspend hosting addon";
|
||||
public const string ERROR_CANCEL_ADDON_MSG = "Could not cancel hosting addon";
|
||||
|
||||
public const string ERROR_ROLLBACK_ORDER_MSG = "Could not rollback operation and delete addon";
|
||||
public const string ERROR_ROLLBACK_MSG = "Could not rollback operation and revert addon state";
|
||||
|
||||
public const string ADDON_NOT_FOUND_MSG = "Could not find hosting addon";
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
protected HostingAddonSvc GetHostingAddonSvc(int serviceId)
|
||||
{
|
||||
return ObjectUtils.FillObjectFromDataReader<HostingAddonSvc>(
|
||||
EcommerceProvider.GetHostingAddonSvc(SecurityContext.User.UserId, serviceId));
|
||||
}
|
||||
|
||||
protected InvoiceItem GetAddonSvcFee(HostingAddonSvc service)
|
||||
{
|
||||
InvoiceItem line = new InvoiceItem();
|
||||
|
||||
line.ItemName = service.ServiceName;
|
||||
line.ServiceId = service.ServiceId;
|
||||
line.Quantity = service.Quantity;
|
||||
line.UnitPrice = service.CyclePrice;
|
||||
|
||||
if (service.Recurring && service.Status != ServiceStatus.Ordered)
|
||||
line.TypeName = "Recurring Fee";
|
||||
else
|
||||
line.TypeName = Product.HOSTING_ADDON_NAME;
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
protected InvoiceItem GetAddonSvcSetupFee(HostingAddonSvc service)
|
||||
{
|
||||
InvoiceItem line = new InvoiceItem();
|
||||
|
||||
line.ItemName = service.ServiceName;
|
||||
line.Quantity = service.Quantity;
|
||||
line.UnitPrice = service.SetupFee;
|
||||
line.TypeName = "Setup Fee";
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
#region IServiceProvisioning Members
|
||||
|
||||
public ServiceHistoryRecord[] GetServiceHistory(int serviceId)
|
||||
{
|
||||
List<ServiceHistoryRecord> history = ObjectUtils.CreateListFromDataReader<ServiceHistoryRecord>(
|
||||
EcommerceProvider.GetHostingAddonSvcHistory(SecurityContext.User.UserId, serviceId));
|
||||
//
|
||||
if (history != null)
|
||||
return history.ToArray();
|
||||
//
|
||||
return new ServiceHistoryRecord[] { };
|
||||
}
|
||||
|
||||
public InvoiceItem[] CalculateInvoiceLines(int serviceId)
|
||||
{
|
||||
List<InvoiceItem> lines = new List<InvoiceItem>();
|
||||
//
|
||||
HostingAddonSvc addonSvc = GetHostingAddonSvc(serviceId);
|
||||
// addon svc fee
|
||||
lines.Add(GetAddonSvcFee(addonSvc));
|
||||
// addon svc setup fee
|
||||
if (addonSvc.SetupFee > 0M && addonSvc.Status == ServiceStatus.Ordered)
|
||||
lines.Add(GetAddonSvcSetupFee(addonSvc));
|
||||
//
|
||||
return lines.ToArray();
|
||||
}
|
||||
|
||||
public int AddServiceInfo(string contractId, string currency, OrderItem orderItem)
|
||||
{
|
||||
// get hosting addon product
|
||||
HostingAddon addon = StorehouseController.GetHostingAddon(SecurityContext.User.UserId,
|
||||
orderItem.ProductId);
|
||||
// uncountable addons always have 1 for quantity
|
||||
int quantity = addon.Countable ? orderItem.Quantity : 1;
|
||||
// add hosting addon
|
||||
return EcommerceProvider.AddHostingAddonSvc(contractId, orderItem.ParentSvcId, orderItem.ProductId,
|
||||
quantity, orderItem.ItemName, orderItem.BillingCycle, currency);
|
||||
}
|
||||
|
||||
public Service GetServiceInfo(int serviceId)
|
||||
{
|
||||
return GetHostingAddonSvc(serviceId);
|
||||
}
|
||||
|
||||
public int UpdateServiceInfo(Service serviceInfo)
|
||||
{
|
||||
HostingAddonSvc addonSvc = (HostingAddonSvc)serviceInfo;
|
||||
//
|
||||
return EcommerceProvider.UpdateHostingAddonSvc(SecurityContext.User.UserId, addonSvc.ServiceId,
|
||||
addonSvc.ProductId, addonSvc.ServiceName, (int)addonSvc.Status, addonSvc.PlanId,
|
||||
addonSvc.PackageAddonId, addonSvc.Recurring, addonSvc.DummyAddon);
|
||||
}
|
||||
|
||||
public GenericSvcResult ActivateService(ProvisioningContext context)
|
||||
{
|
||||
GenericSvcResult result = new GenericSvcResult();
|
||||
|
||||
// remeber svc state
|
||||
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
|
||||
|
||||
// concretize service to be provisioned
|
||||
HostingAddonSvc addonSvc = (HostingAddonSvc)context.ServiceInfo;
|
||||
// concretize parent svc
|
||||
HostingPackageSvc packageSvc = (HostingPackageSvc)context.ParentSvcInfo;
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_ACTIVATE);
|
||||
|
||||
// LOG INFO
|
||||
TaskManager.Write(START_ACTIVATION_MSG);
|
||||
TaskManager.WriteParameter(CONTRACT_PARAM, addonSvc.ContractId);
|
||||
TaskManager.WriteParameter(SVC_PARAM, addonSvc.ServiceName);
|
||||
TaskManager.WriteParameter(SVC_ID_PARAM, addonSvc.ServiceId);
|
||||
|
||||
// 0. Do security checks
|
||||
if (!CheckOperationClientPermissions(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
//
|
||||
if (!CheckOperationClientStatus(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
// dummy addon should be just updated in metabase
|
||||
if (addonSvc.DummyAddon)
|
||||
goto UpdateSvcMetaInfo;
|
||||
|
||||
if (addonSvc.Status == ServiceStatus.Ordered)
|
||||
{
|
||||
// error: hosting addon should have parent svc assigned
|
||||
if (packageSvc == null || packageSvc.PackageId == 0)
|
||||
{
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.Error = PARENT_SVC_NOT_FOUND_MSG;
|
||||
//
|
||||
result.ResultCode = EcommerceErrorCodes.ERROR_PARENT_SVC_NOT_FOUND;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(result.Error);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
// fill package add-on fields
|
||||
PackageAddonInfo addon = new PackageAddonInfo();
|
||||
//
|
||||
addon.PackageId = packageSvc.PackageId;
|
||||
//
|
||||
addon.PlanId = addonSvc.PlanId;
|
||||
// set addon quantity
|
||||
addon.Quantity = addonSvc.Quantity;
|
||||
//
|
||||
addon.StatusId = (int)PackageStatus.Active;
|
||||
//
|
||||
addon.PurchaseDate = DateTime.Now;
|
||||
|
||||
// Create hosting addon through WebsitePanel API
|
||||
PackageResult apiResult = PackageController.AddPackageAddon(addon);
|
||||
// Failed to create addon
|
||||
if (apiResult.Result < 1)
|
||||
{
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.ResultCode = apiResult.Result;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CREATE_ADDON_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
// store package id
|
||||
addonSvc.PackageAddonId = apiResult.Result;
|
||||
}
|
||||
else
|
||||
{
|
||||
// load package addon
|
||||
PackageAddonInfo addonInfo = PackageController.GetPackageAddon(addonSvc.PackageAddonId);
|
||||
// package addon not found
|
||||
if (addonInfo == null)
|
||||
{
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.ResultCode = EcommerceErrorCodes.ERROR_PCKG_ADDON_NOT_FOUND;
|
||||
//
|
||||
result.Error = ADDON_NOT_FOUND_MSG;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(result.Error);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
// workaround for bug in GetPackageAddon routine
|
||||
//addonInfo.PackageAddonId = addonSvc.PackageAddonId;
|
||||
// change package add-on status
|
||||
addonInfo.StatusId = (int)PackageStatus.Active;
|
||||
|
||||
// save hosting addon changes
|
||||
PackageResult apiResult = PackageController.UpdatePackageAddon(addonInfo);
|
||||
// check returned result
|
||||
if (apiResult.Result < 0)
|
||||
{
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.ResultCode = apiResult.Result;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_ACTIVATE_ADDON_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
UpdateSvcMetaInfo:
|
||||
// update status only if necessary
|
||||
if (addonSvc.Status != ServiceStatus.Active)
|
||||
{
|
||||
// change service status to active
|
||||
addonSvc.Status = ServiceStatus.Active;
|
||||
// put data into metabase
|
||||
int svcResult = UpdateServiceInfo(addonSvc);
|
||||
// failed to update metabase
|
||||
if (svcResult < 0)
|
||||
{
|
||||
result.ResultCode = svcResult;
|
||||
//
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.Error = ERROR_SVC_UPDATE_MSG;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(result.Error);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(addonSvc.PackageAddonId);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
}
|
||||
//
|
||||
SetOutboundParameters(context);
|
||||
// LOG INFO
|
||||
TaskManager.Write(ADDON_PROVISIONED_MSG);
|
||||
//
|
||||
result.Succeed = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
TaskManager.WriteError(ex);
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(addonSvc.PackageAddonId);
|
||||
|
||||
//
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.Error = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// complete task
|
||||
TaskManager.CompleteTask();
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
public GenericSvcResult SuspendService(ProvisioningContext context)
|
||||
{
|
||||
GenericSvcResult result = new GenericSvcResult();
|
||||
//
|
||||
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
|
||||
// concretize service to be provisioned
|
||||
HostingAddonSvc addonSvc = (HostingAddonSvc)context.ServiceInfo;
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_SUSPEND);
|
||||
// LOG INFO
|
||||
TaskManager.Write(START_SUSPENSION_MSG);
|
||||
TaskManager.WriteParameter(CONTRACT_PARAM, addonSvc.ContractId);
|
||||
TaskManager.WriteParameter(SVC_PARAM, addonSvc.ServiceName);
|
||||
TaskManager.WriteParameter(SVC_ID_PARAM, addonSvc.ServiceId);
|
||||
|
||||
// 0. Do security checks
|
||||
if (!CheckOperationClientPermissions(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
//
|
||||
if (!CheckOperationClientStatus(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
// dummy addon should be just updated in metabase
|
||||
if (addonSvc.DummyAddon)
|
||||
goto UpdateSvcMetaInfo;
|
||||
|
||||
PackageAddonInfo addonInfo = PackageController.GetPackageAddon(addonSvc.PackageAddonId);
|
||||
addonInfo.StatusId = (int)PackageStatus.Suspended;
|
||||
// suspend hosting addon
|
||||
int apiResult = PackageController.UpdatePackageAddon(addonInfo).Result;
|
||||
|
||||
// check WebsitePanel API result
|
||||
if (apiResult < 0)
|
||||
{
|
||||
result.ResultCode = apiResult;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_SUSPEND_ADDON_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// exit
|
||||
return result;
|
||||
}
|
||||
|
||||
UpdateSvcMetaInfo:
|
||||
// change addon status to Suspended
|
||||
addonSvc.Status = ServiceStatus.Suspended;
|
||||
// put data into metabase
|
||||
int svcResult = UpdateServiceInfo(addonSvc);
|
||||
//
|
||||
if (svcResult < 0)
|
||||
{
|
||||
result.ResultCode = svcResult;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_SVC_UPDATE_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(addonSvc.PackageAddonId);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
//
|
||||
SetOutboundParameters(context);
|
||||
// LOG INFO
|
||||
TaskManager.Write(ADDON_PROVISIONED_MSG);
|
||||
//
|
||||
result.Succeed = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
TaskManager.WriteError(ex);
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(addonSvc.PackageAddonId);
|
||||
|
||||
//
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.Error = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// complete task
|
||||
TaskManager.CompleteTask();
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
public GenericSvcResult CancelService(ProvisioningContext context)
|
||||
{
|
||||
GenericSvcResult result = new GenericSvcResult();
|
||||
//
|
||||
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
|
||||
// concretize service to be provisioned
|
||||
HostingAddonSvc addonSvc = (HostingAddonSvc)context.ServiceInfo;
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_CANCEL);
|
||||
// LOG INFO
|
||||
TaskManager.Write(START_CANCELLATION_MSG);
|
||||
TaskManager.WriteParameter(CONTRACT_PARAM, addonSvc.ContractId);
|
||||
TaskManager.WriteParameter(SVC_PARAM, addonSvc.ServiceName);
|
||||
TaskManager.WriteParameter(SVC_ID_PARAM, addonSvc.ServiceId);
|
||||
|
||||
// 0. Do security checks
|
||||
if (!CheckOperationClientPermissions(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
//
|
||||
if (!CheckOperationClientStatus(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
// dummy addon should be just updated in metabase
|
||||
if (addonSvc.DummyAddon)
|
||||
goto UpdateSvcMetaInfo;
|
||||
|
||||
PackageAddonInfo addonInfo = PackageController.GetPackageAddon(addonSvc.PackageAddonId);
|
||||
addonInfo.StatusId = (int)PackageStatus.Cancelled;
|
||||
// cancel hosting addon
|
||||
int apiResult = PackageController.UpdatePackageAddon(addonInfo).Result;
|
||||
|
||||
// check WebsitePanel API result
|
||||
if (apiResult < 0)
|
||||
{
|
||||
result.ResultCode = apiResult;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CANCEL_ADDON_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// exit
|
||||
return result;
|
||||
}
|
||||
|
||||
UpdateSvcMetaInfo:
|
||||
// change addon status to Cancelled
|
||||
addonSvc.Status = ServiceStatus.Cancelled;
|
||||
// put data into metabase
|
||||
int svcResult = UpdateServiceInfo(addonSvc);
|
||||
//
|
||||
if (svcResult < 0)
|
||||
{
|
||||
result.ResultCode = svcResult;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_SVC_UPDATE_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(addonSvc.PackageAddonId);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
//
|
||||
SetOutboundParameters(context);
|
||||
// LOG INFO
|
||||
TaskManager.Write(ADDON_PROVISIONED_MSG);
|
||||
//
|
||||
result.Succeed = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
TaskManager.WriteError(ex);
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(addonSvc.PackageAddonId);
|
||||
|
||||
//
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.Error = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// complete task
|
||||
TaskManager.CompleteTask();
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
public void LogServiceUsage(ProvisioningContext context)
|
||||
{
|
||||
// concretize service to be logged
|
||||
HostingAddonSvc addonSvc = (HostingAddonSvc)context.ServiceInfo;
|
||||
|
||||
// addon is recurring
|
||||
if (addonSvc.Recurring)
|
||||
{
|
||||
// log service usage
|
||||
base.LogServiceUsage(context.ServiceInfo, addonSvc.SvcCycleId,
|
||||
addonSvc.BillingPeriod, addonSvc.PeriodLength);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
protected void RollbackOperation(int packageAddonId)
|
||||
{
|
||||
// check input parameters first
|
||||
if (packageAddonId < 1)
|
||||
return; // exit
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
TaskManager.Write(START_ROLLBACK_MSG);
|
||||
// restore service
|
||||
HostingAddonSvc addonSvc = (HostingAddonSvc)RestoreObjectState(SERVICE_INFO);
|
||||
PackageAddonInfo addonInfo = PackageController.GetPackageAddon(addonSvc.PackageAddonId);
|
||||
//
|
||||
int apiResult = 0;
|
||||
|
||||
// during rollback addon should be reverted to its original state
|
||||
// compensation logic - revert back addon status
|
||||
switch (addonSvc.Status)
|
||||
{
|
||||
// Active State
|
||||
case ServiceStatus.Active:
|
||||
addonInfo.StatusId = (int)PackageStatus.Active;
|
||||
apiResult = PackageController.UpdatePackageAddon(addonInfo).Result;
|
||||
break;
|
||||
// Suspended State
|
||||
case ServiceStatus.Suspended:
|
||||
addonInfo.StatusId = (int)PackageStatus.Suspended;
|
||||
apiResult = PackageController.UpdatePackageAddon(addonInfo).Result;
|
||||
break;
|
||||
// Cancelled State
|
||||
case ServiceStatus.Cancelled:
|
||||
addonInfo.StatusId = (int)PackageStatus.Cancelled;
|
||||
apiResult = PackageController.UpdatePackageAddon(addonInfo).Result;
|
||||
break;
|
||||
// service has been just ordered & during rollback should be removed
|
||||
case ServiceStatus.Ordered:
|
||||
// compensation logic - remove created package
|
||||
apiResult = PackageController.DeletePackageAddon(packageAddonId);
|
||||
break;
|
||||
}
|
||||
// check WebsitePanel API result
|
||||
if (apiResult < 0)
|
||||
{
|
||||
//
|
||||
if (addonSvc.Status == ServiceStatus.Ordered)
|
||||
TaskManager.WriteError(ERROR_ROLLBACK_ORDER_MSG);
|
||||
else
|
||||
TaskManager.WriteError(ERROR_ROLLBACK_MSG);
|
||||
//
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, apiResult);
|
||||
}
|
||||
|
||||
// rollback service changes in EC metabase
|
||||
apiResult = UpdateServiceInfo(addonSvc);
|
||||
// check API result
|
||||
if (apiResult < 0)
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_ROLLBACK_SVC_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, apiResult);
|
||||
|
||||
//
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
TaskManager.Write(ROLLBACK_SUCCEED_MSG);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TaskManager.WriteError(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,676 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class HostingPackageController : ServiceProvisioningBase, IServiceProvisioning
|
||||
{
|
||||
//
|
||||
public const string SOURCE_NAME = "SPF_HOSTING_PKG";
|
||||
|
||||
#region Trace Messages
|
||||
|
||||
public const string START_ACTIVATION_MSG = "Starting package activation";
|
||||
public const string START_SUSPENSION_MSG = "Starting package suspension";
|
||||
public const string START_CANCELLATION_MSG = "Starting package cancellation";
|
||||
|
||||
public const string CREATE_PCKG_MSG = "Creating new hosting package";
|
||||
public const string CREATE_PCKG_ERROR_MSG = "Could not create hosting package";
|
||||
|
||||
public const string ERROR_ACTIVATE_PCKG_MSG = "Could not activate hosting package";
|
||||
public const string ERROR_SUSPEND_PCKG_MSG = "Could not suspend hosting package";
|
||||
public const string ERROR_CANCEL_PCKG_MSG = "Could not cancel hosting package";
|
||||
|
||||
public const string START_USR_ACTIVATION_MSG = "Activating service consumer account";
|
||||
public const string START_CHANGE_USR_ROLE_MSG = "Changing consumer user role";
|
||||
public const string ERROR_USR_ACTIVATION_MSG = "Could not activate consumer account";
|
||||
public const string ERROR_CHANGE_USR_ROLE_MSG = "Could not change consumer user role";
|
||||
|
||||
public const string PCKG_PROVISIONED_MSG = "Package has been provisioned";
|
||||
|
||||
#endregion
|
||||
|
||||
protected HostingPackageSvc GetHostingPackageSvc(int serviceId)
|
||||
{
|
||||
return ObjectUtils.FillObjectFromDataReader<HostingPackageSvc>(
|
||||
EcommerceProvider.GetHostingPackageSvc(SecurityContext.User.UserId, serviceId));
|
||||
}
|
||||
|
||||
protected InvoiceItem GetSetupFeeInvoiceLine(HostingPackageSvc service)
|
||||
{
|
||||
InvoiceItem line = new InvoiceItem();
|
||||
|
||||
line.ItemName = service.ServiceName;
|
||||
line.Quantity = 1;
|
||||
line.UnitPrice = service.SetupFee;
|
||||
line.TypeName = "Setup Fee";
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
protected InvoiceItem GetRecurringFeeInvoiceLine(HostingPackageSvc service)
|
||||
{
|
||||
InvoiceItem line = new InvoiceItem();
|
||||
|
||||
line.ItemName = service.ServiceName;
|
||||
line.ServiceId = service.ServiceId;
|
||||
line.Quantity = 1;
|
||||
line.UnitPrice = service.RecurringFee;
|
||||
line.TypeName = (service.Status == ServiceStatus.Ordered) ? Product.HOSTING_PLAN_NAME : "Recurring Fee";
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
#region IServiceProvisioning Members
|
||||
|
||||
public ServiceHistoryRecord[] GetServiceHistory(int serviceId)
|
||||
{
|
||||
List<ServiceHistoryRecord> history = ObjectUtils.CreateListFromDataReader<ServiceHistoryRecord>(
|
||||
EcommerceProvider.GetHostingPackageSvcHistory(SecurityContext.User.UserId, serviceId));
|
||||
|
||||
if (history != null)
|
||||
return history.ToArray();
|
||||
|
||||
return new ServiceHistoryRecord[] { };
|
||||
}
|
||||
|
||||
public InvoiceItem[] CalculateInvoiceLines(int serviceId)
|
||||
{
|
||||
List<InvoiceItem> lines = new List<InvoiceItem>();
|
||||
// load svc
|
||||
HostingPackageSvc packageSvc = GetHostingPackageSvc(serviceId);
|
||||
|
||||
// recurring fee
|
||||
lines.Add(GetRecurringFeeInvoiceLine(packageSvc));
|
||||
// setup fee
|
||||
if (packageSvc.Status == ServiceStatus.Ordered && packageSvc.SetupFee > 0M)
|
||||
lines.Add(GetSetupFeeInvoiceLine(packageSvc));
|
||||
|
||||
return lines.ToArray();
|
||||
}
|
||||
|
||||
public int AddServiceInfo(string contractId, string currency, OrderItem orderItem)
|
||||
{
|
||||
return EcommerceProvider.AddHostingPlanSvc(contractId, orderItem.ProductId,
|
||||
orderItem.ItemName, orderItem.BillingCycle, currency);
|
||||
}
|
||||
|
||||
public Service GetServiceInfo(int serviceId)
|
||||
{
|
||||
return GetHostingPackageSvc(serviceId);
|
||||
}
|
||||
|
||||
public int UpdateServiceInfo(Service service)
|
||||
{
|
||||
HostingPackageSvc packageSvc = (HostingPackageSvc)service;
|
||||
//
|
||||
return EcommerceProvider.UpdateHostingPlanSvc(SecurityContext.User.UserId, packageSvc.ServiceId,
|
||||
packageSvc.ProductId, packageSvc.ServiceName, (int)packageSvc.Status, packageSvc.PlanId,
|
||||
packageSvc.PackageId, (int)packageSvc.UserRole, (int)packageSvc.InitialStatus);
|
||||
}
|
||||
|
||||
public GenericSvcResult ActivateService(ProvisioningContext context)
|
||||
{
|
||||
GenericSvcResult result = new GenericSvcResult();
|
||||
|
||||
//
|
||||
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
|
||||
//
|
||||
SaveObjectState(CONSUMER_INFO, context.ConsumerInfo);
|
||||
|
||||
// concretize service to be provisioned
|
||||
HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo;
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_ACTIVATE);
|
||||
|
||||
// LOG INFO
|
||||
TaskManager.Write(START_ACTIVATION_MSG);
|
||||
TaskManager.WriteParameter(USERNAME_PARAM, context.ConsumerInfo[ContractAccount.USERNAME]);
|
||||
TaskManager.WriteParameter(SVC_PARAM, context.ServiceInfo.ServiceName);
|
||||
TaskManager.WriteParameter(SVC_ID_PARAM, context.ServiceInfo.ServiceId);
|
||||
TaskManager.TaskParameters[SystemTaskParams.PARAM_SEND_EMAIL] = context.SendEmail;
|
||||
|
||||
// 0. Do security checks
|
||||
if (!CheckOperationClientPermissions(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
//
|
||||
if (!CheckOperationClientStatus(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
// 1. Hosting package is just ordered
|
||||
if (context.ServiceInfo.Status == ServiceStatus.Ordered && context.ContractInfo.CustomerId > 0)
|
||||
{
|
||||
// LOG INFO
|
||||
TaskManager.Write(CREATE_PCKG_MSG);
|
||||
// create new package
|
||||
PackageResult apiResult = PackageController.AddPackage(context.ContractInfo.CustomerId, packageSvc.PlanId,
|
||||
packageSvc.ServiceName, String.Empty, (int)packageSvc.InitialStatus, DateTime.Now, true, true);
|
||||
|
||||
// failed to instantiate package
|
||||
if (apiResult.Result <= 0)
|
||||
{
|
||||
result.ResultCode = apiResult.Result;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(CREATE_PCKG_ERROR_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
// save result PackageId
|
||||
packageSvc.PackageId = apiResult.Result;
|
||||
}
|
||||
else // 2. Package requires only to update its status
|
||||
{
|
||||
// LOG INFO
|
||||
TaskManager.Write(START_ACTIVATION_MSG);
|
||||
|
||||
//
|
||||
int apiResult = PackageController.ChangePackageStatus(packageSvc.PackageId,
|
||||
PackageStatus.Active, false);
|
||||
//
|
||||
if (apiResult < 0)
|
||||
{
|
||||
result.ResultCode = apiResult;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_ACTIVATE_PCKG_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
}
|
||||
// check user role
|
||||
if (context.ContractInfo.CustomerId > 0)
|
||||
{
|
||||
UserInfo user = UserController.GetUserInternally(context.ContractInfo.CustomerId);
|
||||
// check user status
|
||||
//
|
||||
if (user.Status != UserStatus.Active)
|
||||
{
|
||||
// LOG INFO
|
||||
TaskManager.Write(START_USR_ACTIVATION_MSG);
|
||||
|
||||
// trying to change user status
|
||||
int userResult = UserController.ChangeUserStatus(context.ContractInfo.CustomerId,
|
||||
UserStatus.Active);
|
||||
// failed to activate user account
|
||||
if (userResult < 0)
|
||||
{
|
||||
result.ResultCode = userResult;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_USR_ACTIVATION_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
}
|
||||
// check user role
|
||||
if (user.Role != packageSvc.UserRole)
|
||||
{
|
||||
// LOG INFO
|
||||
TaskManager.Write(START_CHANGE_USR_ROLE_MSG);
|
||||
//
|
||||
user.Role = packageSvc.UserRole;
|
||||
// trying to change user role
|
||||
int roleResult = UserController.UpdateUser(user);
|
||||
// failed to change user role
|
||||
if (roleResult < 0)
|
||||
{
|
||||
result.ResultCode = roleResult;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
//
|
||||
TaskManager.WriteError(ERROR_CHANGE_USR_ROLE_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
// update plan status if necessary
|
||||
if (packageSvc.Status != ServiceStatus.Active)
|
||||
{
|
||||
// change service status to active
|
||||
packageSvc.Status = ServiceStatus.Active;
|
||||
// put data into metabase
|
||||
int svcResult = UpdateServiceInfo(packageSvc);
|
||||
|
||||
// error updating svc details
|
||||
if (svcResult < 0)
|
||||
{
|
||||
result.ResultCode = svcResult;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(packageSvc.PackageId);
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_SVC_UPDATE_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
}
|
||||
//
|
||||
SetOutboundParameters(context);
|
||||
// LOG INFO
|
||||
TaskManager.Write(PCKG_PROVISIONED_MSG);
|
||||
|
||||
//
|
||||
result.Succeed = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
TaskManager.WriteError(ex);
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(packageSvc.PackageId);
|
||||
|
||||
//
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.Error = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// complete task
|
||||
TaskManager.CompleteTask();
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
public GenericSvcResult SuspendService(ProvisioningContext context)
|
||||
{
|
||||
GenericSvcResult result = new GenericSvcResult();
|
||||
|
||||
//
|
||||
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
|
||||
//
|
||||
SaveObjectState(CONSUMER_INFO, context.ConsumerInfo);
|
||||
|
||||
// concretize service to be provisioned
|
||||
HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo;
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_SUSPEND);
|
||||
// LOG INFO
|
||||
TaskManager.Write(START_SUSPENSION_MSG);
|
||||
TaskManager.WriteParameter(CONTRACT_PARAM, context.ConsumerInfo[ContractAccount.USERNAME]);
|
||||
TaskManager.WriteParameter(SVC_PARAM, context.ServiceInfo.ServiceName);
|
||||
TaskManager.WriteParameter(SVC_ID_PARAM, context.ServiceInfo.ServiceId);
|
||||
|
||||
// 0. Do security checks
|
||||
if (!CheckOperationClientPermissions(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
//
|
||||
if (!CheckOperationClientStatus(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
// suspend hosting package
|
||||
int apiResult = PackageController.ChangePackageStatus(packageSvc.PackageId,
|
||||
PackageStatus.Suspended, false);
|
||||
|
||||
// check WebsitePanel API result
|
||||
if (apiResult < 0)
|
||||
{
|
||||
result.ResultCode = apiResult;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_SUSPEND_PCKG_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// exit
|
||||
return result;
|
||||
}
|
||||
|
||||
// change service status to Suspended
|
||||
packageSvc.Status = ServiceStatus.Suspended;
|
||||
// put data into metabase
|
||||
int svcResult = UpdateServiceInfo(packageSvc);
|
||||
|
||||
//
|
||||
if (svcResult < 0)
|
||||
{
|
||||
result.ResultCode = svcResult;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_SVC_UPDATE_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(packageSvc.PackageId);
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
//
|
||||
SetOutboundParameters(context);
|
||||
// LOG INFO
|
||||
TaskManager.Write(PCKG_PROVISIONED_MSG);
|
||||
//
|
||||
result.Succeed = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
TaskManager.WriteError(ex);
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(packageSvc.PackageId);
|
||||
|
||||
//
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.Error = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// complete task
|
||||
TaskManager.CompleteTask();
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
public GenericSvcResult CancelService(ProvisioningContext context)
|
||||
{
|
||||
GenericSvcResult result = new GenericSvcResult();
|
||||
|
||||
//
|
||||
SaveObjectState(SERVICE_INFO, context.ServiceInfo);
|
||||
//
|
||||
SaveObjectState(CONSUMER_INFO, context.ConsumerInfo);
|
||||
|
||||
// concretize service to be provisioned
|
||||
HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo;
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_CANCEL);
|
||||
// LOG INFO
|
||||
TaskManager.Write(START_CANCELLATION_MSG);
|
||||
TaskManager.WriteParameter(CONTRACT_PARAM, context.ConsumerInfo[ContractAccount.USERNAME]);
|
||||
TaskManager.WriteParameter(SVC_PARAM, context.ServiceInfo.ServiceName);
|
||||
TaskManager.WriteParameter(SVC_ID_PARAM, context.ServiceInfo.ServiceId);
|
||||
|
||||
// 0. Do security checks
|
||||
if (!CheckOperationClientPermissions(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
//
|
||||
if (!CheckOperationClientStatus(result))
|
||||
{
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
// cancel hosting package
|
||||
int apiResult = PackageController.ChangePackageStatus(packageSvc.PackageId,
|
||||
PackageStatus.Cancelled, false);
|
||||
|
||||
// check WebsitePanel API result
|
||||
if (apiResult < 0)
|
||||
{
|
||||
//
|
||||
result.ResultCode = apiResult;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(ERROR_CANCEL_PCKG_MSG);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
|
||||
// change service status to Cancelled
|
||||
packageSvc.Status = ServiceStatus.Cancelled;
|
||||
// put data into metabase
|
||||
int svcResult = UpdateServiceInfo(packageSvc);
|
||||
|
||||
//
|
||||
if (svcResult < 0)
|
||||
{
|
||||
result.ResultCode = svcResult;
|
||||
//
|
||||
result.Error = ERROR_SVC_UPDATE_MSG;
|
||||
//
|
||||
result.Succeed = false;
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(packageSvc.PackageId);
|
||||
|
||||
// LOG ERROR
|
||||
TaskManager.WriteError(result.Error);
|
||||
TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
|
||||
|
||||
// EXIT
|
||||
return result;
|
||||
}
|
||||
//
|
||||
SetOutboundParameters(context);
|
||||
// LOG INFO
|
||||
TaskManager.Write(PCKG_PROVISIONED_MSG);
|
||||
//
|
||||
result.Succeed = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
TaskManager.WriteError(ex);
|
||||
|
||||
// ROLLBACK CHANGES
|
||||
RollbackOperation(packageSvc.PackageId);
|
||||
|
||||
//
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.Error = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// complete task
|
||||
TaskManager.CompleteTask();
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
public void LogServiceUsage(ProvisioningContext context)
|
||||
{
|
||||
// concretize service to be logged
|
||||
HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo;
|
||||
|
||||
// log service usage
|
||||
base.LogServiceUsage(context.ServiceInfo, packageSvc.SvcCycleId,
|
||||
packageSvc.BillingPeriod, packageSvc.PeriodLength);
|
||||
}
|
||||
|
||||
protected void RollbackOperation(int packageId)
|
||||
{
|
||||
// check input parameters first
|
||||
if (packageId < 1)
|
||||
return; // exit
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
TaskManager.Write("Trying rollback operation");
|
||||
// restore service
|
||||
HostingPackageSvc packageSvc = (HostingPackageSvc)RestoreObjectState("ServiceInfo");
|
||||
// restore consumer
|
||||
UserInfo consumer = (UserInfo)RestoreObjectState("ConsumerInfo");
|
||||
|
||||
//
|
||||
int apiResult = 0;
|
||||
|
||||
// rollback consumer changes first
|
||||
apiResult = UserController.UpdateUser(consumer);
|
||||
// check WebsitePanel API result
|
||||
if (apiResult < 0)
|
||||
{
|
||||
//
|
||||
TaskManager.WriteError("Could not rollback consumer changes");
|
||||
//
|
||||
TaskManager.WriteParameter("ResultCode", apiResult);
|
||||
}
|
||||
|
||||
// during rollback package should be reverted to its original state
|
||||
// compensation logic - revert back package status
|
||||
switch (packageSvc.Status)
|
||||
{
|
||||
// Active State
|
||||
case ServiceStatus.Active:
|
||||
apiResult = PackageController.ChangePackageStatus(packageId, PackageStatus.Active, false);
|
||||
break;
|
||||
// Suspended State
|
||||
case ServiceStatus.Suspended:
|
||||
apiResult = PackageController.ChangePackageStatus(packageId, PackageStatus.Suspended, false);
|
||||
break;
|
||||
// Cancelled State
|
||||
case ServiceStatus.Cancelled:
|
||||
apiResult = PackageController.ChangePackageStatus(packageId, PackageStatus.Cancelled, false);
|
||||
break;
|
||||
// service has been just ordered & during rollback should be removed
|
||||
case ServiceStatus.Ordered:
|
||||
// compensation logic - remove created package
|
||||
apiResult = PackageController.DeletePackage(packageId);
|
||||
break;
|
||||
}
|
||||
// check WebsitePanel API result
|
||||
if (apiResult < 0)
|
||||
{
|
||||
//
|
||||
if (packageSvc.Status == ServiceStatus.Ordered)
|
||||
TaskManager.WriteError("Could not rollback operation and delete package");
|
||||
else
|
||||
TaskManager.WriteError("Could not rollback operation and revert package state");
|
||||
//
|
||||
TaskManager.WriteParameter("ResultCode", apiResult);
|
||||
}
|
||||
|
||||
// rollback service changes in EC metabase
|
||||
apiResult = UpdateServiceInfo(packageSvc);
|
||||
// check API result
|
||||
if (apiResult < 0)
|
||||
{
|
||||
//
|
||||
TaskManager.WriteError("Could not rollback service changes");
|
||||
//
|
||||
TaskManager.WriteParameter("ResultCode", apiResult);
|
||||
}
|
||||
|
||||
//
|
||||
TaskManager.Write("Rollback succeed");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TaskManager.WriteError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
using WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public interface IServiceProvisioning
|
||||
{
|
||||
ServiceHistoryRecord[] GetServiceHistory(int serviceId);
|
||||
InvoiceItem[] CalculateInvoiceLines(int serviceId);
|
||||
ProvisioningContext GetProvisioningContext(int serviceId, bool sendEmail);
|
||||
int AddServiceInfo(string contractId, string currency, OrderItem orderItem);
|
||||
int UpdateServiceInfo(Service serviceInfo);
|
||||
Service GetServiceInfo(int serviceId);
|
||||
GenericSvcResult ActivateService(ProvisioningContext context);
|
||||
GenericSvcResult SuspendService(ProvisioningContext context);
|
||||
GenericSvcResult CancelService(ProvisioningContext context);
|
||||
void LogServiceUsage(ProvisioningContext context);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Configuration;
|
||||
using System.Web;
|
||||
using System.Web.Security;
|
||||
using System.Web.UI;
|
||||
using System.Web.UI.WebControls;
|
||||
using System.Web.UI.WebControls.WebParts;
|
||||
using System.Web.UI.HtmlControls;
|
||||
|
||||
using WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents context for provisioning controllers
|
||||
/// </summary>
|
||||
public class ProvisioningContext
|
||||
{
|
||||
private Contract contractInfo;
|
||||
private ContractAccount consumerInfo;
|
||||
private Service serviceInfo;
|
||||
private Service parentSvcInfo;
|
||||
private bool sendEmail;
|
||||
|
||||
public bool SendEmail
|
||||
{
|
||||
get { return sendEmail; }
|
||||
set { sendEmail = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets service consumer contract information
|
||||
/// </summary>
|
||||
public Contract ContractInfo
|
||||
{
|
||||
get { return contractInfo; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets service consumer information
|
||||
/// </summary>
|
||||
public ContractAccount ConsumerInfo
|
||||
{
|
||||
get { return consumerInfo; }
|
||||
}
|
||||
/// <summary>
|
||||
/// Get service information
|
||||
/// </summary>
|
||||
public Service ServiceInfo
|
||||
{
|
||||
get { return serviceInfo; }
|
||||
}
|
||||
/// <summary>
|
||||
/// Get parent service information
|
||||
/// </summary>
|
||||
public Service ParentSvcInfo
|
||||
{
|
||||
get { return parentSvcInfo; }
|
||||
}
|
||||
/// <summary>
|
||||
/// Ctor.
|
||||
/// </summary>
|
||||
/// <param name="service"></param>
|
||||
/// <param name="consumer"></param>
|
||||
public ProvisioningContext(Contract contract, Service service, ContractAccount consumer, Service parentSvc)
|
||||
{
|
||||
this.contractInfo = contract;
|
||||
this.serviceInfo = service;
|
||||
this.consumerInfo = consumer;
|
||||
this.parentSvcInfo = parentSvc;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,362 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Text;
|
||||
|
||||
using WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class Memento
|
||||
{
|
||||
private string mStateObjectType;
|
||||
private Hashtable mementoState;
|
||||
|
||||
public Memento()
|
||||
{
|
||||
//
|
||||
mementoState = new Hashtable();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves object public properties state using reflection. Does not support indexed properties.
|
||||
/// </summary>
|
||||
/// <param name="objectKey"></param>
|
||||
/// <param name="value"></param>
|
||||
public void SaveObjectState(object value)
|
||||
{
|
||||
//
|
||||
Type valueType = value.GetType();
|
||||
//
|
||||
PropertyInfo[] properties = valueType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
|
||||
//
|
||||
if (properties != null && properties.Length > 0)
|
||||
{
|
||||
//
|
||||
Hashtable stateHash = new Hashtable();
|
||||
//
|
||||
foreach (PropertyInfo property in properties)
|
||||
{
|
||||
// copy property value
|
||||
if (property.GetIndexParameters() == null || property.GetIndexParameters().Length == 0)
|
||||
mementoState.Add(property.Name, property.GetValue(value, null));
|
||||
}
|
||||
// save object full-qualified name
|
||||
mStateObjectType = valueType.AssemblyQualifiedName;
|
||||
}
|
||||
}
|
||||
|
||||
public object RestoreObjectState()
|
||||
{
|
||||
// create object instance
|
||||
object keyObject = Activator.CreateInstance(Type.GetType(mStateObjectType));
|
||||
//
|
||||
Type objectType = keyObject.GetType();
|
||||
//
|
||||
PropertyInfo[] properties = objectType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
|
||||
//
|
||||
if (properties != null && properties.Length > 0)
|
||||
{
|
||||
// load object state back
|
||||
foreach (PropertyInfo property in properties)
|
||||
{
|
||||
// restore property value back
|
||||
if (property.GetIndexParameters() == null || property.GetIndexParameters().Length == 0)
|
||||
property.SetValue(keyObject, mementoState[property.Name], null);
|
||||
}
|
||||
}
|
||||
//
|
||||
return keyObject;
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class ServiceProvisioningBase
|
||||
{
|
||||
// Contants
|
||||
public const string SERVICE_INFO = "ServiceInfo";
|
||||
public const string CONSUMER_INFO = "ConsumerInfo";
|
||||
|
||||
#region Error Messages
|
||||
|
||||
public const string ERROR_SVC_UPDATE_MSG = "Could not update service data";
|
||||
public const string PARENT_SVC_NOT_FOUND_MSG = "Could not find parent service assigned";
|
||||
public const string ERROR_ROLLBACK_SVC_MSG = "Could not rollback service changes";
|
||||
public const string ERROR_CLIENT_OPERATION_PERMISSIONS = "Account does not have enough permissions to do this operation";
|
||||
public const string ERROR_CLIENT_OPERATION_STATUS = "Account is demo or suspended and not allowed to do this operation";
|
||||
|
||||
#endregion
|
||||
|
||||
#region Trace Messages
|
||||
|
||||
public const string ROLLBACK_SUCCEED_MSG = "Rollback succeed";
|
||||
|
||||
#endregion
|
||||
|
||||
#region Trace Parameters
|
||||
|
||||
public const string CONTRACT_PARAM = "ContractID";
|
||||
public const string USERNAME_PARAM = "Username";
|
||||
public const string SVC_PARAM = "Service";
|
||||
public const string SVC_ID_PARAM = "ServiceID";
|
||||
public const string RESULT_CODE_PARAM = "ResultCode";
|
||||
public const string PCKG_PARAM = "Package";
|
||||
public const string PCKG_ID_PARAM = "PackageID";
|
||||
|
||||
#endregion
|
||||
|
||||
public bool CheckOperationClientPermissions(GenericSvcResult result)
|
||||
{
|
||||
// 1. Do security checks
|
||||
SecurityResult secResult = StorehouseController.CheckAccountIsAdminOrReseller();
|
||||
// ERROR
|
||||
if (!secResult.Success)
|
||||
{
|
||||
result.Succeed = false;
|
||||
result.ResultCode = secResult.ResultCode;
|
||||
//
|
||||
return false;
|
||||
}
|
||||
//
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool CheckOperationClientStatus(GenericSvcResult result)
|
||||
{
|
||||
// 2. Check account status
|
||||
SecurityResult secResult = StorehouseController.CheckAccountNotDemoAndActive();
|
||||
// ERROR
|
||||
if (!secResult.Success)
|
||||
{
|
||||
result.Succeed = false;
|
||||
result.ResultCode = secResult.ResultCode;
|
||||
//
|
||||
return false;
|
||||
}
|
||||
//
|
||||
return true;
|
||||
}
|
||||
|
||||
public ProvisioningContext GetProvisioningContext(int serviceId, bool sendEmail)
|
||||
{
|
||||
IServiceProvisioning controller = (IServiceProvisioning)this;
|
||||
Service serviceInfo = controller.GetServiceInfo(serviceId);
|
||||
Contract contractInfo = ContractSystem.ContractController.GetContract(serviceInfo.ContractId);
|
||||
ContractAccount consumerInfo = ContractSystem.ContractController.GetContractAccountSettings(
|
||||
serviceInfo.ContractId, true);
|
||||
// load parent svc
|
||||
Service parentSvcInfo = (serviceInfo.ParentId == 0) ? null :
|
||||
ServiceController.GetService(serviceInfo.ParentId);
|
||||
// return prepeared context
|
||||
ProvisioningContext ctx = new ProvisioningContext(contractInfo, serviceInfo, consumerInfo, parentSvcInfo);
|
||||
//
|
||||
ctx.SendEmail = sendEmail;
|
||||
//
|
||||
return ctx;
|
||||
}
|
||||
|
||||
//
|
||||
private Dictionary<string, Memento> undoSteps = new Dictionary<string, Memento>();
|
||||
|
||||
protected void SaveObjectState(string objectKey, object value)
|
||||
{
|
||||
//
|
||||
Memento memento = new Memento();
|
||||
//
|
||||
memento.SaveObjectState(value);
|
||||
//
|
||||
undoSteps.Add(objectKey, memento);
|
||||
}
|
||||
|
||||
protected object RestoreObjectState(string objectKey)
|
||||
{
|
||||
//
|
||||
if (!undoSteps.ContainsKey(objectKey))
|
||||
return null;
|
||||
//
|
||||
Memento memento = undoSteps[objectKey];
|
||||
//
|
||||
return memento.RestoreObjectState();
|
||||
}
|
||||
|
||||
protected void LogServiceUsage(Service service, int svcCycleId, string billingPeriod, int periodLength)
|
||||
{
|
||||
// define start date
|
||||
DateTime startDate = ServiceController.GetServiceSuspendDate(service.ServiceId);
|
||||
//
|
||||
DateTime endDate = startDate;
|
||||
//
|
||||
switch (billingPeriod)
|
||||
{
|
||||
case "day":
|
||||
endDate = startDate.AddDays(periodLength);
|
||||
break;
|
||||
case "month":
|
||||
endDate = endDate.AddMonths(periodLength);
|
||||
break;
|
||||
case "year":
|
||||
endDate = endDate.AddYears(periodLength);
|
||||
break;
|
||||
}
|
||||
// add service usage record
|
||||
EcommerceProvider.AddServiceUsageRecord(SecurityContext.User.UserId, service.ServiceId,
|
||||
svcCycleId, startDate, endDate);
|
||||
}
|
||||
|
||||
protected void SetOutboundParameters(ProvisioningContext context)
|
||||
{
|
||||
// set task outbound parameters
|
||||
TaskManager.TaskParameters[SystemTaskParams.PARAM_SERVICE] = context.ServiceInfo;
|
||||
TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT] = context.ContractInfo;
|
||||
TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT_ACCOUNT] = context.ConsumerInfo;
|
||||
TaskManager.TaskParameters[SystemTaskParams.PARAM_SEND_EMAIL] = context.SendEmail;
|
||||
}
|
||||
}
|
||||
|
||||
/*public abstract class ProvisioningController
|
||||
{
|
||||
// user info (context)
|
||||
// product general info
|
||||
// cart prov settings
|
||||
// product prov settings
|
||||
// product type prov settings
|
||||
//
|
||||
#region Private vars
|
||||
|
||||
private string notificationTemplate;
|
||||
private bool notificationLoaded;
|
||||
|
||||
private UserInfo userInfo;
|
||||
private Service serviceInfo;
|
||||
private KeyValueBunch serviceSettings;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public properties
|
||||
|
||||
public string NotificationTemplate
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!notificationLoaded)
|
||||
|
||||
return notificationTemplate;
|
||||
}
|
||||
}
|
||||
|
||||
public UserInfo UserInfo
|
||||
{
|
||||
get { return userInfo; }
|
||||
}
|
||||
|
||||
public Service ServiceInfo
|
||||
{
|
||||
get { return serviceInfo; }
|
||||
}
|
||||
|
||||
public KeyValueBunch ServiceSettings
|
||||
{
|
||||
get { return serviceSettings; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Abstract routines
|
||||
|
||||
//
|
||||
public abstract GenericSvcResult ActivateService(Service service);
|
||||
//
|
||||
public abstract GenericSvcResult SuspendService();
|
||||
//
|
||||
public abstract GenericSvcResult CancelService();
|
||||
//
|
||||
public abstract void RollbackOperation();
|
||||
|
||||
#endregion
|
||||
|
||||
protected ProvisioningController(Service serviceInfo)
|
||||
{
|
||||
this.serviceInfo = serviceInfo;
|
||||
|
||||
Initialize();
|
||||
}
|
||||
|
||||
protected virtual void Initialize()
|
||||
{
|
||||
// get user profile
|
||||
userInfo = UserController.GetUser(serviceInfo.UserId);
|
||||
}
|
||||
|
||||
protected DateTime CalculateNextSuspendDate(DateTime startDate, string cyclePeriod, int cycleLength)
|
||||
{
|
||||
// calculate next suspend date
|
||||
switch (cyclePeriod)
|
||||
{
|
||||
case "day":
|
||||
return startDate.AddDays(cycleLength);
|
||||
|
||||
case "month":
|
||||
return startDate.AddMonths(cycleLength);
|
||||
|
||||
case "year":
|
||||
return startDate.AddYears(cycleLength);
|
||||
}
|
||||
//
|
||||
return startDate;
|
||||
}
|
||||
|
||||
public virtual void LoadProvisioningSettings()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
// get service settings
|
||||
/*serviceSettings = ServiceController.GetServiceSettings(
|
||||
serviceInfo.SpaceId,
|
||||
serviceInfo.ServiceId
|
||||
);*/
|
||||
/*}
|
||||
|
||||
public virtual void SaveProvisioningSettings()
|
||||
{
|
||||
if (ServiceSettings.HasPendingChanges)
|
||||
{
|
||||
/*int result = ServiceController.SetServiceSettings(
|
||||
serviceInfo.SpaceId,
|
||||
serviceInfo.ServiceId,
|
||||
serviceSettings
|
||||
);
|
||||
|
||||
if (result < 0)
|
||||
throw new Exception("Unable to save provisioning settings. Status code: " + result);*/
|
||||
/*}
|
||||
}
|
||||
}*/
|
||||
}
|
|
@ -0,0 +1,304 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Xml;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
|
||||
using ES = WebsitePanel.EnterpriseServer;
|
||||
using Common.Utils;
|
||||
using Microsoft.ApplicationBlocks.Data;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class ServiceController
|
||||
{
|
||||
private ServiceController()
|
||||
{
|
||||
}
|
||||
|
||||
public static int SetUsageRecordsClosed(int[] serviceIds)
|
||||
{
|
||||
return EcommerceProvider.SetSvcsUsageRecordsClosed(
|
||||
ES.SecurityContext.User.UserId, serviceIds);
|
||||
}
|
||||
|
||||
#region Ecommerce v 2.1.0 routines
|
||||
|
||||
public static DateTime GetSvcsSuspendDateAligned(int[] services, DateTime defaultValue)
|
||||
{
|
||||
string svcsXml = Utils.BuildIdentityXmlFromArray(services, "Svcs", "Svc");
|
||||
return EcommerceProvider.GetSvcsSuspendDateAligned(ES.SecurityContext.User.UserId,
|
||||
svcsXml, defaultValue);
|
||||
}
|
||||
|
||||
public static int ChangeHostingPlanSvcCycle(int serviceId, int productId, int cycleId, string currency)
|
||||
{
|
||||
return EcommerceProvider.ChangeHostingPlanSvcCycle(ES.SecurityContext.User.UserId, serviceId,
|
||||
productId, cycleId, currency);
|
||||
}
|
||||
|
||||
public static ProductType GetServiceItemType(int serviceId)
|
||||
{
|
||||
return ES.ObjectUtils.FillObjectFromDataReader<ProductType>(
|
||||
EcommerceProvider.GetServiceItemType(serviceId));
|
||||
}
|
||||
|
||||
public static Service GetRawCustomerService(int serviceId)
|
||||
{
|
||||
return ES.ObjectUtils.FillObjectFromDataReader<Service>(
|
||||
EcommerceProvider.GetCustomerService(ES.SecurityContext.User.UserId, serviceId));
|
||||
}
|
||||
|
||||
public static Service GetService(int serviceId)
|
||||
{
|
||||
// read service type
|
||||
ProductType svcType = GetServiceItemType(serviceId);
|
||||
// create svc controller
|
||||
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
|
||||
Type.GetType(svcType.ProvisioningController));
|
||||
//
|
||||
return controller.GetServiceInfo(serviceId);
|
||||
}
|
||||
|
||||
public static Dictionary<int, Service> GetServicesDictionary(List<InvoiceItem> invoiceLines)
|
||||
{
|
||||
List<int> serviceIds = new List<int>();
|
||||
//
|
||||
foreach (InvoiceItem invoiceLine in Array.FindAll<InvoiceItem>(
|
||||
invoiceLines.ToArray(), x => x.ServiceId > 0))
|
||||
{
|
||||
serviceIds.Add(invoiceLine.ServiceId);
|
||||
}
|
||||
//
|
||||
return GetServicesDictionary(serviceIds);
|
||||
}
|
||||
|
||||
public static Dictionary<int, Service> GetServicesDictionary(List<int> serviceIds)
|
||||
{
|
||||
Dictionary<int, Service> hash = new Dictionary<int, Service>();
|
||||
//
|
||||
foreach (int serviceId in serviceIds)
|
||||
hash.Add(serviceId, GetService(serviceId));
|
||||
//
|
||||
return hash;
|
||||
}
|
||||
|
||||
public static int UpdateService(Service service)
|
||||
{
|
||||
// read service type
|
||||
ProductType svcType = GetServiceItemType(service.ServiceId);
|
||||
// create svc controller
|
||||
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
|
||||
Type.GetType(svcType.ProvisioningController));
|
||||
//
|
||||
return controller.UpdateServiceInfo(service);
|
||||
}
|
||||
|
||||
public static void AddServiceUsageRecord(int serviceId)
|
||||
{
|
||||
// read service type
|
||||
ProductType svcType = GetServiceItemType(serviceId);
|
||||
// create svc controller
|
||||
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
|
||||
Type.GetType(svcType.ProvisioningController));
|
||||
//
|
||||
controller.LogServiceUsage(controller.GetProvisioningContext(serviceId, false));
|
||||
}
|
||||
|
||||
public static ServiceHistoryRecord[] GetServiceHistory(int serviceId)
|
||||
{
|
||||
// read service type
|
||||
ProductType svcType = GetServiceItemType(serviceId);
|
||||
// create svc controller
|
||||
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
|
||||
Type.GetType(svcType.ProvisioningController));
|
||||
//
|
||||
return controller.GetServiceHistory(serviceId);
|
||||
}
|
||||
|
||||
public static GenericSvcResult ActivateService(int serviceId, bool sendEmail)
|
||||
{
|
||||
GenericSvcResult result = new GenericSvcResult();
|
||||
|
||||
try
|
||||
{
|
||||
Service svc = GetRawCustomerService(serviceId);
|
||||
//
|
||||
ES.TaskManager.StartTask(SystemTasks.SOURCE_SPF, SystemTasks.SVC_ACTIVATE);
|
||||
ES.TaskManager.WriteParameter("Service", svc.ServiceName);
|
||||
//
|
||||
ActivatePaidInvoicesTask task = new ActivatePaidInvoicesTask();
|
||||
// obtain result
|
||||
result = task.ActivateService(serviceId, sendEmail, false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ES.TaskManager.WriteError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ES.TaskManager.CompleteTask();
|
||||
}
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<GenericSvcResult> ActivateInvoice(int invoiceId, bool sendEmail)
|
||||
{
|
||||
List<GenericSvcResult> results = new List<GenericSvcResult>();
|
||||
|
||||
try
|
||||
{
|
||||
Invoice invoice = InvoiceController.GetCustomerInvoiceInternally(invoiceId);
|
||||
//
|
||||
ES.TaskManager.StartTask("SPF", "ACTIVATE_INVOICE");
|
||||
ES.TaskManager.WriteParameter("InvoiceID", invoiceId);
|
||||
//
|
||||
ActivatePaidInvoicesTask task = new ActivatePaidInvoicesTask();
|
||||
// load invoice lines
|
||||
List<InvoiceItem> lines = InvoiceController.GetCustomerInvoiceItems(invoiceId);
|
||||
// iterate and activate
|
||||
foreach (InvoiceItem line in lines)
|
||||
{
|
||||
if (!line.Processed && line.ServiceId > 0)
|
||||
results.Add(task.ActivateInvoiceItem(line));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ES.TaskManager.WriteError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ES.TaskManager.CompleteTask();
|
||||
}
|
||||
//
|
||||
return results;
|
||||
}
|
||||
|
||||
public static GenericSvcResult SuspendService(int serviceId, bool sendEmail)
|
||||
{
|
||||
GenericSvcResult result = new GenericSvcResult();
|
||||
|
||||
try
|
||||
{
|
||||
Service svc = GetRawCustomerService(serviceId);
|
||||
//
|
||||
ES.TaskManager.StartTask(SystemTasks.SOURCE_SPF, SystemTasks.SVC_SUSPEND);
|
||||
ES.TaskManager.WriteParameter("Service", svc.ServiceName);
|
||||
//
|
||||
SuspendOverdueInvoicesTask task = new SuspendOverdueInvoicesTask();
|
||||
// obtain result
|
||||
result = task.SuspendService(serviceId, sendEmail);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ES.TaskManager.WriteError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ES.TaskManager.CompleteTask();
|
||||
}
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
public static GenericSvcResult CancelService(int serviceId, bool sendEmail)
|
||||
{
|
||||
GenericSvcResult result = new GenericSvcResult();
|
||||
|
||||
try
|
||||
{
|
||||
Service svc = GetRawCustomerService(serviceId);
|
||||
//
|
||||
ES.TaskManager.StartTask(SystemTasks.SOURCE_SPF, SystemTasks.SVC_CANCEL);
|
||||
ES.TaskManager.WriteParameter("Service", svc.ServiceName);
|
||||
//
|
||||
CancelOverdueInvoicesTask task = new CancelOverdueInvoicesTask();
|
||||
// obtain result
|
||||
result = task.CancelService(serviceId, sendEmail);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ES.TaskManager.WriteError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ES.TaskManager.CompleteTask();
|
||||
}
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public static DateTime GetServiceSuspendDate(int serviceId)
|
||||
{
|
||||
// get service suspend date
|
||||
DateTime date = EcommerceProvider.GetServiceSuspendDate(ES.SecurityContext.User.UserId, serviceId);
|
||||
|
||||
// check returned result
|
||||
if (date == DateTime.MinValue)
|
||||
date = DateTime.UtcNow;
|
||||
|
||||
// return service suspend date
|
||||
return date;
|
||||
}
|
||||
|
||||
public static List<Service> GetServicesToInvoice(int resellerId, DateTime todayDate, int daysOffset)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<Service>(EcommerceProvider.GetServicesToInvoice(
|
||||
ES.SecurityContext.User.UserId, resellerId, todayDate,daysOffset));
|
||||
}
|
||||
|
||||
public static int GetCustomersServicesCount(int userId, bool isReseller)
|
||||
{
|
||||
return EcommerceProvider.GetCustomersServicesCount(ES.SecurityContext.User.UserId, userId, isReseller);
|
||||
}
|
||||
|
||||
public static List<Service> GetCustomersServicesPaged(int userId, bool isReseller,
|
||||
int maximumRows, int startRowIndex)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<Service>(EcommerceProvider.GetCustomersServicesPaged(
|
||||
ES.SecurityContext.User.UserId, userId, isReseller, maximumRows, startRowIndex));
|
||||
}
|
||||
|
||||
public static int DeleteCustomerService(int serviceId)
|
||||
{
|
||||
SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();
|
||||
//
|
||||
if (!result.Success)
|
||||
return result.ResultCode;
|
||||
//
|
||||
return EcommerceProvider.DeleteCustomerService(ES.SecurityContext.User.UserId, serviceId);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
|
||||
using ES = WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class ServiceHandlerController
|
||||
{
|
||||
public static void AddServiceHandlerTextResponse(string serviceId, string contractId, int invoiceId, string dataReceived)
|
||||
{
|
||||
EcommerceProvider.AddServiceHandlerTextResponse(serviceId, contractId, invoiceId, dataReceived);
|
||||
}
|
||||
|
||||
public static void UpdateServiceHandlersResponses(int resellerId, string xmlData)
|
||||
{
|
||||
EcommerceProvider.UpdateServiceHandlersResponses(resellerId, xmlData);
|
||||
}
|
||||
|
||||
internal static List<HandlerResponse> GetServiceHandlersResponsesByReseller(int resellerId)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<HandlerResponse>(
|
||||
EcommerceProvider.GetServiceHandlersResponsesByReseller(resellerId));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,373 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
|
||||
using ES = WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public sealed class StorefrontController
|
||||
{
|
||||
public const int EMPTY_ORDER_ITEMS_CODE = -15;
|
||||
|
||||
private StorefrontController()
|
||||
{
|
||||
}
|
||||
|
||||
public static string GetContractInvoiceFormatted(string contractId, int invoiceId, string cultureName)
|
||||
{
|
||||
//
|
||||
ContractSystem.ContractController.ImpersonateAsContractReseller(contractId);
|
||||
//
|
||||
return InvoiceController.GetCustomerInvoiceFormattedInternally(contractId, invoiceId, cultureName);
|
||||
}
|
||||
|
||||
#region Ecommerce v 2.1.0 routines
|
||||
|
||||
public static TopLevelDomain GetResellerTopLevelDomain(int resellerId, string tld)
|
||||
{
|
||||
return ES.ObjectUtils.FillObjectFromDataReader<TopLevelDomain>(
|
||||
EcommerceProvider.GetResellerTopLevelDomain(resellerId, tld));
|
||||
}
|
||||
|
||||
public static List<Product> GetStorefrontProductsByType(int resellerId, int typeId)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<Product>(
|
||||
EcommerceProvider.GetStorefrontProductsByType(resellerId, typeId)
|
||||
);
|
||||
}
|
||||
|
||||
public static Product GetStorefrontProduct(int resellerId, int productId)
|
||||
{
|
||||
return ES.ObjectUtils.FillObjectFromDataReader<Product>(
|
||||
EcommerceProvider.GetStorefrontProduct(resellerId, productId));
|
||||
}
|
||||
|
||||
public static List<HostingAddon> GetHostingPlanAddons(int resellerId, int planId)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<HostingAddon>(
|
||||
EcommerceProvider.GetStorefrontHostingPlanAddons(resellerId, planId));
|
||||
}
|
||||
|
||||
public static OrderResult SubmitCustomerOrder(string contractId, OrderItem[] orderItems, KeyValueBunch extraArgs)
|
||||
{
|
||||
//
|
||||
Contract contract = ContractSystem.ContractController.GetContract(contractId);
|
||||
// Impersonate
|
||||
ContractSystem.ContractController.ImpersonateAsContractReseller(contract);
|
||||
//
|
||||
OrderResult oResult = new OrderResult();
|
||||
// check account
|
||||
SecurityResult sResult = StorehouseController.CheckAccountActive();
|
||||
//
|
||||
if (!sResult.Success)
|
||||
{
|
||||
//
|
||||
oResult.Succeed = false;
|
||||
//
|
||||
oResult.ResultCode = sResult.ResultCode;
|
||||
//
|
||||
return oResult;
|
||||
}
|
||||
// check order items not empty
|
||||
if (orderItems == null || orderItems.Length == 0)
|
||||
{
|
||||
//
|
||||
oResult.Succeed = false;
|
||||
//
|
||||
oResult.ResultCode = EMPTY_ORDER_ITEMS_CODE;
|
||||
//
|
||||
return oResult;
|
||||
}
|
||||
//
|
||||
ES.TaskManager.StartTask("Storefront", "SUBMIT_CUSTOMER_ORDER");
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
string currency = StorehouseController.GetBaseCurrency(contract.ResellerId);
|
||||
// ordered services
|
||||
List<int> orderedSvcs = new List<int>();
|
||||
// build services to be ordered
|
||||
for (int i = 0; i < orderItems.Length; i++)
|
||||
{
|
||||
//
|
||||
OrderItem orderItem = orderItems[i];
|
||||
//
|
||||
int orderedSvcId = 0;
|
||||
//
|
||||
orderItem.ParentSvcId = (orderItem.ParentIndex > -1) ? orderedSvcs[orderItem.ParentIndex] : orderItem.ParentSvcId;
|
||||
// load svc type
|
||||
ProductType svcType = StorehouseController.GetProductType(orderItem.TypeId);
|
||||
//
|
||||
IServiceProvisioning controller = (IServiceProvisioning)Activator.CreateInstance(
|
||||
Type.GetType(svcType.ProvisioningController));
|
||||
// add service
|
||||
orderedSvcId = controller.AddServiceInfo(contractId, currency, orderItem);
|
||||
// check service controller result
|
||||
if (orderedSvcId < 1)
|
||||
{
|
||||
// ROLLBACK HERE
|
||||
StorehouseController.BulkServiceDelete(contractId, orderedSvcs.ToArray());
|
||||
oResult.Succeed = false;
|
||||
oResult.ResultCode = orderedSvcId;
|
||||
return oResult;
|
||||
// EXIT
|
||||
}
|
||||
//
|
||||
orderedSvcs.Add(orderedSvcId);
|
||||
}
|
||||
// build invoice lines
|
||||
List<InvoiceItem> invoiceLines = InvoiceController.CalculateInvoiceLinesForServices(orderedSvcs);
|
||||
//
|
||||
int resultCode = InvoiceController.AddInvoice(contractId, invoiceLines, extraArgs);
|
||||
// ERROR
|
||||
if (resultCode < 1)
|
||||
{
|
||||
// ROLLBACK HERE
|
||||
StorehouseController.BulkServiceDelete(contractId, orderedSvcs.ToArray());
|
||||
oResult.Succeed = false;
|
||||
oResult.ResultCode = resultCode;
|
||||
return oResult;
|
||||
}
|
||||
//
|
||||
oResult.OrderInvoice = resultCode;
|
||||
//
|
||||
oResult.Succeed = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
oResult.ResultCode = -1;
|
||||
//
|
||||
oResult.Succeed = false;
|
||||
//
|
||||
ES.TaskManager.WriteError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
//
|
||||
ES.TaskManager.CompleteTask();
|
||||
}
|
||||
//
|
||||
return oResult;
|
||||
}
|
||||
|
||||
public static List<PaymentMethod> GetResellerPaymentMethods(int resellerId)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<PaymentMethod>(
|
||||
EcommerceProvider.GetResellerPaymentMethods(resellerId));
|
||||
}
|
||||
|
||||
public static PaymentMethod GetContractPaymentMethod(string contractId, string methodName)
|
||||
{
|
||||
Contract contract = ContractSystem.ContractController.GetContract(contractId);
|
||||
|
||||
return ES.ObjectUtils.FillObjectFromDataReader<PaymentMethod>(
|
||||
EcommerceProvider.GetResellerPaymentMethod(contract.ResellerId, methodName));
|
||||
}
|
||||
|
||||
public static ES.UserInfo GetCustomerProfile(int resellerId, int userId, string sessionId)
|
||||
{
|
||||
//
|
||||
ES.SecurityContext.SetThreadPrincipal(resellerId);
|
||||
//
|
||||
return ES.UserController.GetUser(userId);
|
||||
}
|
||||
|
||||
public static string GetCustomerInvoiceFormatted(int resellerId, int userId, int invoiceId, string sessionId)
|
||||
{
|
||||
return null;// InvoiceController.GetCustomerInvoiceFormattedInternally(resellerId, userId, invoiceId);
|
||||
}
|
||||
|
||||
public static Invoice GetCustomerInvoice(int resellerId, int userId, int invoiceId, string sessionId)
|
||||
{
|
||||
return InvoiceController.GetCustomerInvoiceInternally(invoiceId);
|
||||
}
|
||||
|
||||
public static CheckoutResult CompleteCheckout(string contractId, int invoiceId,
|
||||
string methodName, CheckoutDetails details)
|
||||
{
|
||||
//
|
||||
return PaymentGatewayController.CheckOut(contractId, invoiceId, methodName, details);
|
||||
}
|
||||
|
||||
public static KeyValueBunch GetHostingPlansQuotas(int resellerId, int planId)
|
||||
{
|
||||
KeyValueBunch hpQuotas = new KeyValueBunch();
|
||||
//
|
||||
ES.SecurityContext.SetThreadPrincipal(resellerId);
|
||||
//
|
||||
ES.HostingPlanContext ctx = ES.PackageController.GetHostingPlanContext(planId);
|
||||
//
|
||||
if (ctx != null)
|
||||
{
|
||||
//
|
||||
ES.QuotaValueInfo[] quotasArray = ctx.QuotasArray;
|
||||
//
|
||||
for (int i = 0; i < ctx.GroupsArray.Length; i++)
|
||||
{
|
||||
//
|
||||
ES.HostingPlanGroupInfo group = ctx.GroupsArray[i];
|
||||
//
|
||||
if (group.Enabled)
|
||||
{
|
||||
//
|
||||
List<string> planQuota = new List<string>();
|
||||
//
|
||||
foreach (ES.QuotaValueInfo quota in quotasArray)
|
||||
{
|
||||
//
|
||||
if (quota.QuotaName.StartsWith(group.GroupName))
|
||||
{
|
||||
// boolean quota
|
||||
if (quota.QuotaTypeId == 1)
|
||||
{
|
||||
// only enabled quotas will be displayed
|
||||
if (quota.QuotaAllocatedValue == 1)
|
||||
planQuota.Add(quota.QuotaName + "=Enabled");
|
||||
}
|
||||
// numeric
|
||||
else
|
||||
{
|
||||
if (quota.QuotaAllocatedValue > 0)
|
||||
planQuota.Add(quota.QuotaName + "=" + quota.QuotaAllocatedValue);
|
||||
else if (quota.QuotaAllocatedValue == -1)
|
||||
planQuota.Add(quota.QuotaName + "=Unlimited");
|
||||
}
|
||||
}
|
||||
}
|
||||
// only filled-up groups are allowed to display
|
||||
if (planQuota.Count > 0)
|
||||
hpQuotas[group.GroupName] = String.Join(",", planQuota.ToArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
//
|
||||
return hpQuotas;
|
||||
}
|
||||
|
||||
public static CheckDomainResult CheckDomain(int resellerId, string domain, string tld)
|
||||
{
|
||||
//
|
||||
CheckDomainResult result = new CheckDomainResult();
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
TopLevelDomain rslTld = GetResellerTopLevelDomain(resellerId, tld);
|
||||
//
|
||||
if (rslTld != null && !rslTld.WhoisEnabled)
|
||||
{
|
||||
//
|
||||
result.Succeed = true;
|
||||
//
|
||||
result.ResultCode = 0;
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
WhoisResult wResult = WhoisLookup.Query(domain, tld);
|
||||
// query error
|
||||
if (!wResult.Success)
|
||||
{
|
||||
//
|
||||
result.ErrorMessage = wResult.ErrorMessage;
|
||||
//
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.ResultCode = CheckDomainResult.QUERY_ERROR;
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
// whois record found
|
||||
if (wResult.RecordFound)
|
||||
{
|
||||
//
|
||||
result.ResultCode = CheckDomainResult.DOMAIN_BUSY;
|
||||
//
|
||||
result.Succeed = true;
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
// whois record not found - domain is available for purchase
|
||||
result.Succeed = true;
|
||||
//
|
||||
result.ResultCode = 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
result.ErrorMessage = ex.StackTrace;
|
||||
//
|
||||
result.Succeed = false;
|
||||
//
|
||||
result.ResultCode = CheckDomainResult.UNSPECIFIED_ERROR;
|
||||
}
|
||||
//
|
||||
return result;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Storefront Categories routines
|
||||
|
||||
public static List<Category> GetStorefrontPath(int resellerId, int categoryId)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<Category>(
|
||||
EcommerceProvider.GetStorefrontPath(resellerId, categoryId));
|
||||
}
|
||||
|
||||
public static List<Category> GetStorefrontCategories(int resellerId, int parentId)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<Category>(
|
||||
EcommerceProvider.GetStorefrontCategories(resellerId, parentId));
|
||||
}
|
||||
|
||||
public static Category GetStorefrontCategory(int resellerId, int categoryId)
|
||||
{
|
||||
return ES.ObjectUtils.FillObjectFromDataReader<Category>(
|
||||
EcommerceProvider.GetStorefrontCategory(resellerId, categoryId));
|
||||
}
|
||||
|
||||
public static List<Product> GetStorefrontProductsInCategory(int resellerId, int categoryId)
|
||||
{
|
||||
return ES.ObjectUtils.CreateListFromDataReader<Product>(
|
||||
EcommerceProvider.GetStorefrontProductsInCategory(resellerId, categoryId));
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load diff
|
@ -0,0 +1,320 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Configuration;
|
||||
using System.Reflection;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class SystemPluginController
|
||||
{
|
||||
#region Ecommerce v 2.1.0
|
||||
|
||||
/// <summary>
|
||||
/// Gets contracts' payment provider
|
||||
/// </summary>
|
||||
/// <param name="contractInfo"></param>
|
||||
/// <param name="methodName"></param>
|
||||
/// <returns></returns>
|
||||
internal static SystemPluginBase GetContractPaymentMethod(Contract contractInfo, string methodName)
|
||||
{
|
||||
// Load supported plugin
|
||||
SupportedPlugin plugin = GetResellerPMPlugin(contractInfo.ResellerId, methodName);
|
||||
//
|
||||
return GetSystemPluginInstance(contractInfo, plugin, true);
|
||||
}
|
||||
|
||||
internal static void SetupSystemPlugin(int resellerId, SystemPluginBase pluginObj)
|
||||
{
|
||||
// load plugin settings
|
||||
pluginObj.PluginSettings = GetPluginPropertiesInternal(resellerId, pluginObj.PluginId,
|
||||
false, pluginObj.SecureSettings);
|
||||
// check whether plugin settings should be decrypted
|
||||
if (pluginObj.SecureSettings != null && pluginObj.SecureSettings.Length > 0)
|
||||
{
|
||||
// decrypt secret settings
|
||||
foreach (string keyName in pluginObj.SecureSettings)
|
||||
{
|
||||
// call WebsitePanel Crypto API
|
||||
pluginObj.PluginSettings[keyName] = CryptoUtils.Decrypt(pluginObj.PluginSettings[keyName]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static SystemPluginBase GetSystemPluginInstance(string contractId, SupportedPlugin plugin,
|
||||
bool setupPlugin)
|
||||
{
|
||||
Contract contract = ContractSystem.ContractController.GetContract(contractId);
|
||||
//
|
||||
return GetSystemPluginInstance(contract, plugin, setupPlugin);
|
||||
}
|
||||
|
||||
internal static SystemPluginBase GetSystemPluginInstance(Contract contract, SupportedPlugin plugin,
|
||||
bool setupPlugin)
|
||||
{
|
||||
// load plugin
|
||||
SystemPluginBase pluginObj = GetSystemPluginInstance(plugin);
|
||||
//
|
||||
if (setupPlugin)
|
||||
SetupSystemPlugin(contract.ResellerId, pluginObj);
|
||||
//
|
||||
return pluginObj;
|
||||
}
|
||||
|
||||
internal static SystemPluginBase GetSystemPluginInstance(int resellerId, int pluginId, bool setupPlugin)
|
||||
{
|
||||
// load plugin
|
||||
SystemPluginBase pluginObj = GetSystemPluginInstance(pluginId);
|
||||
//
|
||||
if (setupPlugin)
|
||||
SetupSystemPlugin(resellerId, pluginObj);
|
||||
//
|
||||
return pluginObj;
|
||||
}
|
||||
|
||||
internal static SystemPluginBase GetSystemPluginInstance(string contractId, int pluginId, bool setupPlugin)
|
||||
{
|
||||
Contract contract = ContractSystem.ContractController.GetContract(contractId);
|
||||
// load plugin
|
||||
SystemPluginBase pluginObj = GetSystemPluginInstance(pluginId);
|
||||
//
|
||||
if (setupPlugin)
|
||||
SetupSystemPlugin(contract.ResellerId, pluginObj);
|
||||
//
|
||||
return pluginObj;
|
||||
}
|
||||
|
||||
internal static SystemPluginBase GetSystemPluginInstance(int pluginId)
|
||||
{
|
||||
// load plugin
|
||||
SupportedPlugin plugin = GetSupportedPluginById(pluginId);
|
||||
//
|
||||
return GetSystemPluginInstance(plugin);
|
||||
}
|
||||
|
||||
internal static SystemPluginBase GetSystemPluginInstance(SupportedPlugin plugin)
|
||||
{
|
||||
// check plugin not empty
|
||||
if (plugin == null)
|
||||
throw new ArgumentNullException("plugin");
|
||||
// create system plugin instance
|
||||
SystemPluginBase pluginObj = (SystemPluginBase)Activator.CreateInstance(Type.GetType(plugin.TypeName));
|
||||
// copy fields
|
||||
pluginObj.PluginId = plugin.PluginId;
|
||||
pluginObj.PluginName = plugin.PluginName;
|
||||
// return
|
||||
return pluginObj;
|
||||
}
|
||||
|
||||
internal static SupportedPlugin GetResellerPMPlugin(int resellerId, string methodName)
|
||||
{
|
||||
SupportedPlugin plugin = ObjectUtils.FillObjectFromDataReader<SupportedPlugin>(
|
||||
EcommerceProvider.GetResellerPMPlugin(resellerId, methodName));
|
||||
//
|
||||
if (plugin == null)
|
||||
throw new Exception("RESELLER_PM_PLUGIN_NOT_FOUND");
|
||||
//
|
||||
return plugin;
|
||||
}
|
||||
|
||||
internal static KeyValueBunch GetPluginPropertiesInternal(int userId, int pluginId, bool skipSensitive,
|
||||
string[] secureSettings)
|
||||
{
|
||||
// load plugin settings
|
||||
KeyValueBunch properties = SettingsHelper.FillProperties(EcommerceProvider.GetPluginProperties(
|
||||
SecurityContext.User.UserId, userId, pluginId));
|
||||
// cleanup plugin settings
|
||||
if (skipSensitive && secureSettings != null)
|
||||
{
|
||||
// iterate through secure settings
|
||||
foreach (string keyName in secureSettings)
|
||||
{
|
||||
// remove secure setting
|
||||
properties.RemoveKey(keyName);
|
||||
}
|
||||
}
|
||||
// return plugin settings
|
||||
return properties;
|
||||
}
|
||||
|
||||
public static KeyValueBunch GetPluginProperties(int userId, int pluginId)
|
||||
{
|
||||
// get plugin
|
||||
SystemPluginBase pluginObj = GetSystemPluginInstance(pluginId);
|
||||
// get settings
|
||||
return GetPluginPropertiesInternal(userId, pluginId, true, pluginObj.SecureSettings);
|
||||
}
|
||||
|
||||
public static int SetPluginProperties(int userId, int pluginId, KeyValueBunch props)
|
||||
{
|
||||
string xmlText = String.Empty;
|
||||
string[][] pluginProps = null;
|
||||
SecurityResult result = StorehouseController.CheckAccountNotDemoAndActive();
|
||||
//
|
||||
if (!result.Success)
|
||||
return result.ResultCode;
|
||||
if (props != null)
|
||||
{
|
||||
// create system plugin
|
||||
SystemPluginBase pluginObj = GetSystemPluginInstance(userId, pluginId, false);
|
||||
// crypt sensitive data
|
||||
foreach (string keyName in props.GetAllKeys())
|
||||
{
|
||||
//
|
||||
string keyValue = props[keyName];
|
||||
//
|
||||
if (pluginObj.SecureSettings != null)
|
||||
{
|
||||
int indexOf = Array.IndexOf(pluginObj.SecureSettings, keyName);
|
||||
// crypt sensitive data
|
||||
if (indexOf > -1)
|
||||
keyValue = CryptoUtils.Encrypt(keyValue);
|
||||
}
|
||||
//
|
||||
props[keyName] = keyValue;
|
||||
}
|
||||
|
||||
// load old properties
|
||||
KeyValueBunch oldProps = GetPluginPropertiesInternal(userId, pluginId,
|
||||
false, pluginObj.SecureSettings);
|
||||
// merge old props with new props
|
||||
foreach (string keyName in props.GetAllKeys())
|
||||
{
|
||||
// copy
|
||||
oldProps[keyName] = props[keyName];
|
||||
}
|
||||
//
|
||||
pluginProps = oldProps.KeyValueArray;
|
||||
}
|
||||
// build update xml
|
||||
xmlText = SettingsHelper.ConvertObjectSettings(pluginProps, "properties", "property");
|
||||
//
|
||||
return EcommerceProvider.SetPluginProperties(SecurityContext.User.UserId, userId, pluginId, xmlText);
|
||||
}
|
||||
|
||||
public static int LogContractPayment(Contract contract, string methodName, string rawData)
|
||||
{
|
||||
SupportedPlugin plugin = GetResellerPMPlugin(contract.ResellerId, methodName);
|
||||
//
|
||||
return EcommerceProvider.WriteSupportedPluginLog(contract.ContractId, plugin.PluginId, 0, rawData);
|
||||
}
|
||||
|
||||
private static int WriteSupportedPluginLog(string contractId, int pluginId, int recordType, string rawData)
|
||||
{
|
||||
return EcommerceProvider.WriteSupportedPluginLog(contractId, pluginId, recordType, rawData);
|
||||
}
|
||||
|
||||
public static List<SupportedPlugin> GetSupportedPluginsByGroup(string groupName)
|
||||
{
|
||||
return ObjectUtils.CreateListFromDataReader<SupportedPlugin>(
|
||||
EcommerceProvider.GetSupportedPluginsByGroup(groupName));
|
||||
}
|
||||
|
||||
public static SupportedPlugin GetSupportedPlugin(string pluginName, string groupName)
|
||||
{
|
||||
return ObjectUtils.FillObjectFromDataReader<SupportedPlugin>(
|
||||
EcommerceProvider.GetSupportedPlugin(pluginName, groupName));
|
||||
}
|
||||
|
||||
public static SupportedPlugin GetSupportedPluginById(int pluginId)
|
||||
{
|
||||
return ObjectUtils.FillObjectFromDataReader<SupportedPlugin>(
|
||||
EcommerceProvider.GetSupportedPluginById(pluginId));
|
||||
}
|
||||
|
||||
public static CheckoutFormParams GetCheckoutFormParams(string contractId, int invoiceId,
|
||||
string methodName, KeyValueBunch options)
|
||||
{
|
||||
Contract contractInfo = ContractSystem.ContractController.GetContract(contractId);
|
||||
// Impersonate
|
||||
ContractSystem.ContractController.ImpersonateAsContractReseller(contractInfo);
|
||||
//
|
||||
SupportedPlugin pmPlugin = GetResellerPMPlugin(contractInfo.ResellerId, methodName);
|
||||
//
|
||||
if (pmPlugin == null)
|
||||
throw new Exception("Incorrect payment method has been specified");
|
||||
// create instance of plugin
|
||||
IInteractivePaymentGatewayProvider provider = (IInteractivePaymentGatewayProvider)
|
||||
SystemPluginController.GetSystemPluginInstance(contractInfo, pmPlugin, true);
|
||||
//
|
||||
Invoice userInvoice = InvoiceController.GetCustomerInvoiceInternally(invoiceId);
|
||||
//
|
||||
List<InvoiceItem> invoiceLines = InvoiceController.GetCustomerInvoiceItems(invoiceId);
|
||||
// load contract account
|
||||
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(contractId);
|
||||
|
||||
// build form parameters
|
||||
FormParameters formParams = new FormParameters();
|
||||
// copy reseller id
|
||||
formParams[FormParameters.CONTRACT] = userInvoice.ContractId;
|
||||
// copy invoice number
|
||||
formParams[FormParameters.INVOICE] = userInvoice.InvoiceId.ToString();
|
||||
// copy invoice amount
|
||||
formParams[FormParameters.AMOUNT] = userInvoice.Total.ToString("0.00");
|
||||
// copy invoice tax amount
|
||||
formParams[FormParameters.TAX_AMOUNT] = userInvoice.TaxAmount.ToString("0.00");
|
||||
// copy invoice currency
|
||||
formParams[FormParameters.CURRENCY] = userInvoice.Currency;
|
||||
|
||||
// copy first name
|
||||
formParams[FormParameters.FIRST_NAME] = account[ContractAccount.FIRST_NAME];
|
||||
// copy last name
|
||||
formParams[FormParameters.LAST_NAME] = account[ContractAccount.LAST_NAME];
|
||||
// copy email
|
||||
formParams[FormParameters.EMAIL] = account[ContractAccount.EMAIL];
|
||||
// copy address
|
||||
formParams[FormParameters.ADDRESS] = account[ContractAccount.ADDRESS];
|
||||
// copy country
|
||||
formParams[FormParameters.COUNTRY] = account[ContractAccount.COUNTRY];
|
||||
// copy phone number
|
||||
formParams[FormParameters.PHONE] = account[ContractAccount.PHONE_NUMBER];
|
||||
// copy city
|
||||
formParams[FormParameters.CITY] = account[ContractAccount.CITY];
|
||||
// copy state
|
||||
formParams[FormParameters.STATE] = account[ContractAccount.STATE];
|
||||
// copy zip
|
||||
formParams[FormParameters.ZIP] = account[ContractAccount.ZIP];
|
||||
// copy options if any
|
||||
if (options != null)
|
||||
{
|
||||
foreach (string keyName in options.GetAllKeys())
|
||||
formParams[keyName] = options[keyName];
|
||||
}
|
||||
|
||||
// return result
|
||||
return provider.GetCheckoutFormParams(formParams, invoiceLines.ToArray());
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
|
@ -0,0 +1,165 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer.TaskEventHandlers
|
||||
{
|
||||
public class SendEmailNotification : TaskEventHandler
|
||||
{
|
||||
public override void OnStart()
|
||||
{
|
||||
// Nothing to do
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends corresponding notifications.
|
||||
/// </summary>
|
||||
public override void OnComplete()
|
||||
{
|
||||
if (!TaskManager.HasErrors)
|
||||
{
|
||||
switch (TaskManager.TaskName)
|
||||
{
|
||||
case SystemTasks.SVC_SUSPEND:
|
||||
case SystemTasks.SVC_CANCEL:
|
||||
case SystemTasks.SVC_ACTIVATE:
|
||||
SendServiceStatusChangedNotification();
|
||||
break;
|
||||
case SystemTasks.TASK_ADD_INVOICE:
|
||||
SendInvoiceNotification();
|
||||
break;
|
||||
case SystemTasks.TASK_UPDATE_PAYMENT:
|
||||
case SystemTasks.TASK_ADD_PAYMENT:
|
||||
SendPaymentNotification();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void SendServiceStatusChangedNotification()
|
||||
{
|
||||
// send an e-mail notification
|
||||
try
|
||||
{
|
||||
bool sendNotification = (bool)TaskManager.TaskParameters[SystemTaskParams.PARAM_SEND_EMAIL];
|
||||
// Ensure notification is required
|
||||
if (!sendNotification)
|
||||
{
|
||||
TaskManager.Write("Notification send is not required, thus skipped");
|
||||
return;
|
||||
}
|
||||
|
||||
Service service = (Service)TaskManager.TaskParameters[SystemTaskParams.PARAM_SERVICE];
|
||||
int smtpResult = 0;
|
||||
switch (service.Status)
|
||||
{
|
||||
case ServiceStatus.Active:
|
||||
smtpResult = MiscController.SendServiceActivatedNotification(service.ServiceId);
|
||||
break;
|
||||
case ServiceStatus.Suspended:
|
||||
smtpResult = MiscController.SendServiceSuspendedNotification(service.ServiceId);
|
||||
break;
|
||||
case ServiceStatus.Cancelled:
|
||||
smtpResult = MiscController.SendServiceCanceledNotification(service.ServiceId);
|
||||
break;
|
||||
}
|
||||
//
|
||||
if (smtpResult != 0)
|
||||
{
|
||||
TaskManager.WriteWarning("Unable to send e-mail notification");
|
||||
TaskManager.WriteParameter("SMTP Status", smtpResult);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TaskManager.WriteError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void SendPaymentNotification()
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
// Read task parameters
|
||||
Invoice invoice = (Invoice)TaskManager.TaskParameters[SystemTaskParams.PARAM_INVOICE];
|
||||
CustomerPayment payment = (CustomerPayment)TaskManager.TaskParameters[SystemTaskParams.PARAM_PAYMENT];
|
||||
//
|
||||
if (payment.Status == TransactionStatus.Approved)
|
||||
{
|
||||
//
|
||||
int smtpResult = MiscController.SendPaymentReceivedNotification(payment);
|
||||
//
|
||||
if (smtpResult != 0)
|
||||
{
|
||||
TaskManager.WriteWarning("Unable to send e-mail notification");
|
||||
TaskManager.WriteParameter("SMTP Status", smtpResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TaskManager.WriteError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void SendInvoiceNotification()
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
// Read task parameters
|
||||
Contract contract = (Contract)TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT];
|
||||
Invoice invoice = (Invoice)TaskManager.TaskParameters[SystemTaskParams.PARAM_INVOICE];
|
||||
List<InvoiceItem> invoiceLines = (List<InvoiceItem>)TaskManager.TaskParameters[SystemTaskParams.PARAM_INVOICE_LINES];
|
||||
KeyValueBunch extraArgs = (KeyValueBunch)TaskManager.TaskParameters[SystemTaskParams.PARAM_EXTRA_ARGS];
|
||||
// modify invoice direct url
|
||||
if (extraArgs != null && !String.IsNullOrEmpty(extraArgs["InvoiceDirectURL"]))
|
||||
extraArgs["InvoiceDirectURL"] += "&InvoiceId=" + invoice.InvoiceId;
|
||||
//
|
||||
int smtpResult = MiscController.SendNewInvoiceNotification(invoice, invoiceLines, extraArgs);
|
||||
//
|
||||
if (smtpResult != 0)
|
||||
{
|
||||
TaskManager.WriteWarning("Unable to send e-mail notification");
|
||||
TaskManager.WriteParameter("SMTP Status", smtpResult);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TaskManager.WriteError(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,106 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
|
||||
using WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer.TaskEventHandlers
|
||||
{
|
||||
public class SystemTriggersAgent : TaskEventHandler
|
||||
{
|
||||
public override void OnStart()
|
||||
{
|
||||
// Nothing to do
|
||||
}
|
||||
|
||||
public override void OnComplete()
|
||||
{
|
||||
if (!TaskManager.HasErrors)
|
||||
{
|
||||
switch (TaskManager.TaskName)
|
||||
{
|
||||
case SystemTasks.TASK_ADD_INVOICE:
|
||||
RegisterInvoiceActivationTrigger();
|
||||
break;
|
||||
case SystemTasks.TASK_ADD_CONTRACT:
|
||||
RegisterContractActivationTrigger();
|
||||
break;
|
||||
case SystemTasks.TASK_UPDATE_PAYMENT:
|
||||
case SystemTasks.TASK_ADD_PAYMENT:
|
||||
ActivatePaymentSystemTriggers();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RegisterInvoiceActivationTrigger()
|
||||
{
|
||||
// Read contract invoice
|
||||
Invoice invoice = (Invoice)TaskManager.TaskParameters[SystemTaskParams.PARAM_INVOICE];
|
||||
//
|
||||
TriggerSystem.TriggerController.AddSystemTrigger(invoice.InvoiceId.ToString(),
|
||||
ActivateInvoiceTrigger.STATUS_AWAITING_PAYMENT, typeof(ActivateInvoiceTrigger));
|
||||
}
|
||||
|
||||
private void RegisterContractActivationTrigger()
|
||||
{
|
||||
// Ensure the contract has been registered successfully
|
||||
if (TaskManager.TaskParameters.ContainsKey(SystemTaskParams.PARAM_CONTRACT))
|
||||
{
|
||||
Contract contract = (Contract)TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT];
|
||||
//
|
||||
if (contract.Status == ContractStatus.Pending)
|
||||
{
|
||||
TriggerSystem.TriggerController.AddSystemTrigger(contract.ContractId,
|
||||
ActivateContractTrigger.STATUS_AWAITING_PAYMENT, typeof(ActivateContractTrigger));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ActivatePaymentSystemTriggers()
|
||||
{
|
||||
CustomerPayment payment = (CustomerPayment)TaskManager.TaskParameters[SystemTaskParams.PARAM_PAYMENT];
|
||||
Contract contract = (Contract)TaskManager.TaskParameters[SystemTaskParams.PARAM_CONTRACT];
|
||||
|
||||
// Run activate contract trigger if the transaction was approved
|
||||
if (payment.Status == TransactionStatus.Approved)
|
||||
{
|
||||
// Activate contract
|
||||
TriggerSystem.TriggerController.ExecuteSystemTrigger(contract.ContractId,
|
||||
ActivateContractTrigger.NAMESPACE, null);
|
||||
// Activate invoice
|
||||
TriggerSystem.TriggerController.ExecuteSystemTrigger(payment.InvoiceId.ToString(),
|
||||
ActivateInvoiceTrigger.NAMESPACE, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,153 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using ES = WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer
|
||||
{
|
||||
public class ActivateInvoiceTrigger : TriggerHandlerBase
|
||||
{
|
||||
public const string NAMESPACE = "INVOICE";
|
||||
public const string STATUS_AWAITING_PAYMENT = "AWAITING_PAYMENT";
|
||||
|
||||
public override string TriggerNamespace
|
||||
{
|
||||
get { return NAMESPACE; }
|
||||
}
|
||||
|
||||
public override void ExecuteTrigger(TriggerEventArgs eventArgs)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
ActivatePaidInvoicesTask activator = new ActivatePaidInvoicesTask();
|
||||
// Load invoice items to activate
|
||||
List<InvoiceItem> items = InvoiceController.GetCustomerInvoiceItems(Convert.ToInt32(ReferenceId));
|
||||
//
|
||||
foreach (InvoiceItem item in items)
|
||||
{
|
||||
try
|
||||
{
|
||||
ES.TaskManager.Write("Activating service");
|
||||
// activating
|
||||
GenericSvcResult result = activator.ActivateInvoiceItem(item);
|
||||
// LOG ERROR
|
||||
if (!result.Succeed)
|
||||
{
|
||||
ES.TaskManager.WriteError(result.Error);
|
||||
if (!String.IsNullOrEmpty(result.ErrorCode))
|
||||
ES.TaskManager.WriteParameter("Error code", result.ErrorCode);
|
||||
ES.TaskManager.WriteParameter("Result code", result.ResultCode);
|
||||
// go to next item
|
||||
continue;
|
||||
}
|
||||
//
|
||||
ES.TaskManager.Write("Activated");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ES.TaskManager.WriteError(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TriggerStatus = "ERROR";
|
||||
ES.TaskManager.WriteError(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class ActivateContractTrigger : TriggerHandlerBase
|
||||
{
|
||||
public const string NAMESPACE = "CONTRACT";
|
||||
public const string STATUS_AWAITING_PAYMENT = "AWAITING_PAYMENT";
|
||||
|
||||
public override string TriggerNamespace
|
||||
{
|
||||
get { return NAMESPACE; }
|
||||
}
|
||||
|
||||
public override void ExecuteTrigger(TriggerEventArgs eventArgs)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
Contract contract = ContractSystem.ContractController.GetContract(ReferenceId);
|
||||
//
|
||||
if (contract.Status == ContractStatus.Pending)
|
||||
{
|
||||
//
|
||||
ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(ReferenceId);
|
||||
//
|
||||
// create user account
|
||||
ES.UserInfo userInfo = new ES.UserInfo();
|
||||
userInfo.Username = account[ContractAccount.USERNAME];
|
||||
userInfo.Password = account[ContractAccount.PASSWORD];
|
||||
userInfo.Email = account[ContractAccount.EMAIL];
|
||||
userInfo.FirstName = account[ContractAccount.FIRST_NAME];
|
||||
userInfo.LastName = account[ContractAccount.LAST_NAME];
|
||||
userInfo.HtmlMail = (account[ContractAccount.MAIL_FORMAT] == "HTML");
|
||||
userInfo.Address = account[ContractAccount.ADDRESS];
|
||||
userInfo.City = account[ContractAccount.CITY];
|
||||
userInfo.CompanyName = account[ContractAccount.COMPANY_NAME];
|
||||
userInfo.Country = account[ContractAccount.COUNTRY];
|
||||
userInfo.State = account[ContractAccount.STATE];
|
||||
userInfo.PrimaryPhone = account[ContractAccount.PHONE_NUMBER];
|
||||
userInfo.Fax = account[ContractAccount.FAX_NUMBER];
|
||||
userInfo.InstantMessenger = account[ContractAccount.INSTANT_MESSENGER];
|
||||
userInfo.Zip = account[ContractAccount.ZIP];
|
||||
userInfo.Role = ES.UserRole.User;
|
||||
userInfo.Status = ES.UserStatus.Active;
|
||||
// set account parent
|
||||
userInfo.OwnerId = contract.ResellerId;
|
||||
userInfo.Created = DateTime.Now;
|
||||
// create account
|
||||
int resultCode = ES.UserController.AddUser(userInfo, true);
|
||||
//
|
||||
if (resultCode > 0)
|
||||
{
|
||||
ContractSystem.ContractController.UpdateContract(ReferenceId, resultCode, contract.AccountName,
|
||||
ContractStatus.Active, 0m, contract.FirstName, contract.LastName, contract.Email,
|
||||
contract.CompanyName, null, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
TriggerStatus = "ERROR";
|
||||
ES.TaskManager.WriteError(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
// Copyright (c) 2012, Outercurve Foundation.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without modification,
|
||||
// are permitted provided that the following conditions are met:
|
||||
//
|
||||
// - Redistributions of source code must retain the above copyright notice, this
|
||||
// list of conditions and the following disclaimer.
|
||||
//
|
||||
// - Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// - Neither the name of the Outercurve Foundation nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from this
|
||||
// software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
|
||||
using ES = WebsitePanel.EnterpriseServer;
|
||||
|
||||
namespace WebsitePanel.Ecommerce.EnterpriseServer.TriggerSystem
|
||||
{
|
||||
public class TriggerController
|
||||
{
|
||||
public static void AddSystemTrigger(string referenceId, string triggerStatus, Type triggerType)
|
||||
{
|
||||
//
|
||||
ITriggerHandler trigger = (ITriggerHandler)Activator.CreateInstance(triggerType);
|
||||
//
|
||||
EcommerceProvider.AddSystemTrigger(ES.SecurityContext.User.UserId, ES.SecurityContext.User.UserId,
|
||||
triggerType.AssemblyQualifiedName, referenceId, trigger.TriggerNamespace, triggerStatus);
|
||||
}
|
||||
|
||||
public static void ExecuteSystemTrigger(string referenceId, string triggerNamespace, TriggerEventArgs eventArgs)
|
||||
{
|
||||
//
|
||||
IDataReader dr = null;
|
||||
try
|
||||
{
|
||||
ES.TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.TASK_EXEC_SYSTEM_TRIGGER);
|
||||
|
||||
List<ITriggerHandler> triggers = new List<ITriggerHandler>();
|
||||
dr = EcommerceProvider.GetSystemTrigger(ES.SecurityContext.User.UserId, referenceId, triggerNamespace);
|
||||
//
|
||||
while(dr.Read())
|
||||
{
|
||||
int ownerId = Convert.ToInt32(dr["OwnerID"]);
|
||||
string triggerId = Convert.ToString(dr["TriggerID"]);
|
||||
string triggerHandler = Convert.ToString(dr["TriggerHandler"]);
|
||||
string triggerStatus = (dr["Status"] == DBNull.Value) ? null : Convert.ToString(dr["Status"]);
|
||||
// Instantiate trigger handler
|
||||
ITriggerHandler trigger = (ITriggerHandler)Activator.CreateInstance(Type.GetType(triggerHandler));
|
||||
//
|
||||
trigger.TriggerId = triggerId;
|
||||
trigger.OwnerId = ownerId;
|
||||
trigger.TriggerStatus = triggerStatus;
|
||||
trigger.ReferenceId = referenceId;
|
||||
//
|
||||
triggers.Add(trigger);
|
||||
//
|
||||
}
|
||||
dr.Close();
|
||||
//
|
||||
foreach (ITriggerHandler trigger in triggers)
|
||||
{
|
||||
try
|
||||
{
|
||||
trigger.ExecuteTrigger(eventArgs);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ES.TaskManager.WriteError(ex);
|
||||
continue;
|
||||
}
|
||||
//
|
||||
DeleteSystemTrigger(trigger.TriggerId);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw ES.TaskManager.WriteError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (dr != null)
|
||||
dr.Close();
|
||||
//
|
||||
ES.TaskManager.CompleteTask();
|
||||
}
|
||||
}
|
||||
|
||||
private static void DeleteSystemTrigger(string triggerId)
|
||||
{
|
||||
EcommerceProvider.DeleteSystemTrigger(ES.SecurityContext.User.UserId, triggerId);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue