public async Task SaveCouponsAsync(Coupon[] coupons)
        {
            if (coupons.Any(x => x.Code.IsNullOrEmpty()))
            {
                throw new InvalidOperationException($"Coupon can't have empty code!");
            }

            var pkMap          = new PrimaryKeyResolvingMap();
            var changedEntries = new List <GenericChangedEntry <Coupon> >();

            using (var repository = _repositoryFactory())
            {
                var existCouponEntities = await repository.GetCouponsByIdsAsync(coupons.Where(x => !x.IsTransient()).Select(x => x.Id).ToArray());

                var nonUniqueCouponErrors = await repository.CheckCouponsForUniquenessAsync(coupons.Where(x => x.IsTransient()).ToArray());

                if (!nonUniqueCouponErrors.IsNullOrEmpty())
                {
                    throw new InvalidOperationException(string.Join(Environment.NewLine, nonUniqueCouponErrors));
                }

                foreach (var coupon in coupons)
                {
                    var sourceEntity = AbstractTypeFactory <CouponEntity> .TryCreateInstance();

                    if (sourceEntity != null)
                    {
                        sourceEntity = sourceEntity.FromModel(coupon, pkMap);
                        var targetCouponEntity = existCouponEntities.FirstOrDefault(x => x.Id == coupon.Id);
                        if (targetCouponEntity != null)
                        {
                            changedEntries.Add(new GenericChangedEntry <Coupon>(coupon, sourceEntity.ToModel(AbstractTypeFactory <Coupon> .TryCreateInstance()), EntryState.Modified));
                            sourceEntity.Patch(targetCouponEntity);
                        }
                        else
                        {
                            changedEntries.Add(new GenericChangedEntry <Coupon>(coupon, EntryState.Added));
                            repository.Add(sourceEntity);
                        }
                    }
                }
                await repository.UnitOfWork.CommitAsync();

                pkMap.ResolvePrimaryKeys();

                ClearCache(coupons.Select(x => x.PromotionId).ToArray());

                await _eventPublisher.Publish(new CouponChangedEvent(changedEntries));
            }
        }
        /// <summary>
        /// Evaluation product prices.
        /// Will get either all prices or one price per currency depending on the settings in evalContext.
        /// </summary>
        /// <param name="evalContext"></param>
        /// <returns></returns>
        public virtual async Task <IEnumerable <Price> > EvaluateProductPricesAsync(PriceEvaluationContext evalContext)
        {
            if (evalContext == null)
            {
                throw new ArgumentNullException(nameof(evalContext));
            }
            if (evalContext.ProductIds == null)
            {
                throw new MissingFieldException("ProductIds");
            }

            var result = new List <Price>();

            Price[] prices;
            using (var repository = _repositoryFactory())
            {
                //Get a price range satisfying by passing context
                var query = repository.Prices.Include(x => x.Pricelist)
                            .Where(x => evalContext.ProductIds.Contains(x.ProductId))
                            .Where(x => evalContext.Quantity >= x.MinQuantity || evalContext.Quantity == 0);

                if (evalContext.PricelistIds.IsNullOrEmpty())
                {
                    evalContext.PricelistIds = (await EvaluatePriceListsAsync(evalContext)).Select(x => x.Id).ToArray();
                }

                query = query.Where(x => evalContext.PricelistIds.Contains(x.PricelistId));

                // Filter by date expiration
                // Always filter on date, so that we limit the results to process.
                var certainDate = evalContext.CertainDate ?? DateTime.UtcNow;
                query = query.Where(x => (x.StartDate == null || x.StartDate <= certainDate) &&
                                    (x.EndDate == null || x.EndDate > certainDate));

                var queryResult = await query.AsNoTracking().ToArrayAsync();

                prices = queryResult.Select(x => x.ToModel(AbstractTypeFactory <Price> .TryCreateInstance())).ToArray();
            }

            //Apply pricing  filtration strategy for found prices
            result.AddRange(_pricingPriorityFilterPolicy.FilterPrices(prices, evalContext));

            //Then variation inherited prices
            if (_productService != null)
            {
                var productIdsWithoutPrice = evalContext.ProductIds.Except(result.Select(x => x.ProductId).Distinct()).ToArray();
                //Try to inherit prices for variations from their main product
                //Need find products without price it may be a variation without implicitly price defined and try to get price from main product
                if (productIdsWithoutPrice.Any())
                {
                    var variations = (await _productService.GetByIdsAsync(productIdsWithoutPrice, ItemResponseGroup.ItemInfo.ToString())).Where(x => x.MainProductId != null).ToList();
                    evalContext            = evalContext.Clone() as PriceEvaluationContext;
                    evalContext.ProductIds = variations.Select(x => x.MainProductId).Distinct().ToArray();
                    if (!evalContext.ProductIds.IsNullOrEmpty())
                    {
                        var inheritedPrices = await EvaluateProductPricesAsync(evalContext);

                        foreach (var inheritedPrice in inheritedPrices)
                        {
                            foreach (var variation in variations.Where(x => x.MainProductId == inheritedPrice.ProductId))
                            {
                                var variationPrice = inheritedPrice.Clone() as Price;
                                //Reset id for correct override price in possible update
                                variationPrice.Id        = null;
                                variationPrice.ProductId = variation.Id;
                                result.Add(variationPrice);
                            }
                        }
                    }
                }
            }
            return(result);
        }
        public virtual async Task SavePricesAsync(Price[] prices)
        {
            var pkMap          = new PrimaryKeyResolvingMap();
            var changedEntries = new List <GenericChangedEntry <Price> >();

            using (var repository = _repositoryFactory())
            {
                var pricesIds = prices.Select(x => x.Id).Where(x => x != null).Distinct().ToArray();
                var alreadyExistPricesEntities = await repository.GetPricesByIdsAsync(pricesIds);

                //Create default priceLists for prices without pricelist
                foreach (var priceWithoutPricelistGroup in prices.Where(x => x.PricelistId == null).GroupBy(x => x.Currency))
                {
                    var defaultPriceListId = GetDefaultPriceListName(priceWithoutPricelistGroup.Key);
                    var pricelists         = await GetPricelistsByIdAsync(new[] { defaultPriceListId });

                    if (pricelists.IsNullOrEmpty())
                    {
                        var defaultPriceList = AbstractTypeFactory <Pricelist> .TryCreateInstance();

                        defaultPriceList.Id          = defaultPriceListId;
                        defaultPriceList.Currency    = priceWithoutPricelistGroup.Key;
                        defaultPriceList.Name        = defaultPriceListId;
                        defaultPriceList.Description = defaultPriceListId;
                        repository.Add(AbstractTypeFactory <PricelistEntity> .TryCreateInstance().FromModel(defaultPriceList, pkMap));
                    }
                    foreach (var priceWithoutPricelist in priceWithoutPricelistGroup)
                    {
                        priceWithoutPricelist.PricelistId = defaultPriceListId;
                    }
                }

                foreach (var price in prices)
                {
                    var sourceEntity = AbstractTypeFactory <PriceEntity> .TryCreateInstance().FromModel(price, pkMap);

                    var targetEntity = alreadyExistPricesEntities.FirstOrDefault(x => x.Id == price.Id);
                    if (targetEntity != null)
                    {
                        changedEntries.Add(new GenericChangedEntry <Price>(price, targetEntity.ToModel(AbstractTypeFactory <Price> .TryCreateInstance()), EntryState.Modified));
                        sourceEntity.Patch(targetEntity);
                    }
                    else
                    {
                        changedEntries.Add(new GenericChangedEntry <Price>(price, EntryState.Added));
                        repository.Add(sourceEntity);
                    }
                }

                await repository.UnitOfWork.CommitAsync();

                pkMap.ResolvePrimaryKeys();

                foreach (var price in prices)
                {
                    PricesCacheRegion.ExpirePrice(price.Id);
                }
                ResetCache();

                await _eventPublisher.Publish(new PriceChangedEvent(changedEntries));
            }
        }
        public virtual ItemEntity FromModel(CatalogProduct product, PrimaryKeyResolvingMap pkMap)
        {
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }

            pkMap.AddPair(product, this);

            this.Id           = product.Id;
            this.CreatedDate  = product.CreatedDate;
            this.CreatedBy    = product.CreatedBy;
            this.ModifiedDate = product.ModifiedDate;
            this.ModifiedBy   = product.ModifiedBy;

            this.CatalogId              = product.CatalogId;
            this.CategoryId             = product.CategoryId;
            this.Code                   = product.Code;
            this.DownloadExpiration     = product.DownloadExpiration;
            this.DownloadType           = product.DownloadType;
            this.EnableReview           = product.EnableReview;
            this.EndDate                = product.EndDate;
            this.Gtin                   = product.Gtin;
            this.HasUserAgreement       = product.HasUserAgreement;
            this.Height                 = product.Height;
            this.IsActive               = product.IsActive ?? true;
            this.IsBuyable              = product.IsBuyable ?? true;
            this.Length                 = product.Length;
            this.ParentId               = product.MainProductId;
            this.ManufacturerPartNumber = product.ManufacturerPartNumber;
            this.MaxNumberOfDownload    = product.MaxNumberOfDownload;
            this.MaxQuantity            = product.MaxQuantity ?? 0;
            this.MeasureUnit            = product.MeasureUnit;
            this.MinQuantity            = product.MinQuantity ?? 0;
            this.Name                   = product.Name;
            this.PackageType            = product.PackageType;
            this.Priority               = product.Priority;
            this.ProductType            = product.ProductType;
            this.ShippingType           = product.ShippingType;
            this.TaxType                = product.TaxType;
            this.TrackInventory         = product.TrackInventory ?? true;
            this.Vendor                 = product.Vendor;
            this.Weight                 = product.Weight;
            this.WeightUnit             = product.WeightUnit;
            this.Width                  = product.Width;

            this.StartDate = product.StartDate == default(DateTime) ? DateTime.UtcNow : product.StartDate;

            //Constant fields
            //Only for main product
            this.AvailabilityRule = (int)VirtoCommerce.Domain.Catalog.Model.AvailabilityRule.Always;

            this.CatalogId  = product.CatalogId;
            this.CategoryId = string.IsNullOrEmpty(product.CategoryId) ? null : product.CategoryId;

            #region ItemPropertyValues
            if (product.PropertyValues != null)
            {
                this.ItemPropertyValues = new ObservableCollection <PropertyValueEntity>();
                foreach (var propertyValue in product.PropertyValues)
                {
                    if (!propertyValue.IsInherited && propertyValue.Value != null && !string.IsNullOrEmpty(propertyValue.Value.ToString()))
                    {
                        this.ItemPropertyValues.Add(AbstractTypeFactory <PropertyValueEntity> .TryCreateInstance().FromModel(propertyValue, pkMap));
                    }
                }
            }
            #endregion

            #region Assets
            if (product.Assets != null)
            {
                this.Assets = new ObservableCollection <AssetEntity>(product.Assets.Where(x => !x.IsInherited).Select(x => AbstractTypeFactory <AssetEntity> .TryCreateInstance().FromModel(x, pkMap)));
            }
            #endregion

            #region Images
            if (product.Images != null)
            {
                this.Images = new ObservableCollection <ImageEntity>(product.Images.Where(x => !x.IsInherited).Select(x => AbstractTypeFactory <ImageEntity> .TryCreateInstance().FromModel(x, pkMap)));
            }
            #endregion

            #region Links
            if (product.Links != null)
            {
                this.CategoryLinks = new ObservableCollection <CategoryItemRelationEntity>(product.Links.Select(x => AbstractTypeFactory <CategoryItemRelationEntity> .TryCreateInstance().FromModel(x)));
            }
            #endregion

            #region EditorialReview
            if (product.Reviews != null)
            {
                this.EditorialReviews = new ObservableCollection <EditorialReviewEntity>(product.Reviews.Where(x => !x.IsInherited).Select(x => AbstractTypeFactory <EditorialReviewEntity> .TryCreateInstance().FromModel(x, pkMap)));
            }
            #endregion

            #region Associations
            if (product.Associations != null)
            {
                this.Associations = new ObservableCollection <AssociationEntity>(product.Associations.Select(x => AbstractTypeFactory <AssociationEntity> .TryCreateInstance().FromModel(x)));
            }
            #endregion

            if (product.Variations != null)
            {
                this.Childrens = new ObservableCollection <ItemEntity>(product.Variations.Select(x => AbstractTypeFactory <ItemEntity> .TryCreateInstance().FromModel(x, pkMap)));
            }

            return(this);
        }
