public async Task <IActionResult> CreatStopForTrip(int tripId, [FromBody] StopForCreationModel stop)
        {
            if (stop == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(new CoreHelpers.Validations.UnprocessableEntityObjectResult(ModelState));
            }

            if (!_repository.TripExists(tripId))
            {
                return(NotFound());
            }
            var stopEntity = _mapper.Map <Stop>(stop);

            stopEntity.TripId = tripId;
            _repository.Add(stopEntity);

            if (!await _repository.SaveChangesAsync())
            {
                throw new Exception($"Creating a stop for trip {tripId} failed on save");
            }

            var stopToReturn = _mapper.Map <StopModel>(stopEntity);

            return(CreatedAtRoute("GetStopForTrip",
                                  new { tripId = tripId, id = stopToReturn.Id },
                                  stopToReturn));
        }
        public async void ShouldSaveTrip()
        {
            //Given
            var trip = Trips[0];

            //When
            trip = await Repository.Add(trip);

            //Then
            Assert.NotNull(trip);
            Assert.Equal(1, trip.Key);
        }
Exemple #3
0
        public async Task <IActionResult> CreateTripsCollection(IEnumerable <TripForCreationModel> tripCollection)
        {
            if (tripCollection == null)
            {
                return(BadRequest());
            }
            var tripEntities = _mapper.Map <ICollection <Trip> >(tripCollection);

            foreach (var trip in tripEntities)
            {
                _repository.Add(trip);
            }

            if (!await _repository.SaveChangesAsync())
            {
                throw new Exception("Creating an trip collection failed on save");
            }

            var tripCollectionToReturn = _mapper.Map <IEnumerable <TripModel> >(tripEntities);
            var idAsString             = string.Join(",", tripCollectionToReturn.Select(t => t.Id));

            //TODO: Uncoment when null Model in ModelBindingContext will be fixed

            //return CreatedAtRoute("GetTripCollection",
            //    new { ids = idAsString },
            //    tripCollectionToReturn);
            return(Ok());
        }
Exemple #4
0
 //Add trip
 public void AddTrip(string destination, string arrival, DateTime arrivalTime, DateTime destinationTime)
 {
     tripRepository.Add(new Trip()
     {
         TripId      = Guid.NewGuid(), Arrival = arrival, Destination = destination,
         ArrivalTime = arrivalTime, DestinationTime = destinationTime
     });
 }
Exemple #5
0
        public async Task Add(AddTripInput input)
        {
            var result = await _tripRepository.Add(input);

            var trip = await _tripRepository.GetById(id : result);

            _outputPort.Ok(trip);
        }
Exemple #6
0
        public async Task <IActionResult> Trip(int?id)
        {
            var user = await _userManager.GetUserAsync(User);

            if (id == null)
            {
                if (user.Status != UserStatus.Trip)
                {
                    return(RedirectToAction("Map"));
                }
                else
                {
                    var trip = _tripRepository.GetTrip(user.Id);

                    return(View(trip));
                }
            }
            else
            {
                if (user.Status == UserStatus.Trip)
                {
                    return(RedirectToAction("Trip", new { id = "" }));
                }
                else if (user.Status != UserStatus.Stays)
                {
                    return(RedirectToAction("Map"));
                }

                var location = _locationRepository.GetLocations().SingleOrDefault(x => x.Id == id);

                if (location == null)
                {
                    ViewBag.ErrorMessage = $"Nie można znaleźć lokacji o Id: '{id}'.";
                    return(View("NotFound"));
                }

                var distance = Math.Round(Math.Sqrt(Math.Pow((user.PositionX - location.X), 2) + Math.Pow((user.PositionY - location.Y), 2)) * 100, 1);

                var trip = new Trip()
                {
                    UserId   = user.Id,
                    Start    = DateTime.UtcNow,
                    End      = DateTime.UtcNow + TimeSpan.FromSeconds((distance / 100) * 300),
                    X        = location.X,
                    Y        = location.Y,
                    Distance = (int)distance
                };

                user.Status = UserStatus.Trip;
                await _userManager.UpdateAsync(user);

                _tripRepository.Add(trip);

                return(RedirectToAction("Trip"));
            }
        }
