Exemplo n.º 1
0
        public IHttpActionResult Post([FromBody] InspectionDTO inspection)
        {
            HttpResponseMessage response = new HttpResponseMessage();

            if (inspection != null)
            {
                try
                {
                    Guid    token = this.GetToken();
                    UserDTO user  = this.userService.GetUserLoggedIn(token);
                    inspection.CreatorUserName = user.UserName;
                    PermissionHandler permissionHandler = new PermissionHandler();
                    bool permissionInPort = permissionHandler.IsUserAllowedToCreateInspectionOnPort(user.Role);
                    bool permissionInYard = permissionHandler.IsUserAllowedToCreateInspectionOnYard(user.Role);
                    if ((permissionInPort && this.LocationIsPort(inspection.Location)) ||
                        (permissionInYard && this.LocationIsYard(inspection.Location)))
                    {
                        this.inspectionService.CreateInspection(inspection);
                        response = this.Request.CreateResponse(HttpStatusCode.OK);
                    }
                    else if (this.LocationIsPort(inspection.Location) || this.LocationIsYard(inspection.Location))
                    {
                        response = this.Request.CreateResponse(HttpStatusCode.Unauthorized, "El usuario no tiene permisos para ejecutar esta accion");
                    }
                    else
                    {
                        response = this.Request.CreateResponse(HttpStatusCode.Unauthorized, "El lugar ingresado no es un lugar válido");
                    }
                }
                catch (UserNotExistException e)
                {
                    response = this.Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
                }
                catch (ImageNotFoundException e)
                {
                    response = this.Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
                }
                catch (FormatException)
                {
                    string message = "El token enviado no tiene un formato valido.";
                    response = this.Request.CreateResponse(HttpStatusCode.BadRequest, message);
                }
                catch (InvalidOperationException)
                {
                    string message = "No se ha enviado header de autenticación.";
                    response = this.Request.CreateResponse(HttpStatusCode.BadRequest, message);
                }
                catch (VehicleNotFoundException e)
                {
                    response = this.Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
                }
            }
            else
            {
                string message = "El formato de usuario es incorrecto";
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, message);
            }

            return(ResponseMessage(response));
        }
Exemplo n.º 2
0
        public Guid CreateInspection(InspectionDTO inspection)
        {
            bool existVehicle      = this.ExistVehicle(inspection.IdVehicle);
            bool damagesHaveImages = this.DamageHaveImage(inspection.Damages);

            if (existVehicle && damagesHaveImages)
            {
                string statusVehicle = this.StatusVehicle(inspection.IdVehicle);
                if (statusVehicle == StatusCode.InPort)
                {
                    this.CreateInspectionInPort(inspection);
                }
                else if (statusVehicle == StatusCode.Waiting)
                {
                    this.CreateInspectionInYard(inspection);
                }
                else
                {
                    throw new InspectionNotFoundException("Error al crear la inspección debido a que el vehículo no se encuentra en lugar de inspección");
                }
            }
            else if (!damagesHaveImages)
            {
                throw new ImageNotFoundException("Un daño que desea ingresar no contiene ninguna imagen asociada.");
            }
            else if (!existVehicle)
            {
                throw new VehicleNotFoundException("El vehículo ingresado no está registrado en el sistema.");
            }
            return(inspection.Id);
        }
Exemplo n.º 3
0
        public void MapInspectionDTOToInspectionTest()
        {
            UserDTO    user    = this.CreateUser();
            VehicleDTO vehicle = this.CreateVehicle();

            InspectionMapper mapper        = new InspectionMapper();
            InspectionDTO    inspectionDTO = new InspectionDTO();

            inspectionDTO.Damages         = new List <DamageDTO>();
            inspectionDTO.CreatorUserName = user.UserName;
            inspectionDTO.Date            = DateTime.Now;
            inspectionDTO.Location        = "Puerto 1";
            inspectionDTO.IdVehicle       = vehicle.Vin;

            Inspection inspectionEntity = mapper.ToEntity(inspectionDTO);

            Assert.AreEqual(inspectionDTO.Location, inspectionEntity.IdLocation.Name);
            Assert.AreEqual(inspectionDTO.Id, inspectionEntity.Id);
            Assert.AreEqual(inspectionDTO.Date, inspectionEntity.Date);
            Assert.AreEqual(inspectionDTO.CreatorUserName, inspectionEntity.IdUser.UserName);
            Assert.AreEqual(inspectionDTO.IdVehicle, inspectionEntity.IdVehicle.Vin);
            foreach (DamageDTO damageDTO in inspectionDTO.Damages)
            {
                Assert.IsNotNull(inspectionEntity.Damages.Find(d => d.Description == damageDTO.Description));
            }
        }
