Пример #1
0
        public ActionResult Edit(string id, FormCollection collection)
        {
            if (!collection.HasKeys())
            {
                return(JsonNet(CommandResult.Instance_Error));
            }
            try
            {
                var js = JsonHelper.ToJson(collection.ToDictionary());

                var entity = JsonHelper.ToObject <VD_Sys_Menu>(js);
                // TODO: Add update logic here

                using (var service = GetService <ISys_MenuService>())
                {
                    if (!service.SaveMenu(entity))
                    {
                        return(JsonNet(CommandResult.Instance_Error));
                    }
                }
                return(JsonNet(CommandResult.Instance_Succeed));
            }
            catch
            {
                return(JsonNet(CommandResult.Instance_Error));
            }
        }
Пример #2
0
        /// <summary>
        /// Get the child nodes of a tree node.
        /// </summary>
        private async Task <ActionResult <TreeNodeCollection> > GetChildren(Tree tree, int id, FormCollection querystring)
        {
            if (tree == null)
            {
                throw new ArgumentNullException(nameof(tree));
            }

            // the method we proxy has an 'id' parameter which is *not* in the querystring,
            // we need to add it for the proxy to work (else, it does not find the method,
            // when trying to run auth filters etc).
            var d = querystring?.ToDictionary(x => x.Key, x => x.Value) ?? new Dictionary <string, StringValues>();

            d["id"] = StringValues.Empty;
            var proxyQuerystring = new FormCollection(d);

            var controllerResult = await GetApiControllerProxy(tree.TreeControllerType, "GetNodes", proxyQuerystring);

            if (!(controllerResult.Result is null))
            {
                return(new ActionResult <TreeNodeCollection>(controllerResult.Result));
            }

            var controller = (TreeControllerBase)controllerResult.Value;

            return(await controller.GetNodes(id.ToInvariantString(), querystring));
        }
        public ActionResult Edit(string id, FormCollection collection)
        {
            if (!collection.HasKeys())
            {
                return(JsonNet(CommandResult.Instance_Error));
            }
            var js = JsonHelper.ToJson(collection.ToDictionary());

            var entity = JsonHelper.ToObject <VD_SalesOrder>(js);

            entity.ExtendedProperties.Add(ConstantSetting.TraceFieldCollection, collection.AllKeys);
            var key  = $"{typeof(OnlineController).FullName}_Edit";
            var list = GetSessionCache().TryGet(key, () => new List <VD_SalesOrderDetail>());// Session[key] as List<VD_SalesOrderDetail> ?? new List<VD_SalesOrderDetail>();

            // TODO: Add update logic here
            //处理新的记录
            if (entity.BillCode.Equals(NewItemMark) || entity.BillCode.IsEmpty())
            {
                entity.BillCode = DateTime.Now.ToString("yyMMddhhmmss");
            }
            entity.Maker    = entity.Maker ?? "admin";
            entity.MakeDate = entity.MakeDate.HasValue ? entity.MakeDate : DateTime.Now;

            if (entity.CustomerID_Code.IsEmpty())
            {
                entity.CustomerID = Guid.Empty;
            }

            int i = 0;
            int j = 0;

            foreach (var item in list)
            {
                i++;
                item.RowNo  = i;
                item.MainID = entity.Id;
                //子材
                if (item.InID.HasValue && !item.InID.Value.IsEmpty())
                {
                    var parent = list.FirstOrDefault(w => w.Id == item.InID.Value);
                    var index  = item.SalesOrderTraceCode.IndexOf('-') + 1;
                    item.SalesOrderTraceCode = $"{parent.SalesOrderTraceCode}-{item.SalesOrderTraceCode.Substring(index).PadLeft(2, '0')}";
                }
                else
                {
                    j++;
                    item.SalesOrderTraceCode = $"{entity.BillCode}{j.PadLeft(3)}";
                }
            }
            if (GetService <ISalesOrderService>().Save(entity, list))
            {
                return(JsonNet(CommandResult.Instance_Succeed));
            }
            return(JsonNet(CommandResult.Instance_Error));
        }
        public ActionResult Unlock(FormCollection form)
        {
            var appSettings = form.ToDictionary();

            if (appSettings != null)
            {
                // Remove all whitespaces and split
                var userEmails = Regex.Replace(appSettings["userEmails"], @"\s+", string.Empty).Split(',');

                Guid promotionId;
                Guid.TryParse(appSettings["promotionIdToUnlock"], out promotionId);

                var userAccoundIds =
                    (from userEmail in userEmails
                     select _accountDao.FindByEmail(userEmail) into accountDetail
                     where accountDetail != null
                     select accountDetail.Id).ToArray();

                if (userAccoundIds.Any() && promotionId.HasValue())
                {
                    ViewBag.Error = null;

                    _commandBus.Send(new AddUserToPromotionWhiteList
                    {
                        PromoId    = promotionId,
                        AccountIds = userAccoundIds
                    });

                    var promotion = _promotionDao.FindById(promotionId);

                    TempData["Info"] = string.Format("Promotion \"{0} ({1})\"\n was sent to users {2}",
                                                     promotion.Name,
                                                     promotion.Code,
                                                     userEmails.Flatten(","));
                }
                else
                {
                    var message = promotionId.HasValue()
                        ? string.Empty
                        : "You must select a promotion to send to the customer." + Environment.NewLine;

                    message = userAccoundIds.Any()
                        ? message.Replace(Environment.NewLine, string.Empty)
                        : message + "You must enter one or more valid customer email.";

                    ViewBag.Error = message;

                    var promotions = GetCustomerSupportPromoCodes();

                    return(View(promotions));
                }
            }

            return(RedirectToAction("Unlock"));
        }
