Beispiel #1
0
        public async Task <AcceptShopCommandResponse> Handle(AcceptShopCommand command)
        {
            var shop = _repository.Find(command.Id);

            if (shop == null)
            {
                throw new DomainException("شخص یافت نشد");
            }
            var shopStatusLog = new ShopStatusLog(Guid.NewGuid(), command.UserId, command.FirstName, command.LastName, ShopStatus.Accept);

            shop.ShopStatus        = ShopStatus.Accept;
            shop.DescriptionStatus = command.DescriptionStatus;
            shop.ShopStatusLogs.Add(shopStatusLog);
            await _fcmNotification.SendToIds(shop.GetPushTokens(), "تایید فروشگاه", "تایید فروشگاه با موفقیت انجام شد",
                                             NotificationType.ShopActivated, AppType.Shop, NotificationSound.Shopper);

            return(new AcceptShopCommandResponse());
        }
        public async Task <ShipmentSendFactorCommandResponse> Handle(ShipmentSendFactorCommand command)
        {
            var factor = _repository.AsQuery().SingleOrDefault(p => p.Id == command.Id);

            if (factor == null)
            {
                throw new DomainException("فاکتور یافت نشد");
            }
            if (factor.FactorState == FactorState.Pending || factor.FactorState == FactorState.Failed)
            {
                throw new DomainException(" فاکتور پرداخت نشد است");
            }
            factor.SendShipment();
            await _fcmNotification.SendToIds(factor.Customer.GetPushTokens(),
                                             "Invoice",
                                             "Your invoice has been sent",
                                             NotificationType.SendFactor,
                                             AppType.Customer, NotificationSound.Shopper);

            return(new ShipmentSendFactorCommandResponse());
        }
