Esempio n. 1
0
 public PurchasedGoods GetPaid(string uniqueDownloadId)
 {
     return(Adapter.ReadByContext(c => {
         PurchasedGoods purchasedGoods = GetPurchasedGoods(uniqueDownloadId, c);
         return purchasedGoods != null && IsPaidStatus(purchasedGoods) ? purchasedGoods : null;
     }));
 }
Esempio n. 2
0
        /// <summary>
        /// Run through all purchasing that takes place.
        /// </summary>
        public void BuyPhase()
        {
            // go through each pop in order of priority
            foreach (var buyer in Populous.PopsByPriority)
            {
                // go through their list of needs
                foreach (var needPair in buyer.TotalNeeds)
                {
                    // Check that there is stuff that the pop
                    // can trade for goods
                    if (buyer.ForSale.All(x => x.Item2 <= 0))
                    {
                        break; // if they don't they stop
                    }
                    // get the product and amount
                    var need    = needPair.Item1;
                    var desired = needPair.Item2; // the units desired

                    try
                    {
                        // Check if the product is available to buy
                        if (ProductSupply.GetProductValue(need) <= 0)
                        {
                            // if nothing is available, add it to the shortfall.
                            Shortfall.AddProducts(need, desired);
                            continue; // and go to the next need
                        }
                    }
                    catch (KeyNotFoundException) // If it doesn't exist in the supply at all.
                    {
                        // Add it in at 0
                        ProductSupply.IncludeProduct(need);
                        // Subtract the missing product from shortfall.
                        Shortfall.AddProducts(need, desired);
                        continue; // and skip it here.
                    }

                    // Go to the market and buy what we can.
                    var reciept = BuyGoodsFromMarket(buyer, need, desired);

                    // process our reciept, getting how satisfied our need was.
                    var satisfaction = reciept.GetProductValue(need);

                    // Add satisfaction to our purchased good recorder
                    _purchasedGoods.AddProducts(need, satisfaction);

                    // Remove bought good from supply
                    ProductSupply.SubtractProducts(need, satisfaction);

                    // get the number of goods that couldn't be bought.
                    var shortfall = desired - satisfaction;

                    // add that to shortfall
                    Shortfall.AddProducts(need, shortfall);
                }
            }

            // with all buying done, get surplus supply available by removing bought goods.
            _surplus.AddProducts(PurchasedGoods.Multiply(-1));
        }
Esempio n. 3
0
        /// <summary>
        /// Метод вызывается платежной системой после оплаты и после сообщения нам о платеже(см. метод Result <see cref="Result"/>)
        /// </summary>
        /// <returns></returns>
        //[HttpPost]
        public ActionResult Success()
        {
            RobokassaApi           robokassaApi  = ApiFactory.GetRobokassaApi(WebSettingsConfig.Instance);
            RobokassaPaymentResult paymentResult = robokassaApi.ProcessSuccess(Request.Params);

            if (paymentResult == null)
            {
                LoggerWrapper.RemoteMessage(LoggingType.Error,
                                            "PaymentController.Success. PaymentResult is null. Params={0}",
                                            HttpContextHelper.ParamsToString(Request.Params, RobokassaApi.IsValidParamName));
                return(GetFailView());
            }

            var            purchasedGoogsQuery = new PurchasedGoodsQuery();
            PurchasedGoods purchasedGoods      = purchasedGoogsQuery.Get(paymentResult.PaymentId);

            if (purchasedGoods == null)
            {
                LoggerWrapper.RemoteMessage(LoggingType.Error,
                                            "PaymentController.Success. GetUniqueDownloadId не вернул уникальный идентификатор скачивания. PaymentId={0}, Price={1}, Params={2}",
                                            paymentResult.PaymentId, paymentResult.Price,
                                            HttpContextHelper.ParamsToString(Request.Params, RobokassaApi.IsValidParamName));
                return(GetFailView());
            }

            LoggerWrapper.RemoteMessage(LoggingType.Info,
                                        "PaymentController.Success. Перед тем как сообщить пользователю об успешном платеже на сумму {0} с идентификатором {1}",
                                        MoneyFormatter.ToRubles(paymentResult.Price), paymentResult.PaymentId);

            return(GetSuccessView(purchasedGoods));
        }