Exemple #7
0
        public ActionResult ProcessarDados(TripViewModel tripViewModel)
        {
            _tripRepository.Add(_mapper.Map <Trip>(new TripViewModel()
            {
                IdRick = tripViewModel.IdRick, IdDimensao = tripViewModel.IdDimensao, Descricao = tripViewModel.Descricao
            }));


            return(Redirect("Index"));
        }
Exemple #8
0
        public TripDto Checkin()
        {
            var trip = new Trip
            {
                TripIdentifier = Guid.NewGuid().ToString()
            };

            _tripRepository.Add(trip);

            return(DtoMapper.ConvertTripToDto(trip));
        }
Exemple #9
0
 public void AddTrip(TripRecord trip)
 {
     try
     {
         m_tripRepository.Add(trip);
         ;
     }
     catch (Common.TripDBException ex)
     {
         throw new Common.TripDBException(ex.Message);
     }
 }
Exemple #10
0
        public ActionResult Create([Bind(Include = "TripID,Date,CostPerHead,PlaceID")] Trip trip)
        {
            if (ModelState.IsValid)
            {
                _tripRepository.Add(trip);
                _unitOfWork.Commit();
                return(RedirectToAction("Index"));
            }

            ViewBag.PlaceID = new SelectList(_placeRepository.GetAll(), "PlaceID", "Name", trip.PlaceID);
            return(View(trip));
        }
Exemple #11
0
        public Result Execute(CreateAndUpdateTripModel model, Guid userId)
        {
            var user = _userRepository.Get(userId);

            var trip = new Trip(user, model.From, model.To, model.StartingTime, model.FinishTime, model.Price, model.Seats, model.OnlyTwo);

            trip.AddComment(model.Comment);

            _tripRepository.Add(trip);

            _unitOfWork.Save();

            return(Result.Ok());
        }
Exemple #12
0
        public async Task <IActionResult> PostAsync([FromBody] TripDTO value)
        {
            var now = DateTime.Now;

            var existingTask = TripRepository.Find(value.AlternateKey);

            var trip = Mapper.Map <Trip>(value);

            trip.FirstSeen = trip.LastSeen = now;

            // Get the reference properties set up
            var vehicleTask = VehicleRepository.Find(value.VehicleName);
            var endDateTask = CalendarRepository.Find(value.EndTime);
            var companyTask = CompanyRepository.Find(value.CompanyName);

            // await this first before finding the next date
            trip.EndDateKey = (await endDateTask).Key;
            var startDateTask = CalendarRepository.Find(value.StartTime);

            trip.CompanyKey = (await companyTask).Key;

            trip.StartDateKey = (await startDateTask).Key;

            var vehicle = await vehicleTask ?? await VehicleRepository.Add(new Vehicle { Name = value.VehicleName });

            trip.VehicleKey = vehicle.Key;

            var existing = await existingTask;

            if (existing != null)
            {
                trip.Key       = existing.Key;
                trip.FirstSeen = existing.FirstSeen == DateTime.MinValue ? now : existing.FirstSeen;
            }

            var upsertTask = existing == null?TripRepository.Add(trip, false) : TripRepository.Update(trip, false);

            try
            {
                await upsertTask;
                await TripRepository.SaveChanges();
            }
            catch (Exception e)
            {
                Logger.LogError("Error adding trip:\n{message}\n{inner}", e.Message, e.InnerException?.Message);
                return(BadRequest(e.ToString()));
            }
            return(Ok(Mapper.Map <TripDTO>(trip)));
        }
        public async Task <Response> Create(string passengerName, string date, string time, string origin, string destination)
        {
            ValidateEntity(passengerName, date, time, origin, destination);

            if (!IsValid())
            {
                _response.AddNotifications(Notifications);
                return(_response);
            }


            var trip = await _tripRepository.Add(new Domain.Entities.Trip(passengerName, GetDate(date), GetTime(time), origin, destination));

            _response.AddValue(trip);
            return(_response);
        }
        public Trip Add(Trip addedTrip)
        {
            if (addedTrip.ProjectName == "")
            {
                addedTrip.ProjectName = "Not set!";
            }

            if (addedTrip.TaskName == "")
            {
                addedTrip.TaskName = "Not set!";
            }

            addedTrip.Status = 2;

            return(tripRepository.Add(addedTrip));
        }
        public IActionResult Create([FromBody] Trip Trip)
        {
            try
            {
                if (Trip == null || !ModelState.IsValid)
                {
                    return(BadRequest("Invalid State"));
                }

                TripRepository.Add(Trip);
            }
            catch (Exception)
            {
                return(BadRequest("Error while creating"));
            }
            return(Ok(Trip));
        }