Exemplo n.º 4
0
        public void PersistInspectionTest()
        {
            InspectionDAO inspectionDAO = new InspectionDAOImp(new VehicleDAOImpl());
            UserDAO       userDAO       = new UserDAOImp();

            List <DamageDTO> damages = this.CreateDamages();
            UserDTO          user    = this.CreateUser();
            VehicleDTO       vehicle = this.CreateVehicle();

            InspectionDTO inspection = new InspectionDTO();

            inspection.Damages         = damages;
            inspection.CreatorUserName = user.UserName;
            inspection.Date            = DateTime.Now;
            inspection.Location        = "Puerto 1";
            inspection.IdVehicle       = vehicle.Vin;

            Guid id = inspectionDAO.AddInspection(inspection);

            InspectionDTO resultInspection = inspectionDAO.FindInspectionById(inspection.Id);

            Assert.AreEqual(inspection.CreatorUserName, resultInspection.CreatorUserName);
            Assert.AreEqual(inspection.Id, resultInspection.Id);
            Assert.AreEqual(inspection.Location, resultInspection.Location);
            foreach (DamageDTO damage in inspection.Damages)
            {
                Assert.IsNotNull(resultInspection.Damages.Find(d => d.Description == damage.Description));
            }
        }
Exemplo n.º 5
0
        public void ErrorCreatingInspectionYardWithoutInspectionPortTest()
        {
            List <DamageDTO> damages = this.CreateDamages();
            UserDTO          user    = this.CreateUser();
            VehicleDTO       vehicle = this.CreateVehicle();

            InspectionDTO inspection = new InspectionDTO();

            inspection.Damages         = damages;
            inspection.CreatorUserName = user.UserName;
            inspection.Date            = DateTime.Now;
            inspection.Location        = "Patio 1";
            inspection.IdVehicle       = vehicle.Vin;

            var mockInspectionDAO = new Mock <InspectionDAO>();

            mockInspectionDAO.Setup(vs => vs.ExistInspectionInPort(inspection.IdVehicle)).Returns(false);
            var mockVehicleDAO = new Mock <VehicleDAO>();

            mockVehicleDAO.Setup(v => v.FindVehicleByVin(vehicle.Vin)).Returns(vehicle);

            var inspectionService = new InspectionServiceImpl(mockInspectionDAO.Object, mockVehicleDAO.Object);

            Guid id = inspectionService.CreateInspection(inspection);
        }
Exemplo n.º 6
0
        public InspectionDTO FindInspectionById(Guid id)
        {
            Inspection    inspection    = null;
            InspectionDTO inspectionDTO = null;

            using (VehicleTrackingDbContext context = new VehicleTrackingDbContext())
            {
                inspection = context.Inspections
                             .Include("Damages")
                             .Include("IdLocation")
                             .Include("IdUser")
                             .Include("IdVehicle")
                             .Where(i => i.Id == id)
                             .ToList().FirstOrDefault();
                if (inspection != null)
                {
                    List <Damage> damages = new List <Damage>();
                    foreach (Damage damage in inspection.Damages)
                    {
                        Damage dam = context.Damages
                                     .Include("Images")
                                     .Where(d => d.Id == damage.Id)
                                     .ToList().FirstOrDefault();
                        damages.Add(dam);
                    }
                    inspection.Damages = damages;
                }
            }
            if (inspection != null)
            {
                inspectionDTO = this.inspectionMapper.ToDTO(inspection);
            }
            return(inspectionDTO);
        }
