Exemplo n.º 1
0
        public async Task <ClientResponseModel> CreateClient(ClientRequestModel clientRequestModel)
        {
            var client = new Clients
            {
                Name    = clientRequestModel.Name,
                Email   = clientRequestModel.Email,
                Phones  = clientRequestModel.Phones,
                Address = clientRequestModel.Address,
                AddedBy = clientRequestModel.AddedBy,
                AddedOn = clientRequestModel.AddedOn,
            };
            var createdClient = await _clientsRepository.AddAsync(client);

            var response = new ClientResponseModel
            {
                Id      = createdClient.Id,
                Name    = createdClient.Name,
                Email   = createdClient.Email,
                Phones  = createdClient.Phones,
                Address = createdClient.Address,
                AddedBy = createdClient.AddedBy,
                AddedOn = createdClient.AddedOn,
            };

            return(response);
        }
Exemplo n.º 2
0
        public async Task Post_WhenCreateAclient_ShouldReturnsTheCreatedClient()
        {
            //Arrenge
            var clientId          = 10;
            var newClientName     = "Jose";
            var newClientLastName = "Perez";

            _serviceMock.Setup(s => s.AddNewClient(It.IsAny <ClientDto>()))
            .ReturnsAsync(new ClientDto {
                Id = clientId, Name = newClientName, LastName = newClientLastName
            });

            var newClientRequest = new ClientRequestModel
            {
                Name     = newClientName,
                LastName = newClientLastName
            };

            //Act
            var result = await _sut.Post(newClientRequest);

            //Assert
            result.Should().BeOfType(typeof(CreatedAtActionResult));
            var value = result.As <ObjectResult>().Value.As <ClientResponseModel>();

            value.Id.Should().Be(clientId);
            value.Name.Should().Be(newClientName);
            value.Lastname.Should().Be(newClientLastName);

            _serviceMock.Verify(s => s.AddNewClient(It.Is <ClientDto>(c => c.Name == newClientName && c.LastName == newClientLastName)), Times.Once);
        }
        public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            object appUser     = null;
            bool   tryGetValue = actionContext.Request.Properties.TryGetValue("AppUser", out appUser);

            if (tryGetValue && appUser is ApplicationUser user)
            {
                ClientRequestModel client =
                    new ClientRequestModel(actionContext)
                {
                    UserName = user.UserName, ShopId = user.ShopId
                };

                string clientConnectionId = client.ConnectionId;
                Thread.SetData(Thread.GetNamedDataSlot("AppUser"), user);
                logger.Debug("Query Request: {@Client} {ConnectionId}", client, clientConnectionId);
                bool containsKey = actionContext.ActionArguments.ContainsKey("request");
                if (containsKey)
                {
                    dynamic request = actionContext.ActionArguments["request"];
                    request.ShopId = user.ShopId;
                    if (request.Keyword != null)
                    {
                        logger.Debug(
                            "Request model : {Username} requested {RawUrl} with values {@Request}",
                            user.UserName,
                            client.RawUrl,
                            request);
                    }
                }
            }

            return(base.OnActionExecutingAsync(actionContext, cancellationToken));
        }
        public async Task <IActionResult> PostClientRequestModel([FromBody] ClientRequestModel clientRequestModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (string.IsNullOrEmpty(clientRequestModel.User.Id))
            {
                return(BadRequest());
            }

            var user = _context.Users.Find(clientRequestModel.User.Id);

            _context.Entry(clientRequestModel.User).CurrentValues.SetValues(user);

            // to do make enum Status
            clientRequestModel.Status  = "Open";
            clientRequestModel.InsDate = DateTime.Now;
            clientRequestModel.UpdDate = DateTime.Now;

            _context.ClientRequests.Add(clientRequestModel);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetClientRequestModel", new { id = clientRequestModel.Id }, clientRequestModel));
        }
        public IActionResult Post([FromBody] ClientRequestModel request)
        {
            logger.LogInformation($"POST /api/client reach with body: {request}");

            var response = clientService.Add(request);

            return(response.CreateResponse(this));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Save(ClientRequestModel request)
        {
            var sellerClaim = this.User.Claims.FirstOrDefault(x => x.Type == AccountConstants.Claims.OrganisationIdClaim);

            if (request.Id.HasValue)
            {
                var serviceModel = new UpdateClientServiceModel
                {
                    Id    = request.Id,
                    Name  = request.Name,
                    Email = request.Email,
                    CommunicationLanguage = request.CommunicationLanguage,
                    ClientOrganisationId  = request.OrganisationId,
                    Language       = CultureInfo.CurrentCulture.Name,
                    Username       = this.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value,
                    OrganisationId = GuidHelper.ParseNullable(sellerClaim?.Value)
                };

                var validator = new UpdateClientModelValidator();

                var validationResult = await validator.ValidateAsync(serviceModel);

                if (validationResult.IsValid)
                {
                    var client = await this.clientsService.UpdateAsync(serviceModel);

                    return(this.StatusCode((int)HttpStatusCode.OK, new { Id = client.Id }));
                }

                throw new CustomException(string.Join(ErrorConstants.ErrorMessagesSeparator, validationResult.Errors.Select(x => x.ErrorMessage)), (int)HttpStatusCode.UnprocessableEntity);
            }
            else
            {
                var serviceModel = new CreateClientServiceModel
                {
                    Name  = request.Name,
                    Email = request.Email,
                    CommunicationLanguage = request.CommunicationLanguage,
                    ClientOrganisationId  = request.OrganisationId,
                    Language       = CultureInfo.CurrentCulture.Name,
                    Username       = this.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value,
                    OrganisationId = GuidHelper.ParseNullable(sellerClaim?.Value)
                };

                var validator = new CreateClientModelValidator();

                var validationResult = await validator.ValidateAsync(serviceModel);

                if (validationResult.IsValid)
                {
                    var client = await this.clientsService.CreateAsync(serviceModel);

                    return(this.StatusCode((int)HttpStatusCode.Created, new { Id = client.Id }));
                }

                throw new CustomException(string.Join(ErrorConstants.ErrorMessagesSeparator, validationResult.Errors.Select(x => x.ErrorMessage)), (int)HttpStatusCode.UnprocessableEntity);
            }
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Post([FromBody] ClientRequestModel clientRequest)
        {
            var clientDto      = _mapper.Map <ClientDto>(clientRequest);
            var addedClientDto = await _service.AddNewClient(clientDto);

            var responseModel = _mapper.Map <ClientResponseModel>(addedClientDto);

            return(CreatedAtAction(nameof(GetById), new { id = responseModel.Id }, responseModel));
        }
Exemplo n.º 8
0
        public async Task <IActionResult> Account([FromBody] ClientRequestModel model)
        {
            var token = await HttpContext.GetTokenAsync(ApiExtensionsConstants.TokenName);

            var language = CultureInfo.CurrentUICulture.Name;

            var userId = await this.identityRepository.SaveAsync(token, language, model.Name, model.Email, model.CommunicationLanguage, this.options.CurrentValue.BuyerUrl);

            return(this.StatusCode((int)HttpStatusCode.OK, new { Id = userId, Message = this.clientLocalizer.GetString("AccountCreated").Value }));
        }
Exemplo n.º 9
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            object data = actionContext.ActionArguments["model"];
            //Log.Logger.Debug("Save request: Data {@Data}", data);
            dynamic appUser     = null;
            bool    tryGetValue = actionContext.Request.Properties.TryGetValue("AppUser", out appUser);

            if (tryGetValue && data != null)
            {
                var    user               = appUser as ApplicationUser;
                string username           = user.UserName;
                string isDataMigrationStr = ConfigurationManager.AppSettings["IsDataMigration"];
                bool   isDataMigration    = Convert.ToBoolean(isDataMigrationStr);
                if (!isDataMigration)
                {
                    var    isEntity = data is Entity;
                    Entity entity   = data as Entity;
                    if (isEntity)
                    {
                        entity.Id         = Guid.NewGuid().ToString();
                        entity.Created    = DateTime.Now;
                        entity.Modified   = DateTime.Now;
                        entity.CreatedBy  = username;
                        entity.ModifiedBy = username;
                        entity.IsActive   = true;
                    }
                }


                var isShopChild = data is ShopChild;
                if (isShopChild)
                {
                    var shopChild = data as ShopChild;
                    shopChild.ShopId = user.ShopId;
                }

                ClientRequestModel client =
                    new ClientRequestModel(actionContext)
                {
                    UserName = username, ShopId = user.ShopId
                };
                string clientConnectionId = client.ConnectionId;
                Thread.SetData(Thread.GetNamedDataSlot("ConnectionId"), clientConnectionId);
                appUser.ConnectionId = clientConnectionId;
                // Log.Logger.Debug("AppUser : {@AppUser}", appUser);
                Log.Logger.Debug("Client details: {@Client} ", client);
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Data must not be empty");
            }
        }
Exemplo n.º 10
0
        public void ShouldAddClient()
        {
            var clientRequestModel = new ClientRequestModel {
                Name = "name", Phone = "123"
            };

            var response = clientService.Add(clientRequestModel);

            clientRepositoryMock.Verify(x => x.Add(It.IsAny <Client>()), Times.Once);
            repositoryMock.Verify(x => x.Save(), Times.Once);
            Assert.False(response.HasErrors());

            Assert.AreEqual(response.Messages.Count(x => x.Code == Constants.CLIENT_SAVED), 1);
        }
Exemplo n.º 11
0
        public void ShouldValidateModel()
        {
            var clientRequestModel = new ClientRequestModel {
                Name = "", Phone = ""
            };

            var response = clientService.Add(clientRequestModel);

            clientRepositoryMock.Verify(x => x.Add(It.IsAny <Client>()), Times.Never);
            Assert.True(response.HasErrors());
            Assert.AreEqual(response.Messages.Count(x => x.Type == MessageType.Error), 2);
            Assert.AreEqual(response.Messages.Count(x => x.Code == Constants.NAME_EMPTY), 1);
            Assert.AreEqual(response.Messages.Count(x => x.Code == Constants.PHONE_EMPTY), 1);
        }
Exemplo n.º 12
0
        public void ShouldNotSave()
        {
            repositoryMock.Setup(x => x.Save()).Throws(new Exception());

            var clientRequestModel = new ClientRequestModel {
                Name = "name", Phone = "123"
            };

            var response = clientService.Add(clientRequestModel);

            clientRepositoryMock.Verify(x => x.Add(It.IsAny <Client>()), Times.Once);
            repositoryMock.Verify(x => x.Save(), Times.Once);

            Assert.True(response.HasErrors());
            Assert.AreEqual(response.Messages.Count(x => x.Type == MessageType.Error), 1);
            Assert.AreEqual(response.Messages.Count(x => x.Code == Constants.GENERAL_ERROR), 1);
        }
Exemplo n.º 13
0
 public async Task <IActionResult> DriverLocations([FromRoute] string id, ClientRequestModel clientRequestModel)
 {
     if (string.IsNullOrEmpty(id))
     {
         /////////////////////////////////////////
         if (!string.IsNullOrEmpty(clientRequestModel.Id))
         {
             HttpContext.Session.SetString("ClientRequestModelId", clientRequestModel.Id);
         }
         /////////////////////////////////////////
         return(View((object)id));
     }
     else
     {
         return(Error());
     }
 }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            object data = actionContext.ActionArguments["model"];

            logger.Information("Save request: User {Name}, Data {@Data}",
                               actionContext.RequestContext.Principal.Identity.Name, data);

            if (data != null)
            {
                string username = actionContext.RequestContext.Principal.Identity.Name;
                var    isEntity = data is Entity;
                Entity entity   = data as Entity;
                if (isEntity)
                {
                    entity.Id         = Guid.NewGuid().ToString();
                    entity.Created    = DateTime.UtcNow;
                    entity.Modified   = DateTime.UtcNow;
                    entity.CreatedBy  = username;
                    entity.ModifiedBy = username;
                }
                var isShopChild = data is ShopChild;
                if (isShopChild)
                {
                    var             shopChild = data as ShopChild;
                    var             manager   = actionContext.Request.GetOwinContext().Get <ApplicationUserManager>();
                    var             id        = actionContext.RequestContext.Principal.Identity.GetUserId();
                    ApplicationUser user      = manager.FindById(id);
                    shopChild.ShopId = user.ShopId;
                }

                ClientRequestModel client = new ClientRequestModel(actionContext)
                {
                    UserName = username
                };
                string clientConnectionId = client.ConnectionId;
                Thread.SetData(Thread.GetNamedDataSlot("ConnectionId"), clientConnectionId);
                Trace.TraceInformation("Trace Request: {0}  clientConnectionId: {1}", client, clientConnectionId);
                string clientStr = client.ToString();
                logger.Debug("Client details: {0} ", clientStr);
                logger.Debug("EntitySaveObject: {1}", entity);
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Data must not be empty");
            }
        }