Exemple #16
0
        public void Add_Any_Modify()
        {
            //Arrange
            IList <Trip> trips = new List <Trip>();

            Mock <ITripRepository> MockTripRepository = new Mock <ITripRepository>();

            TripRepositorySetupMoq.Add(MockTripRepository, trips);
            TripRepositorySetupMoq.GetAll(MockTripRepository, trips);
            ITripRepository tripRepository = MockTripRepository.Object;

            //Act
            Trip         trip        = new Trip();
            Trip         result      = tripRepository.Add(trip);
            IList <Trip> findedTrips = tripRepository.GetAll();

            //Assert
            Assert.AreEqual(result, trip);
            Assert.AreEqual(findedTrips.Count, trips.Count);
        }
        public ActionResult <int> PostTrip([FromBody] TripDTO tripDTO)
        {
            if (!ModelState.IsValid || tripDTO == null)
            {
                return(BadRequest("Invalid model"));
            }

            IdentityUser currentUser = GetCurrentUser();

            if (currentUser == null)
            {
                return(BadRequest());
            }

            Trip tripToCreate = new Trip(tripDTO, currentUser);

            _tripRepository.Add(tripToCreate);
            _tripRepository.SaveChanges();
            return(Ok(tripToCreate.Id));
        }
Exemple #18
0
        private async Task <IActionResult> AddSpecificTrip <T>(T trip) where T : class
        {
            if (trip == null)
            {
                return(BadRequest());
            }

            var tripEntity = _mapper.Map <Trip>(trip);

            _repository.Add(tripEntity);

            if (!await _repository.SaveChangesAsync())
            {
                throw new Exception("Creating a trip failed on save");
            }

            var tripToReturn = _mapper.Map <Trip>(tripEntity);


            return(CreatedAtRoute("GetTrip", new { tripCode = tripToReturn.Id }, tripToReturn));
        }