Beispiel #3
0
        public async Task <CreatePrivateMessageCommandResponse> Handle(CreatePrivateMessageCommand command)
        {
            var person = _personRepository.AsQuery().SingleOrDefault(p => p.Id == command.PersonId);

            if (person == null)
            {
                throw new DomainException("شخص یافت نشد");
            }
            var privateMessage = new PrivateMeassge(Guid.NewGuid(), command.Title, command.Body,
                                                    new UserInfo(command.UserInfo.UserId, command.UserInfo.FirstName, command.UserInfo.LastName),
                                                    command.PersonId);

            _repository.Add(privateMessage);
            var appType = person is Customer ? AppType.Customer : AppType.Shop;
            await _fcmNotification.SendToIds(person.GetPushTokens(), command.Title, command.Body,
                                             NotificationType.PrivateMessage, appType, NotificationSound.Default);

            return(new CreatePrivateMessageCommandResponse());
        }
        //test اینکه دستی خودم اینو کال کنم چیه
        public async Task <ActionResult> Verify(long paymentIdentity)
        {
#if DEBUG
            var payment = _paymentRepository.Find(paymentIdentity);
            if (payment == null)
            {
                @ViewBag.hasError     = true;
                @ViewBag.errorMessage = "فاکتور مورد نظر یافت نشد";
                return(View());
            }
            var factor = _factorRepository.Find(payment.FactorId);
            if (factor == null)
            {
                @ViewBag.hasError     = true;
                @ViewBag.errorMessage = "فاکتور مورد نظر یافت نشد";
                return(View());
            }
            var result = await Parbad.Payment.VerifyAsync(System.Web.HttpContext.Current);

            if (result.Status == VerifyResultStatus.Success)
            {
                @ViewBag.hasError       = false;
                @ViewBag.successMessage = "عملیات با موفقیت صورت پذیرفت";

                factor.PayFactor(Guid.NewGuid(), result.ReferenceId, result.TransactionId, result.Status, result.Message);
                payment.PaymentType = PaymentType.Paid;

                _percentDiscountDomainService.AddDiscountSellToPercentDiscount(factor);
                _personDomainService.ShopCustomerSubsetPaidFactor(factor.Shop, factor.Customer);
                _promoterDomainService.PromoterCustomerSubsetPaidFactor(factor.Customer);

                await _fcmNotification.SendToIds(factor.Shop.GetPushTokens(), "Successfull payment",
                                                 $"Your payment with {factor.Id} has been successfully executed", NotificationType.FactorPayed,
                                                 AppType.Shop, NotificationSound.Shopper);
            }
            else
            {
                @ViewBag.hasError                = true;
                @ViewBag.errorMessage            = "خطا در انجام عملیات";
                @ViewBag.errorMesaageDescription = result.Message;
                factor.FailedFactor(Guid.NewGuid(), result.ReferenceId, result.TransactionId, result.Status, result.Message);
                payment.PaymentType = PaymentType.Failed;
            }
            payment.PaymentResponse = new PaymentResponse(result.ReferenceId, result.TransactionId, result.Message,
                                                          result.Status);
            _context.SaveChanges();
            @ViewBag.factorId = factor.Id;
            return(View());
#else
            var tokenString   = Request.Form["Token"];
            var statusString  = Request.Form["status"];
            var orderIdString = Request.Form["OrderId"];
            var rrn           = Request.Form["RRN"];
            if (!string.IsNullOrEmpty(tokenString) && !string.IsNullOrEmpty(statusString) &&
                !string.IsNullOrEmpty(orderIdString) && !string.IsNullOrEmpty(rrn))
            {
                var status  = int.Parse(statusString);
                var orderId = long.Parse(orderIdString);
                var token   = long.Parse(tokenString);
                var payment = _paymentRepository.Find(orderId);
                if (payment == null)
                {
                    @ViewBag.hasError     = true;
                    @ViewBag.errorMessage = "فاکتور مورد نظر یافت نشد";
                    return(View());
                }
                var factor = _factorRepository.Find(payment.FactorId);
                if (factor == null)
                {
                    @ViewBag.hasError     = true;
                    @ViewBag.errorMessage = "فاکتور مورد نظر یافت نشد";
                    return(View());
                }
                try
                {
                    if (status == 0 && token > 0)
                    {
                        var service  = new ConfirmServiceSoapClient();
                        var response = service.ConfirmPayment(new ClientConfirmRequestData
                        {
                            Token        = token,
                            LoginAccount = LoginAccount
                        });
                        bool hasError = false;
                        if (response.Status == 0 && response.RRN > 0)
                        {
                            @ViewBag.hasError       = false;
                            @ViewBag.successMessage = "عملیات با موفقیت صورت پذیرفت";

                            factor.PayFactor(Guid.NewGuid(), rrn, tokenString, VerifyResultStatus.Success, "موفق");
                            payment.PaymentType = PaymentType.Paid;

                            _percentDiscountDomainService.AddDiscountSellToPercentDiscount(factor);
                            _personDomainService.ShopCustomerSubsetPaidFactor(factor.Shop, factor.Customer);
                            _promoterDomainService.PromoterCustomerSubsetPaidFactor(factor.Customer);

                            await _fcmNotification.SendToIds(factor.Shop.GetPushTokens(), "پرداخت فاکتور موفق",
                                                             $"پرداخت فاکتور با شماره {factor.Id} انجام شد", NotificationType.FactorPayed,
                                                             AppType.Shop, NotificationSound.Shopper);
                        }
                        else
                        {
                            hasError              = true;
                            @ViewBag.hasError     = true;
                            @ViewBag.errorMessage = "خطا در انجام عملیات";
                            factor.FailedFactor(Guid.NewGuid(), rrn, tokenString, VerifyResultStatus.Failed, "ناموفق");
                            payment.PaymentType = PaymentType.Failed;
                        }

                        payment.PaymentResponse = new PaymentResponse(rrn, tokenString, "",
                                                                      hasError ? VerifyResultStatus.Failed : VerifyResultStatus.Success);
                        _context.SaveChanges();
                        @ViewBag.factorId = factor.Id;
                        return(View());
                    }
                }
                catch (Exception e)
                {
                    var service = new ReversalServiceSoapClient();
                    service.ReversalRequest(new ClientReversalRequestData
                    {
                        LoginAccount = LoginAccount,
                        Token        = token,
                    });
                    factor.FailedFactor(Guid.NewGuid(), rrn, tokenString, VerifyResultStatus.Failed, "ناموفق");
                    payment.PaymentType     = PaymentType.Reverse;
                    payment.PaymentResponse = new PaymentResponse(rrn, tokenString, "", VerifyResultStatus.Failed);
                    @ViewBag.hasError       = true;
                    @ViewBag.errorMessage   = "در صورت کسر وجه از حساب شما مبلغ مذکور طی 72 ساعت به حساب شما عودت داده خواهد شد. در غیر این صورت جهت پیگیری لطفا با پشتیبانی تماس حاصل فرمایید.";
                    return(View());
                }
            }
            @ViewBag.hasError     = true;
            @ViewBag.errorMessage = "ارتباط با درگاه آنلاین برقرار نشد";
            return(View());
#endif
        }
        public void CreateAreaOrder()
        {
            try
            {
                _logger.Info($"run at{DateTime.Now}");
                using (var db = new ShoppingSchedulerContext())
                {
                    var setting = db.Settings.First();
                    if (setting == null)
                    {
                        return;
                    }
                    var now          = DateTime.Now;
                    var date         = DateTime.Parse("2019/05/19");
                    var ordersExpire = db.PrivateOrder.Where(p => p.CreationTime >= date &&
                                                             p.OrderStatus == OrderStatus.Pending && p.ExpireOpenTime < now &&
                                                             p.IsConvertToAreaOrder == false).ToList();

                    foreach (var order in ordersExpire)
                    {
                        var shopsInArea = db.Shops.Where(item =>
                                                         item.IsActive && item.ShopStatus == ShopStatus.Accept && item.Id != order.Shop.Id &&
                                                         item.ShopAddress.Geography.Distance(order.OrderAddress.Geography) <= item.AreaRadius)
                                          .ToList();
                        if (shopsInArea.Count < 1)
                        {
                            order.IsConvertToAreaOrder = true;
                            db.SaveChanges();
                            continue;
                        }

                        var expireOpenTime = DateTime.Now.AddSeconds(setting.OrderExpireOpenTime);
                        var orderItems     = order.OrderItems.ToList();

                        foreach (var shop in shopsInArea)
                        {
                            var areaOrder = new AreaOrder(order.Customer, order.OrderAddress,
                                                          order.Description,
                                                          expireOpenTime, shop, order, AreaOrderCreator.ByScheduler)
                            {
                                OrderItems = new List <OrderItem>()
                            };
                            foreach (var orderItem in orderItems)
                            {
                                var orderProductTemp = new OrderProduct(orderItem.OrderProduct.ProductId,
                                                                        orderItem.OrderProduct.Name, orderItem.OrderProduct.Price,
                                                                        orderItem.OrderProduct.ProductImage, orderItem.OrderProduct.BrandId,
                                                                        orderItem.OrderProduct.BrandName);
                                OrderItemDiscountBase orderItemDiscountBase = null;
                                if (orderItem.Discount != null)
                                {
                                    orderItemDiscountBase = orderItem.Discount;
                                }

                                var orderItemTemp = new OrderItem(Guid.NewGuid(), orderItem.Quantity,
                                                                  orderItem.Description,
                                                                  orderProductTemp, orderItemDiscountBase);

                                areaOrder.OrderItems.Add(orderItemTemp);
                            }
                            db.AreaOrder.Add(areaOrder);
                            _fcmNotification.SendToIds(shop.GetPushTokens(), "سفارش جدید",
                                                       $"یک سفارش ثبت شد", NotificationType.OrderAdd,
                                                       AppType.Shop, NotificationSound.Shopper);
                        }
                        order.IsConvertToAreaOrder = true;
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Info($"exception run at{DateTime.Now}");
                _logger.Error(JsonConvert.SerializeObject(e));
            }
        }
        public async Task <CreatePrivateOrderCommandResponse> Handle(CreatePrivateOrderCommand command)
        {
            var appSetting = _applicationSettingRepository.AsQuery().FirstOrDefault();

            if (appSetting == null)
            {
                throw new Exception();
            }
            var customer = _personRepository.AsQuery().OfType <Customer>().SingleOrDefault(p => p.UserId == command.UserId);

            if (customer == null)
            {
                throw new DomainException("مشتری یافت نشد");
            }
            await _orderDomainService.CheckCustomerRequestOrderDuration(customer, appSetting);

            var customerAddress =
                customer.CustomerAddresses.SingleOrDefault(p => p.Id == command.CustomerAddressId);

            if (customerAddress == null)
            {
                throw new DomainException("ادرس مشتری یافت نشد");
            }
            var shop = _personRepository.AsQuery().OfType <Shop>().SingleOrDefault(p => p.Id == command.ShopId);

            if (shop == null)
            {
                throw new DomainException("فروشگاه وارد شده یافت نشد");
            }
            var orderAddress = new OrderAddress(customerAddress.AddressText, customerAddress.PhoneNumber,
                                                customerAddress.CityId, customerAddress.CityName, customerAddress.Geography);
            var privateOrder = new PrivateOrder(customer, orderAddress, command.Description, DateTime.Now.AddSeconds(appSetting.OrderExpireOpenTime), shop)
            {
                OrderItems = new List <OrderItem>()
            };

            if (command.OrderItems.Any(p => p.IsPercentDiscount))
            {
                if (_factorDomainService.HavePercentDiscountToday(customer))
                {
                    throw new DomainException("شما مجاز به انتخاب یک کالای دارای تخفیف درصدی در هر روز می باشید");
                }
            }
            decimal totalPrice = 0;

            foreach (var orderItem in command.OrderItems)
            {
                var product = _productRepository.Find(orderItem.ProductId);
                if (product == null)
                {
                    throw new DomainException("کالای انتخابی یافت نشد");
                }
                var orderProduct = new OrderProduct(product.Id, product.Name, product.Price, product.MainImage, product.Brand.Id, product.Brand.Name);
                OrderItemDiscountBase orderItemDiscount = null;
                if (orderItem.IsPercentDiscount)
                {
                    if (product.ProductDiscount != null)
                    {
                        if (product.ProductDiscount is ProductPercentDiscount productPercentDiscount)
                        {
                            if (productPercentDiscount.HasDiscountValid())
                            {
                                var haveRemainOrderCount = _percentDiscountDomainService.HaveRemainOrderCount(productPercentDiscount.DiscountId, customer);
                                if (haveRemainOrderCount)
                                {
                                    orderItemDiscount = new OrderItemPercentDiscount(Guid.NewGuid(),
                                                                                     productPercentDiscount.DiscountId, productPercentDiscount.Title, productPercentDiscount.FromDate,
                                                                                     productPercentDiscount.ToDate, productPercentDiscount.Percent, productPercentDiscount.FromTime,
                                                                                     productPercentDiscount.ToTime);
                                    _percentDiscountDomainService.LowOfNumberRemainOrderCount(productPercentDiscount.DiscountId, customer);
                                }
                            }
                        }
                    }
                }
                privateOrder.OrderItems.Add(new OrderItem(Guid.NewGuid(), orderItem.Quantity,
                                                          orderItem.Description, orderProduct, orderItemDiscount));
                totalPrice = totalPrice + (product.Price * orderItem.Quantity);
            }
            if (privateOrder.OrderItems.Count(item => item.Discount != null) > 1)
            {
                throw new DomainException("شما مجاز به انتخاب یک کالای دارای تخفیف درصدی در هر روز می باشید");
            }
            _applicationSettingDomainService.CheckMinimumBuy(totalPrice);
            _orderDomainService.CalcOrderPercentDiscount(privateOrder);
            _privateOrderRepository.Add(privateOrder);
            DomainEventDispatcher.Raise(new CreateShopOrderLogEvent(shop, privateOrder));
            _context.SaveChanges();
            await _fcmNotification.SendToIds(shop.GetPushTokens(), "سفارش جدید",
                                             $"یک سفارش ثبت شد", NotificationType.OrderAdd,
                                             AppType.Shop, NotificationSound.Shopper);

            SendNotificationToBoss(privateOrder, shop, customer);
            return(new CreatePrivateOrderCommandResponse(privateOrder.Id, appSetting.OrderExpireOpenTime));
        }
Beispiel #7
0
        public async Task <CreateOrderSuggestionCommandResponse> Handle(CreateOrderSuggestionCommand command)
        {
            _applicationSettingDomainService.CheckDiscountInRangeSetting(command.Discount);
            _applicationSettingDomainService.CheckShippingTime(command.ShippingTime);
            if (_repository.AsQuery().Any(p => p.OrderId == command.OrderId))
            {
                throw new DomainException("پیشنهاد بروی این سفارش زده شده است");
            }
            var order = _orderRepository.AsQuery().SingleOrDefault(p => p.Id == command.OrderId);

            if (order == null)
            {
                throw new DomainException("سفارش یافت نشد");
            }

            if (order.OrderStatus == OrderStatus.Cancel)
            {
                throw new DomainException("این سفارش توسط مشتری لغو شده است");
            }
            _applicationSettingDomainService.CheckOrderExpireTime(order.CreationTime);
            if (order.ResponseExpireTime < DateTime.Now)
            {
                throw new DomainException("زمان پاسخ گویی شما به پایان رسیده است");
            }

            var shop = _personRepository.AsQuery().OfType <Shop>().SingleOrDefault(p => p.UserId == command.UserId);

            if (shop == null)
            {
                throw new DomainException("فروشگاه یافت نشد");
            }

            var appSetting = _applicationSettingRepository.AsQuery().SingleOrDefault();

            if (appSetting == null)
            {
                throw new Exception();
            }

            if (command.Discount < appSetting.MinimumDiscount || command.Discount > appSetting.MaximumDiscount)
            {
                throw new DomainException("تخفیف وارد شده در بازه تخفیفات معتبر نمی باشد");
            }
            if (command.ShippingTime > appSetting.MaximumDeliveryTime)
            {
                throw new DomainException("زمان ارسال سفارش از حداکثر زمان ارسال معتبر بیشتر می باشد");
            }

            var orderId         = order is AreaOrder areaOrder ? areaOrder.PrivateOrder.Id : order.Id;
            var orderSuggestion = new OrderSuggestion(Guid.NewGuid(), orderId, command.Discount, command.Description, shop, command.ShippingTime)
            {
                OrderSuggestionItems = new List <OrderSuggestionItemBase>()
            };
            decimal totalPrice = 0;

            foreach (var item in command.OrderSuggestionItems)
            {
                var orderItem = order.OrderItems.SingleOrDefault(p => p.Id == item.OrderItemId);
                if (orderItem == null)
                {
                    throw new DomainException("آیتم سفارش یافت نشد");
                }
                var findProduct = _productRepository.Find(item.ProductId);
                switch (item.OrderSuggestionItemType)
                {
                case OrderSuggestionItemType.AlternativeProduct:
                    if (findProduct == null)
                    {
                        throw new DomainException("کالای ارسالی جایگزین نامعتبر می باشد");
                    }
                    var alternativeProduct =
                        new AlternativeProductSuggestion(findProduct.Id, findProduct.Name, findProduct.MainImage,
                                                         findProduct.Brand.Id, findProduct.Brand.Name);
                    orderItem.Discount = null;
                    var alternativeProductSuggestionItem = new AlternativeProductSuggestionItem(Guid.NewGuid(),
                                                                                                orderItem, item.Quantity, item.Description, item.Price, alternativeProduct,
                                                                                                orderItem.Quantity != item.Quantity);
                    orderSuggestion.OrderSuggestionItems.Add(alternativeProductSuggestionItem);
                    totalPrice = totalPrice + (item.Price * item.Quantity);
                    break;

                case OrderSuggestionItemType.NoProduct:
                    var noProduct = new NoProductSuggestionItem(Guid.NewGuid(), orderItem);
                    orderSuggestion.OrderSuggestionItems.Add(noProduct);
                    break;

                case OrderSuggestionItemType.HasProduct:
                    if (orderItem.Discount != null)
                    {
                        if (!orderItem.Discount.HasDiscountValid())
                        {
                            orderItem.Discount = null;
                        }
                    }
                    var hasProduct = new HasProductSuggestionItem(Guid.NewGuid(), orderItem, item.Quantity,
                                                                  item.Description, item.Price, orderItem.Quantity != item.Quantity);
                    orderSuggestion.OrderSuggestionItems.Add(hasProduct);
                    totalPrice = totalPrice + (item.Price * item.Quantity);
                    break;
                }
            }
            _repository.Add(orderSuggestion);


            //todo order check it
            var expireMinutes = order.ExpireOpenTime.Subtract(DateTime.Now).TotalMinutes;

            order.ExpireOpenTime = order.ExpireOpenTime.AddMinutes(appSetting.OrderSuggestionExpireTime - expireMinutes);
            order.SuggestionTime = DateTime.Now.AddMinutes(appSetting.OrderSuggestionExpireTime);
            DomainEventDispatcher.Raise(new TheOrderStatusWentToHasSuggestionEvent(order));
            if (order is AreaOrder area)
            {
                area.PrivateOrder.SuggestionTime = DateTime.Now.AddMinutes(appSetting.OrderSuggestionExpireTime);
                DomainEventDispatcher.Raise(new TheOrderStatusWentToHasSuggestionEvent(area.PrivateOrder));
            }
            DomainEventDispatcher.Raise(new CreateHasSuggestionsEvent(order.Id, shop.Id, orderSuggestion));
            await _fcmNotification.SendToIds(order.Customer.GetPushTokens(),
                                             "پیشنهاد سفارش",
                                             $"برای سفارش شما با شناسه {order.Id} یک پیشنهاد ثبت شد",
                                             NotificationType.OrderSuggestionAdded,
                                             AppType.Customer, NotificationSound.Shopper);

            return(new CreateOrderSuggestionCommandResponse());
        }