Пример #5
0
        public async Task <ActionResult> ExportToFile(FormCollection form)
        {
            var appSettings = form.ToDictionary();

            appSettings.Remove("__RequestVerificationToken");

            if (!ValidateSettingsValue(appSettings))
            {
                return(RedirectToAction("Index"));
            }



            if (appSettings.Any())
            {
                var      data = appSettings.ToJson(false);
                DateTime date = DateTime.Now;
                return(File(new ASCIIEncoding().GetBytes(data), "text", "CompanySettings-" + date.ToShortDateString() + date.ToShortTimeString() + ".csf"));
            }

            return(RedirectToAction("Index"));
        }
Пример #6
0
        public async Task <ActionResult> Update(FormCollection form)
        {
            var appSettings = form.ToDictionary();

            appSettings.Remove("__RequestVerificationToken");

            if (!ValidateSettingsValue(appSettings))
            {
                return(RedirectToAction("Index"));
            }

            if (appSettings.Any())
            {
                SaveConfigurationChanges(appSettings);
                SetAdminSettings(appSettings);
            }

            TempData["Info"] = "Settings updated";

            // Wait for settings to be updated before reloading the page
            await Task.Delay(2000);

            return(RedirectToAction("Index"));
        }
        public JsonResult EditItem(string id, FormCollection collection)
        {
            if (!collection.HasKeys())
            {
                return(JsonNet(CommandResult.Instance_Error));
            }
            var js     = JsonHelper.ToJson(collection.ToDictionary());
            var entity = JsonHelper.ToObject <VD_SalesOrderDetail>(js);

            if (entity != null)
            {
                if (entity.SurfaceID_Name.IsEmpty())
                {
                    entity.SurfaceID = Guid.Empty;
                }
                if (entity.SectionBarID_Code.IsEmpty())
                {
                    entity.SectionBarID = Guid.Empty;
                }
                if (entity.PackingID_PackingName.IsEmpty())
                {
                    entity.PackingID = Guid.Empty;
                }


                var items = new List <VD_SalesOrderDetail>();
                items.Add(entity);
                //获取session中从表的数据
                var key  = $"{typeof(OnlineController).FullName}_Edit";
                var list = GetSessionCache().TryGet(key, () => new List <VD_SalesOrderDetail>());// Session[key] as List<VD_SalesOrderDetail> ?? new List<VD_SalesOrderDetail>();

                //获取子材
                using (var app = GetService <ISectionBarService>())
                {
                    var childList = app.GetHeatInsulationList(entity.SectionBarID);
                    for (int i = 0; i < childList.Count; i++)
                    {
                        var newItem = entity.CopyObject();
                        newItem.SalesOrderTraceCode = $"{newItem.SalesOrderTraceCode}-{(i + 1).ToString().PadLeft(2, '0')}";
                        newItem.SectionBarID        = childList[i].Id;
                        newItem.SectionBarID_Code   = childList[i].Code;
                        newItem.SectionBarID_Name   = childList[i].Name;
                        newItem.WallThickness       = childList[i].WallThickness;
                        newItem.TheoryMeter         = childList[i].Theoreticalweight;
                        newItem.InID = entity.Id;
                        items.Add(newItem);
                    }
                }

                foreach (var item in items)
                {
                    decimal l = 0;
                    if (!item.OrderLength.IsEmpty())
                    {
                        if (decimal.TryParse(item.OrderLength, out l))
                        {
                            item.OrderLength = l.ToString("#.####");
                        }
                    }
                    item.Theory6Meter = Math.Round(item.TheoryMeter.HasValue ? item.TheoryMeter.Value * l : 0, 3);
                    item.TheoryWeight = item.Theory6Meter * item.TotalQuantity;
                    if (item.TheoryWeight.HasValue)
                    {
                        item.TheoryWeight = Math.Round(item.TheoryWeight.Value, 3);
                    }

                    var old = list.FirstOrDefault(w => w.Id == item.Id);
                    if (old != null)
                    {
                        old.ObjectExtend(item);
                    }
                    else
                    {
                        list.Add(item);
                    }
                }
                GetSessionCache()[key] = list;
                //Session[key] = list;
                var r = CommandResult.Instance_Succeed;
                //r.ResultUrl = "http://www.baidu.com/";
                return(JsonNet(r));
            }
            return(JsonNet(CommandResult.Instance_Error));
        }
        public IHttpActionResult ProcessPayment(FormCollection parameters)
        {
            //first get the payment processor
            var paymentMethodName = parameters.Get(PaymentParameterNames.PaymentMethodTypeName);

            if (string.IsNullOrEmpty(paymentMethodName))
            {
                VerboseReporter.ReportError("Invalid payment method", "process_payment");
                return(RespondFailure());
            }

            //the transaction amount
            decimal amount;
            var     amountString = parameters.Get(PaymentParameterNames.Amount) ?? "0";

            decimal.TryParse(amountString, out amount);

            PaymentMethodType methodType;

            if (System.Enum.TryParse(paymentMethodName, out methodType))
            {
                methodType = PaymentMethodType.CreditCard;
            }

            //get the payment processor now
            var paymentProcessor = _paymentProcessingService.GetPaymentProcessorPlugin(amount, methodType);

            if (paymentProcessor == null)
            {
                VerboseReporter.ReportError("Invalid payment method", "process_payment");
                return(RespondFailure());
            }

            //convert form collection to dictionary to check if parameters are valid
            var formCollectionDictionary = parameters.ToDictionary(pair => pair.Key, pair => (object)pair.Value);

            var isValid = paymentProcessor.AreParametersValid(formCollectionDictionary);

            UserPaymentMethod paymentMethod = null;

            if (!isValid)
            {
                //the parameters are not valid. but that may also mean that the user is selecting an already saved payment method
                //and so he wouldn't have sent that data again
                var savedPaymentMethodIdString = parameters.Get(PaymentParameterNames.UserSavedPaymentMethodId);
                int savedPaymentMethodId;
                if (int.TryParse(savedPaymentMethodIdString, out savedPaymentMethodId))
                {
                    var userPaymentMethods =
                        _paymentMethodService.Get(x => x.UserId == ApplicationContext.Current.CurrentUser.Id && x.Id == savedPaymentMethodId, null);

                    if (userPaymentMethods.Any())
                    {
                        paymentMethod = userPaymentMethods.First();
                        isValid       = true;
                    }
                }
                //still invalid? something is not right then.
                if (!isValid)
                {
                    VerboseReporter.ReportError("Invalid parameters to process payment", "process_payment");
                    return(RespondFailure());
                }
            }

            //we save the payment method in our database if it's CreditCard
            if (paymentProcessor.Supports(PaymentMethodType.CreditCard))
            {
                if (paymentMethod == null)
                {
                    #region saving payment method to database
                    var creditCardNumber = parameters.Get(PaymentParameterNames.CardNumber);
                    //let's validate the card for level 1 check (luhn's test) first before storing
                    var isCardValid = PaymentCardHelper.IsCardNumberValid(creditCardNumber);
                    //card number
                    if (!isCardValid)
                    {
                        VerboseReporter.ReportError("Invalid card number", "process_payment");
                        return(RespondFailure());
                    }
                    //expiration date
                    var expireMonth = parameters.Get(PaymentParameterNames.ExpireMonth);
                    var expireYear  = parameters.Get(PaymentParameterNames.ExpireYear);
                    if (!expireYear.IsInteger() || !expireMonth.IsInteger())
                    {
                        VerboseReporter.ReportError("Invalid expiration month or year", "process_payment");
                        return(RespondFailure());
                    }
                    //card issuer
                    var cardIssuer = PaymentCardHelper.GetCardTypeFromNumber(creditCardNumber);
                    if (!cardIssuer.HasValue)
                    {
                        VerboseReporter.ReportError("Unsupported card provider", "process_payment");
                        return(RespondFailure());
                    }


                    var nameOnCard = parameters.Get(PaymentParameterNames.NameOnCard);
                    //encrypt credit card info to store in db
                    var key  = ConfigurationManager.AppSettings.Get("EncryptionKey");
                    var salt = ConfigurationManager.AppSettings.Get("Salt");

                    var cardNumber = _cryptographyService.Encrypt(creditCardNumber, key, salt); //encrypt the card info
                    //fine if the card is valid, but is the card number already in our record, then not possible to save the same again
                    if (_paymentMethodService.DoesCardNumberExist(cardNumber))
                    {
                        VerboseReporter.ReportError("The card number is already saved in records", "process_payment");
                        return(RespondFailure());
                    }

                    paymentMethod = new UserPaymentMethod()
                    {
                        UserId            = ApplicationContext.Current.CurrentUser.Id,
                        IsVerified        = false,
                        PaymentMethodType = PaymentMethodType.CreditCard,
                        CardIssuerType    = cardIssuer.ToString().ToLowerInvariant(),
                        CardNumber        = creditCardNumber,
                        CardNumberMasked  = PaymentCardHelper.MaskCardNumber(creditCardNumber),
                        NameOnCard        = nameOnCard,
                    };
                    //save this payment method
                    _paymentMethodService.Insert(paymentMethod);
                    #endregion
                }
            }


            //we need to see if we should only authorize or capture as well
            //the idea is if it's a sponsorship context, it's better to authorize the payment transaction and capture later when
            //the sponsorship is accepted //we thought of initially only authorizing sponsorship transactions and capture when it's accepted.
            //but that flow doesn't seem to work quite well, thoughts?
            var authorizeOnly = false; // (parameters.Get(PaymentParameterNames.PaymentContext) ?? string.Empty) == "sponsor";

            //so we are ready for payment processing, let's create a paymenttrasaction for storing in our db
            var paymentTransaction = new PaymentTransaction()
            {
                IsLocalTransaction = true,
                PaymentStatus      = PaymentStatus.Pending,
                TransactionAmount  = amount,
                TransactionGuid    = Guid.NewGuid(),
                CreatedOn          = DateTime.UtcNow,
                UserIpAddress      = WebHelper.GetClientIpAddress()
            };
            _paymentTransactionService.Insert(paymentTransaction);

            //now proceed further with the payment
            //create the transaction request
            var transactionRequest = new TransactionRequest()
            {
                Amount                     = amount,
                CurrencyIsoCode            = "USD",//TODO: SET CURRENCY AS SELECTED BY USER
                PaymentProcessorSystemName = paymentProcessor.PluginInfo.SystemName,
                UserId                     = ApplicationContext.Current.CurrentUser.Id,
                Parameters                 = formCollectionDictionary,
                TransactionUniqueId        = paymentTransaction.TransactionGuid.ToString()
            };


            var response = paymentProcessor.Process(transactionRequest, authorizeOnly);
            //update values of transaction parameters for future reference
            paymentTransaction.TransactionCodes = response.ResponseParameters;
            //update payment transaction
            _paymentTransactionService.Update(paymentTransaction);

            if (response.Success)
            {
                //let's verify the payment method first if it's not
                if (paymentMethod != null && !paymentMethod.IsVerified)
                {
                    paymentMethod.IsVerified = true;
                    _paymentMethodService.Update(paymentMethod);
                }

                //now since the response was success, we can actually assign some credits to the user
                var creditCount = amount * (1 / _paymentSettings.CreditExchangeRate);
                var credit      = new Credit()
                {
                    PaymentTransactionId = paymentTransaction.Id,
                    CreatedOnUtc         = DateTime.UtcNow,
                    CreditCount          = creditCount,
                    CreditExchangeRate   = _paymentSettings.CreditExchangeRate,
                    //if it's authorize only transaction, we assign the credits, but they won't be usable before they are approved by capture
                    CreditTransactionType = CreditTransactionType.Issued,
                    CreditType            = CreditType.Transactional,
                    IsExpired             = false
                };

                //save credit
                _creditService.Insert(credit);

                //get total available credits of user
                var usableCreditCount = _creditService.GetUsableCreditsCount(ApplicationContext.Current.CurrentUser.Id);
                return(RespondSuccess(new {
                    UsableCreditCount = usableCreditCount
                }));
            }
            VerboseReporter.ReportError("An error occured while processing payment", "process_payment");
            return(RespondFailure());
        }
 /// <summary>
 /// Converts the FormCollection to a dictionary
 /// </summary>
 /// <param name="items"></param>
 /// <returns></returns>
 public static IDictionary <string, object> ToDictionary(this FormCollection items)
 {
     return(items.ToDictionary(x => x.Key, x => (object)x.Value));
 }