/// <summary> /// Create a order /// </summary> public static Dictionary<string, string> CreateOrder(Order order, List<OrderRow> orderRows, Domain domain, KeyStringList tt, string paymentType) { // Create the dictionary to return Dictionary<string, string> responseData = new Dictionary<string, string>(10); // Get the webshop settings KeyStringList webshopSettings = WebshopSetting.GetAllFromCache(); // Get the test variable bool payExTest = false; bool.TryParse(webshopSettings.Get("PAYEX-TEST"), out payExTest); // Check if it is test or production if(payExTest == true) { responseData = CreateOrderTest(order, orderRows, domain, webshopSettings, tt, paymentType); } else { responseData = CreateOrderProduction(order, orderRows, domain, webshopSettings, tt, paymentType); } // Return the response data return responseData; } // End of the CreateOrder method
public ActionResult translate(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor", "Translator" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return(View("index")); } else { // Redirect the user to the start page return(RedirectToAction("index", "admin_login")); } // Get the admin default language Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get all the form values Int32 translationLanguageId = Convert.ToInt32(collection["selectLanguage"]); Int32 id = Convert.ToInt32(collection["hiddenUnitId"]); string unit_code = collection["txtTranslatedUnitCode"]; string name = collection["txtTranslatedName"]; // Create the translated unit Unit translatedUnit = new Unit(); translatedUnit.id = id; translatedUnit.unit_code = unit_code; translatedUnit.name = name; // Create a error message string errorMessage = string.Empty; // Check for errors if (translatedUnit.unit_code.Length > 10) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("unit_code"), "10") + "<br/>"; } if (translatedUnit.name.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("name"), "50") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Get the saved unit Unit unit = Unit.GetOneById(id, translationLanguageId); if (unit == null) { // Add a new translated unit Unit.AddLanguagePost(translatedUnit, translationLanguageId); } else { // Update the translated unit unit.unit_code = translatedUnit.unit_code; unit.name = translatedUnit.name; Unit.UpdateLanguagePost(unit, translationLanguageId); } // Redirect the user to the list return(Redirect("/admin_units" + returnUrl)); } else { // Set form values ViewBag.LanguageId = translationLanguageId; ViewBag.Languages = Language.GetAll(adminLanguageId, "name", "ASC"); ViewBag.StandardUnit = Unit.GetOneById(id, adminLanguageId); ViewBag.TranslatedUnit = translatedUnit; ViewBag.ErrorMessage = errorMessage; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the translate view return(View("translate")); } } // End of the translate method
} // End of the clear method #endregion #region Payex payment /// <summary> /// Create a payex payment /// </summary> public ActionResult CreatePayexPayment(Order order, List<OrderRow> orderRows, Domain domain, KeyStringList tt, string paymentType) { // Create the payex payment Dictionary<string, string> response = PayExManager.CreateOrder(order, orderRows, domain, tt, paymentType); // Get the error code string error_code = response.ContainsKey("error_code") == true ? response["error_code"] : ""; // Check if the response is successful if (error_code == "OK" && paymentType == "INVOICE") { // Get response variables string transaction_status = response.ContainsKey("transaction_status") == true ? response["transaction_status"] : ""; string transaction_number = response.ContainsKey("transaction_number") == true ? response["transaction_number"] : ""; // Save the transaction number Order.SetPaymentToken(order.id, transaction_number); if(transaction_status == "3") { // Update the order status Order.UpdatePaymentStatus(order.id, "payment_status_invoice_approved"); // Add customer files CustomerFile.AddCustomerFiles(order); } else if (transaction_status == "5") { // Update the order status Order.UpdatePaymentStatus(order.id, "payment_status_invoice_not_approved"); } // Redirect the user to the order confirmation page return RedirectToAction("confirmation", "order", new { id = order.id }); } else if (error_code == "OK") { // Redirect the user to payex return Redirect(response["redirect_url"]); } else { // Redirect the user to the order confirmation page return RedirectToAction("confirmation", "order", new { id = order.id }); } } // End of the CreatePayexPayment method
} // End of the paypal_confirmation method #endregion #region Payson payment /// <summary> /// Create a payson payment /// </summary> /// <param name="order">A reference to a order</param> /// <param name="orderRows">A reference to a list of order rows</param> /// <param name="domain">A reference to the domain</param> /// <param name="tt">A reference to translated texts</param> /// <param name="paymentType">The payment type, INVOICE, DIRECT</param> /// <returns>A redirect to payson</returns> public ActionResult CreatePaysonPayment(Order order, List<OrderRow> orderRows, Domain domain, KeyStringList tt, string paymentType) { // Get the webshop settings KeyStringList webshopSettings = WebshopSetting.GetAllFromCache(); // Get the language Language language = Language.GetOneById(domain.front_end_language); // Get credentials string paysonEmail = webshopSettings.Get("PAYSON-EMAIL"); string userId = webshopSettings.Get("PAYSON-AGENT-ID"); string md5Key = webshopSettings.Get("PAYSON-MD5-KEY"); bool paysonTest = false; bool.TryParse(webshopSettings.Get("PAYSON-TEST"), out paysonTest); // Set urls string returnUrl = domain.web_address + "/order/payson_confirmation/" + order.id.ToString(); string notificationUrl = domain.web_address + "/api/payments/payson_notification/" + order.id.ToString(); string cancelUrl = domain.web_address + "/order/confirmation/" + order.id.ToString(); // Create the sender PaysonIntegration.Utils.Sender sender = new PaysonIntegration.Utils.Sender(order.customer_email); sender.FirstName = "@"; sender.LastName = "@"; // Get the total amount decimal totalAmount = order.total_sum - order.gift_cards_amount; // Create the receiver List<PaysonIntegration.Utils.Receiver> receivers = new List<PaysonIntegration.Utils.Receiver>(1); PaysonIntegration.Utils.Receiver receiver = new PaysonIntegration.Utils.Receiver(paysonEmail, totalAmount); receiver.SetPrimaryReceiver(true); receivers.Add(receiver); // Create a list of order items List<PaysonIntegration.Utils.OrderItem> orderItems = new List<PaysonIntegration.Utils.OrderItem>(10); // Add order items for (int i = 0; i < orderRows.Count; i++) { // Create a order item PaysonIntegration.Utils.OrderItem orderItem = new PaysonIntegration.Utils.OrderItem(orderRows[i].product_name); orderItem.SetOptionalParameters(orderRows[i].product_code, orderRows[i].quantity, orderRows[i].unit_price, orderRows[i].vat_percent); // Add the order item to the list orderItems.Add(orderItem); } // Add the rounding if(order.rounding_sum != 0) { PaysonIntegration.Utils.OrderItem roundingItem = new PaysonIntegration.Utils.OrderItem(tt.Get("rounding")); roundingItem.SetOptionalParameters("rd", 1, order.rounding_sum, 0); orderItems.Add(roundingItem); } // Add the gift cards amount if (order.gift_cards_amount > 0) { PaysonIntegration.Utils.OrderItem giftCardItem = new PaysonIntegration.Utils.OrderItem(tt.Get("gift_cards")); giftCardItem.SetOptionalParameters("gc", 1, order.gift_cards_amount * -1, 0); orderItems.Add(giftCardItem); } // Create funding constraints depending on the payment method List<PaysonIntegration.Utils.FundingConstraint> fundingConstraints = new List<PaysonIntegration.Utils.FundingConstraint>(); if (paymentType == "INVOICE") { fundingConstraints.Add(PaysonIntegration.Utils.FundingConstraint.Invoice); } else if(paymentType == "DIRECT") { fundingConstraints.Add(PaysonIntegration.Utils.FundingConstraint.Bank); fundingConstraints.Add(PaysonIntegration.Utils.FundingConstraint.CreditCard); } // Create the order memo string orderMemo = tt.Get("order").ToUpper() + "# " + order.id.ToString(); // Create the pay data PaysonIntegration.Data.PayData payData = new PaysonIntegration.Data.PayData(returnUrl, cancelUrl, orderMemo, sender, receivers); payData.SetFundingConstraints(fundingConstraints); payData.GuaranteeOffered = PaysonIntegration.Utils.GuaranteeOffered.No; payData.SetLocaleCode(AnnytabDataValidation.GetPaysonLocaleCode(language)); payData.SetCurrencyCode(order.currency_code); payData.SetOrderItems(orderItems); payData.ShowReceiptPage = false; payData.SetIpnNotificationUrl(notificationUrl); payData.SetTrackingId(order.id.ToString()); // Create the api PaysonIntegration.PaysonApi paysonApi = new PaysonIntegration.PaysonApi(userId, md5Key, null, paysonTest); // Create a respone PaysonIntegration.Response.PayResponse response = null; try { // Create the payment response = paysonApi.MakePayRequest(payData); } catch(Exception ex) { string exMessage = ex.Message; } // Check if the response is successful string forwardUrl = ""; if (response != null && response.Success == true) { // Update the order with the payment token Order.SetPaymentToken(order.id, response.Token); // Get the forward url forwardUrl = paysonApi.GetForwardPayUrl(response.Token); // Redirect the user to the forward url return Redirect(forwardUrl); } else { // Redirect the user to the order confirmation page return RedirectToAction("confirmation", "order", new { id = order.id }); } } // End of the CreatePaysonPayment
} // End of the GetAll method /// <summary> /// Get all static texts as a key string list /// </summary> /// <param name="languageId">The id of the language</param> /// <param name="sortField">The field to sort on</param> /// <param name="sortOrder">The sort order</param> /// <returns>A key string list of static texts</returns> private static KeyStringList GetAllFromDatabase(Int32 languageId, string sortField, string sortOrder) { // Make sure that sort variables are valid sortField = GetValidSortField(sortField); sortOrder = GetValidSortOrder(sortOrder); // Create the KeyStringList to return KeyStringList posts = new KeyStringList(20); // Create the connection string and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT * FROM dbo.static_texts WHERE language_id = @language_id ORDER BY " + sortField + " " + sortOrder + ";"; // The using block is used to call dispose automatically even if there are an exception using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there is a exception using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@language_id", languageId); // Create a reader SqlDataReader reader = null; // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases try { // Open the connection. cn.Open(); // Fill the reader with data from the select command reader = cmd.ExecuteReader(); // Loop through the reader as long as there is something to read while (reader.Read()) { posts.Add(reader["id"].ToString(), reader["value"].ToString()); } } catch (Exception e) { throw e; } finally { // Call Close when done reading to avoid memory leakage if (reader != null) reader.Close(); } } } // Return the list of posts return posts; } // End of the GetAllFromDatabase method
} // End of the CancelTransactionProduction method #endregion #region Invoice methods /// <summary> /// Create a invoice to a person /// </summary> public static Dictionary<string, string> CreateInvoicePrivate(string orderReference, Order order, Domain domain, KeyStringList settings, KeyStringList tt) { // Create the dictionary to return Dictionary<string, string> responseData = new Dictionary<string, string>(10); // Get the webshop settings KeyStringList webshopSettings = WebshopSetting.GetAllFromCache(); // Get the test variable bool payExTest = false; bool.TryParse(webshopSettings.Get("PAYEX-TEST"), out payExTest); // Check if it is test or production if (payExTest == true) { responseData = CreateInvoicePrivateTest(orderReference, order, domain, webshopSettings, tt); } else { responseData = CreateInvoicePrivateProduction(orderReference, order, domain, webshopSettings, tt); } // Return the response data return responseData; } // End of the CreateInvoicePrivate method
} // End of the CheckTransactionProduction method #endregion #region Cancel methods /// <summary> /// Cancel an authorized transaction /// </summary> public static Dictionary<string, string> CancelTransaction(Order order, KeyStringList settings) { // Create the dictionary to return Dictionary<string, string> responseData = new Dictionary<string, string>(10); // Get the webshop settings KeyStringList webshopSettings = WebshopSetting.GetAllFromCache(); // Get the test variable bool payExTest = false; bool.TryParse(webshopSettings.Get("PAYEX-TEST"), out payExTest); // Check if it is test or production if (payExTest == true) { responseData = CancelTransactionTest(order, webshopSettings); } else { responseData = CancelTransactionProduction(order, webshopSettings); } // Return the response data return responseData; } // End of the CancelTransaction method
} // End of the CreateOrder method /// <summary> /// Create a test order /// </summary> private static Dictionary<string, string> CreateOrderTest(Order order, List<OrderRow> orderRows, Domain domain, KeyStringList settings, KeyStringList tt, string paymentType) { // Create the dictionary to return Dictionary<string, string> responseData = new Dictionary<string, string>(10); // Create the PayEx order Annytab.Webshop.Payex.Test.PxOrder pxOrder = new Annytab.Webshop.Payex.Test.PxOrder(); // Get the currency Currency orderCurrency = Currency.GetOneById(order.currency_code); // Calculate the decimal multiplier Int32 decimalMultiplier = (Int32)Math.Pow(10, orderCurrency.decimals); // Add the data long accountNumber = 0; long.TryParse(settings.Get("PAYEX-ACCOUNT-NUMBER"), out accountNumber); string purchaseOperation = "SALE"; if (paymentType == "INVOICE") { purchaseOperation = "AUTHORIZATION"; } Int64 price = (Int64)Math.Round((order.total_sum - order.gift_cards_amount) * 100, MidpointRounding.AwayFromZero); string priceArgList = ""; string currency = order.currency_code; Int32 vat = 0; string orderID = order.id.ToString(); string productNumber = tt.Get("order").ToUpper() + "# " + order.id; string description = domain.webshop_name; string clientIPAddress = Tools.GetUserIP(); string clientIdentifier = ""; string externalID = ""; string returnUrl = domain.web_address + "/order/payex_confirmation/" + order.id.ToString(); string view = paymentType; string agreementRef = ""; string cancelUrl = domain.web_address + "/order/confirmation/" + order.id.ToString(); string clientLanguage = order.language_code.ToLower() + "-" + order.country_code.ToUpper(); // Set additional values string additionalValues = "USECSS=RESPONSIVEDESIGN"; // Change to PayEx Payment Gateway 2.0 if the payment type is CREDITCARD if(paymentType == "CREDITCARD") { additionalValues = "RESPONSIVE=1"; } // Create the md5 hash string hash = GetMD5Hash(accountNumber.ToString() + purchaseOperation + price.ToString() + priceArgList + currency + vat + orderID.ToString() + productNumber + description + clientIPAddress + clientIdentifier + additionalValues + externalID + returnUrl + view + agreementRef + cancelUrl + clientLanguage + settings.Get("PAYEX-ENCRYPTION-KEY")); // Initialize the order string xmlResponse = pxOrder.Initialize8(accountNumber, purchaseOperation, price, priceArgList, currency, vat, orderID, productNumber, description, clientIPAddress, clientIdentifier, additionalValues, externalID, returnUrl, view, agreementRef, cancelUrl, clientLanguage, hash); // Create the xml document XmlDocument doc = new XmlDocument(); try { // Load the xml document doc.LoadXml(xmlResponse); // Add data from the xml responseData.Add("error_code", ParseXmlNode(doc, "/payex/status/errorCode")); responseData.Add("description", ParseXmlNode(doc, "/payex/status/description")); responseData.Add("order_ref", ParseXmlNode(doc, "/payex/orderRef")); responseData.Add("redirect_url", ParseXmlNode(doc, "/payex/redirectUrl")); } catch (Exception ex) { responseData.Add("exception", ex.Message); } // Check if the response data contains the order reference if(responseData.ContainsKey("order_ref") == false) { return responseData; } // Sum of order rows decimal payexSum = 0; // Add order rows for (int i = 0; i < orderRows.Count; i++) { // Calculate values Int32 quantity = (Int32)orderRows[i].quantity; decimal priceValue = Math.Round(orderRows[i].unit_price * quantity * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; decimal vatValue = priceValue * orderRows[i].vat_percent; decimal orderValue = Math.Round((priceValue + vatValue) * 100, MidpointRounding.AwayFromZero) / 100; Int64 amount = (Int64)Math.Round((priceValue + vatValue) * 100, MidpointRounding.AwayFromZero); Int32 vatPrice = (Int32)Math.Round(vatValue * 100, MidpointRounding.AwayFromZero); Int32 vatPercent = (Int32)Math.Round(orderRows[i].vat_percent * 100, MidpointRounding.AwayFromZero); hash = GetMD5Hash(accountNumber.ToString() + responseData["order_ref"] + orderRows[i].product_code + orderRows[i].product_name + quantity.ToString() + amount.ToString() + vatPrice.ToString() + vatPercent.ToString() + settings.Get("PAYEX-ENCRYPTION-KEY")); // Add the order row string error = pxOrder.AddSingleOrderLine2(accountNumber, responseData["order_ref"], orderRows[i].product_code, orderRows[i].product_name, "", "", "", "", quantity, amount, vatPrice, vatPercent, hash); // Add to the payex sum payexSum += orderValue; } // Calculate the rounding amount decimal rounding = Math.Round((order.total_sum - payexSum) * 100, MidpointRounding.AwayFromZero) / 100; // Add the rounding if (rounding != 0) { Int64 roundingAmount = (Int64)Math.Round(rounding * 100, MidpointRounding.AwayFromZero); hash = GetMD5Hash(accountNumber.ToString() + responseData["order_ref"] + "rd" + tt.Get("rounding") + "1" + roundingAmount.ToString() + "0" + "0" + settings.Get("PAYEX-ENCRYPTION-KEY")); string errorMessage = pxOrder.AddSingleOrderLine2(accountNumber, responseData["order_ref"], "rd", tt.Get("rounding"), "", "", "", "", 1, roundingAmount, 0, 0, hash); } // Add the gift cards amount if(order.gift_cards_amount > 0) { decimal amount = order.gift_cards_amount > payexSum ? payexSum : order.gift_cards_amount; Int64 giftCardsAmount = (Int64)Math.Round(amount * -1 * 100, MidpointRounding.AwayFromZero); hash = GetMD5Hash(accountNumber.ToString() + responseData["order_ref"] + "gc" + tt.Get("gift_cards") + "1" + giftCardsAmount.ToString() + "0" + "0" + settings.Get("PAYEX-ENCRYPTION-KEY")); string errorMessage = pxOrder.AddSingleOrderLine2(accountNumber, responseData["order_ref"], "gc", tt.Get("gift_cards"), "", "", "", "", 1, giftCardsAmount, 0, 0, hash); } // Check if we should create an invoice if (paymentType == "INVOICE") { if(order.customer_type == 0) { responseData = CreateInvoiceCorporate(responseData["order_ref"], order, domain, settings, tt); } else if (order.customer_type == 1) { responseData = CreateInvoicePrivate(responseData["order_ref"], order, domain, settings, tt); } } // Return the response data return responseData; } // End of the CreateOrderTest method
} // End of the UpdatePaymentStatus method /// <summary> /// Respond to an updated order status /// </summary> /// <param name="order"></param> /// <param name="paymentOption"></param> /// <param name="orderStatus"></param> /// <returns></returns> private string UpdateOrderStatus(Order order, PaymentOption paymentOption, string orderStatus) { // Create the string to return string error_message = ""; // Get the current domain Domain domain = Tools.GetCurrentDomain(); // Get webshop settings KeyStringList webshopSettings = WebshopSetting.GetAllFromCache(); // Check the order status if (orderStatus == "order_status_delivered") { if(paymentOption.connection == 102) // Payson invoice { // Get credentials string paysonEmail = webshopSettings.Get("PAYSON-EMAIL"); string userId = webshopSettings.Get("PAYSON-AGENT-ID"); string md5Key = webshopSettings.Get("PAYSON-MD5-KEY"); bool paysonTest = false; bool.TryParse(webshopSettings.Get("PAYSON-TEST"), out paysonTest); // Create the api PaysonIntegration.PaysonApi paysonApi = new PaysonIntegration.PaysonApi(userId, md5Key, null, paysonTest); // Update the order PaysonIntegration.Data.PaymentUpdateData paymentUpdateData = new PaysonIntegration.Data.PaymentUpdateData(order.payment_token, PaysonIntegration.Utils.PaymentUpdateAction.ShipOrder); PaysonIntegration.Response.PaymentUpdateResponse paymentUpdateResponse = paysonApi.MakePaymentUpdateRequest(paymentUpdateData); // Check if the response is successful if (paymentUpdateResponse != null && paymentUpdateResponse.Success == false) { // Set error messages foreach (string key in paymentUpdateResponse.ErrorMessages) { error_message += "• " + "Payson: " + paymentUpdateResponse.ErrorMessages[key] + "<br/>"; } } } else if(paymentOption.connection == 301) // Svea invoice { // Get the order rows List<OrderRow> orderRows = OrderRow.GetByOrderId(order.id); // Create the payment configuration SveaSettings sveaConfiguration = new SveaSettings(); // Create the order builder Webpay.Integration.CSharp.Order.Handle.DeliverOrderBuilder inoviceBuilder = Webpay.Integration.CSharp.WebpayConnection.DeliverOrder(sveaConfiguration); // Add order rows for (int i = 0; i < orderRows.Count; i++) { // Get the unit Unit unit = Unit.GetOneById(orderRows[i].unit_id, domain.back_end_language); // Create an order item Webpay.Integration.CSharp.Order.Row.OrderRowBuilder orderItem = new Webpay.Integration.CSharp.Order.Row.OrderRowBuilder(); orderItem.SetArticleNumber(orderRows[i].product_code); orderItem.SetName(orderRows[i].product_name); orderItem.SetQuantity(orderRows[i].quantity); orderItem.SetUnit(unit.unit_code); orderItem.SetAmountExVat(orderRows[i].unit_price); orderItem.SetVatPercent(orderRows[i].vat_percent * 100); // Add the order item inoviceBuilder.AddOrderRow(orderItem); } // Get the order id Int64 sveaOrderId = 0; Int64.TryParse(order.payment_token, out sveaOrderId); // Set invoice values inoviceBuilder.SetOrderId(sveaOrderId); inoviceBuilder.SetNumberOfCreditDays(15); inoviceBuilder.SetInvoiceDistributionType(Webpay.Integration.CSharp.Util.Constant.DistributionType.POST); inoviceBuilder.SetCountryCode(SveaSettings.GetSveaCountryCode(order.country_code)); // Make the request to send the invoice Webpay.Integration.CSharp.WebpayWS.DeliverOrderEuResponse deliverOrderResponse = inoviceBuilder.DeliverInvoiceOrder().DoRequest(); // Check if the response is successful if (deliverOrderResponse.Accepted == false) { // Set error messages error_message += "• " + "Svea code: " + deliverOrderResponse.ResultCode.ToString() + "<br/>"; error_message += "• " + "Svea message: " + deliverOrderResponse.ErrorMessage + "<br/>"; } } else if (paymentOption.connection >= 400 && paymentOption.connection <= 499) // Payex { // Check the transaction Dictionary<string, string> payexResponse = PayExManager.CheckTransaction(order, webshopSettings); // Get response variables string error_code = payexResponse.ContainsKey("error_code") == true ? payexResponse["error_code"] : ""; string description = payexResponse.ContainsKey("description") == true ? payexResponse["description"] : ""; string parameter_name = payexResponse.ContainsKey("parameter_name") == true ? payexResponse["parameter_name"] : ""; string transaction_status = payexResponse.ContainsKey("transaction_status") == true ? payexResponse["transaction_status"] : ""; string transaction_number = payexResponse.ContainsKey("transaction_number") == true ? payexResponse["transaction_number"] : ""; // Check if the response was successful if (error_code.ToUpper() == "OK") { if(transaction_status == "3") // Authorize { // Capture the transaction payexResponse = PayExManager.CaptureTransaction(order); // Get response variables error_code = payexResponse.ContainsKey("error_code") == true ? payexResponse["error_code"] : ""; description = payexResponse.ContainsKey("description") == true ? payexResponse["description"] : ""; parameter_name = payexResponse.ContainsKey("parameter_name") == true ? payexResponse["parameter_name"] : ""; transaction_status = payexResponse.ContainsKey("transaction_status") == true ? payexResponse["transaction_status"] : ""; transaction_number = payexResponse.ContainsKey("transaction_number") == true ? payexResponse["transaction_number"] : ""; string transaction_number_original = payexResponse.ContainsKey("transaction_number_original") == true ? payexResponse["transaction_number_original"] : ""; if(error_code.ToUpper() != "OK" || transaction_status != "6") { // Set error messages error_message += "• " + "Payex code: " + error_code + "<br/>"; error_message += "• " + "Payex message: " + description + "<br/>"; error_message += "• " + "Payex parameter: " + parameter_name + "<br/>"; error_message += "• " + "Payex status: " + transaction_status + "<br/>"; error_message += "• " + "Payex number (original): " + transaction_number + "<br/>"; } else { // Update the transaction number for the order Order.SetPaymentToken(order.id, transaction_number); } } } else { // Set error messages error_message += "• " + "Payex code: " + error_code + "<br/>"; error_message += "• " + "Payex message: " + description + "<br/>"; error_message += "• " + "Payex parameter: " + parameter_name + "<br/>"; error_message += "• " + "Payex status: " + transaction_status + "<br/>"; error_message += "• " + "Payex number: " + transaction_number + "<br/>"; } } } else if (orderStatus == "order_status_cancelled") { if(paymentOption.connection >= 100 && paymentOption.connection <= 199) // Payson { // Get credentials string paysonEmail = webshopSettings.Get("PAYSON-EMAIL"); string userId = webshopSettings.Get("PAYSON-AGENT-ID"); string md5Key = webshopSettings.Get("PAYSON-MD5-KEY"); bool paysonTest = false; bool.TryParse(webshopSettings.Get("PAYSON-TEST"), out paysonTest); // Create the api PaysonIntegration.PaysonApi paysonApi = new PaysonIntegration.PaysonApi(userId, md5Key, null, paysonTest); // Get details about the payment status PaysonIntegration.Response.PaymentDetailsResponse paysonResponse = paysonApi.MakePaymentDetailsRequest(new PaysonIntegration.Data.PaymentDetailsData(order.payment_token)); // Get the type and status of the payment PaysonIntegration.Utils.PaymentType? paymentType = paysonResponse.PaymentDetails.PaymentType; PaysonIntegration.Utils.PaymentStatus? paymentStatus = paysonResponse.PaymentDetails.PaymentStatus; PaysonIntegration.Utils.InvoiceStatus? invoiceStatus = paysonResponse.PaymentDetails.InvoiceStatus; // Payment update PaysonIntegration.Data.PaymentUpdateData paymentUpdateData = null; PaysonIntegration.Response.PaymentUpdateResponse paymentUpdateResponse = null; if (paymentType == PaysonIntegration.Utils.PaymentType.Direct && paymentStatus == PaysonIntegration.Utils.PaymentStatus.Completed) { // Refund the payment paymentUpdateData = new PaysonIntegration.Data.PaymentUpdateData(order.payment_token, PaysonIntegration.Utils.PaymentUpdateAction.Refund); paymentUpdateResponse = paysonApi.MakePaymentUpdateRequest(paymentUpdateData); } else if (paymentType == PaysonIntegration.Utils.PaymentType.Invoice && invoiceStatus == PaysonIntegration.Utils.InvoiceStatus.OrderCreated) { // Cancel the order paymentUpdateData = new PaysonIntegration.Data.PaymentUpdateData(order.payment_token, PaysonIntegration.Utils.PaymentUpdateAction.CancelOrder); paymentUpdateResponse = paysonApi.MakePaymentUpdateRequest(paymentUpdateData); } else if (paymentType == PaysonIntegration.Utils.PaymentType.Invoice && (invoiceStatus == PaysonIntegration.Utils.InvoiceStatus.Shipped || invoiceStatus == PaysonIntegration.Utils.InvoiceStatus.Done)) { // Credit the order paymentUpdateData = new PaysonIntegration.Data.PaymentUpdateData(order.payment_token, PaysonIntegration.Utils.PaymentUpdateAction.CreditOrder); paymentUpdateResponse = paysonApi.MakePaymentUpdateRequest(paymentUpdateData); } // Check if there was any errors if (paymentUpdateResponse != null && paymentUpdateResponse.Success == false) { // Set error messages foreach (string key in paymentUpdateResponse.ErrorMessages) { error_message += "• " + "Payson: " + paymentUpdateResponse.ErrorMessages[key] + "<br/>"; } } } else if(paymentOption.connection == 201) // PayPal { // Get credentials string paypalClientId = webshopSettings.Get("PAYPAL-CLIENT-ID"); string paypalClientSecret = webshopSettings.Get("PAYPAL-CLIENT-SECRET"); string paypalMode = webshopSettings.Get("PAYPAL-MODE"); Dictionary<string, string> config = new Dictionary<string, string> { { "mode", paypalMode } }; try { // Create the credential token PayPal.OAuthTokenCredential tokenCredential = new PayPal.OAuthTokenCredential(paypalClientId, paypalClientSecret, config); // Create the api context PayPal.APIContext paypalContext = new PayPal.APIContext(tokenCredential.GetAccessToken()); paypalContext.Config = config; // Look up the sale PayPal.Api.Payments.Sale sale = PayPal.Api.Payments.Sale.Get(paypalContext, order.payment_token); if (sale.state == "completed") { // Refund the payment paypalContext.HTTPHeaders = null; PayPal.Api.Payments.Refund refund = sale.Refund(paypalContext, new PayPal.Api.Payments.Refund()); if(refund.state != "completed") { error_message += "• " + "PayPal: " + refund.state; } } else { error_message += "• " + "PayPal: " + sale.state; } } catch (Exception ex) { error_message += "• PayPal: " + ex.Message; } } else if(paymentOption.connection == 301) // Svea invoice { // Create the payment configuration SveaSettings sveaConfiguration = new SveaSettings(); // Get the order id Int64 sveaOrderId = 0; Int64.TryParse(order.payment_token, out sveaOrderId); // Cancel the order Webpay.Integration.CSharp.Order.Handle.CloseOrderBuilder closeOrder = Webpay.Integration.CSharp.WebpayConnection.CloseOrder(sveaConfiguration); closeOrder.SetOrderId(sveaOrderId); closeOrder.SetCountryCode(SveaSettings.GetSveaCountryCode(order.country_code)); Webpay.Integration.CSharp.WebpayWS.CloseOrderEuResponse closeOrderResponse = closeOrder.CloseInvoiceOrder().DoRequest(); // Check if the response is successful if (closeOrderResponse.Accepted == false) { // Set error messages error_message += "• " + "Svea code: " + closeOrderResponse.ResultCode.ToString() + "<br/>"; error_message += "• " + "Svea message: " + closeOrderResponse.ErrorMessage + "<br/>"; } } else if(paymentOption.connection >= 400 && paymentOption.connection <= 499) // Payex { // Check the transaction Dictionary<string, string> payexResponse = PayExManager.CheckTransaction(order, webshopSettings); // Get response variables string error_code = payexResponse.ContainsKey("error_code") == true ? payexResponse["error_code"] : ""; string description = payexResponse.ContainsKey("description") == true ? payexResponse["description"] : ""; string parameter_name = payexResponse.ContainsKey("parameter_name") == true ? payexResponse["parameter_name"] : ""; string transaction_status = payexResponse.ContainsKey("transaction_status") == true ? payexResponse["transaction_status"] : ""; string transaction_number = payexResponse.ContainsKey("transaction_number") == true ? payexResponse["transaction_number"] : ""; // Check if the response was successful if(error_code.ToUpper() == "OK") { // Check if we should cancel or credit the order if(transaction_status == "3") // Authorize { // Cancel the transaction payexResponse = PayExManager.CancelTransaction(order, webshopSettings); // Get response variables error_code = payexResponse.ContainsKey("error_code") == true ? payexResponse["error_code"] : ""; description = payexResponse.ContainsKey("description") == true ? payexResponse["description"] : ""; parameter_name = payexResponse.ContainsKey("parameter_name") == true ? payexResponse["parameter_name"] : ""; transaction_status = payexResponse.ContainsKey("transaction_status") == true ? payexResponse["transaction_status"] : ""; transaction_number = payexResponse.ContainsKey("transaction_number") == true ? payexResponse["transaction_number"] : ""; if(error_code.ToUpper() != "OK" || transaction_status != "4") { // Set error messages error_message += "• " + "Payex code: " + error_code + "<br/>"; error_message += "• " + "Payex message: " + description + "<br/>"; error_message += "• " + "Payex parameter: " + parameter_name + "<br/>"; error_message += "• " + "Payex status: " + transaction_status + "<br/>"; error_message += "• " + "Payex number: " + transaction_number + "<br/>"; } } else if(transaction_status == "0" || transaction_status == "6") // Sale or capture { // Get the order rows List<OrderRow> orderRows = OrderRow.GetByOrderId(order.id); // Credit the transaction payexResponse = PayExManager.CreditTransaction(order, orderRows, webshopSettings); // Get response variables error_code = payexResponse.ContainsKey("error_code") == true ? payexResponse["error_code"] : ""; description = payexResponse.ContainsKey("description") == true ? payexResponse["description"] : ""; parameter_name = payexResponse.ContainsKey("parameter_name") == true ? payexResponse["parameter_name"] : ""; transaction_status = payexResponse.ContainsKey("transaction_status") == true ? payexResponse["transaction_status"] : ""; transaction_number = payexResponse.ContainsKey("transaction_number") == true ? payexResponse["transaction_number"] : ""; if (error_code.ToUpper() != "OK" || transaction_status != "2") { // Set error messages error_message += "• " + "Payex code: " + error_code + "<br/>"; error_message += "• " + "Payex message: " + description + "<br/>"; error_message += "• " + "Payex parameter: " + parameter_name + "<br/>"; error_message += "• " + "Payex status: " + transaction_status + "<br/>"; error_message += "• " + "Payex number: " + transaction_number + "<br/>"; } } } else { // Set error messages error_message += "• " + "Payex code: " + error_code + "<br/>"; error_message += "• " + "Payex message: " + description + "<br/>"; error_message += "• " + "Payex parameter: " + parameter_name + "<br/>"; error_message += "• " + "Payex status: " + transaction_status + "<br/>"; error_message += "• " + "Payex number: " + transaction_number + "<br/>"; } } } // Return the error message return error_message; } // End of the UpdateOrderStatus method
public ActionResult edit(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get all the form values Int32 id = Convert.ToInt32(collection["txtId"]); string customer_email = collection["txtEmail"]; string customer_org_number = collection["txtOrgNumber"]; string customer_vat_number = collection["txtVatNumber"]; string customer_phone = collection["txtPhoneNumber"]; string customer_mobile_phone = collection["txtMobilePhoneNumber"]; string customer_name = collection["txtCustomerName"]; string invoice_name = collection["txtInvoiceName"]; string invoice_address_1 = collection["txtInvoiceAddress1"]; string invoice_address_2 = collection["txtInvoiceAddress2"]; string invoice_post_code = collection["txtInvoicePostCode"]; string invoice_city = collection["txtInvoiceCity"]; string invoice_country_id = collection["selectInvoiceCountry"]; string delivery_name = collection["txtDeliveryName"]; string delivery_address_1 = collection["txtDeliveryAddress1"]; string delivery_address_2 = collection["txtDeliveryAddress2"]; string delivery_post_code = collection["txtDeliveryPostCode"]; string delivery_city = collection["txtDeliveryCity"]; string delivery_country_id = collection["selectDeliveryCountry"]; string payment_status = collection["selectPaymentStatus"]; string order_status = collection["selectOrderStatus"]; bool exported_to_erp = Convert.ToBoolean(collection["cbExportedToErp"]); DateTime desired_date_of_delivery = DateTime.MinValue; DateTime.TryParse(collection["txtDesiredDateOfDelivery"], out desired_date_of_delivery); string discount_code = collection["txtDiscountCode"]; // Get translated texts KeyStringList tt = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); // Get the saved order Order order = Order.GetOneById(id); // Get the payment option PaymentOption paymentOption = PaymentOption.GetOneById(order.payment_option, currentDomain.back_end_language); // Create the error message string string error_message = ""; // Check for errors if (invoice_country_id == "0") { error_message += "• " + String.Format(tt.Get("error_select_value"), tt.Get("invoice_address") + ":" + tt.Get("country").ToLower()) + "<br/>"; } else { order.invoice_country_id = Convert.ToInt32(invoice_country_id); } if (delivery_country_id == "0") { error_message += "• " + String.Format(tt.Get("error_select_value"), tt.Get("delivery_address") + ":" + tt.Get("country").ToLower()) + "<br/>"; } else { order.delivery_country_id = Convert.ToInt32(delivery_country_id); } // Check if the payment status has been updated on the order if(order.document_type == 1 && order.payment_status != payment_status) { // Respond to the updated payment status error_message += UpdatePaymentStatus(order, payment_status); } // Check if the order status has been updated on the order if (order.document_type == 1 && order.order_status != order_status) { // Respond to the updated order status error_message += UpdateOrderStatus(order, paymentOption, order_status); } // Update values order.customer_email = AnnytabDataValidation.TruncateString(customer_email, 100); order.customer_org_number = AnnytabDataValidation.TruncateString(customer_org_number, 20); order.customer_vat_number = AnnytabDataValidation.TruncateString(customer_vat_number, 20); order.customer_phone = AnnytabDataValidation.TruncateString(customer_phone, 100); order.customer_mobile_phone = AnnytabDataValidation.TruncateString(customer_mobile_phone, 100); order.customer_name = AnnytabDataValidation.TruncateString(customer_name, 100); order.invoice_name = AnnytabDataValidation.TruncateString(invoice_name, 100); order.invoice_address_1 = AnnytabDataValidation.TruncateString(invoice_address_1, 100); order.invoice_address_2 = AnnytabDataValidation.TruncateString(invoice_address_2, 100); order.invoice_post_code = AnnytabDataValidation.TruncateString(invoice_post_code, 100); order.invoice_city = AnnytabDataValidation.TruncateString(invoice_city, 100); order.delivery_name = AnnytabDataValidation.TruncateString(delivery_name, 100); order.delivery_address_1 = AnnytabDataValidation.TruncateString(delivery_address_1, 100); order.delivery_address_2 = AnnytabDataValidation.TruncateString(delivery_address_2, 100); order.delivery_post_code = AnnytabDataValidation.TruncateString(delivery_post_code, 100); order.delivery_city = AnnytabDataValidation.TruncateString(delivery_city, 100); order.payment_status = payment_status; order.order_status = order_status; order.exported_to_erp = exported_to_erp; order.desired_date_of_delivery = AnnytabDataValidation.TruncateDateTime(desired_date_of_delivery); order.discount_code = AnnytabDataValidation.TruncateString(discount_code, 50); // Check if there is any errors if(error_message == "") { // Update the order Order.Update(order); // Redirect the user to the list return Redirect("/admin_orders" + returnUrl); } else { // Update the order Order.Update(order); // Add data to the view ViewBag.ErrorMessage = error_message; ViewBag.TranslatedTexts = tt; ViewBag.Order = order; ViewBag.ReturnUrl = returnUrl; // Return the edit view return View("edit"); } } // End of the edit method
public void InitPage() { var entMan = new EntityManager(); ErpEntity = entMan.ReadEntity(ParentRecordId ?? Guid.Empty).Object; if (ErpEntity == null) { return; } Field = ErpEntity.Fields.FirstOrDefault(x => x.Id == RecordId); if (Field == null) { return; } var allCards = AdminPageUtils.GetFieldCards(); FieldCard = allCards.First(x => (string)x["type"] == ((int)Field.GetFieldType()).ToString()); #region << Init RecordPermissions >> var valueGrid = new List <KeyStringList>(); PermissionOptions = new List <SelectOption>() { new SelectOption("read", "read"), new SelectOption("update", "update") }; var roles = AdminPageUtils.GetUserRoles(); //Special order is applied foreach (var role in roles) { RoleOptions.Add(new SelectOption(role.Id.ToString(), role.Name)); var keyValuesObj = new KeyStringList() { Key = role.Id.ToString(), Values = new List <string>() }; if (Field.Permissions.CanRead.Contains(role.Id)) { keyValuesObj.Values.Add("read"); } if (Field.Permissions.CanUpdate.Contains(role.Id)) { keyValuesObj.Values.Add("update"); } valueGrid.Add(keyValuesObj); } FieldPermissions = JsonConvert.SerializeObject(valueGrid); #endregion #region << Actions >> if (Field.System) { HeaderActions.Add(PageUtils.GetActionTemplate(PageUtilsActionType.Disabled, label: "Delete Locked", formId: "DeleteRecord", iconClass: "fa fa-trash-alt", titleText: "System objects cannot be deleted")); } else { HeaderActions.Add(PageUtils.GetActionTemplate(PageUtilsActionType.ConfirmAndSubmitForm, label: "Delete Field", formId: "DeleteRecord", btnClass: "btn btn-white btn-sm", iconClass: "fa fa-trash-alt go-red")); }; HeaderActions.Add($"<a href='/sdk/objects/entity/r/{(ErpEntity != null ? ErpEntity.Id : Guid.Empty)}/rl/fields/m/{Field.Id}' class='btn btn-white btn-sm'><i class='fa fa-cog go-orange'></i> Manage</a>"); #endregion ApiUrlFieldInlineEdit = ErpSettings.ApiUrlTemplateFieldInlineEdit.Replace("{entityName}", ErpEntity.Name).Replace("{recordId}", (RecordId ?? Guid.Empty).ToString()); }
public ActionResult edit(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get all the form values Int32 languageId = Convert.ToInt32(collection["txtId"]); string name = collection["txtName"]; string languageCode = collection["txtLanguageCode"]; string countryCode = collection["txtCountryCode"]; // Get the default admin language id Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get the language Language language = Language.GetOneById(languageId, adminLanguageId); bool postExists = true; // Check if the language exists if (language == null) { // Create an empty language post language = new Language(); language.id = languageId; postExists = false; } // Update values for the language language.name = name; language.language_code = languageCode; language.country_code = countryCode; // Create a error message string errorMessage = string.Empty; // Check for errors in the language if (language.name.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("name"), "50") + "<br/>"; } if (language.language_code.Length > 2) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("language_code"), "2") + "<br/>"; } if (language.country_code.Length > 2) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("country_code"), "2") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Check if we should add or update the language if (postExists == false) { // Add the language Int64 insertId = Language.AddMasterPost(language); language.id = Convert.ToInt32(insertId); Language.AddLanguagePost(language, adminLanguageId); } else { // Update the language Language.UpdateMasterPost(language); Language.UpdateLanguagePost(language, adminLanguageId); } // Redirect the user to the list return Redirect(returnUrl); } else { // Set form values ViewBag.ErrorMessage = errorMessage; ViewBag.Language = language; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the edit view return View("edit"); } } // End of the edit method
public ActionResult edit(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get the return url string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get all the form values string id = collection["txtId"]; Int32 language_id = Convert.ToInt32(collection["selectLanguage"]); string currency_code = collection["selectCurrency"]; decimal discount_value = 0; decimal.TryParse(collection["txtDiscountValue"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out discount_value); bool free_freight = Convert.ToBoolean(collection["cbFreeFreight"]); bool once_per_customer = Convert.ToBoolean(collection["cbOncePerCustomer"]); bool exclude_products_on_sale = Convert.ToBoolean(collection["cbExcludeProductsOnSale"]); DateTime end_date = Convert.ToDateTime(collection["txtEndDate"]); decimal minimum_order_value = 0; decimal.TryParse(collection["txtMinimumOrderValue"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out minimum_order_value); // Get translated texts KeyStringList tt = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); // Get the discount code DiscountCode discountCode = DiscountCode.GetOneById(id); bool postExists = true; // Check if the discount code exists if (discountCode == null) { // Create an empty discount code discountCode = new DiscountCode(); postExists = false; } // Update values discountCode.id = id; discountCode.language_id = language_id; discountCode.currency_code = currency_code; discountCode.discount_value = discount_value; discountCode.free_freight = free_freight; discountCode.once_per_customer = once_per_customer; discountCode.exclude_products_on_sale = exclude_products_on_sale; discountCode.end_date = AnnytabDataValidation.TruncateDateTime(end_date); discountCode.minimum_order_value = minimum_order_value; // Create a error message string errorMessage = string.Empty; if (discountCode.id.Length == 0 || discountCode.id.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_certain_length"), tt.Get("id"), "1", "50") + "<br/>"; } if (discountCode.language_id == 0) { errorMessage += "• " + String.Format(tt.Get("error_select_value"), tt.Get("language").ToLower()) + "<br/>"; } if (discountCode.currency_code == "") { errorMessage += "• " + String.Format(tt.Get("error_select_value"), tt.Get("currency").ToLower()) + "<br/>"; } if (discountCode.discount_value < 0 || discountCode.discount_value > 9.999M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("discount"), "9.999") + "<br/>"; } if (discountCode.minimum_order_value < 0 || discountCode.minimum_order_value > 999999999999.99M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("minimum_order_value"), "999 999 999 999.99") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Check if we should add or update the discount code if (postExists == false) { // Add the discount code DiscountCode.Add(discountCode); } else { // Update the discount code DiscountCode.Update(discountCode); } // Redirect the user to the list return Redirect("/admin_discount_codes" + returnUrl); } else { // Set form values ViewBag.ErrorMessage = errorMessage; ViewBag.TranslatedTexts = tt; ViewBag.Languages = Language.GetAll(currentDomain.back_end_language, "id", "ASC"); ViewBag.DiscountCode = discountCode; ViewBag.ReturnUrl = returnUrl; // Return the edit view return View("edit"); } } // End of the edit method
public ActionResult edit(FormCollection collection) { // Get the current domain var currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get the return url string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return(View("index")); } else { // Redirect the user to the start page return(RedirectToAction("index", "admin_login")); } // Get all the form values string currency_code = collection["txtCurrencyCode"]; decimal conversion_rate = 0; decimal.TryParse(collection["txtConversionRate"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out conversion_rate); Int16 currency_base = 0; Int16.TryParse(collection["txtCurrencyBase"].Replace(",", "."), out currency_base); byte decimals = 0; byte.TryParse(collection["txtDecimals"].Replace(",", "."), out decimals); // Get the default admin language id Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get the currency Currency currency = Currency.GetOneById(currency_code); bool postExists = true; // Check if the static text exists if (currency == null) { // Create an empty currency currency = new Currency(); postExists = false; } // Update values currency.currency_code = currency_code; currency.conversion_rate = conversion_rate; currency.currency_base = currency_base; currency.decimals = decimals; // Create a error message string errorMessage = string.Empty; // Check for errors in the currency if (currency.currency_code.Length != 3) { errorMessage += "• " + String.Format(tt.Get("error_field_certain_length"), tt.Get("currency_code"), "3", "3") + "<br/>"; } if (currency.conversion_rate < 0 || currency.conversion_rate > 9999.999999M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("conversion_rate"), "9 999.999999") + "<br/>"; } if (currency.decimals < 0 || currency.decimals > 2) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("number_of_decimals"), "3") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Check if we should add or update the static text if (postExists == false) { // Add the currency Currency.Add(currency); } else { // Update the currency Currency.Update(currency); } // Redirect the user to the list return(Redirect("/admin_currencies" + returnUrl)); } else { // Set form values ViewBag.ErrorMessage = errorMessage; ViewBag.Currency = currency; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the edit view return(View("edit")); } } // End of the edit method
public ActionResult edit(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get the return url string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor", "Author" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get all the form values Int32 id = Convert.ToInt32(collection["txtId"]); string title = collection["txtTitle"]; string media_type = collection["selectMediaType"]; HttpPostedFileBase media_file_content = Request.Files["uploadMediaFile"]; // Get the default admin language id Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get the media file post MediaFile mediaFilePost = MediaFile.GetOneById(id); bool postExists = true; // Check if the media files exists if (mediaFilePost == null) { // Create an empty media file mediaFilePost = new MediaFile(); postExists = false; } // Update values mediaFilePost.title = title; mediaFilePost.media_type = media_type; // Create a error message string errorMessage = string.Empty; // Check for errors in the campaign if (mediaFilePost.title.Length > 100) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("title"), "100") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Check if we should add the media file if (postExists == false) { // Add the media file Int64 insertId = MediaFile.Add(mediaFilePost); mediaFilePost.id = Convert.ToInt32(insertId); } // Update the media file if (media_file_content.ContentLength > 0) { UpdateMediaFile(mediaFilePost, media_file_content); } // Update the media file MediaFile.Update(mediaFilePost); // Redirect the user to the list return Redirect(returnUrl); } else { // Set form values ViewBag.ErrorMessage = errorMessage; ViewBag.TranslatedTexts = tt; ViewBag.MediaFile = mediaFilePost; ViewBag.ReturnUrl = returnUrl; // Return the edit view return View("edit"); } } // End of the edit method
public ActionResult edit(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get all the form values Int32 id = Convert.ToInt32(collection["txtId"]); string link_name = collection["txtLinkname"]; string url = collection["txtUrl"]; string rel = collection["selectRelation"]; string target = collection["selectTarget"]; bool inactive = Convert.ToBoolean(collection["cbInactive"]); // Get the default admin language id Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get the weblink Weblink weblink = Weblink.GetOneById(id, adminLanguageId); // Check if the weblink exists if (weblink == null) { // Create an empty weblink weblink = new Weblink(); } // Update values weblink.rel = rel; weblink.target = target; weblink.link_name = link_name; weblink.url = url; weblink.inactive = inactive; // Create a error message string errorMessage = string.Empty; // Check for errors if (weblink.link_name.Length > 100) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("linkname"), "100") + "<br/>"; } if (weblink.url.Length > 100) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("url"), "100") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Check if we should add or update the weblink if (weblink.id == 0) { // Add the weblink Int64 insertId = Weblink.AddMasterPost(weblink); weblink.id = Convert.ToInt32(insertId); Weblink.AddLanguagePost(weblink, adminLanguageId); } else { // Update the weblink Weblink.UpdateMasterPost(weblink); Weblink.UpdateLanguagePost(weblink, adminLanguageId); } // Redirect the user to the list return Redirect(returnUrl); } else { // Set form values ViewBag.ErrorMessage = errorMessage; ViewBag.Weblink = weblink; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the edit view return View("edit"); } } // End of the edit method
} // End of the CompleteOrderTest method /// <summary> /// Complete a production order /// </summary> private static Dictionary<string, string> CompleteOrderProduction(string orderReference, KeyStringList settings) { // Create the dictionary to return Dictionary<string, string> responseData = new Dictionary<string, string>(10); // Create the PayEx order Annytab.Webshop.Payex.Production.PxOrder pxOrder = new Annytab.Webshop.Payex.Production.PxOrder(); // Get the account number Int64 accountNumber = 0; Int64.TryParse(settings.Get("PAYEX-ACCOUNT-NUMBER"), out accountNumber); // Create the hash string hash = GetMD5Hash(accountNumber.ToString() + orderReference + settings.Get("PAYEX-ENCRYPTION-KEY")); // Get the transaction information string xmlResponse = pxOrder.Complete(accountNumber, orderReference, hash); // Parse the xml response XmlDocument doc = new XmlDocument(); try { // Load the xml document doc.LoadXml(xmlResponse); // Get data from the xml response responseData.Add("error_code", ParseXmlNode(doc, "/payex/status/errorCode")); responseData.Add("description", ParseXmlNode(doc, "/payex/status/description")); responseData.Add("transaction_status", ParseXmlNode(doc, "/payex/transactionStatus")); responseData.Add("transaction_number", ParseXmlNode(doc, "/payex/transactionNumber")); responseData.Add("already_completed", ParseXmlNode(doc, "/payex/alreadyCompleted")); responseData.Add("order_id", ParseXmlNode(doc, "/payex/orderId")); responseData.Add("payment_method", ParseXmlNode(doc, "/payex/paymentMethod")); } catch (Exception ex) { responseData.Add("exception", ex.Message); } // Return the response data return responseData; } // End of the CompleteOrderProduction method
public ActionResult translate(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor", "Translator" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get the admin default language Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get all the form values Int32 translationLanguageId = Convert.ToInt32(collection["selectLanguage"]); Int32 id = Convert.ToInt32(collection["hiddenWeblinkId"]); string link_name = collection["txtTranslatedLinkname"]; string url = collection["txtTranslatedUrl"]; bool inactive = Convert.ToBoolean(collection["cbInactive"]); // Create the translated weblink Weblink translatedWeblink = new Weblink(); translatedWeblink.id = id; translatedWeblink.link_name = link_name; translatedWeblink.url = url; translatedWeblink.inactive = inactive; // Create a error message string errorMessage = string.Empty; // Check for errors if (translatedWeblink.link_name.Length > 100) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("link_name"), "100") + "<br/>"; } if (translatedWeblink.url.Length > 100) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("url"), "100") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Get the saved weblink Weblink weblink = Weblink.GetOneById(id, translationLanguageId); if (weblink == null) { // Add a new translated weblink Weblink.AddLanguagePost(translatedWeblink, translationLanguageId); } else { // Update values for the saved weblink weblink.link_name = translatedWeblink.link_name; weblink.url = translatedWeblink.url; weblink.inactive = translatedWeblink.inactive; // Update the weblink translation Weblink.UpdateLanguagePost(weblink, translationLanguageId); } // Redirect the user to the list return Redirect(returnUrl); } else { // Set form values ViewBag.LanguageId = translationLanguageId; ViewBag.Languages = Language.GetAll(adminLanguageId, "name", "ASC"); ViewBag.StandardWeblink = Weblink.GetOneById(id, adminLanguageId); ViewBag.TranslatedWeblink = translatedWeblink; ViewBag.ErrorMessage = errorMessage; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the translate view return View("translate"); } } // End of the translate method
} // End of the CaptureTransactionTest method /// <summary> /// Capture an authorized production transaction /// </summary> private static Dictionary<string, string> CaptureTransactionProduction(Order order, KeyStringList settings) { // Create the dictionary to return Dictionary<string, string> responseData = new Dictionary<string, string>(10); // Create the PayEx order Annytab.Webshop.Payex.Production.PxOrder pxOrder = new Annytab.Webshop.Payex.Production.PxOrder(); // Get the currency Currency orderCurrency = Currency.GetOneById(order.currency_code); // Calculate the decimal multiplier Int32 decimalMultiplier = (Int32)Math.Pow(10, orderCurrency.decimals); // Get the data Int64 accountNumber = 0; Int64.TryParse(settings.Get("PAYEX-ACCOUNT-NUMBER"), out accountNumber); Int32 transactionNumber = 0; Int32.TryParse(order.payment_token, out transactionNumber); Int64 amount = (Int64)Math.Round(order.total_sum * 100, MidpointRounding.AwayFromZero); Int32 vatAmount = (Int32)Math.Round(order.vat_sum * 100, MidpointRounding.AwayFromZero); string additionalValues = ""; // Create the hash string hash = GetMD5Hash(accountNumber.ToString() + transactionNumber.ToString() + amount.ToString() + order.id.ToString() + vatAmount.ToString() + additionalValues + settings.Get("PAYEX-ENCRYPTION-KEY")); // Get the transaction information string xmlResponse = pxOrder.Capture5(accountNumber, transactionNumber, amount, order.id.ToString(), vatAmount, additionalValues, hash); // Parse the xml response XmlDocument doc = new XmlDocument(); try { // Load the xml document doc.LoadXml(xmlResponse); // Get data from the xml response responseData.Add("error_code", ParseXmlNode(doc, "/payex/status/errorCode")); responseData.Add("description", ParseXmlNode(doc, "/payex/status/description")); responseData.Add("parameter_name", ParseXmlNode(doc, "/payex/paramName")); responseData.Add("transaction_status", ParseXmlNode(doc, "/payex/transactionStatus")); responseData.Add("transaction_number", ParseXmlNode(doc, "/payex/transactionNumber")); responseData.Add("transaction_number_original", ParseXmlNode(doc, "/payex/originalTransactionNumber")); } catch (Exception ex) { responseData.Add("exception", ex.Message); } // Return the response data return responseData; } // End of the CaptureTransactionProduction method
public ActionResult edit(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get all the form values Int32 id = Convert.ToInt32(collection["txtId"]); string product_code = collection["txtProductCode"]; string name = collection["txtName"]; decimal fee = 0; decimal.TryParse(collection["txtFee"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out fee); Int32 unit_id = Convert.ToInt32(collection["selectUnit"]); bool price_based_on_mount_time = Convert.ToBoolean(collection["cbPriceBasedOnMountTime"]); Int32 value_added_tax_id = Convert.ToInt32(collection["selectValueAddedTax"]); string account_code = collection["txtAccountCode"]; bool inactive = Convert.ToBoolean(collection["cbInactive"]); // Get the default admin language id Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get the additional service AdditionalService additionalService = AdditionalService.GetOneById(id, adminLanguageId); // Check if the additional service exists if (additionalService == null) { // Create a empty additional service additionalService = new AdditionalService(); } // Update values additionalService.product_code = product_code; additionalService.name = name; additionalService.fee = fee; additionalService.unit_id = unit_id; additionalService.price_based_on_mount_time = price_based_on_mount_time; additionalService.value_added_tax_id = value_added_tax_id; additionalService.account_code = account_code; additionalService.inactive = inactive; // Create a error message string errorMessage = string.Empty; // Check for errors in the additional service if (additionalService.product_code.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("product_code"), "50") + "<br/>"; } if (additionalService.name.Length > 100) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("name"), "100") + "<br/>"; } if (additionalService.fee < 0 || additionalService.fee > 9999999999.99M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("fee"), "9 999 999 999.99") + "<br/>"; } if (additionalService.account_code.Length > 10) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("account_code"), "10") + "<br/>"; } if (additionalService.unit_id == 0) { errorMessage += "• " + String.Format(tt.Get("error_select_value"), tt.Get("unit").ToLower()) + "<br/>"; } if (additionalService.value_added_tax_id == 0) { errorMessage += "• " + String.Format(tt.Get("error_select_value"), tt.Get("value_added_tax").ToLower()) + "<br/>"; } // Check if there is errors if (errorMessage == "") { // Check if we should add or update the additional service if (additionalService.id == 0) { // Add the additional service Int64 insertId = AdditionalService.AddMasterPost(additionalService); additionalService.id = Convert.ToInt32(insertId); AdditionalService.AddLanguagePost(additionalService, adminLanguageId); } else { // Update the additional service AdditionalService.UpdateMasterPost(additionalService); AdditionalService.UpdateLanguagePost(additionalService, adminLanguageId); } // Redirect the user to the list return Redirect("/admin_additional_services" + returnUrl); } else { // Set form values ViewBag.ErrorMessage = errorMessage; ViewBag.Units = Unit.GetAll(adminLanguageId, "name", "ASC"); ViewBag.AdditionalService = additionalService; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the edit view return View("edit"); } } // End of the edit method
} // End of the CancelTransactionTest method /// <summary> /// Cancel an authorized production transaction /// </summary> public static Dictionary<string, string> CancelTransactionProduction(Order order, KeyStringList settings) { // Create the dictionary to return Dictionary<string, string> responseData = new Dictionary<string, string>(10); // Create the PayEx order Annytab.Webshop.Payex.Production.PxOrder pxOrder = new Annytab.Webshop.Payex.Production.PxOrder(); // Get the data Int64 accountNumber = 0; Int64.TryParse(settings.Get("PAYEX-ACCOUNT-NUMBER"), out accountNumber); Int32 transactionNumber = 0; Int32.TryParse(order.payment_token, out transactionNumber); // Create the hash string hash = GetMD5Hash(accountNumber.ToString() + transactionNumber.ToString() + settings.Get("PAYEX-ENCRYPTION-KEY")); // Get the transaction information string xmlResponse = pxOrder.Cancel2(accountNumber, transactionNumber, hash); // Parse the xml response XmlDocument doc = new XmlDocument(); try { // Load the xml document doc.LoadXml(xmlResponse); // Get data from the xml response paramName responseData.Add("error_code", ParseXmlNode(doc, "/payex/status/errorCode")); responseData.Add("description", ParseXmlNode(doc, "/payex/status/description")); responseData.Add("parameter_name", ParseXmlNode(doc, "/payex/paramName")); responseData.Add("transaction_status", ParseXmlNode(doc, "/payex/transactionStatus")); responseData.Add("transaction_number", ParseXmlNode(doc, "/payex/transactionNumber")); } catch (Exception ex) { responseData.Add("exception", ex.Message); } // Return the response data return responseData; } // End of the CancelTransactionProduction method
public ActionResult translate(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor", "Translator" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get the admin default language Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get all the form values Int32 translationLanguageId = Convert.ToInt32(collection["selectLanguage"]); Int32 id = Convert.ToInt32(collection["hiddenAdditionalServiceId"]); string name = collection["txtTranslatedName"]; Int32 value_added_tax_id = Convert.ToInt32(collection["selectValueAddedTax"]); string account_code = collection["txtAccountCode"]; bool inactive = Convert.ToBoolean(collection["cbInactive"]); // Create the translated additional service AdditionalService translatedAdditionalService = new AdditionalService(); translatedAdditionalService.id = id; translatedAdditionalService.name = name; translatedAdditionalService.value_added_tax_id = value_added_tax_id; translatedAdditionalService.account_code = account_code; translatedAdditionalService.inactive = inactive; // Create a error message string errorMessage = string.Empty; // Check for errors if (translatedAdditionalService.name.Length > 100) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("name"), "100") + "<br/>"; } if (translatedAdditionalService.value_added_tax_id == 0) { errorMessage += "• " + String.Format(tt.Get("error_select_value"), tt.Get("value_added_tax").ToLower()) + "<br/>"; } if (translatedAdditionalService.account_code.Length > 10) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("account_code"), "10") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Get the saved additional service AdditionalService additionalService = AdditionalService.GetOneById(id, translationLanguageId); if (additionalService == null) { // Add a new translated additional service AdditionalService.AddLanguagePost(translatedAdditionalService, translationLanguageId); } else { // Update the translated additional service additionalService.name = translatedAdditionalService.name; additionalService.value_added_tax_id = translatedAdditionalService.value_added_tax_id; additionalService.account_code = translatedAdditionalService.account_code; additionalService.inactive = translatedAdditionalService.inactive; AdditionalService.UpdateLanguagePost(additionalService, translationLanguageId); } // Redirect the user to the list return Redirect("/admin_additional_services" + returnUrl); } else { // Set form values ViewBag.LanguageId = translationLanguageId; ViewBag.Languages = Language.GetAll(adminLanguageId, "name", "ASC"); ViewBag.StandardAdditionalService = AdditionalService.GetOneById(id, adminLanguageId); ViewBag.TranslatedAdditionalService = translatedAdditionalService; ViewBag.ErrorMessage = errorMessage; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the translate view return View("translate"); } } // End of the translate method
} // End of the CreateInvoicePrivate method /// <summary> /// Create a test invoice for a person /// </summary> private static Dictionary<string, string> CreateInvoicePrivateTest(string orderReference, Order order, Domain domain, KeyStringList settings, KeyStringList tt) { // Create the dictionary to return Dictionary<string, string> responseData = new Dictionary<string, string>(10); // Create the PayEx order Annytab.Webshop.Payex.Test.PxOrder pxOrder = new Annytab.Webshop.Payex.Test.PxOrder(); // Get the data that we need for a credit check Int64 accountNumber = 0; Int64.TryParse(settings.Get("PAYEX-ACCOUNT-NUMBER"), out accountNumber); string country = order.country_code; string socialSecurityNumber = order.customer_org_number; string orderRef = orderReference; string customerRef = order.customer_id.ToString(); string customerName = order.invoice_name; string streetAddress = order.invoice_address_1; string coAddress = ""; string postalCode = order.invoice_post_code.Replace(" ", ""); string city = order.invoice_city; string phoneNumber = order.customer_mobile_phone; string email = order.customer_email; string productCode = ""; string creditCheckRef = ""; Int32 mediaDistribution = 11; string invoiceDate = ""; Int16 invoiceDueDays = 0; Int32 invoiceNumber = 0; string invoiceLayout = ""; string invoiceText = tt.Get("order") + " " + order.id.ToString() + " - " + domain.webshop_name; // Create the md5 hash string hash = GetMD5Hash(accountNumber.ToString() + orderRef + customerRef + customerName + streetAddress + coAddress + postalCode + city + country + socialSecurityNumber + phoneNumber + email + productCode + creditCheckRef + mediaDistribution.ToString() + invoiceText + invoiceDate + invoiceDueDays.ToString() + invoiceNumber + invoiceLayout + settings.Get("PAYEX-ENCRYPTION-KEY")); // Create the invoice string xmlResponse = pxOrder.PurchaseInvoicePrivate(accountNumber, orderRef, customerRef, customerName, streetAddress, coAddress, postalCode, city, country, socialSecurityNumber, phoneNumber, email, productCode, creditCheckRef, mediaDistribution, invoiceText, invoiceDate, invoiceDueDays, invoiceNumber, invoiceLayout, hash); // Create the xml document XmlDocument doc = new XmlDocument(); try { // Load the xml document doc.LoadXml(xmlResponse); // Add data from the xml responseData.Add("error_code", ParseXmlNode(doc, "/payex/status/errorCode")); responseData.Add("description", ParseXmlNode(doc, "/payex/status/description")); responseData.Add("transaction_status", ParseXmlNode(doc, "/payex/transactionStatus")); responseData.Add("transaction_number", ParseXmlNode(doc, "/payex/transactionNumber")); } catch (Exception ex) { responseData.Add("exception", ex.Message); } // Return the response data return responseData; } // End of the CreateInvoicePrivateTest method
} // End of the SendEmailToHost method /// <summary> /// Send an email to the customer service /// </summary> /// <param name="customerAddress">The customer address</param> /// <param name="subject">The subject for the mail message</param> /// <param name="message">The message</param> public static bool SendEmailToCustomerService(string customerAddress, string subject, string message) { // Create the boolean to return bool successful = true; // Get the company settings KeyStringList webshopSettings = WebshopSetting.GetAllFromCache(); // Create variables string host = webshopSettings.Get("SEND-EMAIL-HOST"); Int32 port = 0; Int32.TryParse(webshopSettings.Get("SEND-EMAIL-PORT"), out port); string emailAddress = webshopSettings.Get("SEND-EMAIL-ADDRESS"); string password = webshopSettings.Get("SEND-EMAIL-PASSWORD"); string toAddress = webshopSettings.Get("CUSTOMER-SERVICE-EMAIL"); string useSSL = webshopSettings.Get("SEND-EMAIL-USE-SSL"); // Get the customer email MailAddress copyAddress = AnnytabDataValidation.IsEmailAddressValid(customerAddress); // Create the SmtpClient instance SmtpClient smtp = new SmtpClient(host, port); smtp.Credentials = new NetworkCredential(emailAddress, password); // Check if we should enable SSL if (useSSL.ToLower() == "true") { smtp.EnableSsl = true; } // Try to send the mail message try { // Create the mail message instance MailMessage mailMessage = new MailMessage(emailAddress, toAddress); // Add a carbon copy to the customer if (copyAddress != null) { mailMessage.CC.Add(copyAddress); } // Create the mail message mailMessage.Subject = subject; mailMessage.Body = message; mailMessage.IsBodyHtml = true; // Send the mail message smtp.Send(mailMessage); } catch (Exception ex) { string exceptionMessage = ex.Message; successful = false; } // Return the boolean return successful; } // End of the SendEmailToCustomerService method
} // End of the SendEmailToUser method /// <summary> /// Get image urls for the domain /// </summary> /// <param name="domainId">The id for the domain</param> /// <returns>A key string list with urls</returns> public static KeyStringList GetDomainImageUrls(Int32 domainId) { // Create the list to return KeyStringList domainImageUrls = new KeyStringList(5); // Create paths string directoryPath = "/Content/domains/" + domainId.ToString() + "/images/"; // Add images to the key string list domainImageUrls.Add("background_image", directoryPath + "background_image.jpg"); domainImageUrls.Add("default_logotype", directoryPath + "default_logotype.jpg"); domainImageUrls.Add("mobile_logotype", directoryPath + "mobile_logotype.jpg"); domainImageUrls.Add("big_icon", directoryPath + "big_icon.jpg"); domainImageUrls.Add("small_icon", directoryPath + "small_icon.jpg"); // Return the list return domainImageUrls; } // End of the GetDomainImageUrls method
} // End of the delete_marketing_file method #endregion #region Helper methods /// <summary> /// Get image urls for the domain /// </summary> /// <param name="domainId">The id for the domain</param> /// <returns>A key string list with urls</returns> private KeyStringList GetDomainImageUrls(Int32 domainId) { // Create the list to return KeyStringList domainImageUrls = new KeyStringList(5); // Create paths string noImagePath = "/Content/images/annytab_design/no_image_wide.jpg"; string directoryPath = "/Content/domains/" + domainId.ToString() + "/images/"; // Add images to the key string list domainImageUrls.Add("background_image", directoryPath + "background_image.jpg"); domainImageUrls.Add("default_logotype", directoryPath + "default_logotype.jpg"); domainImageUrls.Add("mobile_logotype", directoryPath + "mobile_logotype.jpg"); domainImageUrls.Add("big_icon", directoryPath + "big_icon.jpg"); domainImageUrls.Add("small_icon", directoryPath + "small_icon.jpg"); // Get all the keys in the dictionary List<string> keys = domainImageUrls.dictionary.Keys.ToList<string>(); // Loop all the keys for (int i = 0; i < keys.Count; i++) { // Get the url string url = domainImageUrls.Get(keys[i]); // Check if the file exists if (System.IO.File.Exists(Server.MapPath(url)) == false) { domainImageUrls.Update(keys[i], noImagePath); } } // Return the list return domainImageUrls; } // End of the GetDomainImageUrls method
public ActionResult CreateSveaPayment(Order order, List<OrderRow> orderRows, Domain domain, KeyStringList tt, string paymentType) { // Get webshop settings KeyStringList webshopSettings = WebshopSetting.GetAllFromCache(); // Get the language Language language = Language.GetOneById(domain.front_end_language); // Create the payment configuration SveaSettings sveaConfiguration = new SveaSettings(); // Create the order builder Webpay.Integration.CSharp.Order.Create.CreateOrderBuilder orderBuilder = Webpay.Integration.CSharp.WebpayConnection.CreateOrder(sveaConfiguration); // Add order rows for (int i = 0; i < orderRows.Count; i++) { // Get the unit Unit unit = Unit.GetOneById(orderRows[i].unit_id, domain.front_end_language); unit = unit != null ? unit : new Unit(); // Create an order item Webpay.Integration.CSharp.Order.Row.OrderRowBuilder orderItem = new Webpay.Integration.CSharp.Order.Row.OrderRowBuilder(); orderItem.SetArticleNumber(orderRows[i].product_code); orderItem.SetName(orderRows[i].product_name); orderItem.SetQuantity(orderRows[i].quantity); orderItem.SetUnit(unit.unit_code); orderItem.SetAmountExVat(orderRows[i].unit_price); orderItem.SetVatPercent(orderRows[i].vat_percent * 100); // Add the order item orderBuilder.AddOrderRow(orderItem); } // Add the gift cards amount if (order.gift_cards_amount > 0) { Webpay.Integration.CSharp.Order.Row.OrderRowBuilder orderItem = new Webpay.Integration.CSharp.Order.Row.OrderRowBuilder(); orderItem.SetArticleNumber("gc"); orderItem.SetName(tt.Get("gift_cards")); orderItem.SetQuantity(1); orderItem.SetUnit(""); orderItem.SetAmountExVat(order.gift_cards_amount * -1); orderItem.SetVatPercent(0); // Add the order item orderBuilder.AddOrderRow(orderItem); } // Add the customer if(order.customer_type == 0) // Company { // Set values for the customer Webpay.Integration.CSharp.Order.Identity.CompanyCustomer company = new Webpay.Integration.CSharp.Order.Identity.CompanyCustomer(); company.SetNationalIdNumber(order.customer_org_number); company.SetVatNumber(order.customer_vat_number); company.SetCompanyName(order.invoice_name); company.SetEmail(order.customer_email); company.SetPhoneNumber(order.customer_phone); company.SetIpAddress(Tools.GetUserIP()); // Get addresses //Webpay.Integration.CSharp.WebpayWS.GetCustomerAddressesResponse response = Webpay.Integration.CSharp.WebpayConnection.GetAddresses(sveaConfiguration) //.SetCountryCode(SveaSettings.GetSveaCountryCode(order.country_code)).SetCompany(order.customer_org_number).SetZipCode(order.invoice_post_code).SetOrderTypeInvoice().DoRequest(); // Add customer details orderBuilder.AddCustomerDetails(company); } else if(order.customer_type == 1) // Person { // Set values for the customer Webpay.Integration.CSharp.Order.Identity.IndividualCustomer person = new Webpay.Integration.CSharp.Order.Identity.IndividualCustomer(); person.SetNationalIdNumber(order.customer_org_number); person.SetEmail(order.customer_email); person.SetPhoneNumber(order.customer_phone); person.SetIpAddress(Request.UserHostAddress); // Get addresses //Webpay.Integration.CSharp.WebpayWS.GetCustomerAddressesResponse response = Webpay.Integration.CSharp.WebpayConnection.GetAddresses(sveaConfiguration) //.SetCountryCode(SveaSettings.GetSveaCountryCode(order.country_code)).SetIndividual(order.customer_org_number).SetZipCode(order.invoice_post_code).SetOrderTypeInvoice().DoRequest(); // Add customer details orderBuilder.AddCustomerDetails(person); } // Get the test variable string testOrderString = ""; if (webshopSettings.Get("SVEA-TEST").ToLower() == "true") { testOrderString = ":" + Tools.GeneratePassword(); } // Set order values orderBuilder.SetCountryCode(SveaSettings.GetSveaCountryCode(order.country_code)); orderBuilder.SetOrderDate(order.order_date); orderBuilder.SetClientOrderNumber(order.id.ToString() + testOrderString); orderBuilder.SetCurrency(SveaSettings.GetSveaCurrency(order.currency_code)); // Create the payment if(paymentType == "INVOICE") // Invoice { // Create the invoice payment Webpay.Integration.CSharp.WebpayWS.CreateOrderEuResponse orderResponse = orderBuilder.UseInvoicePayment().DoRequest(); // Check if the order is accepted if(orderResponse.Accepted == true) { // Update the order with the payment token Order.SetPaymentToken(order.id, orderResponse.CreateOrderResult.SveaOrderId.ToString()); // Update the payment status Order.UpdatePaymentStatus(order.id, "payment_status_invoice_approved"); // Add customer files CustomerFile.AddCustomerFiles(order); } else { // Update the payment status Order.UpdatePaymentStatus(order.id, "payment_status_invoice_not_approved"); } } else if(paymentType == "CREDITCARD") { // Add the rounding if(order.rounding_sum != 0) { Webpay.Integration.CSharp.Order.Row.OrderRowBuilder orderItem = new Webpay.Integration.CSharp.Order.Row.OrderRowBuilder(); orderItem.SetArticleNumber("rd"); orderItem.SetName(tt.Get("rounding")); orderItem.SetQuantity(1); orderItem.SetUnit(""); orderItem.SetAmountExVat(order.rounding_sum); orderItem.SetVatPercent(0); // Add the order item orderBuilder.AddOrderRow(orderItem); } // Set the payment option Webpay.Integration.CSharp.Hosted.Payment.PaymentMethodPayment payment = orderBuilder.UsePaymentMethod(Webpay.Integration.CSharp.Util.Constant.PaymentMethod.KORTCERT); payment.SetReturnUrl(domain.web_address + "/order/svea_confirmation/" + order.id.ToString()); payment.SetCancelUrl(domain.web_address + "/order/confirmation/" + order.id.ToString()); payment.SetPayPageLanguageCode(SveaSettings.GetSveaLanguageCode(language.language_code)); // Get the payment form Webpay.Integration.CSharp.Hosted.Helper.PaymentForm paymentForm = payment.GetPaymentForm(); ViewBag.PaymentForm = paymentForm.GetCompleteForm(); // Return the svea webpay view return View("svea_webpay"); } // Redirect the user to the order confirmation page return RedirectToAction("confirmation", "order", new { id = order.id }); } // End of the CreateSveaPayment method
} // End of the GetAllFromCache method /// <summary> /// Get all the settings as a key string list /// </summary> /// <returns>A key string list of settings</returns> public static KeyStringList GetAll() { // Create the KeyStringList to return KeyStringList posts = new KeyStringList(20); // Create the connection string and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT * FROM dbo.website_settings ORDER BY id ASC;"; // The using block is used to call dispose automatically even if there are an exception using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there is a exception using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Create a reader SqlDataReader reader = null; // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases try { // Open the connection. cn.Open(); // Fill the reader with data from the select command reader = cmd.ExecuteReader(); // Loop through the reader as long as there is something to read while (reader.Read()) { posts.Add(reader["id"].ToString(), reader["value"].ToString()); } } catch (Exception e) { throw e; } finally { // Call Close when done reading to avoid memory leakage if (reader != null) reader.Close(); } } } // Return the list of posts return posts; } // End of the GetAll method
} // End of the payex_confirmation method #endregion #region PayPal payment /// <summary> /// Create a paypal payment /// </summary> public ActionResult CreatePayPalPayment(Order order, List<OrderRow> orderRows, Domain domain, KeyStringList tt) { // Create the string to return string error_message = ""; // Get the currency Currency currency = Currency.GetOneById(order.currency_code); // Get the webshop settings KeyStringList webshopSettings = WebshopSetting.GetAllFromCache(); // Get credentials string paypalClientId = webshopSettings.Get("PAYPAL-CLIENT-ID"); string paypalClientSecret = webshopSettings.Get("PAYPAL-CLIENT-SECRET"); string paypalMode = webshopSettings.Get("PAYPAL-MODE"); Dictionary<string, string> config = new Dictionary<string, string> { { "mode", paypalMode } }; // Create a payment variable PayPal.Api.Payments.Payment createdPayment = null; try { // Create the credential token PayPal.OAuthTokenCredential tokenCredential = new PayPal.OAuthTokenCredential(paypalClientId, paypalClientSecret, config); // Create the api context PayPal.APIContext paypalContext = new PayPal.APIContext(tokenCredential.GetAccessToken()); paypalContext.Config = config; // Create the amount details decimal subTotal = order.net_sum + order.rounding_sum - order.gift_cards_amount; PayPal.Api.Payments.Details amountDetails = new PayPal.Api.Payments.Details(); amountDetails.subtotal = subTotal.ToString("F2", CultureInfo.InvariantCulture); amountDetails.tax = order.vat_sum.ToString("F2", CultureInfo.InvariantCulture); // Create the amount decimal totalAmount = order.total_sum - order.gift_cards_amount; PayPal.Api.Payments.Amount amount = new PayPal.Api.Payments.Amount(); amount.total = totalAmount.ToString("F2", CultureInfo.InvariantCulture); amount.currency = order.currency_code; amount.details = amountDetails; // Create a transaction PayPal.Api.Payments.Transaction transaction = new PayPal.Api.Payments.Transaction(); transaction.item_list = new PayPal.Api.Payments.ItemList(); transaction.item_list.items = new List<PayPal.Api.Payments.Item>(10); // Add order rows to the transaction for (int i = 0; i < orderRows.Count; i++) { // Create a new item PayPal.Api.Payments.Item item = new PayPal.Api.Payments.Item(); item.sku = orderRows[i].product_code.Length > 50 ? orderRows[i].product_code.Substring(0, 50) : orderRows[i].product_code; item.name = orderRows[i].product_name.Length > 100 ? orderRows[i].product_name.Substring(0, 50) : orderRows[i].product_name; item.price = orderRows[i].unit_price.ToString("F2", CultureInfo.InvariantCulture); item.quantity = Convert.ToInt32(orderRows[i].quantity).ToString(); item.currency = order.currency_code; // Add the item to the list transaction.item_list.items.Add(item); } // Add the rounding if(order.rounding_sum != 0) { PayPal.Api.Payments.Item roundingItem = new PayPal.Api.Payments.Item(); roundingItem.sku = "rd"; roundingItem.name = tt.Get("rounding"); roundingItem.price = order.rounding_sum.ToString("F2", CultureInfo.InvariantCulture); roundingItem.quantity = "1"; roundingItem.currency = order.currency_code; transaction.item_list.items.Add(roundingItem); } // Add the gift cards amount if (order.gift_cards_amount > 0) { decimal giftCardAmount = order.gift_cards_amount * -1; PayPal.Api.Payments.Item giftCardsItem = new PayPal.Api.Payments.Item(); giftCardsItem.sku = "gc"; giftCardsItem.name = tt.Get("gift_cards"); giftCardsItem.price = giftCardAmount.ToString("F2", CultureInfo.InvariantCulture); giftCardsItem.quantity = "1"; giftCardsItem.currency = order.currency_code; transaction.item_list.items.Add(giftCardsItem); } // Set the transaction amount transaction.amount = amount; List<PayPal.Api.Payments.Transaction> transactions = new List<PayPal.Api.Payments.Transaction>(); transactions.Add(transaction); // Create the payer PayPal.Api.Payments.Payer payer = new PayPal.Api.Payments.Payer(); payer.payment_method = "paypal"; // Create redirect urls string hostUrl = Request.Url.Host; PayPal.Api.Payments.RedirectUrls redirectUrls = new PayPal.Api.Payments.RedirectUrls(); redirectUrls.return_url = domain.web_address + "/order/paypal_confirmation/" + order.id; redirectUrls.cancel_url = domain.web_address + "/order/confirmation/" + order.id; // Create the payment PayPal.Api.Payments.Payment payment = new PayPal.Api.Payments.Payment(); payment.intent = "sale"; payment.payer = payer; payment.redirect_urls = redirectUrls; payment.transactions = transactions; // Create the payment createdPayment = payment.Create(paypalContext); } catch (Exception ex) { error_message = ex.Message; } // Check if there is any errors in the payment if (createdPayment != null) { // Save the paypal payment id Order.SetPaymentToken(order.id, createdPayment.id); // Get the link string link = ""; foreach(PayPal.Api.Payments.Links url in createdPayment.links) { if (url.rel == "approval_url") { link = url.href; break; } } // Redirect the user to the paypal page return Redirect(link); } else { // Redirect the user to the order confirmation page return RedirectToAction("confirmation", "order", new { id = order.id }); } } // End of the CreatePayPalPayment method
public ActionResult edit(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return(View("index")); } else { // Redirect the user to the start page return(RedirectToAction("index", "admin_login")); } // Get all the form values Int32 id = Convert.ToInt32(collection["txtId"]); string unit_code = collection["txtUnitCode"]; string name = collection["txtName"]; string unit_code_si = collection["txtUnitCodeSi"]; string erp_code = collection["txtErpCode"]; // Get the default admin language id Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get the unit Unit unit = Unit.GetOneById(id, adminLanguageId); // Check if the unit exists if (unit == null) { // Create a empty unit unit = new Unit(); } // Update values unit.unit_code_si = unit_code_si; unit.unit_code = unit_code; unit.name = name; unit.erp_code = erp_code; // Create a error message string errorMessage = string.Empty; // Check for errors in the unit if (unit.unit_code_si.Length > 10) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("unit_code_si"), "10") + "<br/>"; } if (unit.unit_code.Length > 10) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("unit_code"), "10") + "<br/>"; } if (unit.name.Length > 50) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("name"), "50") + "<br/>"; } if (unit.erp_code.Length > 10) { errorMessage += "• " + String.Format(tt.Get("error_field_length"), tt.Get("erp_code"), "10") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Check if we should add or update the unit if (unit.id == 0) { // Add the unit Int64 insertId = Unit.AddMasterPost(unit); unit.id = Convert.ToInt32(insertId); Unit.AddLanguagePost(unit, adminLanguageId); } else { // Update the unit Unit.UpdateMasterPost(unit); Unit.UpdateLanguagePost(unit, adminLanguageId); } // Redirect the user to the list return(Redirect("/admin_units" + returnUrl)); } else { // Set form values ViewBag.ErrorMessage = errorMessage; ViewBag.Unit = unit; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the edit view return(View("edit")); } } // End of the edit method