public IActionResult UpdateSpecificationAttribute( [ModelBinder(typeof(JsonModelBinder <SpecificationAttributeDto>))] Delta <SpecificationAttributeDto> specificationAttributeDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } // We do not need to validate the product attribute id, because this will happen in the model binder using the dto validator. var specificationAttributeId = specificationAttributeDelta.Dto.Id; var specificationAttribute = _specificationAttributeService.GetSpecificationAttributeById(specificationAttributeId); if (specificationAttribute == null) { return(Error(HttpStatusCode.NotFound, "specification attribute", "not found")); } specificationAttributeDelta.Merge(specificationAttribute); _specificationAttributeService.UpdateSpecificationAttribute(specificationAttribute); CustomerActivityService.InsertActivity("EditSpecAttribute", LocalizationService.GetResource("ActivityLog.EditSpecAttribute"), specificationAttribute); // Preparing the result dto of the new product attribute var specificationAttributeDto = _dtoHelper.PrepareSpecificationAttributeDto(specificationAttribute); var specificatoinAttributesRootObjectDto = new SpecificationAttributesRootObjectDto(); specificatoinAttributesRootObjectDto.SpecificationAttributes.Add(specificationAttributeDto); var json = JsonFieldsSerializer.Serialize(specificatoinAttributesRootObjectDto, string.Empty); return(new RawJsonActionResult(json)); }
public IActionResult GetCustomers(CustomersParametersModel parameters) { if (parameters.Limit < Constants.Configurations.MinLimit || parameters.Limit > Constants.Configurations.MaxLimit) { return(Error(HttpStatusCode.BadRequest, "limit", "Invalid limit parameter")); } if (parameters.Page < Constants.Configurations.DefaultPageValue) { return(Error(HttpStatusCode.BadRequest, "page", "Invalid request parameters")); } var allCustomers = _customerApiService.GetCustomersDtos(parameters.CreatedAtMin, parameters.CreatedAtMax, parameters.Limit, parameters.Page, parameters.SinceId); var customersRootObject = new CustomersRootObject { Customers = allCustomers }; var json = JsonFieldsSerializer.Serialize(customersRootObject, parameters.Fields); return(new RawJsonActionResult(json)); }
public IActionResult GetVendorById(int id, string fields = "") { if (id <= 0) { return(Error(HttpStatusCode.BadRequest, "id", "invalid id")); } var vendor = _vendorApiService.GetVendorById(id); if (vendor == null) { return(Error(HttpStatusCode.NotFound, "Vendor", "not found")); } var vendorDto = _dtoHelper.PrepareVendorDTO(vendor); var vendorsRootObject = new VendorsRootObjectDto(); vendorsRootObject.Vendors.Add(vendorDto); var json = JsonFieldsSerializer.Serialize(vendorsRootObject, fields); return(new RawJsonActionResult(json)); }
public void WhenValidFieldsParameterPassed_ShouldSerializeTheseFieldsJson_ComplexDummyObject() { var complexDummySerializableObject = new SerializableDummyObjectWithComplexTypes(); complexDummySerializableObject.Items.Add(new DummyObjectWithComplexTypes { StringProperty = "string value", DummyObjectWithSimpleTypes = new DummyObjectWithSimpleTypes { FirstProperty = "first property value", SecondProperty = "second property value" }, ListOfDummyObjectWithSimpleTypes = new List <DummyObjectWithSimpleTypes> { new DummyObjectWithSimpleTypes() { FirstProperty = "first property of list value", SecondProperty = "second property of list value" } } }); // Arange IJsonFieldsSerializer cut = new JsonFieldsSerializer(); // Act string json = cut.Serialize(complexDummySerializableObject, "string_property, dummy_object_with_simple_types, list_of_dummy_object_with_simple_types"); // Assert SerializableDummyObjectWithComplexTypes complexDummySerializableObjectFromJson = JsonConvert.DeserializeObject <SerializableDummyObjectWithComplexTypes>(json); Assert.AreEqual(1, complexDummySerializableObjectFromJson.Items.Count); Assert.AreEqual(1, complexDummySerializableObjectFromJson.Items[0].ListOfDummyObjectWithSimpleTypes.Count); Assert.AreEqual("string value", complexDummySerializableObjectFromJson.Items[0].StringProperty); }
public async Task <IActionResult> UpdateRole([ModelBinder(typeof(JsonModelBinder <RoleDto>))] Delta <RoleDto> roleDelta) { if (!ModelState.IsValid) { return(await Error()); } var currentRole = _roleApiService.GetRoleById(roleDelta.Dto.Id); if (currentRole == null) { return(await Error(HttpStatusCode.NotFound, "role", "not found")); } roleDelta.Merge(currentRole); //permission if (roleDelta.Dto.PermissionIds.Count > 0) { await AddValidPermissions(roleDelta, currentRole); } await UserService.UpdateRoleAsync(currentRole); await UserActivityService.InsertActivityAsync("EditRole", $"Edited a role (ID = {currentRole.Id})", currentRole); var roleDto = currentRole.ToDto(); var rootObj = new RolesRootObject(); rootObj.Roles.Add(roleDto); var json = JsonFieldsSerializer.Serialize(rootObj, string.Empty); return(new RawJsonActionResult(json)); }
public IActionResult UpdateProductAttribute( [ModelBinder(typeof(JsonModelBinder <ProductAttributeDto>))] Delta <ProductAttributeDto> productAttributeDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } var productAttribute = _productAttributesApiService.GetById(productAttributeDelta.Dto.Id); if (productAttribute == null) { return(Error(HttpStatusCode.NotFound, "product attribute", "not found")); } productAttributeDelta.Merge(productAttribute); _productAttributeService.UpdateProductAttribute(productAttribute); CustomerActivityService.InsertActivity("EditProductAttribute", LocalizationService.GetResource("ActivityLog.EditProductAttribute"), productAttribute); // Preparing the result dto of the new product attribute var productAttributeDto = _dtoHelper.PrepareProductAttributeDTO(productAttribute); var productAttributesRootObjectDto = new ProductAttributesRootObjectDto(); productAttributesRootObjectDto.ProductAttributes.Add(productAttributeDto); var json = JsonFieldsSerializer.Serialize(productAttributesRootObjectDto, string.Empty); return(new RawJsonActionResult(json)); }
public async Task <IActionResult> GetDeviceById(int id, string fields = "") { if (id <= 0) { return(await Error(HttpStatusCode.BadRequest, "id", "invalid id")); } var device = _deviceApiService.GetDeviceById(id); if (device == null) { return(await Error(HttpStatusCode.NotFound, "device", "not found")); } var deviceDto = _dtoHelper.PrepareDeviceDto(device); var devicesRootObject = new DevicesRootObject(); devicesRootObject.Devices.Add(deviceDto); var json = JsonFieldsSerializer.Serialize(devicesRootObject, fields); return(new RawJsonActionResult(json)); }
public IActionResult GetCategoryById(int id, string fields = "") { if (id <= 0) { return(Error(HttpStatusCode.BadRequest, "id", "invalid id")); } var category = _categoryApiService.GetCategoryById(id); if (category == null) { return(Error(HttpStatusCode.NotFound, "category", "category not found")); } var categoryDto = _dtoHelper.PrepareCategoryDTO(category); var categoriesRootObject = new CategoriesRootObject(); categoriesRootObject.Categories.Add(categoryDto); var json = JsonFieldsSerializer.Serialize(categoriesRootObject, fields); return(new RawJsonActionResult(json)); }
public IActionResult CreateManufacturer([ModelBinder(typeof(JsonModelBinder <ManufacturerDto>))] Delta <ManufacturerDto> manufacturerDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } // Inserting the new category var manufacturer = _factory.Initialize(); manufacturerDelta.Merge(manufacturer); _manufacturerService.InsertManufacturer(manufacturer); // Preparing the result dto of the new category var newManufacturerDto = _dtoHelper.PrepareManufacturerDTO(manufacturer); var manufacturersRootObject = new ManufacturersRootObject(); manufacturersRootObject.Manufacturers.Add(newManufacturerDto); var json = JsonFieldsSerializer.Serialize(manufacturersRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public async Task <IActionResult> GetUsers(UsersParametersModel parameters) { if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit) { return(await Error(HttpStatusCode.BadRequest, "limit", "Invalid limit parameter")); } if (parameters.Page < Configurations.DefaultPageValue) { return(await Error(HttpStatusCode.BadRequest, "page", "Invalid request parameters")); } var users = _userApiService.GetUserDtos(parameters.CreatedAtMin, parameters.CreatedAtMax, parameters.Limit, parameters.Page, parameters.SinceId, parameters.RoleIds, parameters.StoreIds); var usersRootObject = new UsersRootObject { Users = users }; var json = JsonFieldsSerializer.Serialize(usersRootObject, parameters.Fields); return(new RawJsonActionResult(json)); }
public IActionResult UpdateProductRelations([ModelBinder(typeof(JsonModelBinder <ProductRelationsDto>))] Delta <ProductRelationsDto> productDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } CustomerActivityService.InsertActivity("APIService", "Starting Product Update", null); var product = _productApiService.GetProductById(productDelta.Dto.Id); if (product == null) { return(Error(HttpStatusCode.NotFound, "product", "not found")); } productDelta.Merge(product); UpdateRelatedProducts(product, productDelta.Dto.RelatedProductIds); UpdateCrossProducts(product, productDelta.Dto.CrossProductIds); //UpdateAssociatedProducts(product, productDelta.Dto.AssociatedProductIds); CustomerActivityService.InsertActivity("APIService", LocalizationService.GetResource("ActivityLog.UpdateProduct"), product); // Preparing the result dto of the new product var productDto = _dtoHelper.PrepareProductDTO(product); var productsRootObject = new ProductsRootObjectDto(); productsRootObject.Products.Add(productDto); var json = JsonFieldsSerializer.Serialize(productsRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public async Task <IActionResult> GetOrderById(int id, string fields = "") { if (id <= 0) { return(Error(HttpStatusCode.BadRequest, "id", "invalid id")); } var topic = await _topicService.GetTopicByIdAsync(id); if (topic == null) { return(Error(HttpStatusCode.NotFound, "topic", "not found")); } var topicsRootObject = new TopicsRootObject(); var topicDto = _dtoHelper.PrepareTopicDTO(topic); topicsRootObject.Topics.Add(topicDto); var json = JsonFieldsSerializer.Serialize(topicsRootObject, fields); return(new RawJsonActionResult(json)); }
public async Task <IActionResult> GetProductSpecificationAttributeById(int id, string fields = "") { if (id <= 0) { return(Error(HttpStatusCode.BadRequest, "id", "invalid id")); } var productSpecificationAttribute = await _specificationAttributeService.GetProductSpecificationAttributeByIdAsync(id); if (productSpecificationAttribute == null) { return(Error(HttpStatusCode.NotFound, "product specification attribute", "not found")); } var productSpecificationAttributeDto = _dtoHelper.PrepareProductSpecificationAttributeDto(productSpecificationAttribute); var productSpecificationAttributesRootObject = new ProductSpecificationAttributesRootObjectDto(); productSpecificationAttributesRootObject.ProductSpecificationAttributes.Add(productSpecificationAttributeDto); var json = JsonFieldsSerializer.Serialize(productSpecificationAttributesRootObject, fields); return(new RawJsonActionResult(json)); }
public IActionResult GetSpecificationAttributeById(int id, string fields = "") { if (id <= 0) { return(Error(HttpStatusCode.BadRequest, "id", "invalid id")); } var specificationAttribute = _specificationAttributeService.GetSpecificationAttributeById(id); if (specificationAttribute == null) { return(Error(HttpStatusCode.NotFound, "specification attribute", "not found")); } var specificationAttributeDto = _dtoHelper.PrepareSpecificationAttributeDto(specificationAttribute); var specificationAttributesRootObject = new SpecificationAttributesRootObjectDto(); specificationAttributesRootObject.SpecificationAttributes.Add(specificationAttributeDto); var json = JsonFieldsSerializer.Serialize(specificationAttributesRootObject, fields); return(new RawJsonActionResult(json)); }
public IActionResult GetOrderById(int id, string fields = "") { if (id <= 0) { return(Error(HttpStatusCode.BadRequest, "id", "invalid id")); } var order = _orderApiService.GetOrderById(id); if (order == null) { return(Error(HttpStatusCode.NotFound, "order", "not found")); } var ordersRootObject = new OrdersRootObject(); var orderDto = _dtoHelper.PrepareOrderDTO(order); ordersRootObject.Orders.Add(orderDto); var json = JsonFieldsSerializer.Serialize(ordersRootObject, fields); return(new RawJsonActionResult(json)); }
public IActionResult GetProductById(int id, string fields = "") { if (id <= 0) { return(Error(HttpStatusCode.BadRequest, "id", "invalid id")); } var product = _productApiService.GetProductById(id); if (product == null) { return(Error(HttpStatusCode.NotFound, "product", "not found")); } var productDto = _dtoHelper.PrepareProductDTO(product); var productsRootObject = new ProductsRootObjectDto(); productsRootObject.Products.Add(productDto); var json = JsonFieldsSerializer.Serialize(productsRootObject, fields); return(new RawJsonActionResult(json)); }
public async Task <IActionResult> GetProfileById(int id, string fields = "") { if (id <= 0) { return(await Error(HttpStatusCode.BadRequest, "id", "invalid profile id")); } var profileDto = await _mediator.Send(new GetProfileById.Query { Id = id, Fields = fields }); if (profileDto == null) { return(await Error(HttpStatusCode.NotFound, "profile", "not found")); } var rootObject = new ProfilesRootObject(); rootObject.Profiles.Add(profileDto); var json = JsonFieldsSerializer.Serialize(rootObject, fields); return(new RawJsonActionResult(json)); }
public async Task <IActionResult> GetManufacturerById(int id, string fields = "") { if (id <= 0) { return(Error(HttpStatusCode.BadRequest, "id", "invalid id")); } var manufacturer = _manufacturerApiService.GetManufacturerById(id); if (manufacturer == null) { return(Error(HttpStatusCode.NotFound, "manufacturer", "manufacturer not found")); } var manufacturerDto = await _dtoHelper.PrepareManufacturerDtoAsync(manufacturer); var manufacturersRootObject = new ManufacturersRootObject(); manufacturersRootObject.Manufacturers.Add(manufacturerDto); var json = JsonFieldsSerializer.Serialize(manufacturersRootObject, fields); return(new RawJsonActionResult(json)); }
public IActionResult UpdateShoppingCartItem( [ModelBinder(typeof(JsonModelBinder <ShoppingCartItemDto>))] Delta <ShoppingCartItemDto> shoppingCartItemDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } // We kno that the id will be valid integer because the validation for this happens in the validator which is executed by the model binder. var shoppingCartItemForUpdate = _shoppingCartItemApiService.GetShoppingCartItem(shoppingCartItemDelta.Dto.Id); if (shoppingCartItemForUpdate == null) { return(Error(HttpStatusCode.NotFound, "shopping_cart_item", "not found")); } shoppingCartItemDelta.Merge(shoppingCartItemForUpdate); if (!_productService.GetProductById(shoppingCartItemForUpdate.ProductId).IsRental) { shoppingCartItemForUpdate.RentalStartDateUtc = null; shoppingCartItemForUpdate.RentalEndDateUtc = null; } if (shoppingCartItemDelta.Dto.Attributes != null) { shoppingCartItemForUpdate.AttributesXml = _productAttributeConverter.ConvertToXml(shoppingCartItemDelta.Dto.Attributes, shoppingCartItemForUpdate.ProductId); } var customer = CustomerService.GetCustomerById(shoppingCartItemForUpdate.CustomerId); // The update time is set in the service. var warnings = _shoppingCartService.UpdateShoppingCartItem(customer, shoppingCartItemForUpdate.Id, shoppingCartItemForUpdate.AttributesXml, shoppingCartItemForUpdate.CustomerEnteredPrice, shoppingCartItemForUpdate.RentalStartDateUtc, shoppingCartItemForUpdate.RentalEndDateUtc, shoppingCartItemForUpdate.Quantity); if (warnings.Count > 0) { foreach (var warning in warnings) { ModelState.AddModelError("shopping cart item", warning); } return(Error(HttpStatusCode.BadRequest)); } shoppingCartItemForUpdate = _shoppingCartItemApiService.GetShoppingCartItem(shoppingCartItemForUpdate.Id); // Preparing the result dto of the new product category mapping var newShoppingCartItemDto = _dtoHelper.PrepareShoppingCartItemDTO(shoppingCartItemForUpdate); var shoppingCartsRootObject = new ShoppingCartItemsRootObject(); shoppingCartsRootObject.ShoppingCartItems.Add(newShoppingCartItemDto); var json = JsonFieldsSerializer.Serialize(shoppingCartsRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public IActionResult UpdateCustomer([ModelBinder(typeof(JsonModelBinder <CustomerDto>))] Delta <CustomerDto> customerDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } // Updateting the customer var currentCustomer = _customerApiService.GetCustomerEntityById(customerDelta.Dto.Id); if (currentCustomer == null) { return(Error(HttpStatusCode.NotFound, "customer", "not found")); } customerDelta.Merge(currentCustomer); if (customerDelta.Dto.RoleIds.Count > 0) { // Remove all roles while (currentCustomer.CustomerRoles.Count > 0) { currentCustomer.CustomerRoles.Remove(currentCustomer.CustomerRoles.First()); } AddValidRoles(customerDelta, currentCustomer); } if (customerDelta.Dto.Addresses.Count > 0) { var currentCustomerAddresses = currentCustomer.Addresses.ToDictionary(address => address.Id, address => address); foreach (var passedAddress in customerDelta.Dto.Addresses) { var addressEntity = passedAddress.ToEntity(); if (currentCustomerAddresses.ContainsKey(passedAddress.Id)) { _mappingHelper.Merge(passedAddress, currentCustomerAddresses[passedAddress.Id]); } else { currentCustomer.Addresses.Add(addressEntity); } } } CustomerService.UpdateCustomer(currentCustomer); InsertFirstAndLastNameGenericAttributes(customerDelta.Dto.FirstName, customerDelta.Dto.LastName, currentCustomer); if (!string.IsNullOrEmpty(customerDelta.Dto.LanguageId) && int.TryParse(customerDelta.Dto.LanguageId, out var languageId) && _languageService.GetLanguageById(languageId) != null) { _genericAttributeService.SaveAttribute(currentCustomer, NopCustomerDefaults.LanguageIdAttribute, languageId); } //password if (!string.IsNullOrWhiteSpace(customerDelta.Dto.Password)) { AddPassword(customerDelta.Dto.Password, currentCustomer); } // TODO: Localization // Preparing the result dto of the new customer // We do not prepare the shopping cart items because we have a separate endpoint for them. var updatedCustomer = currentCustomer.ToDto(); // This is needed because the entity framework won't populate the navigation properties automatically // and the country name will be left empty because the mapping depends on the navigation property // so we do it by hand here. PopulateAddressCountryNames(updatedCustomer); // Set the fist and last name separately because they are not part of the customer entity, but are saved in the generic attributes. var firstNameGenericAttribute = _genericAttributeService.GetAttributesForEntity(currentCustomer.Id, typeof(Customer).Name) .FirstOrDefault(x => x.Key == "FirstName"); if (firstNameGenericAttribute != null) { updatedCustomer.FirstName = firstNameGenericAttribute.Value; } var lastNameGenericAttribute = _genericAttributeService.GetAttributesForEntity(currentCustomer.Id, typeof(Customer).Name) .FirstOrDefault(x => x.Key == "LastName"); if (lastNameGenericAttribute != null) { updatedCustomer.LastName = lastNameGenericAttribute.Value; } var languageIdGenericAttribute = _genericAttributeService.GetAttributesForEntity(currentCustomer.Id, typeof(Customer).Name) .FirstOrDefault(x => x.Key == "LanguageId"); if (languageIdGenericAttribute != null) { updatedCustomer.LanguageId = languageIdGenericAttribute.Value; } //activity log CustomerActivityService.InsertActivity("UpdateCustomer", LocalizationService.GetResource("ActivityLog.UpdateCustomer"), currentCustomer); var customersRootObject = new CustomersRootObject(); customersRootObject.Customers.Add(updatedCustomer); var json = JsonFieldsSerializer.Serialize(customersRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public IActionResult CreateCustomer([ModelBinder(typeof(JsonModelBinder <CustomerDto>))] Delta <CustomerDto> customerDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } //If the validation has passed the customerDelta object won't be null for sure so we don't need to check for this. // Inserting the new customer var newCustomer = _factory.Initialize(); customerDelta.Merge(newCustomer); foreach (var address in customerDelta.Dto.Addresses) { // we need to explicitly set the date as if it is not specified // it will default to 01/01/0001 which is not supported by SQL Server and throws and exception if (address.CreatedOnUtc == null) { address.CreatedOnUtc = DateTime.UtcNow; } newCustomer.Addresses.Add(address.ToEntity()); } CustomerService.InsertCustomer(newCustomer); InsertFirstAndLastNameGenericAttributes(customerDelta.Dto.FirstName, customerDelta.Dto.LastName, newCustomer); if (!string.IsNullOrEmpty(customerDelta.Dto.LanguageId) && int.TryParse(customerDelta.Dto.LanguageId, out var languageId) && _languageService.GetLanguageById(languageId) != null) { _genericAttributeService.SaveAttribute(newCustomer, NopCustomerDefaults.LanguageIdAttribute, languageId); } //password if (!string.IsNullOrWhiteSpace(customerDelta.Dto.Password)) { AddPassword(customerDelta.Dto.Password, newCustomer); } // We need to insert the entity first so we can have its id in order to map it to anything. // TODO: Localization // TODO: move this before inserting the customer. if (customerDelta.Dto.RoleIds.Count > 0) { AddValidRoles(customerDelta, newCustomer); CustomerService.UpdateCustomer(newCustomer); } // Preparing the result dto of the new customer // We do not prepare the shopping cart items because we have a separate endpoint for them. var newCustomerDto = newCustomer.ToDto(); // This is needed because the entity framework won't populate the navigation properties automatically // and the country will be left null. So we do it by hand here. PopulateAddressCountryNames(newCustomerDto); // Set the fist and last name separately because they are not part of the customer entity, but are saved in the generic attributes. newCustomerDto.FirstName = customerDelta.Dto.FirstName; newCustomerDto.LastName = customerDelta.Dto.LastName; newCustomerDto.LanguageId = customerDelta.Dto.LanguageId; //activity log CustomerActivityService.InsertActivity("AddNewCustomer", LocalizationService.GetResource("ActivityLog.AddNewCustomer"), newCustomer); var customersRootObject = new CustomersRootObject(); customersRootObject.Customers.Add(newCustomerDto); var json = JsonFieldsSerializer.Serialize(customersRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public async Task <IActionResult> CreateCategory( [ModelBinder(typeof(JsonModelBinder <CategoryDto>))] Delta <CategoryDto> categoryDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } //If the validation has passed the categoryDelta object won't be null for sure so we don't need to check for this. Picture insertedPicture = null; // We need to insert the picture before the category so we can obtain the picture id and map it to the category. if (categoryDelta.Dto.Image?.Binary != null) { insertedPicture = await PictureService.InsertPictureAsync(categoryDelta.Dto.Image.Binary, categoryDelta.Dto.Image.MimeType, string.Empty); } // Inserting the new category var category = await _factory.InitializeAsync(); categoryDelta.Merge(category); if (insertedPicture != null) { category.PictureId = insertedPicture.Id; } await _categoryService.InsertCategoryAsync(category); await UpdateAclRolesAsync(category, categoryDelta.Dto.RoleIds); await UpdateDiscountsAsync(category, categoryDelta.Dto.DiscountIds); await UpdateStoreMappingsAsync(category, categoryDelta.Dto.StoreIds); //search engine name if (categoryDelta.Dto.SeName != null) { var seName = await _urlRecordService.ValidateSeNameAsync(category, categoryDelta.Dto.SeName, category.Name, true); await _urlRecordService.SaveSlugAsync(category, seName, 0); } await CustomerActivityService.InsertActivityAsync("AddNewCategory", await LocalizationService.GetResourceAsync("ActivityLog.AddNewCategory"), category); // Preparing the result dto of the new category var newCategoryDto = await _dtoHelper.PrepareCategoryDTOAsync(category); var categoriesRootObject = new CategoriesRootObject(); categoriesRootObject.Categories.Add(newCategoryDto); var json = JsonFieldsSerializer.Serialize(categoriesRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public IActionResult UpdateOrder( [ModelBinder(typeof(JsonModelBinder <OrderDto>))] Delta <OrderDto> orderDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } var currentOrder = _orderApiService.GetOrderById(orderDelta.Dto.Id); if (currentOrder == null) { return(Error(HttpStatusCode.NotFound, "order", "not found")); } var customer = currentOrder.Customer; var shippingRequired = currentOrder.OrderItems.Any(item => !item.Product.IsFreeShipping); if (shippingRequired) { var isValid = true; if (!string.IsNullOrEmpty(orderDelta.Dto.ShippingRateComputationMethodSystemName) || !string.IsNullOrEmpty(orderDelta.Dto.ShippingMethod)) { var storeId = orderDelta.Dto.StoreId ?? _storeContext.CurrentStore.Id; isValid &= SetShippingOption(orderDelta.Dto.ShippingRateComputationMethodSystemName ?? currentOrder.ShippingRateComputationMethodSystemName, orderDelta.Dto.ShippingMethod, storeId, customer, BuildShoppingCartItemsFromOrderItems(currentOrder.OrderItems.ToList(), customer.Id, storeId)); } if (isValid) { currentOrder.ShippingMethod = orderDelta.Dto.ShippingMethod; } else { return(Error(HttpStatusCode.BadRequest)); } } orderDelta.Merge(currentOrder); customer.BillingAddress = currentOrder.BillingAddress; customer.ShippingAddress = currentOrder.ShippingAddress; _orderService.UpdateOrder(currentOrder); CustomerActivityService.InsertActivity("UpdateOrder", LocalizationService.GetResource("ActivityLog.UpdateOrder"), currentOrder); var ordersRootObject = new OrdersRootObject(); var placedOrderDto = _dtoHelper.PrepareOrderDTO(currentOrder); placedOrderDto.ShippingMethod = orderDelta.Dto.ShippingMethod; ordersRootObject.Orders.Add(placedOrderDto); var json = JsonFieldsSerializer.Serialize(ordersRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public IActionResult CreateProductReview([ModelBinder(typeof(JsonModelBinder <ProductReviewDto>))] Delta <ProductReviewDto> productReviewDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } // We doesn't have to check for value because this is done by the review validator. var customer = CustomerService.GetCustomerById(productReviewDelta.Dto.CustomerId); if (customer == null) { return(Error(HttpStatusCode.NotFound, "customer", "not found")); } var product = _productService.GetProductById(productReviewDelta.Dto.ProductId); if (product == null || product.Deleted || !product.Published || !product.AllowCustomerReviews) { return(Error(HttpStatusCode.NotFound, "product", "not found")); } if (_customerService.IsGuest(customer) && !_catalogSettings.AllowAnonymousUsersToReviewProduct) { return(Error(HttpStatusCode.BadRequest, "customer", _localizationService.GetResource("Reviews.OnlyRegisteredUsersCanWriteReviews"))); } if (_catalogSettings.ProductReviewPossibleOnlyAfterPurchasing) { var hasCompletedOrders = _orderService.SearchOrders(customerId: customer.Id, productId: product.Id, osIds: new List <int> { (int)OrderStatus.Complete }, pageSize: 1).Any(); if (!hasCompletedOrders) { return(Error(HttpStatusCode.BadRequest, "error", _localizationService.GetResource("Reviews.ProductReviewPossibleOnlyAfterPurchasing"))); } } var store = _storeService.GetStoreById(productReviewDelta.Dto.StoreId); //save review var newReview = new ProductReview() { ProductId = product.Id, CustomerId = customer.Id, StoreId = store == null ? _storeContext.CurrentStore.Id : store.Id, Title = productReviewDelta.Dto.Title, ReviewText = productReviewDelta.Dto.ReviewText, IsApproved = !_catalogSettings.ProductReviewsMustBeApproved, CreatedOnUtc = DateTime.UtcNow, HelpfulNoTotal = 0, HelpfulYesTotal = 0, CustomerNotifiedOfReply = _catalogSettings.NotifyCustomerAboutProductReviewReply }; // must be rating betweent 1 - 5 or set default rating var rating = productReviewDelta.Dto.Rating; newReview.Rating = rating < 1 || rating > 5 ? _catalogSettings.DefaultProductRatingValue : rating; _productService.InsertProductReview(newReview); //add product review and review type mapping foreach (var additionalReview in productReviewDelta.Dto.ReviewTypeMappingsDto) { // must be rating betweent 1 - 5 or set default rating var reviewTypeMappingRating = additionalReview.Rating; reviewTypeMappingRating = reviewTypeMappingRating < 1 || reviewTypeMappingRating > 5 ? _catalogSettings.DefaultProductRatingValue : reviewTypeMappingRating; var reviewType = _reviewTypeService.GetReviewTypeById(additionalReview.ReviewTypeId); if (reviewType == null) { // remove new Review after insert _productService.DeleteProductReview(newReview); return(Error(HttpStatusCode.NotFound, "review_type", "not found id = " + additionalReview.ReviewTypeId)); } var additionalProductReview = new ProductReviewReviewTypeMapping { ProductReviewId = newReview.Id, ReviewTypeId = reviewType.Id, Rating = reviewTypeMappingRating }; _reviewTypeService.InsertProductReviewReviewTypeMappings(additionalProductReview); } //update product totals _productService.UpdateProductReviewTotals(product); //notify store owner if (_catalogSettings.NotifyStoreOwnerAboutNewProductReviews) { _workflowMessageService.SendProductReviewNotificationMessage(newReview, _localizationSettings.DefaultAdminLanguageId); } //activity log _customerActivityService.InsertActivity(customer, "PublicStore.AddProductReview", string.Format(_localizationService.GetResource("ActivityLog.PublicStore.AddProductReview"), product.Name), product); //raise event if (newReview.IsApproved) { _eventPublisher.Publish(new ProductReviewApprovedEvent(newReview)); } if (!newReview.IsApproved) { return(Ok(_localizationService.GetResource("Reviews.SeeAfterApproving"))); } var productReviewsRootObject = new ProductReviewsRootObject(); productReviewsRootObject.ProductReviews.Add(_dtoHelper.PrepareProductReviewDTO(newReview)); var json = JsonFieldsSerializer.Serialize(productReviewsRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public IActionResult CreateShoppingCartItem([ModelBinder(typeof(JsonModelBinder <ShoppingCartItemDto>))] Delta <ShoppingCartItemDto> shoppingCartItemDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } var newShoppingCartItem = _factory.Initialize(); shoppingCartItemDelta.Merge(newShoppingCartItem); // We know that the product id and customer id will be provided because they are required by the validator. // TODO: validate var product = _productService.GetProductById(newShoppingCartItem.ProductId); if (product == null) { return(Error(HttpStatusCode.NotFound, "product", "not found")); } var customer = CustomerService.GetCustomerById(newShoppingCartItem.CustomerId); if (customer == null) { return(Error(HttpStatusCode.NotFound, "customer", "not found")); } var shoppingCartType = (ShoppingCartType)Enum.Parse(typeof(ShoppingCartType), shoppingCartItemDelta.Dto.ShoppingCartType); if (!product.IsRental) { newShoppingCartItem.RentalStartDateUtc = null; newShoppingCartItem.RentalEndDateUtc = null; } var attributesXml = _productAttributeConverter.ConvertToXml(shoppingCartItemDelta.Dto.Attributes, product.Id); var currentStoreId = _storeContext.CurrentStore.Id; var warnings = _shoppingCartService.AddToCart(customer, product, shoppingCartType, currentStoreId, attributesXml, 0M, newShoppingCartItem.RentalStartDateUtc, newShoppingCartItem.RentalEndDateUtc, shoppingCartItemDelta.Dto.Quantity ?? 1); if (warnings.Count > 0) { foreach (var warning in warnings) { ModelState.AddModelError("shopping cart item", warning); } return(Error(HttpStatusCode.BadRequest)); } else { // the newly added shopping cart item should be the last one newShoppingCartItem = customer.ShoppingCartItems.LastOrDefault(); } // Preparing the result dto of the new product category mapping var newShoppingCartItemDto = _dtoHelper.PrepareShoppingCartItemDTO(newShoppingCartItem); var shoppingCartsRootObject = new ShoppingCartItemsRootObject(); shoppingCartsRootObject.ShoppingCartItems.Add(newShoppingCartItemDto); var json = JsonFieldsSerializer.Serialize(shoppingCartsRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public IActionResult UpdateProduct( [ModelBinder(typeof(JsonModelBinder <ProductDto>))] Delta <ProductDto> productDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } var product = _productApiService.GetProductById(productDelta.Dto.Id); if (product == null) { return(Error(HttpStatusCode.NotFound, "product", "not found")); } productDelta.Merge(product); product.UpdatedOnUtc = DateTime.UtcNow; _productService.UpdateProduct(product); UpdateProductAttributes(product, productDelta); UpdateProductPictures(product, productDelta.Dto.Images); UpdateProductTags(product, productDelta.Dto.Tags); UpdateProductManufacturers(product, productDelta.Dto.ManufacturerIds); UpdateAssociatedProducts(product, productDelta.Dto.AssociatedProductIds); // Update the SeName if specified if (productDelta.Dto.SeName != null) { var seName = _urlRecordService.ValidateSeName(product, productDelta.Dto.SeName, product.Name, true); _urlRecordService.SaveSlug(product, seName, 0); } UpdateDiscountMappings(product, productDelta.Dto.DiscountIds); UpdateStoreMappings(product, productDelta.Dto.StoreIds); UpdateAclRoles(product, productDelta.Dto.RoleIds); _productService.UpdateProduct(product); CustomerActivityService.InsertActivity("UpdateProduct", LocalizationService.GetResource("ActivityLog.UpdateProduct"), product); // Preparing the result dto of the new product var productDto = _dtoHelper.PrepareProductDTO(product); var productsRootObject = new ProductsRootObjectDto(); productsRootObject.Products.Add(productDto); var json = JsonFieldsSerializer.Serialize(productsRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public IActionResult CreateOrder( [ModelBinder(typeof(JsonModelBinder <OrderDto>))] Delta <OrderDto> orderDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } if (orderDelta.Dto.CustomerId == null) { return(Error()); } // We doesn't have to check for value because this is done by the order validator. var customer = CustomerService.GetCustomerById(orderDelta.Dto.CustomerId.Value); if (customer == null) { return(Error(HttpStatusCode.NotFound, "customer", "not found")); } var shippingRequired = false; if (orderDelta.Dto.OrderItems != null) { var shouldReturnError = AddOrderItemsToCart(orderDelta.Dto.OrderItems, customer, orderDelta.Dto.StoreId ?? _storeContext.CurrentStore.Id); if (shouldReturnError) { return(Error(HttpStatusCode.BadRequest)); } shippingRequired = IsShippingAddressRequired(orderDelta.Dto.OrderItems); } if (shippingRequired) { var isValid = true; isValid &= SetShippingOption(orderDelta.Dto.ShippingRateComputationMethodSystemName, orderDelta.Dto.ShippingMethod, orderDelta.Dto.StoreId ?? _storeContext.CurrentStore.Id, customer, BuildShoppingCartItemsFromOrderItemDtos(orderDelta.Dto.OrderItems.ToList(), customer.Id, orderDelta.Dto.StoreId ?? _storeContext.CurrentStore.Id)); if (!isValid) { return(Error(HttpStatusCode.BadRequest)); } } var newOrder = _factory.Initialize(); orderDelta.Merge(newOrder); customer.BillingAddress = newOrder.BillingAddress; customer.ShippingAddress = newOrder.ShippingAddress; // If the customer has something in the cart it will be added too. Should we clear the cart first? newOrder.Customer = customer; // The default value will be the currentStore.id, but if it isn't passed in the json we need to set it by hand. if (!orderDelta.Dto.StoreId.HasValue) { newOrder.StoreId = _storeContext.CurrentStore.Id; } var placeOrderResult = PlaceOrder(newOrder, customer); if (!placeOrderResult.Success) { foreach (var error in placeOrderResult.Errors) { ModelState.AddModelError("order placement", error); } return(Error(HttpStatusCode.BadRequest)); } CustomerActivityService.InsertActivity("AddNewOrder", LocalizationService.GetResource("ActivityLog.AddNewOrder"), newOrder); var ordersRootObject = new OrdersRootObject(); var placedOrderDto = _dtoHelper.PrepareOrderDTO(placeOrderResult.PlacedOrder); ordersRootObject.Orders.Add(placedOrderDto); var json = JsonFieldsSerializer.Serialize(ordersRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public async Task <IActionResult> UpdateUser([ModelBinder(typeof(JsonModelBinder <UserDto>))] Delta <UserDto> userDelta) { if (!ModelState.IsValid) { return(await Error()); } var currentUser = _userApiService.GetUserEntityById(userDelta.Dto.Id); if (currentUser == null) { return(await Error(HttpStatusCode.NotFound, "user", "not found")); } userDelta.Merge(currentUser); //password if (!string.IsNullOrWhiteSpace(userDelta.Dto.Password)) { await AddPassword(userDelta.Dto.Password, currentUser); } //roles if (userDelta.Dto.RoleIds.Count > 0) { AddValidRoles(userDelta, currentUser); } //stores if (userDelta.Dto.StoreIds.Count > 0) { await AddValidStores(userDelta, currentUser); } await UserService.UpdateUserAsync(currentUser); await InsertFirstAndLastNameGenericAttributes(userDelta.Dto.FirstName, userDelta.Dto.LastName, currentUser); // Preparing the result dto of the new user var updatedUser = currentUser.ToDto(); var firstNameGenericAttribute = (await _genericAttributeService.GetAttributesForEntityAsync(currentUser.Id, typeof(User).Name)) .FirstOrDefault(x => x.Key == "FirstName"); if (firstNameGenericAttribute != null) { updatedUser.FirstName = firstNameGenericAttribute.Value; } var lastNameGenericAttribute = (await _genericAttributeService.GetAttributesForEntityAsync(currentUser.Id, typeof(User).Name)) .FirstOrDefault(x => x.Key == "LastName"); if (lastNameGenericAttribute != null) { updatedUser.LastName = lastNameGenericAttribute.Value; } updatedUser.UserPassword = _userApiService.GetUserPassword(updatedUser.Id); //activity log await UserActivityService.InsertActivityAsync("EditUser", $"Edited a user (ID = {currentUser.Id})", currentUser); var usersRootObject = new UsersRootObject(); usersRootObject.Users.Add(updatedUser); var json = JsonFieldsSerializer.Serialize(usersRootObject, String.Empty); return(new RawJsonActionResult(json)); }
public async Task <IActionResult> CreateOrderItem( int orderId, [ModelBinder(typeof(JsonModelBinder <OrderItemDto>))] Delta <OrderItemDto> orderItemDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } var order = _orderApiService.GetOrderById(orderId); if (order == null) { return(Error(HttpStatusCode.NotFound, "order", "not found")); } var product = GetProduct(orderItemDelta.Dto.ProductId); if (product == null) { return(Error(HttpStatusCode.NotFound, "product", "not found")); } if (product.IsRental) { if (orderItemDelta.Dto.RentalStartDateUtc == null) { return(Error(HttpStatusCode.BadRequest, "rental_start_date_utc", "required")); } if (orderItemDelta.Dto.RentalEndDateUtc == null) { return(Error(HttpStatusCode.BadRequest, "rental_end_date_utc", "required")); } if (orderItemDelta.Dto.RentalStartDateUtc > orderItemDelta.Dto.RentalEndDateUtc) { return(Error(HttpStatusCode.BadRequest, "rental_start_date_utc", "should be before rental_end_date_utc")); } if (orderItemDelta.Dto.RentalStartDateUtc < DateTime.UtcNow) { return(Error(HttpStatusCode.BadRequest, "rental_start_date_utc", "should be a future date")); } } var newOrderItem = await PrepareDefaultOrderItemFromProductAsync(order, product); orderItemDelta.Merge(newOrderItem); await _orderService.InsertOrderItemAsync(newOrderItem); await _orderService.UpdateOrderAsync(order); await CustomerActivityService.InsertActivityAsync("AddNewOrderItem", await LocalizationService.GetResourceAsync("ActivityLog.AddNewOrderItem"), newOrderItem); var orderItemsRootObject = new OrderItemsRootObject(); orderItemsRootObject.OrderItems.Add(newOrderItem.ToDto()); var json = JsonFieldsSerializer.Serialize(orderItemsRootObject, string.Empty); return(new RawJsonActionResult(json)); }
public IActionResult CreateProduct([ModelBinder(typeof(JsonModelBinder <ProductDto>))] Delta <ProductDto> productDelta) { var genricAttribute = _genericAttributeRepository.Table.Where(g => g.Key == "nop.product.admindid" && g.Value == productDelta.Dto.AdmindId.ToString()).FirstOrDefault(); Product product = null; if (genricAttribute == null) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } // Inserting the new product product = _factory.Initialize(); productDelta.Merge(product); _productService.InsertProduct(product); UpdateProductPictures(product, productDelta.Dto.Images); UpdateProductTags(product, productDelta.Dto.Tags); UpdateProductManufacturers(product, productDelta.Dto.ManufacturerIds); UpdateAssociatedProducts(product, productDelta.Dto.AssociatedProductIds); /*EXTRA*/ UpdateProductAttributes(product, productDelta); UpdateProductAttributeCombinations(product, productDelta.Dto.ProductAttributeCombinations); UpdateProductTirePrices(product, productDelta.Dto.DtoTierPrices); UpdateProductGenericAttributes(product, productDelta.Dto.DtoGenericAttributes); _genericAttributeService.SaveAttribute <int>(product, "nop.product.admindid", productDelta.Dto.AdmindId); /*EXTRA*/ //search engine name var seName = _urlRecordService.ValidateSeName(product, productDelta.Dto.SeName, product.Name, true); _urlRecordService.SaveSlug(product, seName, 0); UpdateAclRoles(product, productDelta.Dto.RoleIds); UpdateDiscountMappings(product, productDelta.Dto.DiscountIds); UpdateStoreMappings(product, productDelta.Dto.StoreIds); _productService.UpdateProduct(product); CustomerActivityService.InsertActivity("AddNewProduct", LocalizationService.GetResource("ActivityLog.AddNewProduct"), product); } else { product = _productService.GetProductById(genricAttribute.EntityId); } if (product == null) { return(Error(HttpStatusCode.Conflict, "product", "could not find product!")); } // Preparing the result dto of the new product var productDto = _dtoHelper.PrepareProductDTO(product); /*EXTRA*/ productDto.AdmindId = _genericAttributeService.GetAttribute <int>(product, "nop.product.admindid"); /*EXTRA*/ var productsRootObject = new ProductsRootObjectDto(); productsRootObject.Products.Add(productDto); var json = JsonFieldsSerializer.Serialize(productsRootObject, string.Empty); return(new RawJsonActionResult(json)); }