Exemplo n.º 15
0
        public async Task GivenTheClientIsRegistered(string name, string lastName)
        {
            var clientRequest = new ClientRequestModel
            {
                Name     = name,
                LastName = lastName
            };

            var response = await _client.PostAsJsonAsync("api/clients", clientRequest);

            response.StatusCode.Should().Be(HttpStatusCode.Created);
            var registeredClient = JsonConvert.DeserializeObject <ClientResponseModel>(await response.Content.ReadAsStringAsync());

            registeredClient.Id.Should().Be(1);
            registeredClient.Name.Should().Be(name);
            registeredClient.Lastname.Should().Be(lastName);

            _registeredClient = registeredClient;
        }
        /// <summary>
        /// Create a new client
        /// </summary>
        /// <param name="request"></param>
        public Response Add(ClientRequestModel request)
        {
            var response = new Response();

            logger.LogInformation("Starting request validation");

            if (string.IsNullOrWhiteSpace(request.Name))
            {
                response.AddError(Constants.NAME_EMPTY, "The field name is required");
            }
            if (string.IsNullOrWhiteSpace(request.Phone))
            {
                response.AddError(Constants.PHONE_EMPTY, "The field phone is required");
            }

            if (response.HasErrors())
            {
                return(response);
            }

            logger.LogInformation("Request validated success");

            try
            {
                var domain = new Client {
                    Name = request.Name, Phone = request.Phone, Active = true
                };

                logger.LogInformation("Calling client repository to save new client");

                repository.ClientRepository.Add(domain);
                repository.Save();

                response.AddSuccess(Constants.CLIENT_SAVED, "Client added succesfully");
            }
            catch (Exception e)
            {
                ExceptionUtils.HandleGeneralError(response, logger, e);
            }

            return(response);
        }