Exemplo n.º 7
0
        public async Task <IActionResult> FindAsync(Guid id)
        {
            try
            {
                Inspection result = await _unitOfWork.Inspection.FindEagerAsync(id);

                if (result == null)
                {
                    _logger.LogError($"Inspection with id: {id}, hasn't been found in db.");
                    return(NotFound());
                }
                else
                {
                    _logger.LogInformation($"Returned inspection with id: {id}");

                    InspectionDTO resultDTO = _mapper.Map <Inspection, InspectionDTO>(result);
                    return(Ok(resultDTO));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong inside FindAsync action: {ex.Message}");
                return(StatusCode(500, "Internal server error"));
            }
        }
Exemplo n.º 8
0
        public void CreateInspectionTest()
        {
            List <DamageDTO> damages = this.CreateDamages();
            UserDTO          user    = this.CreateUser();
            VehicleDTO       vehicle = this.CreateVehicle();

            InspectionDTO inspection = new InspectionDTO();

            inspection.Damages         = damages;
            inspection.CreatorUserName = user.UserName;
            inspection.Date            = DateTime.Now;
            inspection.Location        = "Puerto 1";
            inspection.IdVehicle       = vehicle.Vin;

            UserDTO userDTO = this.CreateUser();
            Guid    token   = Guid.NewGuid();

            var mockInspectionService = new Mock <InspectionService>();

            mockInspectionService.Setup(b => b.CreateInspection(inspection)).Verifiable();
            var mockUserService = new Mock <UserService>();

            mockUserService.Setup(us => us.GetUserLoggedIn(token)).Returns(userDTO);

            InspectionController inspectionController = new InspectionController(mockInspectionService.Object, mockUserService.Object);

            inspectionController.Request = createInspectionControllerRequest();
            this.addTokenHeaderToRequest(inspectionController.Request, token);

            ResponseMessageResult response = (ResponseMessageResult)inspectionController.Post(inspection);

            Assert.AreEqual(HttpStatusCode.OK, response.Response.StatusCode);
        }
Exemplo n.º 9
0
        //ADD
        public void ADD(InspectionDTO dto)
        {
            if (checkRecord("inspection", dto.Id, 1))
            {
                MessageBox.Show("ERROR : No se acepta duplicidad de registros en el sistema!!", "Warn");
            }
            else
            {
                //if (GetRecordById(dto.Id))
                //{
                //    MessageBox.Show("ERROR : No se acepta duplicidad de registros en el sistema!");
                //}
                //else
                //{
                cmd.Connection  = conexion.AbrirConexion();
                cmd.CommandText = "insert into inspection values (@CarId, @CarDetails, @CustomerId, @CustomerDetails, @QuantityOfFuel, @HasRefaction, @HasScratches, @HasCat, @Wheel1, @Wheel2, @Wheel3, @Wheel4, @DateOfInspection,  @InspectorId, @Inspector, @Comment, @Status)";
                cmd.CommandType = CommandType.Text;

                FillDtoParams(cmd, dto);

                cmd.ExecuteNonQuery();

                cmd.Parameters.Clear();
                conexion.CerrarConexion();
            }
        }
Exemplo n.º 10
0
        public void MapInspectionToInspectionDTOTest()
        {
            UserDTO    userDTO    = this.CreateUser();
            UserMapper userMapper = new UserMapper(new RoleDAOImp());
            User       user       = userMapper.ToEntity(userDTO);

            VehicleDTO    vehicleDTO    = new VehicleDTO();
            VehicleMapper vehicleMapper = new VehicleMapper();
            Vehicle       vehicle       = vehicleMapper.ToEntity(vehicleDTO);

            InspectionMapper mapper     = new InspectionMapper();
            Inspection       inspection = new Inspection();

            inspection.Date       = DateTime.Now;
            inspection.IdLocation = new Location(Ports.FIRST_PORT);
            inspection.IdUser     = user;
            inspection.Damages    = new List <Damage>();
            inspection.IdVehicle  = vehicle;

            InspectionDTO inspectionDTO = mapper.ToDTO(inspection);

            Assert.AreEqual(inspectionDTO.Location, inspection.IdLocation.Name);
            Assert.AreEqual(inspectionDTO.Id, inspection.Id);
            Assert.AreEqual(inspectionDTO.Date, inspection.Date);
            Assert.AreEqual(inspectionDTO.CreatorUserName, inspection.IdUser.UserName);
            Assert.AreEqual(inspectionDTO.IdVehicle, inspection.IdVehicle.Vin);
            foreach (DamageDTO damageDTO in inspectionDTO.Damages)
            {
                Assert.IsNotNull(inspection.Damages.Find(d => d.Description == damageDTO.Description));
            }
        }
Exemplo n.º 11
0
        public void TestDuplicateInspectionInspectorLogic()
        {
            using (var context = InitAndGetDbContext())
            {
                //Arrange
                var repositori = new InspectionRepository(context);

                Inspector Inspector1 = new Inspector()
                {
                    Id = Guid.NewGuid(), Name = "Inspector 1", Created = DateTime.Today
                };
                Inspection Inspection1 = new Inspection()
                {
                    Id           = Guid.NewGuid(),
                    Customer     = "Customer 1",
                    Address      = "Address 1",
                    Observations = "Observation 1",
                    Status       = Status.Done,
                    Created      = DateTime.Today
                };
                InspectionInspector relation1 = new InspectionInspector()
                {
                    InspectionDate = DateTime.Today.AddDays(-1), InspectionId = Inspection1.Id, InspectorId = Inspector1.Id
                };
                Inspection1.InspectionInspector = new List <InspectionInspector>()
                {
                    relation1
                };

                repositori.Create(Inspection1);
                context.SaveChanges();

                InspectorDTO inspectorDTO = new InspectorDTO()
                {
                    Id = Inspector1.Id, Name = "Inspector 1"
                };
                InspectionDTO InspectionDTO = new InspectionDTO()
                {
                    Id             = Inspection1.Id,
                    Customer       = "Customer 1",
                    Address        = "Address 1",
                    Observations   = "Observation 1",
                    status         = Status.Done,
                    InspectionDate = relation1.InspectionDate,
                    Inspectors     = new List <InspectorDTO>()
                    {
                        inspectorDTO
                    }
                };


                //Act
                Inspection found = repositori.GetSingleEagerAsync(o => o.Id == InspectionDTO.Id &&
                                                                  o.InspectionInspector.Any(ii => ii.InspectionDate == InspectionDTO.InspectionDate) &&
                                                                  o.InspectionInspector.Any(ii => InspectionDTO.Inspectors.Any(i => i.Id == ii.InspectorId))).Result;

                //Assert
                Assert.NotNull(found);
            }
        }
Exemplo n.º 12
0
        //EDIT
        public void EDIT(InspectionDTO dto)
        {
            cmd.Connection  = conexion.AbrirConexion();
            cmd.CommandText = "update inspection set car_id = @CarId, car_details = @CarDetails, customer_id = @CustomerId, customer_details = @CustomerDetails, quantity_of_fuel = @QuantityOfFuel, has_refaction = @HasRefaction, has_scratches = @HasScratches, has_cat = @HasCat, wheel_1_check = @Wheel1, wheel_2_check = @Wheel2, wheel_3_check = @Wheel3, wheel_4_check = @Wheel4, inspector_id = @InspectorId, inspector = @Inspector, comment = @Comment where id = @Id";
            cmd.CommandType = CommandType.Text;

            FillDtoParams(cmd, dto);

            cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();
            conexion.CerrarConexion();
        }
Exemplo n.º 13
0
        private Guid CreateInspectionInYard(InspectionDTO inspection)
        {
            Guid id = Guid.NewGuid();

            if (inspection.Location == "Patio 1" || inspection.Location == "Patio 2" || inspection.Location == "Patio 3")
            {
                inspectionDAO.AddInspection(inspection);
            }
            else
            {
                throw new InspectionNotFoundException("El lugar de inspección no coincide con el lugar del vehículo");
            }
            return(id);
        }
Exemplo n.º 14
0
        public void ErrorCreateInspectionWithoutTokenTest()
        {
            InspectionDTO inspection = new InspectionDTO();

            var mockInspectionService = new Mock <InspectionService>();

            mockInspectionService.Setup(b => b.CreateInspection(inspection)).Verifiable();

            InspectionController inspectionController = new InspectionController(mockInspectionService.Object, null);

            inspectionController.Request = createInspectionControllerRequest();

            ResponseMessageResult response = (ResponseMessageResult)inspectionController.Post(inspection);

            Assert.AreEqual(HttpStatusCode.BadRequest, response.Response.StatusCode);
        }
Exemplo n.º 15
0
        public void CreateVehicleHistory()
        {
            VehicleHistoryDTO         history  = new VehicleHistoryDTO();
            List <HistoricVehicleDTO> vehicles = new List <HistoricVehicleDTO>();

            HistoricVehicleDTO vehicle = new HistoricVehicleDTO();

            vehicle.Brand           = "Chevrolet";
            vehicle.Model           = "Onyx";
            vehicle.Year            = 2016;
            vehicle.Color           = "Gris";
            vehicle.Type            = "Auto";
            vehicle.Vin             = "TEST1234";
            vehicle.Status          = StatusCode.InPort;
            vehicle.CurrentLocation = "Puerto 1";

            vehicles.Add(vehicle);

            List <InspectionDTO> inspections = new List <InspectionDTO>();
            InspectionDTO        inspection  = new InspectionDTO();

            inspection.CreatorUserName = "******";
            inspection.Date            = DateTime.Now;
            inspection.Location        = "Puerto 1";
            inspection.IdVehicle       = vehicle.Vin;
            inspections.Add(inspection);

            history.VehicleHistory    = vehicles;
            history.InspectionHistory = inspections;

            Assert.AreEqual("Chevrolet", history.VehicleHistory.ElementAt(0).Brand);
            Assert.AreEqual("Onyx", history.VehicleHistory.ElementAt(0).Model);
            Assert.AreEqual(2016, history.VehicleHistory.ElementAt(0).Year);
            Assert.AreEqual("Gris", history.VehicleHistory.ElementAt(0).Color);
            Assert.AreEqual("Auto", history.VehicleHistory.ElementAt(0).Type);
            Assert.AreEqual("TEST1234", history.VehicleHistory.ElementAt(0).Vin);
            Assert.AreEqual("Puerto 1", history.VehicleHistory.ElementAt(0).CurrentLocation);
            Assert.AreEqual("En puerto", history.VehicleHistory.ElementAt(0).Status);

            Assert.AreEqual("pepe123", history.InspectionHistory.ElementAt(0).CreatorUserName);
            Assert.AreEqual(inspection.Date, history.InspectionHistory.ElementAt(0).Date);
            Assert.AreEqual("Puerto 1", history.InspectionHistory.ElementAt(0).Location);
            Assert.AreEqual("TEST1234", history.InspectionHistory.ElementAt(0).IdVehicle);
        }
Exemplo n.º 16
0
        public RentForm(InspectionDTO inspectionDto)
        {
            InitializeComponent();

            //Form
            OnlyViewMode     = false;
            CarTX.Text       = inspectionDto.CarDetails;
            CustomerTX.Text  = inspectionDto.CustomerDetails;
            SaveRentBtn.Text = "Procesar renta";

            //DTO params
            employee     = inspectionDto.Inspector;
            carId        = inspectionDto.CarId;
            carInfo      = inspectionDto.CarDetails;
            customerInfo = inspectionDto.CustomerDetails;
            inspectionId = inspectionDto.Id;

            rentsDV.DataSource = dao.GetActiveRents();
        }
Exemplo n.º 17
0
        public async Task <IActionResult> Update(Guid id, [FromBody] InspectionDTO entity)
        {
            try
            {
                if (entity == null)
                {
                    _logger.LogError("Inspection object sent from client is null.");
                    return(BadRequest("Inspection object is null"));
                }

                if (!ModelState.IsValid)
                {
                    _logger.LogError("Invalid inspection object sent from client.");
                    return(BadRequest("Invalid model object"));
                }

                if (DateTime.Compare(entity.InspectionDate, DateTime.Today) < 0)
                {
                    _logger.LogError("Invalid inspection object sent from client.");
                    return(BadRequest("Can't update an older inspection."));
                }

                Inspection inspection      = _mapper.Map <InspectionDTO, Inspection>(entity);
                Inspection foundInspection = await _unitOfWork.Inspection.FindEagerAsync(inspection.Id);

                if (foundInspection == null)
                {
                    _logger.LogError($"Inspection with id: {id}, hasn't been found in db.");
                    return(NotFound());
                }

                foundInspection.Update(inspection);
                await _unitOfWork.CompleteAsync();

                return(NoContent());
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong inside Update action: {ex.Message}");
                return(StatusCode(500, "Internal server error"));
            }
        }
Exemplo n.º 18
0
        public void ErrorCreateInspectionBadTokenTest()
        {
            InspectionDTO inspection = new InspectionDTO();
            Guid          token      = Guid.NewGuid();

            var mockInspectionService = new Mock <InspectionService>();

            mockInspectionService.Setup(b => b.CreateInspection(inspection)).Verifiable();
            var mockUserService = new Mock <UserService>();

            mockUserService.Setup(us => us.GetUserLoggedIn(token)).Throws(new UserNotExistException());

            InspectionController inspectionController = new InspectionController(mockInspectionService.Object, mockUserService.Object);

            inspectionController.Request = createInspectionControllerRequest();

            ResponseMessageResult response = (ResponseMessageResult)inspectionController.Post(inspection);

            Assert.AreEqual(HttpStatusCode.BadRequest, response.Response.StatusCode);
        }
Exemplo n.º 19
0
        //Fills
        private void FillForm(InspectionDTO dto)
        {
            formTile.Text          = "Formulario de edicion";
            SaveInspectionBtn.Text = "Editar inspeccion";

            inspectionId = dto.Id;

            CarCB.SelectedIndex            = CarCB.FindStringExact(dto.CarDetails);
            CustomerCB.SelectedIndex       = CustomerCB.FindStringExact(dto.CustomerDetails);
            QuantityOfFuelCB.SelectedIndex = QuantityOfFuelCB.FindStringExact(dto.QuantityOfFuel);
            inspector.Text           = dto.Inspector;
            inspectionCommentTX.Text = dto.Comment;
            hasBotiquinChek.Checked  = dto.HasCat;
            hasRefactionChek.Checked = dto.HasRefaction;
            hasScratchesChek.Checked = dto.HasScratches;
            checkLlanta1.Checked     = dto.Wheel1Check;
            checkLlanta2.Checked     = dto.Wheel2Check;
            checkLlanta3.Checked     = dto.Wheel3Check;
            checkLlanta4.Checked     = dto.Wheel4Check;
        }
Exemplo n.º 20
0
        public List <InspectionDTO> GetAllInspections()
        {
            List <InspectionDTO> inspections = new List <InspectionDTO>();

            using (VehicleTrackingDbContext context = new VehicleTrackingDbContext())
            {
                List <Inspection> inspectionsEntities = context.Inspections
                                                        .Include("Damages")
                                                        .Include("IdLocation")
                                                        .Include("IdUser")
                                                        .Include("IdVehicle")
                                                        .ToList();
                foreach (Inspection inspection in inspectionsEntities)
                {
                    InspectionDTO inspectionDTO = this.inspectionMapper.ToDTO(inspection);
                    inspections.Add(inspectionDTO);
                }
            }
            return(inspections);
        }
Exemplo n.º 21
0
        public async Task <IActionResult> Create([FromBody] InspectionDTO entity)
        {
            try
            {
                if (entity == null)
                {
                    _logger.LogError("Inspection object sent from client is null.");
                    return(BadRequest("Inspection object is null"));
                }

                if (!ModelState.IsValid)
                {
                    _logger.LogError("Invalid inspection object sent from client.");
                    return(BadRequest("Invalid model object"));
                }

                Inspection found = await _unitOfWork.Inspection.GetSingleEagerAsync(o => o.Id == entity.Id &&
                                                                                    o.InspectionInspector.Any(ii => ii.InspectionDate == entity.InspectionDate) &&
                                                                                    o.InspectionInspector.Any(ii => entity.Inspectors.Any(i => i.Id == ii.InspectorId)));

                if (found != null)
                {
                    _logger.LogError("Invalid inspection object sent from client.");
                    return(BadRequest("No more than 1 Inspection per day/Inspector"));
                }

                Inspection inspection = _mapper.Map <InspectionDTO, Inspection>(entity);

                _unitOfWork.Inspection.Create(inspection);
                await _unitOfWork.CompleteAsync();

                InspectionDTO inspectionDTO = _mapper.Map <Inspection, InspectionDTO>(inspection);

                return(CreatedAtRoute("InspectionById", new { id = inspectionDTO.Id }, inspectionDTO));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong inside Create action: {ex.Message}");
                return(StatusCode(500, "Internal server error"));
            }
        }
Exemplo n.º 22
0
        public Guid AddInspection(InspectionDTO inspection)
        {
            Inspection inspectionEntity = inspectionMapper.ToEntity(inspection);

            using (VehicleTrackingDbContext context = new VehicleTrackingDbContext())
            {
                inspectionEntity.IdUser = this.GetUser(context, inspection.CreatorUserName);
                Vehicle vehicle = this.GetVehicle(context, inspection.IdVehicle);
                inspectionEntity.IdVehicle  = vehicle;
                inspectionEntity.IdLocation = this.GetLocation(context, inspection.Location);
                inspectionEntity.Damages    = this.GetDamages(context, inspection.Damages);
                inspectionEntity.Date       = DateTime.Now;

                if (vehicle.Status == StatusCode.Waiting)
                {
                    vehicle.Status = StatusCode.ReadyToBeLocated;
                    var entry = context.Entry(vehicle);
                    entry.Property(sz => sz.Status).IsModified = true;

                    HistoricVehicle historicVehicle = mapVehicleToHistoricVehicle(vehicle);
                    context.HistoricVehicles.Add(historicVehicle);
                }
                else if (vehicle.Status == StatusCode.InPort)
                {
                    vehicle.Status = StatusCode.InspectedInPort;
                    var entry = context.Entry(vehicle);
                    entry.Property(sz => sz.Status).IsModified = true;

                    HistoricVehicle historicVehicle = mapVehicleToHistoricVehicle(vehicle);
                    context.HistoricVehicles.Add(historicVehicle);
                }


                context.Users.Attach(inspectionEntity.IdUser);

                context.Inspections.Add(inspectionEntity);
                context.SaveChanges();
            }

            return(inspectionEntity.Id);
        }
Exemplo n.º 23
0
        //-----------------------------------------------------------------------Inspection

        private void FillDtoParams(SqlCommand cmd, InspectionDTO dto)
        {
            cmd.Parameters.AddWithValue("@Id", dto.Id);
            cmd.Parameters.AddWithValue("@CarId", dto.CarId);
            cmd.Parameters.AddWithValue("@CarDetails", dto.CarDetails);
            cmd.Parameters.AddWithValue("@CustomerId", dto.CustomerId);
            cmd.Parameters.AddWithValue("@CustomerDetails", dto.CustomerDetails);
            cmd.Parameters.AddWithValue("@QuantityOfFuel", dto.QuantityOfFuel);
            cmd.Parameters.AddWithValue("@HasRefaction", dto.HasRefaction ? 1 : 0);
            cmd.Parameters.AddWithValue("@HasScratches", dto.HasScratches ? 1 : 0);
            cmd.Parameters.AddWithValue("@HasCat", dto.HasCat ? 1 : 0);
            cmd.Parameters.AddWithValue("@Wheel1", dto.Wheel1Check ? 1: 0);
            cmd.Parameters.AddWithValue("@Wheel2", dto.Wheel2Check ? 1 : 0);
            cmd.Parameters.AddWithValue("@Wheel3", dto.Wheel3Check ? 1 : 0);
            cmd.Parameters.AddWithValue("@Wheel4", dto.Wheel4Check ? 1 : 0);
            cmd.Parameters.AddWithValue("@DateOfInspection", dto.DateOfInspection);
            cmd.Parameters.AddWithValue("@InspectorId", dto.InspectorId);
            cmd.Parameters.AddWithValue("@Inspector", dto.Inspector);
            cmd.Parameters.AddWithValue("@Comment", dto.Comment);
            cmd.Parameters.AddWithValue("@Status", dto.State);
        }
Exemplo n.º 24
0
        public void ExistVehicleInspectionTest()
        {
            InspectionDAO inspectionDAO = new InspectionDAOImp(new VehicleDAOImpl());
            UserDAO       userDAO       = new UserDAOImp();

            List <DamageDTO> damages = this.CreateDamages();
            UserDTO          user    = this.CreateUser();
            VehicleDTO       vehicle = this.CreateVehicle();

            InspectionDTO inspection = new InspectionDTO();

            inspection.Damages         = damages;
            inspection.CreatorUserName = user.UserName;
            inspection.Date            = DateTime.Now;
            inspection.Location        = "Puerto 1";
            inspection.IdVehicle       = vehicle.Vin;

            Guid id = inspectionDAO.AddInspection(inspection);

            Assert.IsTrue(inspectionDAO.ExistVehicleInspection(vehicle.Vin));
        }
Exemplo n.º 25
0
        public IHttpActionResult Get(string id)
        {
            HttpResponseMessage response = new HttpResponseMessage();

            Guid guidId;

            try
            {
                guidId = Guid.Parse(id);
            }
            catch (FormatException)
            {
                string message = "El id enviado no tiene un formato valido.";
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, message);
                return(ResponseMessage(response));
            }
            try
            {
                Guid          token = this.GetToken();
                UserDTO       user  = this.userService.GetUserLoggedIn(token);
                InspectionDTO batch = this.inspectionService.FindInspectionById(guidId);
                response = this.Request.CreateResponse(HttpStatusCode.OK, batch);
            }
            catch (UserNotExistException e)
            {
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
            }
            catch (InvalidOperationException)
            {
                string message = "No se ha enviado header de autenticación.";
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, message);
            }
            catch (FormatException)
            {
                string message = "El token enviado no tiene un formato valido.";
                response = this.Request.CreateResponse(HttpStatusCode.BadRequest, message);
            }

            return(ResponseMessage(response));
        }