Esempio n. 4
0
        public ActionResult CheckPurchasedGoods(long userId, string uniqueDownloadId)
        {
            if (IdGenerator.IsInvalidDownloadId(uniqueDownloadId))
            {
                return(JsonResultHelper.Error());
            }

            var            purchasedGoogsQuery = new PurchasedGoodsQuery();
            PurchasedGoods purchasedGoods      = purchasedGoogsQuery.GetPaid(uniqueDownloadId);

            LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                "PaymentController.Check. Пользователь {0} проверял уникальный идентификатор покупки {1}. Статус: {2}!",
                userId, uniqueDownloadId, purchasedGoods != null ? "ОПЛАЧЕНО" : "НЕ оплачен");

            if (purchasedGoods == null)
            {
                return(JsonResultHelper.Error());
            }

            string html = OurHtmlHelper.RenderRazorViewToString(ControllerContext, "PartialDownloadPurchasedGoods",
                                                                new SuccessPaymentModel(
                                                                    purchasedGoods.ShortDescription,
                                                                    purchasedGoods.UniqueDownloadId,
                                                                    (GoodsId)purchasedGoods.GoodsId));

            return(JsonResultHelper.GetUnlimitedJsonResult(new { success = true, result = html }));
        }
Esempio n. 5
0
        private bool FinishPayment(long paymentId, PaymentStatus paymentStatus, Func <Payment, bool> additionalChecker)
        {
            return(Adapter.Transaction(c => {
                Payment payment = c.Payment.FirstOrDefault(e => e.Id == paymentId);
                PurchasedGoods purchasedGoods = GetPurchasedGoods(c, paymentId);

                if (payment == null || purchasedGoods == null)
                {
                    LoggerWrapper.RemoteMessage(LoggingType.Error,
                                                "PurchasedGoodsQuery.FinishPayment. Не удалось получить платежку или купленный товар. PaymentId={0}, payment={1}, purchasedGoods={2}, paymentStatus={3}",
                                                paymentId, payment == null ? "NULL" : "NOT NULL",
                                                purchasedGoods == null ? "NULL" : "NOT NULL",
                                                paymentStatus);
                    return false;
                }

                if (payment.Status != PaymentStatus.InProcess)
                {
                    LoggerWrapper.RemoteMessage(LoggingType.Error,
                                                "PurchasedGoodsQuery.FinishPayment. Платежка с идентификатором {0} похоже пришла повторно! Статус у платежки в БД {1}, paymentStatus={2}",
                                                paymentId, payment.Status, paymentStatus);
                }

                if (purchasedGoods.Status == PurchasedStatus.PostToCustomer)
                {
                    LoggerWrapper.RemoteMessage(LoggingType.Error,
                                                "PurchasedGoodsQuery.FinishPayment. У платежки с идентификатором {0} статус у платежки в БД {1}, paymentStatus={2}. Вернем true",
                                                paymentId, payment.Status, paymentStatus);
                    return true;
                }

                if (additionalChecker != null && !additionalChecker(payment))
                {
                    LoggerWrapper.RemoteMessage(LoggingType.Error,
                                                "PurchasedGoodsQuery.FinishPayment. Для платежки с идентификатором {0} additionalChecker вернул false",
                                                paymentId, payment.Status, paymentStatus);
                    return false;
                }

                payment.PaymentDate = DateTime.Now;
                payment.Status = paymentStatus;

                purchasedGoods.Status = paymentStatus == PaymentStatus.Success
                                            ? PurchasedStatus.Success
                                            : PurchasedStatus.Fail;

                c.SaveChanges();

                return true;
            }));
        }
Esempio n. 6
0
        public T GetJsonGoods <T>(string uniqueDownloadId) where T : class
        {
            T result = null;

            Adapter.Transaction(c => {
                PurchasedGoods purchasedGoods = GetPurchasedGoods(uniqueDownloadId, c);

                if (purchasedGoods == null)
                {
                    LoggerWrapper.RemoteMessage(LoggingType.Error,
                                                "PurchasedGoodsQuery.GetGoods. Для уникального идентификатора {0} не удалось найти купленный товар!!!",
                                                uniqueDownloadId);
                    return(false);
                }

                if (!IsPaidStatus(purchasedGoods))
                {
                    LoggerWrapper.RemoteMessage(LoggingType.Error,
                                                "PurchasedGoodsQuery.GetGoods. Товар с уникальным идентификатором {0} пытаются скачать не оплатив!!! Статус купленного товара {1}",
                                                uniqueDownloadId, purchasedGoods.Status);
                    return(false);
                }

                try {
                    result = JsonConvert.DeserializeObject <T>(purchasedGoods.Goods);
                } catch (Exception e) {
                    LoggerWrapper.RemoteMessage(LoggingType.Error,
                                                "PurchasedGoodsQuery.GetGoods. Товар с уникальным идентификатором {0} не удалось десериализовать в тип {1}. JSON-описание товара: {2}. Исключение: {3}",
                                                uniqueDownloadId, typeof(T).FullName, purchasedGoods.Goods, e);
                    return(false);
                }
                purchasedGoods.PostToCustomerDate = DateTime.Now;
                purchasedGoods.Status             = PurchasedStatus.PostToCustomer;
                c.SaveChanges();
                return(true);
            });
            return(result);
        }