Exemple #5
0
        public void Build(ISchema schema)
        {
            ValueConverter.Register <ExpOrderAddress, Optional <ExpOrderAddress> >(x => new Optional <ExpOrderAddress>(x));

            _ = schema.Query.AddField(new FieldType
            {
                Name      = "order",
                Arguments = AbstractTypeFactory <OrderQueryArguments> .TryCreateInstance(),
                Type      = GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>(),
                Resolver  = new AsyncFieldResolver <object>(async context =>
                {
                    var request = context.ExtractQuery <GetOrderQuery>();

                    context.CopyArgumentsToUserContext();
                    var orderAggregate = await _mediator.Send(request);

                    var authorizationResult = await _authorizationService.AuthorizeAsync(context.GetCurrentPrincipal(), orderAggregate.Order, new CanAccessOrderAuthorizationRequirement());

                    if (!authorizationResult.Succeeded)
                    {
                        throw new AuthorizationError($"Access denied");
                    }

                    var allCurrencies = await _currencyService.GetAllCurrenciesAsync();
                    //Store all currencies in the user context for future resolve in the schema types
                    context.SetCurrencies(allCurrencies, request.CultureName);

                    //store order aggregate in the user context for future usage in the graph types resolvers
                    context.SetExpandedObjectGraph(orderAggregate);

                    return(orderAggregate);
                })
            });

            var orderConnectionBuilder = GraphTypeExtenstionHelper
                                         .CreateConnection <CustomerOrderType, object>()
                                         .Name("orders")
                                         .PageSize(20)
                                         .Arguments();

            orderConnectionBuilder.ResolveAsync(async context => await ResolveOrdersConnectionAsync(_mediator, context));
            schema.Query.AddField(orderConnectionBuilder.FieldType);

            var paymentsConnectionBuilder = GraphTypeExtenstionHelper
                                            .CreateConnection <PaymentInType, object>()
                                            .Name("payments")
                                            .PageSize(20)
                                            .Arguments();

            paymentsConnectionBuilder.ResolveAsync(async context => await ResolvePaymentsConnectionAsync(_mediator, context));
            schema.Query.AddField(paymentsConnectionBuilder.FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, CustomerOrderAggregate>(GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>())
                                         .Name("createOrderFromCart")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputCreateOrderFromCartType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type     = GenericTypeHelper.GetActualType <CreateOrderFromCartCommand>();
                var response = (CustomerOrderAggregate)await _mediator.Send(context.GetArgument(type, _commandName));
                context.SetExpandedObjectGraph(response);
                return(response);
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, bool>(typeof(BooleanGraphType))
                                         .Name("changeOrderStatus")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputChangeOrderStatusType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <ChangeOrderStatusCommand>();
                var command = (ChangeOrderStatusCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, ProcessPaymentRequestResult>(typeof(ProcessPaymentRequestResultType))
                                         .Name("processOrderPayment")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputProcessOrderPaymentType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <ProcessOrderPaymentCommand>();
                var command = (ProcessOrderPaymentCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .DeprecationReason("Obsolete. Use 'initializePayment' mutation")
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, InitializePaymentResult>(typeof(InitializePaymentResultType))
                                         .Name("initializePayment")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputInitializePaymentType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type = GenericTypeHelper.GetActualType <InitializePaymentCommand>();

                var command = (InitializePaymentCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <object, AuthorizePaymentResult>(typeof(AuthorizePaymentResultType))
                                         .Name("authorizePayment")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputAuthorizePaymentType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type = GenericTypeHelper.GetActualType <AuthorizePaymentCommand>();

                var command = (AuthorizePaymentCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);


            _ = schema.Mutation.AddField(FieldBuilder.Create <CustomerOrderAggregate, CustomerOrderAggregate>(GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>())
                                         .Name("updateOrderDynamicProperties")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputUpdateOrderDynamicPropertiesType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <UpdateOrderDynamicPropertiesCommand>();
                var command = (UpdateOrderDynamicPropertiesCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <CustomerOrderAggregate, CustomerOrderAggregate>(GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>())
                                         .Name("updateOrderItemDynamicProperties")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputUpdateOrderItemDynamicPropertiesType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <UpdateOrderItemDynamicPropertiesCommand>();
                var command = (UpdateOrderItemDynamicPropertiesCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <CustomerOrderAggregate, CustomerOrderAggregate>(GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>())
                                         .Name("updateOrderPaymentDynamicProperties")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputUpdateOrderPaymentDynamicPropertiesType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <UpdateOrderPaymentDynamicPropertiesCommand>();
                var command = (UpdateOrderPaymentDynamicPropertiesCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <CustomerOrderAggregate, CustomerOrderAggregate>(GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>())
                                         .Name("updateOrderShipmentDynamicProperties")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputUpdateOrderShipmentDynamicPropertiesType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <UpdateOrderShipmentDynamicPropertiesCommand>();
                var command = (UpdateOrderShipmentDynamicPropertiesCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                return(await _mediator.Send(command));
            })
                                         .FieldType);

            _ = schema.Mutation.AddField(FieldBuilder.Create <CustomerOrderAggregate, CustomerOrderAggregate>(GraphTypeExtenstionHelper.GetActualType <CustomerOrderType>())
                                         .Name("addOrUpdateOrderPayment")
                                         .Argument(GraphTypeExtenstionHelper.GetActualComplexType <NonNullGraphType <InputAddOrUpdateOrderPaymentType> >(), _commandName)
                                         .ResolveAsync(async context =>
            {
                var type    = GenericTypeHelper.GetActualType <AddOrUpdateOrderPaymentCommand>();
                var command = (AddOrUpdateOrderPaymentCommand)context.GetArgument(type, _commandName);
                await CheckAuthAsync(context, command.OrderId);

                var response = await _mediator.Send(command);

                context.SetExpandedObjectGraph(response);

                return(response);
            })
                                         .FieldType);
        }
Exemple #6
0
        public async Task DeleteAsync(IEnumerable <string> ids)
        {
            using (var repository = _repositoryFactory())
            {
                var changedEntries = new List <GenericChangedEntry <FulfillmentCenter> >();
                var dbCenters      = await repository.GetFulfillmentCentersAsync(ids);

                foreach (var dbCenter in dbCenters)
                {
                    repository.Remove(dbCenter);
                    changedEntries.Add(new GenericChangedEntry <FulfillmentCenter>(dbCenter.ToModel(AbstractTypeFactory <FulfillmentCenter> .TryCreateInstance()), EntryState.Deleted));
                }

                await _eventPublisher.Publish(new FulfillmentCenterChangingEvent(changedEntries));

                await repository.UnitOfWork.CommitAsync();

                await _eventPublisher.Publish(new FulfillmentCenterChangedEvent(changedEntries));

                FulfillmentCenterCacheRegion.ExpireRegion();
            }
        }
Exemple #7
0
        public override OperationEntity FromModel(OrderOperation operation, PrimaryKeyResolvingMap pkMap)
        {
            var payment = operation as PaymentIn;

            if (payment == null)
            {
                throw new ArgumentException(@"operation argument must be of type PaymentIn", nameof(operation));
            }

            base.FromModel(payment, pkMap);

            Price                 = payment.Price;
            PriceWithTax          = payment.PriceWithTax;
            DiscountAmount        = payment.DiscountAmount;
            DiscountAmountWithTax = payment.DiscountAmountWithTax;
            TaxType               = payment.TaxType;
            TaxPercentRate        = payment.TaxPercentRate;
            TaxTotal              = payment.TaxTotal;
            Total                 = payment.Total;
            TotalWithTax          = payment.TotalWithTax;

            CustomerId       = payment.CustomerId;
            CustomerName     = payment.CustomerName;
            OrganizationId   = payment.OrganizationId;
            OrganizationName = payment.OrganizationName;
            GatewayCode      = payment.GatewayCode;
            Purpose          = payment.Purpose;
            OuterId          = payment.OuterId;
            Status           = payment.Status;
            AuthorizedDate   = payment.AuthorizedDate;
            CapturedDate     = payment.CapturedDate;
            VoidedDate       = payment.VoidedDate;
            IsCancelled      = payment.IsCancelled;
            CancelledDate    = payment.CancelledDate;
            CancelReason     = payment.CancelReason;
            Sum = payment.Sum;

            if (payment.PaymentMethod != null)
            {
                GatewayCode = payment.PaymentMethod != null ? payment.PaymentMethod.Code : payment.GatewayCode;
            }

            if (payment.BillingAddress != null)
            {
                Addresses = new ObservableCollection <AddressEntity>(new[] { AbstractTypeFactory <AddressEntity> .TryCreateInstance().FromModel(payment.BillingAddress) });
            }

            if (payment.TaxDetails != null)
            {
                TaxDetails = new ObservableCollection <TaxDetailEntity>(payment.TaxDetails.Select(x => AbstractTypeFactory <TaxDetailEntity> .TryCreateInstance().FromModel(x)));
            }

            if (payment.Discounts != null)
            {
                Discounts = new ObservableCollection <DiscountEntity>(payment.Discounts.Select(x => AbstractTypeFactory <DiscountEntity> .TryCreateInstance().FromModel(x)));
            }

            if (payment.Transactions != null)
            {
                Transactions = new ObservableCollection <PaymentGatewayTransactionEntity>(payment.Transactions.Select(x => AbstractTypeFactory <PaymentGatewayTransactionEntity> .TryCreateInstance().FromModel(x, pkMap)));
            }

            if (payment.Status.IsNullOrEmpty())
            {
                Status = payment.PaymentStatus.ToString();
            }

            return(this);
        }
Exemple #8
0
        public virtual DynamicPropertyEntity FromModel(DynamicProperty dynamicProp, PrimaryKeyResolvingMap pkMap)
        {
            if (dynamicProp == null)
            {
                throw new ArgumentNullException(nameof(dynamicProp));
            }

            pkMap.AddPair(dynamicProp, this);

            Id             = dynamicProp.Id;
            CreatedBy      = dynamicProp.CreatedBy;
            CreatedDate    = dynamicProp.CreatedDate;
            ModifiedBy     = dynamicProp.ModifiedBy;
            ModifiedDate   = dynamicProp.ModifiedDate;
            Description    = dynamicProp.Description;
            DisplayOrder   = dynamicProp.DisplayOrder;
            IsArray        = dynamicProp.IsArray;
            IsDictionary   = dynamicProp.IsDictionary;
            IsMultilingual = dynamicProp.IsMultilingual;
            IsRequired     = dynamicProp.IsRequired;
            Name           = dynamicProp.Name;
            ObjectType     = dynamicProp.ObjectType;

            ValueType = dynamicProp.ValueType.ToString();
            if (dynamicProp.DisplayNames != null)
            {
                DisplayNames = new ObservableCollection <DynamicPropertyNameEntity>(dynamicProp.DisplayNames.Select(x => AbstractTypeFactory <DynamicPropertyNameEntity> .TryCreateInstance().FromModel(x)));
            }

            if (dynamicProp is DynamicObjectProperty dynamicObjectProp && dynamicObjectProp.Values != null)
            {
                //Force set these properties from owned property object
                foreach (var value in dynamicObjectProp.Values)
                {
                    value.ObjectId   = dynamicObjectProp.ObjectId;
                    value.ObjectType = dynamicObjectProp.ObjectType;
                    value.ValueType  = dynamicObjectProp.ValueType;
                }
                //ObjectValues = new ObservableCollection<DynamicPropertyObjectValueEntity>(dynamicObjectProp.Values.Select(x => AbstractTypeFactory<DynamicPropertyObjectValueEntity>.TryCreateInstance().FromModel(x)));
            }
            return(this);
        }
        public static ISchemaTypeBuilder <TDerivedSchemaType> OverrideType <TBaseSchemaType, TDerivedSchemaType>(this ISchemaTypeBuilder <TDerivedSchemaType> builder) where TBaseSchemaType : IGraphType where TDerivedSchemaType : TBaseSchemaType, IGraphType
        {
            AbstractTypeFactory <IGraphType> .OverrideType <TBaseSchemaType, TDerivedSchemaType>();

            return(builder);
        }
        public PaymentPlan[] GetByIds(string[] planIds, string responseGroup = null)
        {
            var retVal = new List <PaymentPlan>();

            using (var repository = _subscriptionRepositoryFactory())
            {
                repository.DisableChangesTracking();

                retVal = repository.GetPaymentPlansByIds(planIds).Select(x => x.ToModel(AbstractTypeFactory <PaymentPlan> .TryCreateInstance())).ToList();
            }
            return(retVal.ToArray());
        }
        public void SavePlans(PaymentPlan[] plans)
        {
            var pkMap          = new PrimaryKeyResolvingMap();
            var changedEntries = new List <GenericChangedEntry <PaymentPlan> >();

            using (var repository = _subscriptionRepositoryFactory())
                using (var changeTracker = GetChangeTracker(repository))
                {
                    var existPlanEntities = repository.GetPaymentPlansByIds(plans.Where(x => !x.IsTransient()).Select(x => x.Id).ToArray());
                    foreach (var paymentPlan in plans)
                    {
                        var sourcePlanEntity = AbstractTypeFactory <PaymentPlanEntity> .TryCreateInstance();

                        if (sourcePlanEntity != null)
                        {
                            sourcePlanEntity = sourcePlanEntity.FromModel(paymentPlan, pkMap) as PaymentPlanEntity;
                            var targetPlanEntity = existPlanEntities.FirstOrDefault(x => x.Id == paymentPlan.Id);
                            if (targetPlanEntity != null)
                            {
                                changeTracker.Attach(targetPlanEntity);
                                changedEntries.Add(new GenericChangedEntry <PaymentPlan>(paymentPlan, targetPlanEntity.ToModel(AbstractTypeFactory <PaymentPlan> .TryCreateInstance()), EntryState.Modified));
                                sourcePlanEntity.Patch(targetPlanEntity);
                            }
                            else
                            {
                                repository.Add(sourcePlanEntity);
                                changedEntries.Add(new GenericChangedEntry <PaymentPlan>(paymentPlan, EntryState.Added));
                            }
                        }
                    }

                    //Raise domain events
                    _eventPublisher.Publish(new PaymentPlanChangingEvent(changedEntries));
                    CommitChanges(repository);
                    pkMap.ResolvePrimaryKeys();
                    _eventPublisher.Publish(new PaymentPlanChangedEvent(changedEntries));
                }
        }
Exemple #12
0
        public virtual Member ToModel(Member member)
        {
            if (member == null)
            {
                throw new ArgumentNullException("member");
            }

            //preserve member type
            var memberType = member.MemberType;

            member.InjectFrom(this);
            member.MemberType = memberType;

            member.Addresses = this.Addresses.OrderBy(x => x.Id).Select(x => x.ToModel(AbstractTypeFactory <Address> .TryCreateInstance())).ToList();
            member.Emails    = this.Emails.OrderBy(x => x.Id).Select(x => x.Address).ToList();
            member.Notes     = this.Notes.OrderBy(x => x.Id).Select(x => x.ToModel(new Note())).ToList();
            member.Phones    = this.Phones.OrderBy(x => x.Id).Select(x => x.Number).ToList();
            member.Groups    = this.Groups.OrderBy(x => x.Id).Select(x => x.Group).ToList();

            return(member);
        }
        public virtual ShipmentPackageEntity FromModel(ShipmentPackage package, PrimaryKeyResolvingMap pkMap)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            pkMap.AddPair(package, this);
            this.InjectFrom(package);

            if (!Items.IsNullOrEmpty())
            {
                Items = new ObservableCollection <ShipmentItemEntity>(package.Items.Select(x => AbstractTypeFactory <ShipmentItemEntity> .TryCreateInstance().FromModel(x, pkMap)));
                foreach (var shipmentItem in Items)
                {
                    shipmentItem.ShipmentPackageId = Id;
                }
            }

            return(this);
        }
Exemple #14
0
        public virtual PaymentEntity FromModel(Payment payment, PrimaryKeyResolvingMap pkMap)
        {
            if (payment == null)
            {
                throw new ArgumentNullException(nameof(payment));
            }

            pkMap.AddPair(payment, this);
            this.InjectFrom(payment);

            if (payment.BillingAddress != null)
            {
                Addresses = new ObservableCollection <AddressEntity>(new[] { AbstractTypeFactory <AddressEntity> .TryCreateInstance().FromModel(payment.BillingAddress) });
            }

            if (payment.TaxDetails != null)
            {
                TaxDetails = new ObservableCollection <TaxDetailEntity>(payment.TaxDetails.Select(x => AbstractTypeFactory <TaxDetailEntity> .TryCreateInstance().FromModel(x)));
            }

            if (payment.Discounts != null)
            {
                Discounts = new ObservableCollection <DiscountEntity>(payment.Discounts.Select(x => AbstractTypeFactory <DiscountEntity> .TryCreateInstance().FromModel(x)));
            }

            return(this);
        }
        public virtual MemberDataEntity FromModel(Member member, PrimaryKeyResolvingMap pkMap)
        {
            if (member == null)
            {
                throw new ArgumentNullException(nameof(member));
            }

            pkMap.AddPair(member, this);

            this.InjectFrom(member);

            if (member.Phones != null)
            {
                Phones = new ObservableCollection <PhoneDataEntity>();
                foreach (var phone in member.Phones)
                {
                    var phoneEntity = AbstractTypeFactory <PhoneDataEntity> .TryCreateInstance();

                    phoneEntity.Number   = phone;
                    phoneEntity.MemberId = member.Id;
                    Phones.Add(phoneEntity);
                }
            }

            if (member.Groups != null)
            {
                Groups = new ObservableCollection <MemberGroupDataEntity>();
                foreach (var group in member.Groups)
                {
                    var groupEntity = AbstractTypeFactory <MemberGroupDataEntity> .TryCreateInstance();

                    groupEntity.Group    = group;
                    groupEntity.MemberId = member.Id;
                    Groups.Add(groupEntity);
                }
            }

            if (member.Emails != null)
            {
                Emails = new ObservableCollection <EmailDataEntity>();
                foreach (var email in member.Emails)
                {
                    var emailEntity = AbstractTypeFactory <EmailDataEntity> .TryCreateInstance();

                    emailEntity.Address  = email;
                    emailEntity.MemberId = member.Id;
                    Emails.Add(emailEntity);
                }
            }

            if (member.Addresses != null)
            {
                Addresses = new ObservableCollection <AddressDataEntity>(member.Addresses.Select(x => AbstractTypeFactory <AddressDataEntity> .TryCreateInstance().FromModel(x)));
                foreach (var address in Addresses)
                {
                    address.MemberId = member.Id;
                }
            }

            if (member.Notes != null)
            {
                Notes = new ObservableCollection <NoteDataEntity>(member.Notes.Select(x => AbstractTypeFactory <NoteDataEntity> .TryCreateInstance().FromModel(x)));
                foreach (var note in Notes)
                {
                    note.MemberId = member.Id;
                }
            }
            return(this);
        }
Exemple #16
0
        public async Task SaveSeoForObjectsAsync(ISeoSupport[] seoSupportObjects)
        {
            if (seoSupportObjects == null)
            {
                throw new ArgumentNullException(nameof(seoSupportObjects));
            }

            var changedEntries = new List <GenericChangedEntry <SeoInfo> >();
            var pkMap          = new PrimaryKeyResolvingMap();

            foreach (var seoObject in seoSupportObjects.Where(x => x.Id != null))
            {
                var objectType = seoObject.SeoObjectType;

                using (var repository = _repositoryFactory())
                {
                    if (seoObject.SeoInfos != null)
                    {
                        // Normalize seoInfo
                        foreach (var seoInfo in seoObject.SeoInfos)
                        {
                            if (seoInfo.ObjectId == null)
                            {
                                seoInfo.ObjectId = seoObject.Id;
                            }

                            if (seoInfo.ObjectType == null)
                            {
                                seoInfo.ObjectType = objectType;
                            }
                        }
                    }

                    if (seoObject.SeoInfos != null)
                    {
                        var target = new List <SeoUrlKeywordEntity>(await repository.GetObjectSeoUrlKeywordsAsync(objectType, seoObject.Id));
                        var source = new List <SeoUrlKeywordEntity>(seoObject.SeoInfos.Select(x => AbstractTypeFactory <SeoUrlKeywordEntity> .TryCreateInstance().FromModel(x, pkMap)));

                        var seoComparer = AnonymousComparer.Create((SeoUrlKeywordEntity x) => x.Id ?? string.Join(":", x.StoreId, x.ObjectId, x.ObjectType, x.Language));
                        source.CompareTo(target, seoComparer, (state, sourceEntity, targetEntity) =>
                        {
                            if (state == EntryState.Added)
                            {
                                repository.Add(sourceEntity);
                            }
                            if (state == EntryState.Deleted)
                            {
                                repository.Remove(sourceEntity);
                            }
                            if (state == EntryState.Modified)
                            {
                                sourceEntity.Patch(targetEntity);
                            }
                        });
                        await repository.UnitOfWork.CommitAsync();

                        pkMap.ResolvePrimaryKeys();
                        SeoInfoCacheRegion.ExpireSeoInfos(source.Concat(target).Distinct().Select(x => x.Id));
                    }
                }
            }
        }
Exemple #17
0
        public async Task SaveChangesAsync(IEnumerable <FulfillmentCenter> fulfillmentCenters)
        {
            if (fulfillmentCenters == null)
            {
                throw new ArgumentNullException(nameof(fulfillmentCenters));
            }

            var pkMap          = new PrimaryKeyResolvingMap();
            var changedEntries = new List <GenericChangedEntry <FulfillmentCenter> >();

            using (var repository = _repositoryFactory())
            {
                var existEntities = await repository.GetFulfillmentCentersAsync(fulfillmentCenters.Where(x => !x.IsTransient()).Select(x => x.Id).ToArray());

                foreach (var changedCenter in fulfillmentCenters)
                {
                    var existEntity    = existEntities.FirstOrDefault(x => x.Id == changedCenter.Id);
                    var modifiedEntity = AbstractTypeFactory <FulfillmentCenterEntity> .TryCreateInstance().FromModel(changedCenter, pkMap);

                    if (existEntity != null)
                    {
                        changedEntries.Add(new GenericChangedEntry <FulfillmentCenter>(changedCenter, existEntity.ToModel(AbstractTypeFactory <FulfillmentCenter> .TryCreateInstance()), EntryState.Modified));
                        modifiedEntity.Patch(existEntity);
                    }
                    else
                    {
                        repository.Add(modifiedEntity);
                        changedEntries.Add(new GenericChangedEntry <FulfillmentCenter>(changedCenter, EntryState.Added));
                    }
                }

                await _eventPublisher.Publish(new FulfillmentCenterChangingEvent(changedEntries));

                await repository.UnitOfWork.CommitAsync();

                pkMap.ResolvePrimaryKeys();
                await _eventPublisher.Publish(new FulfillmentCenterChangedEvent(changedEntries));

                FulfillmentCenterCacheRegion.ExpireRegion();
            }
        }
Exemple #18
0
        public virtual async Task SaveChangesAsync(CustomerSegment[] customerSegments)
        {
            var pkMap          = new PrimaryKeyResolvingMap();
            var changedEntries = new List <GenericChangedEntry <CustomerSegment> >();

            using var customerSegmentsRepository = _customerSegmentRepositoryFactory();

            var ids             = customerSegments.Where(x => !x.IsTransient()).Select(x => x.Id).ToArray();
            var dbExistProducts = await customerSegmentsRepository.GetByIdsAsync(ids);

            foreach (var customerSegment in customerSegments)
            {
                var modifiedEntity = AbstractTypeFactory <CustomerSegmentEntity> .TryCreateInstance().FromModel(customerSegment, pkMap);

                var originalEntity = dbExistProducts.FirstOrDefault(x => x.Id == customerSegment.Id);

                if (originalEntity != null)
                {
                    changedEntries.Add(new GenericChangedEntry <CustomerSegment>(customerSegment, originalEntity.ToModel(AbstractTypeFactory <CustomerSegment> .TryCreateInstance()), EntryState.Modified));
                    modifiedEntity.Patch(originalEntity);
                }
                else
                {
                    customerSegmentsRepository.Add(modifiedEntity);
                    changedEntries.Add(new GenericChangedEntry <CustomerSegment>(customerSegment, EntryState.Added));
                }
            }

            await _eventPublisher.Publish(new CustomerSegmentChangingEvent(changedEntries));

            await customerSegmentsRepository.UnitOfWork.CommitAsync();

            pkMap.ResolvePrimaryKeys();

            ClearCache(customerSegments);

            await _eventPublisher.Publish(new CustomerSegmentChangedEvent(changedEntries));
        }
Exemple #19
0
        public override OperationEntity FromModel(OrderOperation operation, PrimaryKeyResolvingMap pkMap)
        {
            var payment = operation as PaymentIn;

            if (payment == null)
            {
                throw new ArgumentException(@"operation argument must be of type PaymentIn", nameof(operation));
            }

            base.FromModel(payment, pkMap);

            Status = payment.PaymentStatus.ToString();

            if (payment.PaymentMethod != null)
            {
                GatewayCode = payment.PaymentMethod != null ? payment.PaymentMethod.Code : payment.GatewayCode;
            }

            if (payment.BillingAddress != null)
            {
                Addresses = new ObservableCollection <AddressEntity>(new[] { AbstractTypeFactory <AddressEntity> .TryCreateInstance().FromModel(payment.BillingAddress) });
            }

            if (payment.TaxDetails != null)
            {
                TaxDetails = new ObservableCollection <TaxDetailEntity>(payment.TaxDetails.Select(x => AbstractTypeFactory <TaxDetailEntity> .TryCreateInstance().FromModel(x)));
            }

            if (payment.Discounts != null)
            {
                Discounts = new ObservableCollection <DiscountEntity>(payment.Discounts.Select(x => AbstractTypeFactory <DiscountEntity> .TryCreateInstance().FromModel(x)));
            }

            if (payment.Transactions != null)
            {
                Transactions = new ObservableCollection <PaymentGatewayTransactionEntity>(payment.Transactions.Select(x => AbstractTypeFactory <PaymentGatewayTransactionEntity> .TryCreateInstance().FromModel(x, pkMap)));
            }

            return(this);
        }
Exemple #20
0
        public virtual LineItemEntity FromModel(LineItem lineItem, PrimaryKeyResolvingMap pkMap)
        {
            if (lineItem == null)
            {
                throw new ArgumentNullException(nameof(lineItem));
            }

            ModelLineItem = lineItem;
            pkMap.AddPair(lineItem, this);

            Id           = lineItem.Id;
            CreatedDate  = lineItem.CreatedDate;
            CreatedBy    = lineItem.CreatedBy;
            ModifiedDate = lineItem.ModifiedDate;
            ModifiedBy   = lineItem.ModifiedBy;

            PriceId                 = lineItem.PriceId;
            CatalogId               = lineItem.CatalogId;
            CategoryId              = lineItem.CategoryId;
            Currency                = lineItem.Currency;
            ProductId               = lineItem.ProductId;
            Sku                     = lineItem.Sku;
            ProductType             = lineItem.ProductType;
            Name                    = lineItem.Name;
            ImageUrl                = lineItem.ImageUrl;
            ShippingMethodCode      = lineItem.ShippingMethodCode;
            FulfillmentLocationCode = lineItem.FulfillmentLocationCode;

            Price                 = lineItem.Price;
            PriceWithTax          = lineItem.PriceWithTax;
            DiscountAmount        = lineItem.DiscountAmount;
            DiscountAmountWithTax = lineItem.DiscountAmountWithTax;
            Quantity              = lineItem.Quantity;
            TaxTotal              = lineItem.TaxTotal;
            TaxPercentRate        = lineItem.TaxPercentRate;
            Weight                = lineItem.Weight;
            Height                = lineItem.Height;
            Width                 = lineItem.Width;
            MeasureUnit           = lineItem.MeasureUnit;
            WeightUnit            = lineItem.WeightUnit;
            Length                = lineItem.Length;
            TaxType               = lineItem.TaxType;
            IsCancelled           = lineItem.IsCancelled;
            CancelledDate         = lineItem.CancelledDate;
            CancelReason          = lineItem.CancelReason;
            Comment               = lineItem.Comment;

            IsGift = lineItem.IsGift ?? false;

            if (lineItem.Discounts != null)
            {
                Discounts = new ObservableCollection <DiscountEntity>();
                Discounts.AddRange(lineItem.Discounts.Select(x => AbstractTypeFactory <DiscountEntity> .TryCreateInstance().FromModel(x)));
            }

            if (lineItem.TaxDetails != null)
            {
                TaxDetails = new ObservableCollection <TaxDetailEntity>();
                TaxDetails.AddRange(lineItem.TaxDetails.Select(x => AbstractTypeFactory <TaxDetailEntity> .TryCreateInstance().FromModel(x)));
            }

            return(this);
        }
        public virtual CatalogProduct ToModel(CatalogProduct product, bool convertChildrens = true, bool convertAssociations = true)
        {
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }


            product.Id           = this.Id;
            product.CreatedDate  = this.CreatedDate;
            product.CreatedBy    = this.CreatedBy;
            product.ModifiedDate = this.ModifiedDate;
            product.ModifiedBy   = this.ModifiedBy;

            product.CatalogId              = this.CatalogId;
            product.CategoryId             = this.CategoryId;
            product.Code                   = this.Code;
            product.DownloadExpiration     = this.DownloadExpiration;
            product.DownloadType           = this.DownloadType;
            product.EnableReview           = this.EnableReview;
            product.EndDate                = this.EndDate;
            product.Gtin                   = this.Gtin;
            product.HasUserAgreement       = this.HasUserAgreement;
            product.Height                 = this.Height;
            product.IsActive               = this.IsActive;
            product.IsBuyable              = this.IsBuyable;
            product.Length                 = this.Length;
            product.MainProductId          = this.ParentId;
            product.ManufacturerPartNumber = this.ManufacturerPartNumber;
            product.MaxNumberOfDownload    = this.MaxNumberOfDownload;
            product.MaxQuantity            = (int)this.MaxQuantity;
            product.MeasureUnit            = this.MeasureUnit;
            product.MinQuantity            = (int)this.MinQuantity;
            product.Name                   = this.Name;
            product.PackageType            = this.PackageType;
            product.Priority               = this.Priority;
            product.ProductType            = this.ProductType;
            product.ShippingType           = this.ShippingType;
            product.StartDate              = this.StartDate;
            product.TaxType                = this.TaxType;
            product.TrackInventory         = this.TrackInventory;
            product.Vendor                 = this.Vendor;
            product.Weight                 = this.Weight;
            product.WeightUnit             = this.WeightUnit;
            product.Width                  = this.Width;

            //Links
            product.Links = this.CategoryLinks.Select(x => x.ToModel(AbstractTypeFactory <CategoryLink> .TryCreateInstance())).ToList();
            //Images
            product.Images = this.Images.OrderBy(x => x.SortOrder).Select(x => x.ToModel(AbstractTypeFactory <Image> .TryCreateInstance())).ToList();
            //Assets
            product.Assets = this.Assets.OrderBy(x => x.CreatedDate).Select(x => x.ToModel(AbstractTypeFactory <Asset> .TryCreateInstance())).ToList();
            // EditorialReviews
            product.Reviews = this.EditorialReviews.Select(x => x.ToModel(AbstractTypeFactory <EditorialReview> .TryCreateInstance())).ToList();

            if (convertAssociations)
            {
                // Associations
                product.Associations = this.Associations.Select(x => x.ToModel(AbstractTypeFactory <ProductAssociation> .TryCreateInstance())).OrderBy(x => x.Priority).ToList();
            }

            //Self item property values
            product.PropertyValues = this.ItemPropertyValues.OrderBy(x => x.Name).Select(x => x.ToModel(AbstractTypeFactory <PropertyValue> .TryCreateInstance())).ToList();

            if (this.Parent != null)
            {
                product.MainProduct = this.Parent.ToModel(AbstractTypeFactory <CatalogProduct> .TryCreateInstance(), false, convertAssociations);
            }

            if (convertChildrens)
            {
                // Variations
                product.Variations = new List <CatalogProduct>();
                foreach (var variation in this.Childrens)
                {
                    var productVariation = variation.ToModel(AbstractTypeFactory <CatalogProduct> .TryCreateInstance());
                    productVariation.MainProduct   = product;
                    productVariation.MainProductId = product.Id;
                    product.Variations.Add(productVariation);
                }
            }
            return(product);
        }
        public virtual async Task SaveSubscriptionsAsync(Subscription[] subscriptions)
        {
            var pkMap          = new PrimaryKeyResolvingMap();
            var changedEntries = new List <GenericChangedEntry <Subscription> >();

            using (var repository = _subscriptionRepositoryFactory())
            {
                var existEntities = await repository.GetSubscriptionsByIdsAsync(subscriptions.Where(x => !x.IsTransient()).Select(x => x.Id).ToArray());

                foreach (var subscription in subscriptions)
                {
                    //Generate numbers for new subscriptions
                    if (string.IsNullOrEmpty(subscription.Number))
                    {
                        var store = await _storeService.GetByIdAsync(subscription.StoreId, StoreResponseGroup.StoreInfo.ToString());

                        var numberTemplate = store.Settings.GetSettingValue(ModuleConstants.Settings.General.NewNumberTemplate.Name, ModuleConstants.Settings.General.NewNumberTemplate.DefaultValue.ToString());
                        subscription.Number = _uniqueNumberGenerator.GenerateNumber(numberTemplate);
                    }
                    //Save subscription order prototype with same as subscription Number
                    if (subscription.CustomerOrderPrototype != null)
                    {
                        subscription.CustomerOrderPrototype.Number      = subscription.Number;
                        subscription.CustomerOrderPrototype.IsPrototype = true;
                        await _customerOrderService.SaveChangesAsync(new[] { subscription.CustomerOrderPrototype });
                    }
                    var originalEntity = existEntities.FirstOrDefault(x => x.Id == subscription.Id);

                    var modifiedEntity = AbstractTypeFactory <SubscriptionEntity> .TryCreateInstance().FromModel(subscription, pkMap);

                    if (originalEntity != null)
                    {
                        changedEntries.Add(new GenericChangedEntry <Subscription>(subscription, originalEntity.ToModel(AbstractTypeFactory <Subscription> .TryCreateInstance()), EntryState.Modified));
                        modifiedEntity.Patch(originalEntity);
                        //force the subscription.ModifiedDate update, because the subscription object may not have any changes in its properties
                        originalEntity.ModifiedDate = DateTime.UtcNow;
                    }
                    else
                    {
                        repository.Add(modifiedEntity);
                        changedEntries.Add(new GenericChangedEntry <Subscription>(subscription, EntryState.Added));
                    }
                }

                //Raise domain events
                await _eventPublisher.Publish(new SubscriptionChangingEvent(changedEntries));

                await repository.UnitOfWork.CommitAsync();

                pkMap.ResolvePrimaryKeys();

                ClearCacheFor(subscriptions);

                await _eventPublisher.Publish(new SubscriptionChangedEvent(changedEntries));
            }
        }
        public virtual NotificationEntity FromModel(Notification notification, PrimaryKeyResolvingMap pkMap)
        {
            if (notification == null)
            {
                throw new ArgumentNullException(nameof(notification));
            }

            pkMap.AddPair(notification, this);

            Id           = notification.Id;
            TenantId     = notification.TenantIdentity?.Id;
            TenantType   = notification.TenantIdentity?.Type;
            Type         = notification.Type;
            IsActive     = notification.IsActive;
            CreatedBy    = notification.CreatedBy;
            CreatedDate  = notification.CreatedDate;
            ModifiedBy   = notification.ModifiedBy;
            ModifiedDate = notification.ModifiedDate;
            Kind         = notification.Kind;

            if (notification.Templates != null && notification.Templates.Any())
            {
                Templates = new ObservableCollection <NotificationTemplateEntity>(notification.Templates
                                                                                  .Select(x => AbstractTypeFactory <NotificationTemplateEntity> .TryCreateInstance($"{Kind}TemplateEntity").FromModel(x, pkMap)));
            }

            return(this);
        }
Exemple #24
0
        protected virtual void SaveChanges(Catalog[] catalogs)
        {
            var pkMap          = new PrimaryKeyResolvingMap();
            var changedEntries = new List <GenericChangedEntry <Catalog> >();

            using (var repository = _repositoryFactory())
                using (var changeTracker = GetChangeTracker(repository))
                {
                    ValidateCatalogProperties(catalogs);
                    var dbExistEntities = repository.GetCatalogsByIds(catalogs.Where(x => !x.IsTransient()).Select(x => x.Id).ToArray());
                    foreach (var catalog in catalogs)
                    {
                        var originalEntity = dbExistEntities.FirstOrDefault(x => x.Id == catalog.Id);
                        var modifiedEntity = AbstractTypeFactory <CatalogEntity> .TryCreateInstance().FromModel(catalog, pkMap);

                        if (originalEntity != null)
                        {
                            changeTracker.Attach(originalEntity);

                            changedEntries.Add(new GenericChangedEntry <Catalog>(catalog, originalEntity.ToModel(AbstractTypeFactory <Catalog> .TryCreateInstance()), EntryState.Modified));

                            modifiedEntity.Patch(originalEntity);
                        }
                        else
                        {
                            repository.Add(modifiedEntity);

                            changedEntries.Add(new GenericChangedEntry <Catalog>(catalog, EntryState.Added));
                        }
                    }

                    _eventPublisher.Publish(new CatalogChangingEvent(changedEntries));

                    CommitChanges(repository);
                    pkMap.ResolvePrimaryKeys();
                    //Reset cached catalogs and catalogs
                    ResetCache();

                    _eventPublisher.Publish(new CatalogChangedEvent(changedEntries));
                }
        }
        public virtual async Task <PricelistAssignment[]> GetAllPricelistAssignments()
        {
            using (var repository = _repositoryFactory())
            {
                repository.DisableChangesTracking();

                return((await repository.PricelistAssignments.Include(x => x.Pricelist).AsNoTracking().ToArrayAsync()).Select(x => x.ToModel(AbstractTypeFactory <PricelistAssignment> .TryCreateInstance())).ToArray());
            }
        }
        public async Task LoadAssociationsAsync(IHasAssociations[] owners)
        {
            using (var repository = _repositoryFactory())
            {
                //Optimize performance and CPU usage
                repository.DisableChangesTracking();

                var productEntities = await repository.GetItemByIdsAsync(owners.Select(x => x.Id).ToArray(), ItemResponseGroup.ItemAssociations.ToString());

                foreach (var productEntity in productEntities)
                {
                    var owner = owners.FirstOrDefault(x => x.Id == productEntity.Id);
                    if (owner != null)
                    {
                        if (owner.Associations == null)
                        {
                            owner.Associations = new List <ProductAssociation>();
                        }

                        owner.Associations.Clear();
                        owner.Associations.AddRange(productEntity.Associations.Select(x => x.ToModel(AbstractTypeFactory <ProductAssociation> .TryCreateInstance())));
                    }
                }
            }
        }
        public virtual async Task <PricelistAssignment[]> GetPricelistAssignmentsByIdAsync(string[] ids)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(GetPricelistAssignmentsByIdAsync), string.Join("-", ids));

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async cacheEntry =>
            {
                PricelistAssignment[] result = null;
                if (ids != null)
                {
                    using (var repository = _repositoryFactory())
                    {
                        cacheEntry.AddExpirationToken(PricelistAssignmentsCacheRegion.CreateChangeToken(ids));
                        result = (await repository.GetPricelistAssignmentsByIdAsync(ids)).Select(x => x.ToModel(AbstractTypeFactory <PricelistAssignment> .TryCreateInstance())).ToArray();
                    }
                }
                return result;
            }));
        }
 public DynamicPropertySearchCriteriaBuilder()
 {
     _searchCriteria = AbstractTypeFactory <DynamicPropertySearchCriteria> .TryCreateInstance();
 }
        public virtual DynamicContentItemEntity FromModel(DynamicContentItem item, PrimaryKeyResolvingMap pkMap)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            pkMap.AddPair(item, this);

            Id           = item.Id;
            CreatedBy    = item.CreatedBy;
            CreatedDate  = item.CreatedDate;
            ModifiedBy   = item.ModifiedBy;
            ModifiedDate = item.ModifiedDate;

            Name          = item.Name;
            FolderId      = item.FolderId;
            ImageUrl      = item.ImageUrl;
            ContentTypeId = item.ContentType;
            Description   = item.Description;

            if (item.DynamicProperties != null)
            {
                ContentTypeId = item.GetDynamicPropertyValue <string>("Content type", null);
                DynamicPropertyObjectValues = new ObservableCollection <DynamicContentItemDynamicPropertyObjectValueEntity>(item.DynamicProperties.SelectMany(p => p.Values
                                                                                                                                                              .Select(v => AbstractTypeFactory <DynamicContentItemDynamicPropertyObjectValueEntity> .TryCreateInstance().FromModel(v, item, p))).OfType <DynamicContentItemDynamicPropertyObjectValueEntity>());
            }

            return(this);
        }