Exemplo n.º 26
0
        private void SaveInspectionBtn_Click(object sender, EventArgs e)
        {
            InspectionDTO dto = FillUpDto();

            if (SaveInspectionBtn.Text.Equals("Editar inspeccion"))
            {
                dao.EDIT(dto);
                MessageBox.Show("SUCCESS : editado correctamente!");
                RefreshForm();
            }
            else if (SaveInspectionBtn.Text.Equals("Guardar inspeccion"))
            {
                dao.ADD(dto);
                MessageBox.Show("SUCCESS : vehiculo agregado correctamente!");
                RefreshForm();
            }
            else
            {
                MessageBox.Show("ERROR : probleamas al ejecutar la operacion.");
                RefreshForm();
            }
        }
Exemplo n.º 27
0
        public void CreateVehicleHistory()
        {
            VehicleHistoryDTO         history  = new VehicleHistoryDTO();
            List <HistoricVehicleDTO> vehicles = new List <HistoricVehicleDTO>();

            HistoricVehicleDTO vehicle = new HistoricVehicleDTO();

            vehicle.Brand           = "Chevrolet";
            vehicle.Model           = "Onyx";
            vehicle.Year            = 2016;
            vehicle.Color           = "Gris";
            vehicle.Type            = "Auto";
            vehicle.Vin             = "TEST1234";
            vehicle.Status          = StatusCode.InPort;
            vehicle.CurrentLocation = "Puerto 1";

            vehicles.Add(vehicle);

            List <InspectionDTO> inspections = new List <InspectionDTO>();
            InspectionDTO        inspection  = new InspectionDTO();

            inspection.CreatorUserName = "******";
            inspection.Date            = DateTime.Now;
            inspection.Location        = "Puerto 1";
            inspection.IdVehicle       = vehicle.Vin;
            inspections.Add(inspection);

            history.VehicleHistory    = vehicles;
            history.InspectionHistory = inspections;

            var mockHistoryDAO = new Mock <HistoryDAO>();

            mockHistoryDAO.Setup(h => h.GetHistory("TEST1234")).Returns(history);

            HistoryServiceImp service = new HistoryServiceImp(mockHistoryDAO.Object);

            Assert.IsNotNull(service.GetHistory("TEST1234"));
        }