Esempio n. 7
0
        /// <summary>
        /// Добавляет купленный товар и создает платеж
        /// </summary>
        /// <param name="purchasedGoodsForUser">данные о купленном товаре</param>
        /// <returns>true - купленный товар и платеж успешно добавлены, false - купленный товар и платеж не удалось добавить</returns>
        public long WantToBuyGoods <T>(PurchasedGoodsForUser <T> purchasedGoodsForUser)
        {
            if (purchasedGoodsForUser == null || purchasedGoodsForUser.Price <= 0 ||
                EnumValidator.IsInvalid(purchasedGoodsForUser.GoodsId))
            {
                LoggerWrapper.RemoteMessage(LoggingType.Error,
                                            "PurchasedGoodsQuery.WantToBuyGoods. Не удалось сохранить платежку. {0}",
                                            purchasedGoodsForUser != null
                                                ? "Некорректная цена: " + purchasedGoodsForUser.Price
                                                : "purchasedGoodsForUser == null");
                return(IdValidator.INVALID_ID);
            }

            string serializedGoods;

            try {
                serializedGoods = JsonConvert.SerializeObject(purchasedGoodsForUser.Goods);
            } catch (Exception e) {
                LoggerWrapper.RemoteMessage(LoggingType.Error,
                                            "PurchasedGoodsQuery.WantToBuyGoods. Товар с уникальным идентификатором {0} не удалось сериализовать из типа {1}. Исключение: {2}",
                                            purchasedGoodsForUser.UniqueDownloadId, typeof(T).FullName, e);
                return(IdValidator.INVALID_ID);
            }

            long result = IdValidator.INVALID_ID;

            Adapter.Transaction(c => {
                var payment = new Payment {
                    Price        = purchasedGoodsForUser.Price,
                    Status       = PaymentStatus.InProcess,
                    Description  = purchasedGoodsForUser.FullDescription,
                    UserId       = purchasedGoodsForUser.UserId,
                    CreationDate = DateTime.Now,
                    PaymentDate  = new DateTime().GetDbDateTime(),
                    System       = purchasedGoodsForUser.PaymentSystem
                };
                c.Payment.Add(payment);
                c.SaveChanges();

                if (IdValidator.IsInvalid(payment.Id))
                {
                    LoggerWrapper.RemoteMessage(LoggingType.Error,
                                                "PurchasedGoodsQuery.WantToBuyGoods. Не удалось сохранить платежку. UniqueDownloadId={0}, UserId={1}, Price={2}, Description={3}",
                                                purchasedGoodsForUser.UniqueDownloadId, purchasedGoodsForUser.UserId,
                                                purchasedGoodsForUser.Price, purchasedGoodsForUser.FullDescription);
                    return(false);
                }

                var purchasedGoods = new PurchasedGoods {
                    UserId             = purchasedGoodsForUser.UserId,
                    Price              = purchasedGoodsForUser.Price,
                    Goods              = serializedGoods,
                    LanguageId         = purchasedGoodsForUser.LanguageId,
                    UniqueDownloadId   = purchasedGoodsForUser.UniqueDownloadId,
                    FullDescription    = purchasedGoodsForUser.FullDescription,
                    ShortDescription   = purchasedGoodsForUser.ShortDescription,
                    PaymentId          = payment.Id,
                    PurchaseDate       = DateTime.Now,
                    PostToCustomerDate = new DateTime().GetDbDateTime(),
                    Status             = PurchasedStatus.WaitPayment,
                    GoodsId            = (byte)purchasedGoodsForUser.GoodsId
                };
                c.PurchasedGoods.Add(purchasedGoods);
                c.SaveChanges();

                bool innerResult = IdValidator.IsValid(purchasedGoods.Id);
                if (innerResult)
                {
                    result = payment.Id;
                }
                else
                {
                    LoggerWrapper.RemoteMessage(LoggingType.Error,
                                                "PurchasedGoodsQuery.WantToBuyGoods. Не удалось сохранить купленные товары. PaymentId={0}, UniqueDownloadId={1}, UserId={2}, Price={3}, Description={4}, LanguageId={5}",
                                                payment.Id, purchasedGoodsForUser.UniqueDownloadId,
                                                purchasedGoodsForUser.UserId,
                                                purchasedGoodsForUser.Price, purchasedGoodsForUser.FullDescription,
                                                purchasedGoodsForUser.LanguageId);
                }
                return(innerResult);
            });
            return(result);
        }
Esempio n. 8
0
 private static bool IsPaidStatus(PurchasedGoods purchasedGoods)
 {
     return(purchasedGoods.Status == PurchasedStatus.Success ||
            purchasedGoods.Status == PurchasedStatus.PostToCustomer);
 }
Esempio n. 9
0
 private ViewResult GetSuccessView(PurchasedGoods purchasedGoods)
 {
     return(View("../Sales/SuccessPayment",
                 new SuccessPaymentModel(purchasedGoods.ShortDescription, purchasedGoods.UniqueDownloadId, (GoodsId)purchasedGoods.GoodsId)));
 }