Exemple #30
0
        private static void RegisterConditionRewards()
        {
            AbstractTypeFactory <IConditionTree> .RegisterType <PromotionConditionAndRewardTree>();

            AbstractTypeFactory <IConditionTree> .RegisterType <BlockConditionAndOr>();

            AbstractTypeFactory <IConditionTree> .RegisterType <BlockCustomerCondition>();

            AbstractTypeFactory <IConditionTree> .RegisterType <ConditionIsRegisteredUser>();

            AbstractTypeFactory <IConditionTree> .RegisterType <ConditionIsEveryone>();

            AbstractTypeFactory <IConditionTree> .RegisterType <ConditionIsFirstTimeBuyer>();

            AbstractTypeFactory <IConditionTree> .RegisterType <UserGroupsContainsCondition>();

            AbstractTypeFactory <IConditionTree> .RegisterType <BlockCatalogCondition>();

            AbstractTypeFactory <IConditionTree> .RegisterType <ConditionAtNumItemsInCart>();

            AbstractTypeFactory <IConditionTree> .RegisterType <ConditionAtNumItemsInCategoryAreInCart>();

            AbstractTypeFactory <IConditionTree> .RegisterType <ConditionAtNumItemsOfEntryAreInCart>();

            AbstractTypeFactory <IConditionTree> .RegisterType <ConditionCartSubtotalLeast>();

            AbstractTypeFactory <IConditionTree> .RegisterType <BlockCartCondition>();

            AbstractTypeFactory <IConditionTree> .RegisterType <ConditionCategoryIs>();

            AbstractTypeFactory <IConditionTree> .RegisterType <ConditionCodeContains>();

            AbstractTypeFactory <IConditionTree> .RegisterType <ConditionCurrencyIs>();

            AbstractTypeFactory <IConditionTree> .RegisterType <ConditionEntryIs>();

            AbstractTypeFactory <IConditionTree> .RegisterType <ConditionInStockQuantity>();

            AbstractTypeFactory <IConditionTree> .RegisterType <BlockReward>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardCartGetOfAbsSubtotal>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardCartGetOfRelSubtotal>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardItemGetFreeNumItemOfProduct>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardItemGetOfAbs>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardItemGetOfAbsForNum>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardItemGetOfRel>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardItemGetOfRelForNum>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardItemGiftNumItem>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardShippingGetOfAbsShippingMethod>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardShippingGetOfRelShippingMethod>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardPaymentGetOfAbs>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardPaymentGetOfRel>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardItemForEveryNumInGetOfRel>();

            AbstractTypeFactory <IConditionTree> .RegisterType <RewardItemForEveryNumOtherItemInGetOfRel>();

            AbstractTypeFactory <PromotionReward> .RegisterType <GiftReward>();

            AbstractTypeFactory <PromotionReward> .RegisterType <CartSubtotalReward>();

            AbstractTypeFactory <PromotionReward> .RegisterType <CatalogItemAmountReward>();

            AbstractTypeFactory <PromotionReward> .RegisterType <PaymentReward>();

            AbstractTypeFactory <PromotionReward> .RegisterType <ShipmentReward>();

            AbstractTypeFactory <PromotionReward> .RegisterType <SpecialOfferReward>();
        }