Exemplo n.º 17
0
        public bool DistanceIsOk(DriverLocationModel dr, ClientRequestModel cr)
        {
            var distance = 100D;
            var isLat1   = double.TryParse(dr.Latitude, out var lat1);
            var isLng1   = double.TryParse(dr.Longitude, out var lng1);
            var isLat2   = double.TryParse(cr.Latitude, out var lat2);
            var isLng2   = double.TryParse(cr.Longitude, out var lng2);

            if (isLat1 && isLng1 && isLat2 && isLng2)
            {
                distance = FuncHelper.Distance(lat1, lng1, lat2, lng2, 2);
            }

            if (distance > 5D)
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 18
0
        public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            ApplicationUserManager manager = actionContext.Request.GetOwinContext().Get <ApplicationUserManager>();

            string username = actionContext.RequestContext.Principal.Identity.Name;

            if (!string.IsNullOrWhiteSpace(username))
            {
                ApplicationUser user = manager.FindByName(username);
                if (user != null)
                {
                    actionContext.Request.Properties.Add("AppUser", user);
                    dynamic controller = actionContext.ControllerContext.Controller;
                    controller.AppUser = user;
                    ClientRequestModel client = new ClientRequestModel(actionContext)
                    {
                        UserName = user.UserName,
                        ShopId   = user.ShopId
                    };

                    string clientConnectionId = client.ConnectionId;
                    Thread.SetData(Thread.GetNamedDataSlot("AppUser"), user);
                    Trace.TraceInformation("Trace Query Request: {0} {1}", client, clientConnectionId);
                    string clientStr = client.ToString();
                    logger.Debug("Query Request: {ClientStr} {ConnectionId}", clientStr, clientConnectionId);
                    bool containsKey = actionContext.ActionArguments.ContainsKey("request");
                    if (containsKey)
                    {
                        dynamic request = actionContext.ActionArguments["request"];
                        request.ShopId = user.ShopId;
                        if (request.Keyword != null)
                        {
                            logger.Debug("Request model : {Username} requested {RawUrl} with values {@Request}", username, client.RawUrl, request);
                        }
                    }
                }
            }


            return(base.OnActionExecutingAsync(actionContext, cancellationToken));
        }