Exemplo n.º 28
0
        public void ExistVehicleInspectionTest()
        {
            List <DamageDTO> damages = this.CreateDamages();
            UserDTO          user    = this.CreateUser();
            VehicleDTO       vehicle = this.CreateVehicle();

            InspectionDTO inspection = new InspectionDTO();

            inspection.Damages         = damages;
            inspection.CreatorUserName = user.UserName;
            inspection.Date            = DateTime.Now;
            inspection.Location        = "Puerto 1";
            inspection.IdVehicle       = vehicle.Vin;

            var mockInspectionDAO = new Mock <InspectionDAO>();

            mockInspectionDAO.Setup(vs => vs.ExistVehicleInspection(vehicle.Vin)).Returns(true);
            var mockVehicleDAO = new Mock <VehicleDAO>();

            var inspectionService = new InspectionServiceImpl(mockInspectionDAO.Object, mockVehicleDAO.Object);

            Assert.IsTrue(inspectionService.ExistVehicleInspection(vehicle.Vin));
        }
Exemplo n.º 29
0
        public void CreateInspectionSuccessfullyTest()
        {
            List <DamageDTO> damages = this.CreateDamages();
            UserDTO          user    = this.CreateUser();
            VehicleDTO       vehicle = this.CreateVehicle();

            InspectionDTO inspection = new InspectionDTO();

            inspection.Damages         = damages;
            inspection.CreatorUserName = user.UserName;
            inspection.Date            = DateTime.Now;
            inspection.Location        = "Puerto 1";
            inspection.IdVehicle       = vehicle.Vin;

            var mockInspectionDAO = new Mock <InspectionDAO>();

            mockInspectionDAO.Setup(vs => vs.FindInspectionById(inspection.Id)).Returns(inspection);
            var mockVehicleDAO = new Mock <VehicleDAO>();

            mockVehicleDAO.Setup(vs => vs.FindVehicleByVin(inspection.IdVehicle)).Returns(vehicle);

            var inspectionService = new InspectionServiceImpl(mockInspectionDAO.Object, mockVehicleDAO.Object);

            Guid id = inspectionService.CreateInspection(inspection);

            InspectionDTO resultInspection = inspectionService.FindInspectionById(inspection.Id);

            Assert.AreEqual(inspection.CreatorUserName, resultInspection.CreatorUserName);
            Assert.AreEqual(inspection.Date, resultInspection.Date);
            Assert.AreEqual(inspection.Id, resultInspection.Id);
            Assert.AreEqual(inspection.Location, resultInspection.Location);
            Assert.AreEqual(inspection.IdVehicle, resultInspection.IdVehicle);
            foreach (DamageDTO damage in inspection.Damages)
            {
                Assert.IsNotNull(resultInspection.Damages.Find(d => d.Description == damage.Description));
            }
        }
