private int GetOrganizationIdForByCard(PaymentFrom paymentFrom, GeographicGroup geographicGroup, DateTime?orderCreateDate)
 {
     if (paymentFrom == null ||
         paymentFrom.Id == _orderParametersProvider.GetPaymentByCardFromFastPaymentServiceId ||
         paymentFrom.Id == _orderParametersProvider.GetPaymentByCardFromAvangardId)
     {
         return(_organizationParametersProvider.VodovozNorthOrganizationId);
     }
     if (paymentFrom.Id == _orderParametersProvider.GetPaymentByCardFromMarketplaceId)
     {
         return(_organizationParametersProvider.VodovozOrganizationId);
     }
     if (paymentFrom.Id == _orderParametersProvider.PaymentByCardFromSmsId)
     {
         if (geographicGroup == null || orderCreateDate == null)
         {
             return(_organizationParametersProvider.VodovozNorthOrganizationId);
         }
         if (geographicGroup.Id == _geographicGroupParametersProvider.NorthGeographicGroupId &&
             orderCreateDate.Value.TimeOfDay < _organizationParametersProvider.LatestCreateTimeForSouthOrganizationInByCardOrder)
         {
             return(_organizationParametersProvider.VodovozSouthOrganizationId);
         }
         return(_organizationParametersProvider.VodovozNorthOrganizationId);
     }
     return(_orderParametersProvider.PaymentsByCardFromForNorthOrganization.Contains(paymentFrom.Id)
                         ? _organizationParametersProvider.VodovozNorthOrganizationId
                         : _organizationParametersProvider.VodovozSouthOrganizationId);
 }
        private Organization GetOrganizationForOtherOptions(IUnitOfWork uow, PaymentType paymentType, DateTime?orderCreateDate,
                                                            PaymentFrom paymentFrom, GeographicGroup geographicGroup)
        {
            int organizationId;

            switch (paymentType)
            {
            case PaymentType.barter:
            case PaymentType.cashless:
            case PaymentType.ContractDoc:
                organizationId = _organizationParametersProvider.VodovozOrganizationId;
                break;

            case PaymentType.cash:
                organizationId = _organizationParametersProvider.VodovozNorthOrganizationId;
                break;

            case PaymentType.Terminal:
                organizationId = _organizationParametersProvider.VodovozNorthOrganizationId;
                break;

            case PaymentType.ByCard:
                organizationId = GetOrganizationIdForByCard(paymentFrom, geographicGroup, orderCreateDate);
                break;

            default:
                throw new NotSupportedException($"Тип оплаты {paymentType} не поддерживается, невозможно подобрать организацию.");
            }

            return(uow.GetById <Organization>(organizationId));
        }
        /// <summary>
        /// Метод подбора организации.<br/>
        /// Если в заказе установлена наша организация - берем ее.<br/>
        /// Иначе, если у клиента прописана организация с которой он работает - возвращаем ее.<br/>
        /// Иначе подбираем организацию по параметрам: если заполнены параметры paymentFrom и paymentType,
        /// то они берутся для подбора организации вместо соответствующих полей заказа<br/>
        /// </summary>
        /// <param name="uow">Unit Of Work</param>
        /// <param name="order">Заказ, для которого подбираем организацию</param>
        /// <param name="paymentFrom">Источник оплаты, если не null берем его для подбора организации</param>
        /// <param name="paymentType">Тип оплаты, если не null берем его для подбора организации</param>
        /// <returns>Организация для заказа</returns>
        /// <exception cref="ArgumentNullException">Исключение при order = null</exception>
        public Organization GetOrganization(IUnitOfWork uow, Order order, PaymentFrom paymentFrom = null, PaymentType?paymentType = null)
        {
            if (order == null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            if (order.OurOrganization != null)
            {
                return(order.OurOrganization);
            }
            if (order.Client.WorksThroughOrganization != null)
            {
                return(order.Client.WorksThroughOrganization);
            }

            var isSelfDelivery = order.SelfDelivery || order.DeliveryPoint == null;

            return(GetOrganizationForOrderParameters(uow, paymentType ?? order.PaymentType, isSelfDelivery, order.CreateDate,
                                                     order.OrderItems, paymentFrom ?? order.PaymentByCardFrom, order.DeliveryPoint?.District?.GeographicGroup));
        }
Exemplo n.º 4
0
        public StatusCode ReceivePayment(RequestBody body)
        {
            var externalId = body.ExternalId;
            var status     = (SmsPaymentStatus)body.Status;
            var paidDate   = DateTime.Parse(body.PaidDate);
            int orderId;

            logger.Info($"Поступил запрос на изменения статуса платежа с параметрами externalId: {externalId}, status: {status} и paidDate: {paidDate}");

            var acceptedStatuses = new[] { SmsPaymentStatus.Paid, SmsPaymentStatus.Cancelled };

            if (externalId == 0 || !acceptedStatuses.Contains(status))
            {
                logger.Error($"Запрос на изменение статуса пришёл с неверным статусом (status: {status})");
                return(new StatusCode(HttpStatusCode.UnsupportedMediaType));
            }
            try {
                using (IUnitOfWork uow = UnitOfWorkFactory.CreateWithoutRoot()) {
                    var payment = uow.Session.QueryOver <SmsPayment>().Where(x => x.ExternalId == externalId).Take(1).SingleOrDefault();
                    if (payment == null)
                    {
                        logger.Error($"Запрос на изменение статуса платежа указывает на несуществующий платеж (externalId: {externalId})");
                        return(new StatusCode(HttpStatusCode.UnsupportedMediaType));
                    }
                    var oldStatus      = payment.SmsPaymentStatus;
                    var oldPaymentType = payment.Order.PaymentType;

                    payment.SmsPaymentStatus = status;

                    if (status == SmsPaymentStatus.Paid)
                    {
                        payment.PaidDate = paidDate;

                        PaymentFrom smsPaymentFrom = uow.GetById <PaymentFrom>(new BaseParametersProvider().GetSmsPaymentByCardFromId);
                        if (payment.Order.PaymentType != PaymentType.ByCard || payment.Order.PaymentByCardFrom.Id != smsPaymentFrom.Id)
                        {
                            payment.Order.PaymentType       = PaymentType.ByCard;
                            payment.Order.PaymentByCardFrom = smsPaymentFrom;
                            payment.Order.OnlineOrder       = externalId;
                        }
                    }
                    uow.Save(payment);
                    uow.Commit();
                    orderId = payment.Order.Id;

                    if (oldStatus != status)
                    {
                        logger.Info($"Статус платежа № {payment.Id} изменён c {oldStatus} на {status}");
                    }
                    if (oldPaymentType != PaymentType.ByCard)
                    {
                        logger.Info($"Тип оплаты заказа № {payment.Order.Id} изменён c {oldPaymentType} на {PaymentType.ByCard}");
                    }
                }
            }
            catch (Exception ex) {
                logger.Error(ex, $"Ошибка при обработке поступившего платежа (externalId: {externalId}, status: {status})");
                return(new StatusCode(HttpStatusCode.InternalServerError));
            }

            try {
                androidDriverService.RefreshPaymentStatus(orderId);
            }
            catch (Exception ex) {
                logger.Error(ex, $"Не получилось уведомить службу водителей об обновлении статуса заказа");
            }

            return(new StatusCode(HttpStatusCode.OK));
        }
        public SmsPaymentDTO CreateSmsPaymentDTO(IUnitOfWork uow, SmsPayment smsPayment, Order order, PaymentFrom paymentFrom)
        {
            var newSmsPaymentDTO = new SmsPaymentDTO
            {
                Recepient           = smsPayment.Recepient.Name,
                RecepientId         = smsPayment.Recepient.Id,
                PhoneNumber         = smsPayment.PhoneNumber,
                PaymentStatus       = SmsPaymentStatus.WaitingForPayment,
                OrderId             = smsPayment.Order.Id,
                PaymentCreationDate = smsPayment.CreationDate,
                Amount         = smsPayment.Amount,
                RecepientType  = smsPayment.Recepient.PersonType,
                Items          = GetCalculatedSmsPaymentItemDTOs(order.OrderItems),
                OrganizationId = _organizationProvider.GetOrganization(uow, order, paymentFrom, PaymentType.ByCard).Id
            };

            return(newSmsPaymentDTO);
        }
Exemplo n.º 6
0
        private Organization GetOrganizationForSelfDelivery(IUnitOfWork uow, PaymentType paymentType, PaymentFrom paymentFrom = null)
        {
            int organizationId;

            switch (paymentType)
            {
            case PaymentType.barter:
            case PaymentType.cashless:
            case PaymentType.ContractDoc:
                organizationId = _organizationParametersProvider.VodovozOrganizationId;
                break;

            case PaymentType.cash:
                organizationId = _organizationParametersProvider.VodovozDeshitsOrganizationId;
                break;

            case PaymentType.Terminal:
            case PaymentType.ByCard:
                organizationId =
                    paymentFrom?.Id == _orderParametersProvider.PaymentByCardFromSmsId
                                                        ? _organizationParametersProvider.VodovozNorthOrganizationId
                                                        : _organizationParametersProvider.VodovozSouthOrganizationId;
                break;

            case PaymentType.BeveragesWorld:
                organizationId = _organizationParametersProvider.BeveragesWorldOrganizationId;
                break;

            default:
                throw new NotSupportedException(
                          $"Невозможно подобрать организацию, так как тип оплаты {paymentType} не поддерживается.");
            }

            return(uow.GetById <Organization>(organizationId));
        }
Exemplo n.º 7
0
        public Organization GetOrganization(IUnitOfWork uow, PaymentType paymentType, bool isSelfDelivery,
                                            IEnumerable <OrderItem> orderItems = null, PaymentFrom paymentFrom = null, GeographicGroup geographicGroup = null)
        {
            if (uow == null)
            {
                throw new ArgumentNullException(nameof(uow));
            }

            if (HasAnyOnlineStoreNomenclature(orderItems))
            {
                return(GetOrganizationForOnlineStore(uow));
            }

            return(isSelfDelivery
                                ? GetOrganizationForSelfDelivery(uow, paymentType, paymentFrom)
                                : GetOrganizationForOtherOptions(uow, paymentType, paymentFrom, geographicGroup));
        }
Exemplo n.º 8
0
        private Organization GetOrganizationForOtherOptions(IUnitOfWork uow, PaymentType paymentType, PaymentFrom paymentFrom = null,
                                                            GeographicGroup geographicGroup = null)
        {
            int organizationId;

            switch (paymentType)
            {
            case PaymentType.barter:
            case PaymentType.cashless:
            case PaymentType.ContractDoc:
                organizationId = _organizationParametersProvider.VodovozOrganizationId;
                break;

            case PaymentType.cash:
                organizationId = _organizationParametersProvider.VodovozDeshitsOrganizationId;
                break;

            case PaymentType.Terminal:
            case PaymentType.ByCard:
                organizationId =
                    paymentFrom?.Id == _orderParametersProvider.PaymentByCardFromSmsId &&
                    _northOrganizationGeoGroupsIds.Contains(geographicGroup?.Id ?? -1)
                                                        ? _organizationParametersProvider.VodovozNorthOrganizationId
                                                        : _organizationParametersProvider.VodovozSouthOrganizationId;
                break;

            case PaymentType.BeveragesWorld:
                organizationId = _organizationParametersProvider.BeveragesWorldOrganizationId;
                break;

            default:
                throw new NotSupportedException($"Тип оплаты {paymentType} не поддерживается, невозможно подобрать организацию.");
            }

            return(uow.GetById <Organization>(organizationId));
        }
Exemplo n.º 9
0
 public Organization GetOrganization(IUnitOfWork uow, PaymentType paymentType, bool isSelfDelivery,
                                     IEnumerable <OrderItem> orderItems = null,
                                     PaymentFrom paymentFrom            = null, GeographicGroup geographicGroup = null)
 {
     throw new NotSupportedException();
 }
Exemplo n.º 10
0
        private IQueryOver <VodovozOrder> GetOrdersQuery(IUnitOfWork uow)
        {
            OrderJournalNode     resultAlias           = null;
            VodovozOrder         orderAlias            = null;
            Nomenclature         nomenclatureAlias     = null;
            OrderItem            orderItemAlias        = null;
            Counterparty         counterpartyAlias     = null;
            DeliveryPoint        deliveryPointAlias    = null;
            DeliverySchedule     deliveryScheduleAlias = null;
            Employee             authorAlias           = null;
            Employee             lastEditorAlias       = null;
            District             districtAlias         = null;
            CounterpartyContract contractAlias         = null;
            PaymentFrom          paymentFromAlias      = null;

            Nomenclature sanitizationNomenclature = nomenclatureRepository.GetSanitisationNomenclature(uow);

            var query = uow.Session.QueryOver <VodovozOrder>(() => orderAlias);

            if (FilterViewModel.ViewTypes != ViewTypes.Order && FilterViewModel.ViewTypes != ViewTypes.All)
            {
                query.Where(o => o.Id == -1);
            }

            if (FilterViewModel.RestrictStatus != null)
            {
                query.Where(o => o.OrderStatus == FilterViewModel.RestrictStatus);
            }

            if (FilterViewModel.RestrictPaymentType != null)
            {
                query.Where(o => o.PaymentType == FilterViewModel.RestrictPaymentType);
            }

            if (FilterViewModel.HideStatuses != null)
            {
                query.WhereRestrictionOn(o => o.OrderStatus).Not.IsIn(FilterViewModel.HideStatuses);
            }

            if (FilterViewModel.RestrictOnlySelfDelivery != null)
            {
                query.Where(o => o.SelfDelivery == FilterViewModel.RestrictOnlySelfDelivery);
            }

            if (FilterViewModel.RestrictWithoutSelfDelivery != null)
            {
                query.Where(o => o.SelfDelivery != FilterViewModel.RestrictWithoutSelfDelivery);
            }

            if (FilterViewModel.RestrictCounterparty != null)
            {
                query.Where(o => o.Client == FilterViewModel.RestrictCounterparty);
            }

            if (FilterViewModel.RestrictDeliveryPoint != null)
            {
                query.Where(o => o.DeliveryPoint == FilterViewModel.RestrictDeliveryPoint);
            }

            if (FilterViewModel.RestrictStartDate != null)
            {
                query.Where(o => o.DeliveryDate >= FilterViewModel.RestrictStartDate);
            }

            if (FilterViewModel.RestrictEndDate != null)
            {
                query.Where(o => o.DeliveryDate <= FilterViewModel.RestrictEndDate.Value.AddDays(1).AddTicks(-1));
            }

            if (FilterViewModel.RestrictLessThreeHours == true)
            {
                query.Where(Restrictions
                            .GtProperty(Projections.SqlFunction(
                                            new SQLFunctionTemplate(NHibernateUtil.Time, "ADDTIME(?1, ?2)"),
                                            NHibernateUtil.Time,
                                            Projections.Property(() => deliveryScheduleAlias.From),
                                            Projections.Constant("3:0:0")),
                                        Projections.Property(() => deliveryScheduleAlias.To)));
            }

            if (FilterViewModel.RestrictHideService != null)
            {
                query.Where(o => o.IsService != FilterViewModel.RestrictHideService);
            }

            if (FilterViewModel.RestrictOnlyService != null)
            {
                query.Where(o => o.IsService == FilterViewModel.RestrictOnlyService);
            }

            if (FilterViewModel.OrderPaymentStatus != null)
            {
                query.Where(o => o.OrderPaymentStatus == FilterViewModel.OrderPaymentStatus);
            }

            if (FilterViewModel.Organisation != null)
            {
                query.Where(() => contractAlias.Organization.Id == FilterViewModel.Organisation.Id);
            }

            if (FilterViewModel.PaymentByCardFrom != null)
            {
                query.Where(o => o.PaymentByCardFrom.Id == FilterViewModel.PaymentByCardFrom.Id);
            }

            var bottleCountSubquery = QueryOver.Of <OrderItem>(() => orderItemAlias)
                                      .Where(() => orderAlias.Id == orderItemAlias.Order.Id)
                                      .JoinAlias(() => orderItemAlias.Nomenclature, () => nomenclatureAlias)
                                      .Where(() => nomenclatureAlias.Category == NomenclatureCategory.water && nomenclatureAlias.TareVolume == TareVolume.Vol19L)
                                      .Select(Projections.Sum(() => orderItemAlias.Count));

            var sanitisationCountSubquery = QueryOver.Of <OrderItem>(() => orderItemAlias)
                                            .Where(() => orderAlias.Id == orderItemAlias.Order.Id)
                                            .Where(() => orderItemAlias.Nomenclature.Id == sanitizationNomenclature.Id)
                                            .Select(Projections.Sum(() => orderItemAlias.Count));

            var orderSumSubquery = QueryOver.Of <OrderItem>(() => orderItemAlias)
                                   .Where(() => orderItemAlias.Order.Id == orderAlias.Id)
                                   .Select(
                Projections.Sum(
                    Projections.SqlFunction(
                        new SQLFunctionTemplate(NHibernateUtil.Decimal, "ROUND(IFNULL(?1, ?2) * ?3 - ?4, 2)"),
                        NHibernateUtil.Decimal,
                        Projections.Property <OrderItem>(x => x.ActualCount),
                        Projections.Property <OrderItem>(x => x.Count),
                        Projections.Property <OrderItem>(x => x.Price),
                        Projections.Property <OrderItem>(x => x.DiscountMoney)
                        )
                    )
                );

            query.Left.JoinAlias(o => o.DeliveryPoint, () => deliveryPointAlias)
            .Left.JoinAlias(o => o.DeliverySchedule, () => deliveryScheduleAlias)
            .Left.JoinAlias(o => o.Client, () => counterpartyAlias)
            .Left.JoinAlias(o => o.Author, () => authorAlias)
            .Left.JoinAlias(o => o.LastEditor, () => lastEditorAlias)
            .Left.JoinAlias(() => deliveryPointAlias.District, () => districtAlias)
            .Left.JoinAlias(o => o.Contract, () => contractAlias);

            query.Where(GetSearchCriterion(
                            () => orderAlias.Id,
                            () => counterpartyAlias.Name,
                            () => deliveryPointAlias.CompiledAddress,
                            () => authorAlias.LastName,
                            () => orderAlias.DriverCallId,
                            () => orderAlias.OnlineOrder,
                            () => orderAlias.EShopOrder,
                            () => orderAlias.OrderPaymentStatus
                            ));

            var resultQuery = query
                              .SelectList(list => list
                                          .Select(() => orderAlias.Id).WithAlias(() => resultAlias.Id)
                                          .Select(() => orderAlias.SelfDelivery).WithAlias(() => resultAlias.IsSelfDelivery)
                                          .Select(() => orderAlias.DeliveryDate).WithAlias(() => resultAlias.Date)
                                          .Select(() => orderAlias.CreateDate).WithAlias(() => resultAlias.CreateDate)
                                          .Select(() => deliveryScheduleAlias.Name).WithAlias(() => resultAlias.DeliveryTime)
                                          .Select(() => orderAlias.OrderStatus).WithAlias(() => resultAlias.StatusEnum)
                                          .Select(() => orderAlias.Address1c).WithAlias(() => resultAlias.Address1c)
                                          .Select(() => authorAlias.LastName).WithAlias(() => resultAlias.AuthorLastName)
                                          .Select(() => authorAlias.Name).WithAlias(() => resultAlias.AuthorName)
                                          .Select(() => authorAlias.Patronymic).WithAlias(() => resultAlias.AuthorPatronymic)
                                          .Select(() => lastEditorAlias.LastName).WithAlias(() => resultAlias.LastEditorLastName)
                                          .Select(() => lastEditorAlias.Name).WithAlias(() => resultAlias.LastEditorName)
                                          .Select(() => lastEditorAlias.Patronymic).WithAlias(() => resultAlias.LastEditorPatronymic)
                                          .Select(() => orderAlias.LastEditedTime).WithAlias(() => resultAlias.LastEditedTime)
                                          .Select(() => orderAlias.DriverCallId).WithAlias(() => resultAlias.DriverCallId)
                                          .Select(() => orderAlias.OnlineOrder).WithAlias(() => resultAlias.OnlineOrder)
                                          .Select(() => counterpartyAlias.Name).WithAlias(() => resultAlias.Counterparty)
                                          .Select(() => districtAlias.DistrictName).WithAlias(() => resultAlias.DistrictName)
                                          .Select(() => deliveryPointAlias.CompiledAddress).WithAlias(() => resultAlias.CompilledAddress)
                                          .Select(() => deliveryPointAlias.City).WithAlias(() => resultAlias.City)
                                          .Select(() => deliveryPointAlias.Street).WithAlias(() => resultAlias.Street)
                                          .Select(() => deliveryPointAlias.Building).WithAlias(() => resultAlias.Building)
                                          .Select(() => orderAlias.EShopOrder).WithAlias(() => resultAlias.EShopOrder)
                                          .Select(() => orderAlias.OrderPaymentStatus).WithAlias(() => resultAlias.OrderPaymentStatus)
                                          .Select(
                                              Projections.Conditional(
                                                  Restrictions.Or(
                                                      Restrictions.Eq(Projections.Constant(true), userHaveAccessToRetail),
                                                      Restrictions.Not(Restrictions.Eq(Projections.Property(() => orderAlias.IsForRetail), true))
                                                      ),
                                                  Projections.Constant(true),
                                                  Projections.Constant(false)
                                                  )).WithAlias(() => resultAlias.Sensitive
                                                               )
                                          .SelectSubQuery(orderSumSubquery).WithAlias(() => resultAlias.Sum)
                                          .SelectSubQuery(bottleCountSubquery).WithAlias(() => resultAlias.BottleAmount)
                                          .SelectSubQuery(sanitisationCountSubquery).WithAlias(() => resultAlias.SanitisationAmount)
                                          )
                              .OrderBy(x => x.CreateDate).Desc
                              .SetTimeout(60)
                              .TransformUsing(Transformers.AliasToBean <OrderJournalNode <VodovozOrder> >());

            return(resultQuery);
        }
        private Organization GetOrganizationForOrderParameters(IUnitOfWork uow, PaymentType paymentType, bool isSelfDelivery,
                                                               DateTime?orderCreateDate, IEnumerable <OrderItem> orderItems, PaymentFrom paymentFrom, GeographicGroup geographicGroup)
        {
            if (uow == null)
            {
                throw new ArgumentNullException(nameof(uow));
            }

            if (HasAnyOnlineStoreNomenclature(orderItems))
            {
                return(GetOrganizationForOnlineStore(uow));
            }

            return(isSelfDelivery
                                ? GetOrganizationForSelfDelivery(uow, paymentType, orderCreateDate, paymentFrom, geographicGroup)
                                : GetOrganizationForOtherOptions(uow, paymentType, orderCreateDate, paymentFrom, geographicGroup));
        }