Exemplo n.º 19
0
        public async Task <IActionResult> InsertAsync([FromBody] ClientRequestModel data)
        {
            JsonResult          result;
            ClientResponseModel response = new ClientResponseModel();

            Klijent newClient = new Klijent {
                BrojRacuna = long.Parse(data.BrojRacuna), AdresaISediste = data.AdresaISediste, ImeIPrezimeKlijenta = data.ImeIPrezimeKlijenta, PIB = long.Parse(data.PIB)
            };

            bool insertedClient = await _clientFacade.InsertAsync(newClient);

            if (!insertedClient)
            {
                response.Message = "Insert failed!";
                result           = new JsonResult(response);

                return(BadRequest(result));
            }

            response.Message = "Client inserted successfully!";
            result           = new JsonResult(response);

            return(result);
        }
        public async Task <IActionResult> PutClientRequestModel([FromRoute] string id, [FromBody] ClientRequestModel clientRequestModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != clientRequestModel.Id)
            {
                return(BadRequest());
            }

            // get object from db
            var clientRequest = _context.ClientRequests.Find(id);

            //check status
            if (clientRequest.Status != clientRequestModel.Status)
            {
                clientRequest.Status  = clientRequestModel.Status;
                clientRequest.UpdDate = DateTime.Now;
            }

            _context.Entry(clientRequest).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ClientRequestModelExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Exemplo n.º 21
0
        public async Task <IActionResult> CreateClient(ClientRequestModel clientRequestModel)
        {
            var createdClient = await _clientsService.CreateClient(clientRequestModel);

            return(CreatedAtRoute("GetClient", new { id = createdClient.Id }, createdClient));
        }