Exemple #19
0
        public async Task <Trip> CreateAsync(Trip trip)
        {
            if (trip.Id != 0)
            {
                throw new ArgumentException("The Id must be 0", nameof(trip.Id));
            }

            Traveler traveler = await travelerRepository.GetByIdAsync(trip.IdDriver);

            if (traveler == null)
            {
                throw new TravelerNotExistException($"'{trip.IdDriver}' doesn´t exists");
            }

            if (!traveler.IsDriver)
            {
                throw new TravelerIsNotDriverException($"The traveler '{traveler.Id} - {traveler.Name}' not is a driver");
            }

            trip = tripRepository.Add(trip);
            await tripRepository.UnitOfWork.SaveChangesAsync();

            return(trip);
        }
 public Trip Add(Trip trip)
 {
     _tripRepository.Add(trip);
     return(trip);
 }
        public async Task <IActionResult> Post([FromBody] TripReserveDto tripReserveDto)
        {
            await _HubContext.Clients.All.SendAsync("Driver", "Hello From Another Application");

            return(Ok());


            string userId      = User.FindFirstValue(ClaimTypes.NameIdentifier);
            string userRole    = User.FindFirstValue(ClaimTypes.Role);
            var    currentUser = await this.userRepository.FindOneById(int.Parse(userId));

            if (currentUser == null || currentUser.Role.ToString() != userRole.ToString())
            {
                return(Unauthorized());
            }

            var originPoint = new Point(tripReserveDto.OriginLocation.Lat, tripReserveDto.OriginLocation.Lng)
            {
                SRID = 4326
            };
            var destinationPoint = new Point(tripReserveDto.DistanceLocation.Lat, tripReserveDto.DistanceLocation.Lng)
            {
                SRID = 4326
            };
            var trip = await this.tripRepository.FindTripNearestByLocation(originPoint, destinationPoint);

            var originPlace = new Place {
                Location = originPoint, Name = tripReserveDto.OriginAddress
            };
            var destantPlace = new Place {
                Location = destinationPoint, Name = tripReserveDto.DistantAddress
            };


            if (trip == null)
            {
                Driver driver = await this.driverRepository.FindAnyDriver();

                await _HubContext.Clients.All.SendAsync("Driver", "Hello From Another Application");

                return(Ok());

                if (driver == null)
                {
                    return(UnprocessableEntity());
                }
                else
                {
                    var newTrip = new Trip
                    {
                        StartLocation = originPlace,
                        FinalLocation = destantPlace,
                        DriverId      = driver.Id,
                        Status        = Models.enums.TripStatus.PICKING_USER,
                    };
                    tripRepository.Add(newTrip);
                    await this.tripRepository.SaveAll();

                    var clientInTrip = new ClientTrip()
                    {
                        ClientId     = currentUser.Id,
                        Status       = Models.enums.ClientTripStatus.WAITING_FOR_DRIVER,
                        FromLocation = originPlace,
                        ToLocation   = destantPlace,
                        StartedAt    = DateTime.Now,
                    };

                    newTrip.Clients.Add(clientInTrip);
                    tripRepository.Add(newTrip);
                    await this.tripRepository.SaveAll();

                    var point = new ClientTripPointAtTime {
                        ClientId = currentUser.Id, TripId = newTrip.Id, Location = originPoint, Time = DateTime.Now
                    };


                    clientInTrip.Points.Add(point);

                    clientTripRepository.Add(clientInTrip);
                    await this.clientTripRepository.SaveAll();

                    var expectedPoints = TripHelper.convertFromDirectionToListOfExpectedRoutes(
                        await getDirectionInfo(new TripCheckQuery {
                        OriginLat = tripReserveDto.OriginLocation.Lat, OriginLng = tripReserveDto.OriginLocation.Lng, DestinationLat = tripReserveDto.DistanceLocation.Lat, DestinationLng = tripReserveDto.DistanceLocation.Lng
                    })
                        );

                    //trip.ExpectedRoad = expectedPoints;

                    tripRepository.Add(newTrip);


                    if (await tripRepository.SaveAll())
                    {
                        return(Ok(trip));
                    }
                    else
                    {
                        return(StatusCode(500));
                    }
                }
            }
            else
            {
                var clientInTrip = new ClientTrip()
                {
                    ClientId     = currentUser.Id,
                    Status       = Models.enums.ClientTripStatus.WAITING_FOR_DRIVER,
                    FromLocation = originPlace,
                    ToLocation   = destantPlace,
                    StartedAt    = DateTime.Now
                };

                var point = new ClientTripPointAtTime {
                    ClientId = currentUser.Id, TripId = trip.Id, Location = originPoint, Time = DateTime.Now
                };


                clientInTrip.Points.Add(point);

                trip.Clients.Add(clientInTrip);
                trip.Status = Models.enums.TripStatus.ANOTHER_CLIENT;
                tripRepository.Update(trip);

                if (await tripRepository.SaveAll())
                {
                    return(Ok(trip));
                }
                else
                {
                    return(StatusCode(500));
                }
            }
        }
Exemple #22
0
 public bool Add(Trip trip)
 {
     return(_tripRepository.Add(trip));
 }
 public async Task CreateTrip(Trip trip)
 {
     _repo.Add(trip);
     await _uow.CommitAsync();
 }
Exemple #24
0
 public void CreateTrip(Trip Trip)
 {
     TripRepository.Add(Trip);
 }