Exemplo n.º 30
0
        public VehicleHistoryDTO GetHistory(string vin)
        {
            VehicleHistoryDTO      historyDTO          = null;
            List <HistoricVehicle> historicVehicles    = null;
            List <Inspection>      historicInspections = null;

            using (VehicleTrackingDbContext context = new VehicleTrackingDbContext())
            {
                historicVehicles = context.HistoricVehicles
                                   .Where(hv => hv.Vin == vin)
                                   .ToList();

                historicInspections = context.Inspections
                                      .Include("IdUser")
                                      .Include("IdLocation")
                                      .Include("Damages")
                                      .Include("IdVehicle")
                                      .Where(i => i.IdVehicle.Vin == vin)
                                      .ToList();

                if ((historicVehicles != null && historicVehicles.Count > 0) || (historicInspections != null && historicInspections.Count > 0))
                {
                    historyDTO = new VehicleHistoryDTO();

                    if (historicVehicles != null && historicVehicles.Count > 0)
                    {
                        List <HistoricVehicleDTO> historicVehiclesDTO = new List <HistoricVehicleDTO>();
                        foreach (HistoricVehicle historicVehicle in historicVehicles)
                        {
                            HistoricVehicleDTO historicVehicleDTO = new HistoricVehicleDTO();
                            historicVehicleDTO.Brand           = historicVehicle.Brand;
                            historicVehicleDTO.Color           = historicVehicle.Color;
                            historicVehicleDTO.CurrentLocation = historicVehicle.CurrentLocation;
                            historicVehicleDTO.Date            = historicVehicle.Date;
                            historicVehicleDTO.Model           = historicVehicle.Model;
                            historicVehicleDTO.Status          = historicVehicle.Status;
                            historicVehicleDTO.Type            = historicVehicle.Type;
                            historicVehicleDTO.Vin             = historicVehicle.Vin;
                            historicVehicleDTO.Year            = historicVehicle.Year;

                            historicVehiclesDTO.Add(historicVehicleDTO);
                        }
                        historyDTO.VehicleHistory = historicVehiclesDTO;
                    }

                    if (historicInspections != null && historicInspections.Count > 0)
                    {
                        List <InspectionDTO> historicInspectionsDTO = new List <InspectionDTO>();
                        InspectionMapper     inspectionMapper       = new InspectionMapper();

                        foreach (Inspection historicInspection in historicInspections)
                        {
                            InspectionDTO historicInspectionDTO = inspectionMapper.ToDTO(historicInspection);
                            historicInspectionsDTO.Add(historicInspectionDTO);
                        }

                        historyDTO.InspectionHistory = historicInspectionsDTO;
                    }
                }
            }

            return(historyDTO);
        }