Exemple #1
0
 public ServiceOperationResult ResetPassword(string email, string password, string token)
 {
     using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
     {
         var account = dbContext.Accounts
                       .FirstOrDefault(acc => acc.Email == email);
         if (account.ResetPasswordCode != null && account.ResetPasswordCode.ToString() == token)
         {
             account.Password = PasswordHash.CreateHash(password);
             dbContext.SaveChanges();
             return(new ServiceOperationResult()
             {
                 IsSuccessfull = true
             });
         }
         else
         {
             return(new ServiceOperationResult()
             {
                 IsSuccessfull = false,
                 Errors = new List <ErrorCodes>()
                 {
                     ErrorCodes.UnKnown
                 }
             });
         }
     }
 }
Exemple #2
0
        public ServiceOperationResult ChangePassword(string oldPassword, string newPassword)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var account = dbContext.Accounts.FirstOrDefault(acc => acc.Id == _accountId);

                if (PasswordHash.ValidatePassword(oldPassword, account.Password))
                {
                    account.Password = PasswordHash.CreateHash(newPassword);
                    dbContext.SaveChanges();

                    return(new ServiceOperationResult()
                    {
                        IsSuccessfull = true
                    });
                }
                else
                {
                    return(new ServiceOperationResult()
                    {
                        IsSuccessfull = false, Errors = new List <ErrorCodes>()
                        {
                            ErrorCodes.InvalidPassword
                        }
                    });
                }
            }
        }
        public List <Aircraft> SetAircraftUnavailable(Guid aircraftId)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var aircraft = dbContext.Aircrafts
                               .FirstOrDefault(a => a.Id == aircraftId);

                var availabilities = dbContext.AircraftsAvailability
                                     .Where(av => av.AircraftId == aircraftId);

                var emptyLegs = dbContext.EmptyLegs
                                .Where(el => el.AircraftId == aircraftId);

                foreach (var availability in availabilities)
                {
                    availability.Available = false;
                }

                foreach (var leg in emptyLegs)
                {
                    leg.Available = false;
                }

                dbContext.Aircrafts.Attach(aircraft);

                aircraft.Available = false;

                dbContext.SaveChanges();

                return(GetProviderAircrafts());
            }
        }
Exemple #4
0
        public ServiceOperationResult VerifyAccount(string token)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var account = dbContext.Accounts
                              .FirstOrDefault(acc => acc.VerificationCode == token);

                //account is present, meaning user has signed up
                if (account != null)
                {
                    account.Status = (byte)AccountStatuses.Active;
                    try {
                        dbContext.SaveChanges();
                    } catch (DbUpdateException e) {
                        throw e;
                    }
                    return(new ServiceOperationResult()
                    {
                        IsSuccessfull = true
                    });
                }
                else
                {
                    return(new ServiceOperationResult()
                    {
                        IsSuccessfull = false,
                        Errors = new List <ErrorCodes>()
                        {
                            ErrorCodes.NotFound
                        }
                    });
                }
            }
        }
Exemple #5
0
        public ServiceOperationResult AddMember(string firstName, string lastName, string email, string mobile,
                                                string address)
        {
            ServiceOperationResult result = new ServiceOperationResult();

            result.IsSuccessfull = true;

            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var accountId = Guid.Parse(_httpContextAccessor.HttpContext.User.Identity.Name);

                var member = new AccountFamilyMember()
                {
                    Id        = Guid.NewGuid(),
                    FirstName = firstName,
                    LastName  = lastName,
                    Email     = email,
                    Mobile    = mobile,
                    Address   = address,
                    AccountId = accountId,
                    CreatedOn = DateTime.UtcNow
                };

                dbContext.AccountFamilyMembers.Add(member);
                dbContext.SaveChanges();

                return(result);
            }
        }
        public ServiceOperationResult Create(int departureId, int arrivalId, DateTime departureDate, DateTime?arrivalDate, byte bookingType, int passengers)
        {
            var result = new ServiceOperationResult();

            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var newSearch = new SearchHistory()
                {
                    Id            = Guid.NewGuid(),
                    FlyerId       = _accountId,
                    DepartureId   = departureId,
                    DepartureDate = departureDate,
                    ArrivalId     = arrivalId,
                    ArrivalDate   = arrivalDate,
                    BookingType   = bookingType,
                    CreatedOn     = DateTime.UtcNow,
                    Passengers    = passengers
                };

                dbContext.SearchHistories.Add(newSearch);
                try {
                    dbContext.SaveChanges();
                    result.IsSuccessfull = true;
                } catch (Exception e)
                {
                    result.IsSuccessfull = false;
                    result.Errors        = new List <ErrorCodes>()
                    {
                        ErrorCodes.UnKnown
                    };
                }
            }
            return(result);
        }
        public void NewCreate(Guid receiverId, NotificationsTypes type, string text, List <NotificationParam> @params)
        {
            var newNotification = PrepareNotification(receiverId, type, text, @params);

            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                //send notification to database
                dbContext.Notifications.Add(newNotification);

                dbContext.SaveChanges();
            }
            //get list of unread notifications
            /* GetNotifications(receiverId); */
        }
        public List <AircraftAvailability> SetAvailabilityUnavailable(Guid availabilityId)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var availability = dbContext.AircraftsAvailability
                                   .FirstOrDefault(a => a.Id == availabilityId);

                dbContext.AircraftsAvailability.Attach(availability);

                availability.Available = false;

                dbContext.SaveChanges();

                return(GetAvailability());
            }
        }
        public List <EmptyLeg> SetLegUnavailable(Guid emptyLegId)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var emptyLeg = dbContext.EmptyLegs
                               .FirstOrDefault(leg => leg.Id == emptyLegId);

                dbContext.EmptyLegs.Attach(emptyLeg);

                emptyLeg.Available = false;

                dbContext.SaveChanges();

                return(GetList());
            }
        }
        public void SetRead(string text)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var query = dbContext.Notifications
                            .Where(notification => notification.Text == text)
                            .ToArray();

                foreach (var notification in query)
                {
                    notification.Read = true;
                }

                dbContext.SaveChanges();
                GetNotifications(adminId);
            }
        }
Exemple #11
0
        public void UpdateNotificationChannel(byte?channel)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var account = new Account()
                {
                    Id = _accountId,
                    NotificationsChannel = channel
                };

                dbContext.Accounts.Attach(account);
                dbContext.Entry(account).Property(x => x.NotificationsChannel).IsModified = true;

                //dbContext.Configuration.ValidateOnSaveEnabled = false;
                dbContext.SaveChanges();
            }
        }
        public ServiceOperationResult <EmptyLeg> Create(Guid aircraftId, byte direction, int departureAirportId,
                                                        int arrivalAirportId, DateTime departureDate, DateTime?returnDate, decimal exclusiveCost)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                ServiceOperationResult <EmptyLeg> result = new ServiceOperationResult <EmptyLeg>();
                result.IsSuccessfull = true;

                var departure = _locationService.GetLocation(departureAirportId);
                var arrival   = _locationService.GetLocation(arrivalAirportId);

                var distance = Utilities.GetDistance(departure.Lat.Value, departure.Lng.Value,
                                                     arrival.Lat.Value, arrival.Lng.Value);

                var aircraftSpeed = (from aircraft in dbContext.Aircrafts
                                     where aircraft.Id == aircraftId
                                     select aircraft.Speed)
                                    .First();

                var duration = FlightService.CalculateFlightDuration(distance, aircraftSpeed);

                EmptyLeg emptyLeg = new EmptyLeg()
                {
                    Id                 = Guid.NewGuid(),
                    AircraftId         = aircraftId,
                    Direction          = direction,
                    DepartureAirportId = departureAirportId,
                    ArrivalAirportId   = arrivalAirportId,
                    DepartureDate      = departureDate,
                    ReturnDate         = returnDate,
                    ExclusiveCost      = exclusiveCost,
                    Distance           = distance,
                    Duration           = duration,
                    CreatedById        = _accountId,
                    CreatedOn          = DateTime.UtcNow,
                    Available          = true
                };

                dbContext.EmptyLegs.Add(emptyLeg);
                dbContext.SaveChanges();

                result.Item = emptyLeg;

                return(result);
            }
        }
Exemple #13
0
        public Flight CreateCharterAircraftFlight(Guid aircraftId, int departureId, DateTime departureDate, TimeSpan?departureTime,
                                                  int arrivalId, DateTime arrivalDate, TimeSpan?arrivalTime, byte order, short numberOfBookedSeats, byte flightType)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var aircraft = dbContext.Aircrafts
                               .First(a => a.Id == aircraftId);

                var departure = _locationService.GetLocation(departureId);
                var arrival   = _locationService.GetLocation(arrivalId);

                var distance = Utilities.GetDistance(departure.Lat.Value, departure.Lng.Value,
                                                     arrival.Lat.Value, arrival.Lng.Value);

                var duration = CalculateFlightDuration(distance, aircraft.Speed);

                var newFlight = new Flight()
                {
                    Id                     = Guid.NewGuid(),
                    Number                 = aircraft.TailNumber,
                    AircraftId             = aircraft.Id,
                    DepartureId            = departureId,
                    DepartureDate          = departureDate,
                    DepartureTime          = departureTime,
                    ArrivalId              = arrivalId,
                    ArrivalDate            = arrivalDate,
                    ArrivalTime            = arrivalTime,
                    Duration               = duration,
                    Distance               = distance,
                    NumberOfSeats          = aircraft.MaxPassengers,
                    NumberOfSeatsAvailable = (short)(aircraft.MaxPassengers - numberOfBookedSeats),
                    Order                  = order,
                    FlightType             = flightType,
                    Status                 = (byte)BookingFlightStatuses.OnSchedule,
                    CreatedOn              = DateTime.UtcNow,
                    CreatedById            = _accountId
                };

                dbContext.Flights.Add(newFlight);

                dbContext.SaveChanges();

                return(newFlight);
            }
        }
        public ServiceOperationResult <EmptyLeg> Update(Guid emptyLegId, Guid aircraftId, byte direction, int departureAirportId,
                                                        int arrivalAirportId, DateTime departureDate, DateTime?returnDate, decimal exclusiveCost)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                ServiceOperationResult <EmptyLeg> result = new ServiceOperationResult <EmptyLeg>();
                result.IsSuccessfull = true;

                var departure = _locationService.GetLocation(departureAirportId);
                var arrival   = _locationService.GetLocation(arrivalAirportId);

                var distance = Utilities.GetDistance(departure.Lat.Value, departure.Lng.Value,
                                                     arrival.Lat.Value, arrival.Lng.Value) / 1852;

                var aircraftSpeed = (from aircraft in dbContext.Aircrafts
                                     where aircraft.Id == aircraftId
                                     select aircraft.Speed)
                                    .First();

                var duration = FlightService.CalculateFlightDuration(distance, aircraftSpeed);

                EmptyLeg emptyLeg = dbContext.EmptyLegs
                                    .First(el => el.Id == emptyLegId);

                emptyLeg.AircraftId         = aircraftId;
                emptyLeg.Direction          = direction;
                emptyLeg.DepartureAirportId = departureAirportId;
                emptyLeg.ArrivalAirportId   = arrivalAirportId;
                emptyLeg.DepartureDate      = departureDate;
                emptyLeg.ReturnDate         = returnDate;
                emptyLeg.ExclusiveCost      = exclusiveCost;
                emptyLeg.Distance           = distance;
                emptyLeg.Duration           = duration;

                dbContext.SaveChanges();

                result.Item = emptyLeg;

                return(result);
            }
        }
Exemple #15
0
        public ServiceOperationResult DeleteMember(Guid memberId)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                ServiceOperationResult result = new ServiceOperationResult();
                result.IsSuccessfull = true;

                var accountId = Guid.Parse(_httpContextAccessor.HttpContext.User.Identity.Name);

                var member = new AccountFamilyMember()
                {
                    Id        = memberId,
                    AccountId = accountId
                };

                dbContext.Entry(member).State = EntityState.Deleted;
                dbContext.SaveChanges();

                return(result);
            }
        }
Exemple #16
0
        public void ForgotPassword(string email)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var account = dbContext.Accounts
                              .FirstOrDefault(acc => acc.Email == email);

                string credEmail = _config.GetSection("CredentialEmail").Value;
                string credPass  = _config.GetSection("CredentialPassword").Value;
                if (account != null)
                {
                    //set reset token for later use
                    account.ResetPasswordCode = Guid.NewGuid().ToString();

                    //get rid of old password temporarily
                    account.Password = Guid.NewGuid().ToString();

                    string receiverName = string.Join(account.FirstName, " ", account.LastName);
                    string message      = string.Format("Your password has been reset. please visit {0}/app/ForgotPassword/{1} to reset it again. This reset token will expire in 10 minutes", _config.GetSection("MailerUrl").Value, account.ResetPasswordCode);

                    _mailerService.Send(email, receiverName, message, "Reset your FLYJETS password", credEmail, credPass);

                    //this is a biiiiiig O O F but it works.
                    Timer passwordResetTimeout = new Timer((object state) => {
                        using (FlyJetsDbContext _dbContext = new FlyJetsDbContext(_config))
                        {
                            var __account = _dbContext.Accounts
                                            .FirstOrDefault(acc => acc.Email == email);
                            __account.ResetPasswordCode = null;
                            _dbContext.SaveChanges();
                        }
                    }, null, 600000, Timeout.Infinite);
                    dbContext.SaveChanges();
                }
                else
                {
                    _mailerService.Send(email, "To Whom it May Concern", "We did not find a FLYJETS account associated with this email address.", "Reset your FLYJETS password", credEmail, credPass);
                }
            }
        }
Exemple #17
0
        public Account GetAccount(string email, string password)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var account = dbContext.Accounts.FirstOrDefault(acc => acc.Email == email);

                if (account == null)
                {
                    return(null);
                }

                if (account.ManagedByFlyJets && account.PasswordExpired)
                {
                    return(null);
                }

                if (PasswordHash.ValidatePassword(password, account.Password))
                {
                    account.LastLogInDate     = DateTime.UtcNow;
                    account.ResetPasswordCode = null;

                    if (account.ManagedByFlyJets)
                    {
                        account.PasswordExpired = true;
                        string newPassword = GenerateRandomPassword(16);

                        account.Password = PasswordHash.CreateHash(newPassword);
                    }

                    dbContext.SaveChanges();

                    return(account);
                }
                else
                {
                    return(null);
                }
            }
        }
Exemple #18
0
        private Customer GetStripeCustomer()
        {
            Data.Account currentAccount;

            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                currentAccount = (from account in dbContext.Accounts
                                  where account.Id == _accountId
                                  select account)
                                 .FirstOrDefault();


                var customerService = new CustomerService();

                if (string.IsNullOrEmpty(currentAccount.StripeCustomerId))
                {
                    var customerOptions = new CustomerCreateOptions
                    {
                        Email    = currentAccount.Email,
                        Metadata = new Dictionary <string, string>()
                        {
                            { "AccountId", currentAccount.Id.ToString() }
                        }
                    };

                    Customer customer = customerService.Create(customerOptions);

                    currentAccount.StripeCustomerId = customer.Id;
                    dbContext.SaveChanges();

                    return(customer);
                }
                else
                {
                    return(customerService.Get(currentAccount.StripeCustomerId));
                }
            }
        }
Exemple #19
0
        public ServiceOperationResult AcceptAircraftProviderSignupRequest(Guid accountId)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var result = new ServiceOperationResult();

                var account = dbContext.Accounts
                              .First(acc => acc.Id == accountId);

                account.Status = (byte)AccountStatuses.Active;
                dbContext.SaveChanges();

                result.IsSuccessfull = true;

                string receiverName = string.Join(account.FirstName, " ", account.LastName);
                string credEmail    = _config.GetSection("CredentialEmail").Value;
                string credPass     = _config.GetSection("CredentialPassword").Value;
                string message      = string.Format("Thank you for your patience. Your request to join FLYJETS has been approved. Please visit {0} to log in and begin booking.", _config.GetSection("MailerUrl").Value);

                _mailerService.Send(account.Email, receiverName, message, "Welcome to FLYJETS!", credEmail, credPass);

                return(result);
            }
        }
Exemple #20
0
        public string CreateAircraftProviderOneTimePassword(Guid accountId)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var account = dbContext.Accounts
                              .FirstOrDefault(acc => acc.Id == accountId &&
                                              acc.Type == (byte)AccountTypes.AircraftProvider &&
                                              acc.ManagedByFlyJets == true);

                if (account == null)
                {
                    return(string.Empty);
                }

                var password = GenerateRandomPassword(12);

                account.Password        = PasswordHash.CreateHash(password);
                account.PasswordExpired = false;

                dbContext.SaveChanges();

                return(password);
            }
        }
Exemple #21
0
        public ServiceOperationResult <Guid> CreateAccount(string email, string password, string firstName, string middleName,
                                                           string lastName, AccountTypes accountType, string companyName, string mobile, bool managedByFlyJets)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                if (dbContext.Accounts.Any(acc => acc.Email == email))
                {
                    return(new ServiceOperationResult <Guid>()
                    {
                        IsSuccessfull = false,
                        Errors = new List <ErrorCodes>()
                        {
                            ErrorCodes.EmailExists
                        }
                    });
                }

                string accountNumber = "";
                string referenceCode;

                if (accountType != AccountTypes.Admin)
                {
                    switch (accountType)
                    {
                    case AccountTypes.Flyer:
                        referenceCode = "FLYER";
                        accountNumber = "FLR{0}{1}";
                        break;

                    case AccountTypes.AircraftProvider:
                        referenceCode = "AIRCRAFTPROVIDER";
                        accountNumber = "AP{0}{1}";
                        break;

                    default:
                        throw new Exception("Unsupported account type");
                    }

                    SqlParameter[] @params =
                    {
                        new SqlParameter("ReturnVal",     SqlDbType.Int)
                        {
                            Direction = ParameterDirection.Output
                        },
                        new SqlParameter("ReferenceCode", referenceCode),
                        new SqlParameter("Year",          DateTime.UtcNow.Year)
                    };

                    dbContext.Database.ExecuteSqlCommand("FJSP_GetNextNumber @ReferenceCode, @Year, @ReturnVal Output",
                                                         @params);

                    var number = @params[0].Value.ToString();

                    accountNumber = string.Format(accountNumber, DateTime.UtcNow.Year, number);
                }

                var newAccount = new Account()
                {
                    Id                   = Guid.NewGuid(),
                    Number               = accountNumber,
                    Type                 = (byte)accountType,
                    Email                = email,
                    Password             = PasswordHash.CreateHash(password),
                    FirstName            = firstName,
                    MiddleName           = middleName,
                    LastName             = lastName,
                    CreatedOn            = DateTime.UtcNow,
                    CompanyName          = companyName,
                    Status               = accountType == AccountTypes.AircraftProvider ? (byte)AccountStatuses.PendingApproval : (byte)AccountStatuses.PendingConfirmation,
                    LastLogInDate        = DateTime.UtcNow,
                    NotificationsChannel = (byte)NotificationsChannels.Email,
                    Mobile               = mobile,
                    VerificationCode     = Guid.NewGuid().ToString(),
                    ManagedByFlyJets     = managedByFlyJets,
                    PasswordExpired      = false
                };

                dbContext.Accounts.Add(newAccount);

                try
                {
                    dbContext.SaveChanges();

                    var flyJetsId = dbContext.Accounts
                                    .Where(account => account.Type == (byte)AccountTypes.Admin)
                                    .Select(account => account.Id)
                                    .First();

                    if (newAccount.Type == (byte)AccountTypes.AircraftProvider)
                    {
                        _notificationService.NewCreate(flyJetsId,
                                                       NotificationsTypes.NewAircraftProviderRegistrationRequest,
                                                       "New Aircraft Provider",
                                                       new List <NotificationService.NotificationParam>()
                        {
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountId",
                                Value = newAccount.Id.ToString()
                            },
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountFirstName",
                                Value = newAccount.FirstName
                            },
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountLastName",
                                Value = newAccount.LastName
                            },
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountCompany",
                                Value = newAccount.CompanyName
                            },
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountMobile",
                                Value = newAccount.Mobile
                            },
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountEmail",
                                Value = newAccount.Email
                            },
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountCreation",
                                Value = newAccount.CreatedOn.ToString()
                            }
                        });
                    }
                    else
                    {
                        _notificationService.NewCreate(flyJetsId,
                                                       NotificationsTypes.NewFlyer,
                                                       "New Flyer",
                                                       new List <NotificationService.NotificationParam>()
                        {
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountId",
                                Value = newAccount.Id.ToString()
                            },
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountFirstName",
                                Value = newAccount.FirstName
                            },
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountLastName",
                                Value = newAccount.LastName
                            },
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountMobile",
                                Value = newAccount.Mobile
                            },
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountEmail",
                                Value = newAccount.Email
                            },
                            new NotificationService.NotificationParam()
                            {
                                Key   = "AccountCreation",
                                Value = newAccount.CreatedOn.ToString()
                            }
                        });
                        string receiverName = string.Join(newAccount.FirstName, " ", newAccount.LastName);
                        string credEmail    = _config.GetSection("CredentialEmail").Value;
                        string credPass     = _config.GetSection("CredentialPassword").Value;
                        string message      = string.Format("Thank you for signing up with FLYJETS. Please visit <a href={0}/app/Verify/{1}>this page</a> to finish signing up", _config.GetSection("MailerUrl").Value, newAccount.VerificationCode);

                        _mailerService.Send(newAccount.Email, receiverName, message, "Thank you for signing up with FLYJETS", credEmail, credPass);
                    }

                    //AzureQueueService.Instance.AddMessage("mailqueue", "Welcome to FlyJets");

                    //if (accountType == AccountTypes.AircraftProvider)
                    //{
                    //    CustomPrincipal userPrincipal = new CustomPrincipal(newAccount.Id);

                    //    userPrincipal.FirstName = newAccount.FirstName;
                    //    userPrincipal.LastName = newAccount.LastName;
                    //    userPrincipal.Email = newAccount.Email;
                    //    userPrincipal.Type = accountType;
                    //    //userPrincipal.AvatarUrl = newAccount.AvatarUrl;

                    //    Thread.CurrentPrincipal = userPrincipal;


                    return(new ServiceOperationResult <Guid>()
                    {
                        IsSuccessfull = true,
                        Item = newAccount.Id
                    });
                }
                catch (DbUpdateException e)
                {
                    //if (e.InnerException != null && e.InnerException.InnerException != null)
                    //{
                    //    if (e.InnerException.InnerException is SqlException sqlException)
                    //    {
                    //        if (sqlException.Number == (int)DbUpdateErrorCodes.UniqueKeyError)
                    //        {
                    //            return new OperationResult<AccountDto>()
                    //            {
                    //                IsSuccessfull = false,
                    //                Errors = new List<ErrorCodes>() { ErrorCodes.EmailExists }
                    //            };
                    //        }
                    //    }
                    //}

                    return(new ServiceOperationResult <Guid>()
                    {
                        IsSuccessfull = false,
                        Errors = new List <ErrorCodes>()
                        {
                            ErrorCodes.UnKnown
                        }
                    });
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                    return(new ServiceOperationResult <Guid>()
                    {
                        IsSuccessfull = false,
                        Errors = new List <ErrorCodes>()
                        {
                            ErrorCodes.UnKnown
                        }
                    });
                }
            }
        }
Exemple #22
0
        public ServiceOperationResult UpdateAccount(string firstName, string middleName, string lastName, DateTime?dateOfBirth,
                                                    string email, string mobile, string address, string companyName, string companyAddress, string companyEmail, string companyPhone, byte[] profileImage, string profileImageExtention)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var accountId = Guid.Parse(_httpContextAccessor.HttpContext.User.Identity.Name);
                var account   = dbContext.Accounts.FirstOrDefault(acc => acc.Id == accountId);

                if (account == null)
                {
                    return(new ServiceOperationResult()
                    {
                        IsSuccessfull = false, Errors = new List <ErrorCodes>()
                        {
                            ErrorCodes.NotFound
                        }
                    });
                }

                var errors = new List <ErrorCodes>();

                if (string.IsNullOrEmpty(firstName))
                {
                    errors.Add(ErrorCodes.FirstNameIsRequired);
                }

                if (string.IsNullOrEmpty(lastName))
                {
                    errors.Add(ErrorCodes.LastNameIsRequired);
                }

                if ((!string.IsNullOrEmpty(firstName) && firstName.Length > 30) ||
                    (!string.IsNullOrEmpty(middleName) && middleName.Length > 30) ||
                    (!string.IsNullOrEmpty(lastName) && lastName.Length > 30))
                {
                    errors.Add(ErrorCodes.StringLengthExceededMaximumAllowedLength);
                }

                string profileImageName = account.ImageFileName;

                if (profileImage != null && profileImage.Length != 0)
                {
                    profileImageName = _storageManager.UploadImage(_config["ProfileImagesContainer"], profileImage, profileImageExtention, true);
                }

                account.FirstName     = firstName;
                account.MiddleName    = middleName;
                account.LastName      = lastName;
                account.DateOfBirth   = dateOfBirth;
                account.Email         = email;
                account.Mobile        = mobile;
                account.Address       = address;
                account.ImageFileName = profileImageName;

                account.CompanyName    = companyName;
                account.CompanyAddress = companyAddress;
                account.CompanyEmail   = companyEmail;
                account.CompanyPhone   = companyPhone;

                dbContext.SaveChanges();


                return(new ServiceOperationResult()
                {
                    IsSuccessfull = true
                });
            }
        }
        public ServiceOperationResult Update(Guid aircraftId, string tailNumber, Guid typeId, Guid modelId, int HomeBaseId,
                                             string argusSafetyRating, string wyvernSafetyRating, short?manufactureYear, short?lastIntRefurbish,
                                             short?lastExtRefurbish, byte maxPassengers, short?hoursFlown, short speed, short range,
                                             bool wiFi, bool bookableDemo, short?numberOfTelevision, short?cargoCapability, bool sellAsCharterAircraft,
                                             bool sellAsCharterSeat, decimal pricePerHour, List <AircraftDocumentDto> images, List <AircraftDocumentDto> documents)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                ServiceOperationResult result = new ServiceOperationResult();
                result.IsSuccessfull = true;

                var aircraft = dbContext.Aircrafts
                               .Include("Images")
                               .Include("Documents")
                               .FirstOrDefault(a => a.Id == aircraftId);

                aircraft.TailNumber         = tailNumber;
                aircraft.TypeId             = typeId;
                aircraft.ModelId            = modelId;
                aircraft.HomeBaseId         = HomeBaseId;
                aircraft.ArgusSafetyRating  = argusSafetyRating;
                aircraft.WyvernSafetyRating = wyvernSafetyRating;
                aircraft.ManufactureYear    = manufactureYear;
                aircraft.LastIntRefurbish   = lastIntRefurbish;
                aircraft.LastExtRefurbish   = lastExtRefurbish;
                aircraft.MaxPassengers      = maxPassengers;
                aircraft.HoursFlown         = hoursFlown;
                aircraft.Speed                 = speed;
                aircraft.Range                 = range;
                aircraft.WiFi                  = wiFi;
                aircraft.BookableDemo          = bookableDemo;
                aircraft.Television            = numberOfTelevision.HasValue && numberOfTelevision.Value > 0 ? true : false;
                aircraft.NumberOfTelevision    = numberOfTelevision;
                aircraft.CargoCapability       = cargoCapability;
                aircraft.SellAsCharterAircraft = true; // sellAsCharterAircraft;
                aircraft.SellAsCharterSeat     = true; // sellAsCharterSeat;
                aircraft.PricePerHour          = pricePerHour;

                foreach (var image in images)
                {
                    var currentImage = aircraft.Images.FirstOrDefault(img => img.Order == image.Order);

                    if (currentImage != null)
                    {
                        currentImage.FileName = image.FileName;
                    }
                    else
                    {
                        aircraft.Images.Add(new AircraftImage()
                        {
                            Id         = Guid.NewGuid(),
                            AircraftId = aircraft.Id,
                            Name       = image.Name,
                            FileName   = image.FileName,
                            Order      = image.Order
                        });
                    }
                }

                foreach (var document in documents)
                {
                    aircraft.Documents.Add(new AircraftDocument()
                    {
                        Id         = Guid.NewGuid(),
                        AircraftId = aircraft.Id,
                        FileName   = document.FileName,
                        Name       = "Document",
                        Type       = document.Type
                    });
                }



                dbContext.SaveChanges();

                return(result);
            }
        }
        public ServiceOperationResult Create(string tailNumber, Guid typeId, Guid modelId, int HomeBaseId,
                                             string argusSafetyRating, string wyvernSafetyRating, short?manufactureYear, short?lastIntRefurbish,
                                             short?lastExtRefurbish, byte maxPassengers, short?hoursFlown, short speed, short range,
                                             bool wiFi, bool bookableDemo, short?numberOfTelevision, short?cargoCapability, bool sellAsCharterAircraft,
                                             bool sellAsCharterSeat, decimal pricePerHour, List <AircraftDocumentDto> images, List <AircraftDocumentDto> documents)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                ServiceOperationResult result = new ServiceOperationResult();
                result.IsSuccessfull = true;

                var newAircraft = new Aircraft();

                newAircraft.Id                    = Guid.NewGuid();
                newAircraft.TailNumber            = tailNumber;
                newAircraft.TypeId                = typeId;
                newAircraft.ModelId               = modelId;
                newAircraft.HomeBaseId            = HomeBaseId;
                newAircraft.ArgusSafetyRating     = argusSafetyRating;
                newAircraft.WyvernSafetyRating    = wyvernSafetyRating;
                newAircraft.ManufactureYear       = manufactureYear;
                newAircraft.LastIntRefurbish      = lastIntRefurbish;
                newAircraft.LastExtRefurbish      = lastExtRefurbish;
                newAircraft.MaxPassengers         = maxPassengers;
                newAircraft.HoursFlown            = hoursFlown;
                newAircraft.Speed                 = speed;
                newAircraft.Range                 = range;
                newAircraft.WiFi                  = wiFi;
                newAircraft.BookableDemo          = bookableDemo;
                newAircraft.Television            = numberOfTelevision.HasValue;
                newAircraft.NumberOfTelevision    = numberOfTelevision;
                newAircraft.CargoCapability       = cargoCapability;
                newAircraft.SellAsCharterAircraft = true; //sellAsCharterAircraft;
                newAircraft.SellAsCharterSeat     = true; //sellAsCharterSeat;
                newAircraft.PricePerHour          = pricePerHour;
                newAircraft.Available             = true;

                newAircraft.ProviderId  = _accountId;
                newAircraft.CreatedById = _accountId;
                newAircraft.CreatedOn   = DateTime.UtcNow;

                newAircraft.Images = new List <AircraftImage>();

                foreach (var image in images)
                {
                    newAircraft.Images.Add(new AircraftImage()
                    {
                        Id         = Guid.NewGuid(),
                        AircraftId = newAircraft.Id,
                        Name       = image.Name,
                        FileName   = image.FileName,
                        Order      = image.Order
                    });
                }

                newAircraft.Documents = new List <AircraftDocument>();

                foreach (var document in documents)
                {
                    newAircraft.Documents.Add(new AircraftDocument()
                    {
                        Id         = Guid.NewGuid(),
                        AircraftId = newAircraft.Id,
                        FileName   = document.FileName,
                        Type       = document.Type,
                        Name       = "Document"
                    });
                }


                dbContext.Aircrafts.Add(newAircraft);
                dbContext.SaveChanges();

                return(result);
            }
        }
Exemple #25
0
        public AccountPaymentMethod CreateBankAccountPaymentMethod(string accountHolderName, string accountHolderType, string routingNumber, string accountNumber, byte usedFor)
        {
            try
            {
                var tokenOptions = new TokenCreateOptions
                {
                    BankAccount = new BankAccountOptions
                    {
                        Country           = "US",
                        Currency          = "usd",
                        AccountHolderName = accountHolderName,
                        AccountHolderType = accountHolderType,
                        RoutingNumber     = routingNumber,
                        AccountNumber     = accountNumber
                    }
                };

                var   tokenService = new TokenService();
                Token token        = tokenService.Create(tokenOptions);

                var stripeCustomer = GetStripeCustomer();

                var bankAccountOptions = new BankAccountCreateOptions
                {
                    Source = token.Id,
                };

                var         bankAccountService = new BankAccountService();
                BankAccount bankAccount        = bankAccountService.Create(stripeCustomer.Id, bankAccountOptions);

                using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
                {
                    var paymentMehtod = new AccountPaymentMethod()
                    {
                        Id                       = Guid.NewGuid(),
                        AccountId                = _accountId,
                        PaymentMethod            = (byte)PaymentMethods.BankTransfer,
                        TokenId                  = token.Id,
                        BankName                 = token.BankAccount.BankName,
                        RoutingNumber            = token.BankAccount.RoutingNumber,
                        HolderName               = token.BankAccount.AccountHolderName,
                        AccountLast4             = token.BankAccount.Last4,
                        UsedFor                  = usedFor,
                        ReferencePaymentMethodId = bankAccount.Id,
                        CreatedOn                = DateTime.UtcNow
                    };

                    dbContext.AccountPaymentMethods.Add(paymentMehtod);
                    dbContext.SaveChanges();

                    return(paymentMehtod);
                }
            }
            catch (StripeException e)
            {
                switch (e.StripeError.ErrorType)
                {
                case "card_error":
                    break;

                case "api_connection_error":
                    break;

                case "api_error":
                    break;

                case "authentication_error":
                    break;

                case "invalid_request_error":
                    break;

                case "rate_limit_error":
                    break;

                case "validation_error":
                    break;

                default:
                    break;
                }

                return(null);
            }
        }
        public ServiceOperationResult CreateAvailability(Guid aircraftId, int?reroutingRadius,
                                                         List <AircraftAvailabilityLocationDto> departureLocations,
                                                         List <AircraftAvailabilityLocationDto> arrivalLocations, List <AircraftAvailabilityPeriodDto> availabileDates,
                                                         decimal?pricePerHour, decimal?minimumAcceptablePrice, bool sellCharterSeat)
        {
            using (var dbContext = new FlyJetsDbContext(_config))
            {
                ServiceOperationResult result = new ServiceOperationResult();

                result.IsSuccessfull = true;

                var newAvailability = new AircraftAvailability()
                {
                    Id           = Guid.NewGuid(),
                    AircraftId   = aircraftId,
                    PricePerHour = pricePerHour,
                    MinimumAcceptablePricePerTrip = minimumAcceptablePrice,
                    CreatedOn       = DateTime.UtcNow,
                    CreatedById     = _accountId,
                    SellCharterSeat = sellCharterSeat,
                    ReroutingRadius = reroutingRadius,
                    Available       = true
                };

                newAvailability.Locations = new List <AircraftAvailabilityLocation>();

                if (reroutingRadius.HasValue)
                {
                    var homebaseLoc = (from aircraft in dbContext.Aircrafts
                                       join homebase in dbContext.LocationsTree on aircraft.HomeBaseId equals homebase.Id
                                       where aircraft.Id == aircraftId
                                       select new { Lat = homebase.Lat, Lng = homebase.Lng })
                                      .First();

                    var reroutingLocations = _locationService.GetLocationsWithinXMiles(homebaseLoc.Lat.Value, homebaseLoc.Lng.Value,
                                                                                       reroutingRadius.Value, (byte)LocationsTypes.Airport);

                    foreach (var reroutingLocation in reroutingLocations)
                    {
                        var newLoc = new AircraftAvailabilityLocation()
                        {
                            Id = Guid.NewGuid(),
                            AircraftAvailabilityId = newAvailability.Id,
                            LocationTreeId         = reroutingLocation.Id,
                            IsForDeparture         = true,
                            Rerouting = true
                        };

                        newAvailability.Locations.Add(newLoc);
                    }
                }

                foreach (var departureLocation in departureLocations)
                {
                    var newLoc = new AircraftAvailabilityLocation()
                    {
                        Id = Guid.NewGuid(),
                        AircraftAvailabilityId = newAvailability.Id,
                        LocationTreeId         = departureLocation.LocationTreeId,
                        IsForDeparture         = true,
                        Rerouting = false
                    };

                    newAvailability.Locations.Add(newLoc);
                }

                foreach (var arrivalLocation in arrivalLocations)
                {
                    var newLoc = new AircraftAvailabilityLocation()
                    {
                        Id = Guid.NewGuid(),
                        AircraftAvailabilityId = newAvailability.Id,
                        LocationTreeId         = arrivalLocation.LocationTreeId,
                        IsForDeparture         = false,
                        Rerouting = false
                    };

                    newAvailability.Locations.Add(newLoc);
                }

                newAvailability.Periods = new List <AircraftAvailabilityPeriod>();

                foreach (var availableDate in availabileDates)
                {
                    newAvailability.Periods.Add(new AircraftAvailabilityPeriod()
                    {
                        Id = Guid.NewGuid(),
                        AircraftAvailabilityId = newAvailability.Id,
                        From = availableDate.From,
                        To   = availableDate.To
                    });
                }

                dbContext.AircraftsAvailability.Add(newAvailability);
                dbContext.SaveChanges();

                return(result);
            }
        }
Exemple #27
0
        public AccountPaymentMethod CreateCreditCardPaymentMethod(string cardNumber, long cardExpYear, long cardExpMonth, string cardCvc, byte usedFor)
        {
            try
            {
                /* var options = new PaymentMethodCreateOptions */
                /* { */
                /*   Type = "card", */
                /*   Card = new PaymentMethodCardOptions */
                /*   { */
                /*     Number = cardNumber, */
                /*     ExpMonth = cardExpMonth, */
                /*     ExpYear = cardExpYear, */
                /*     Cvc = cardCvc */
                /*   }, */
                /* }; */
                /* var service = new PaymentMethodService(); */
                /* PaymentMethod pm = service.Create(options); */
                var tokenOptions = new TokenCreateOptions
                {
                    Card = new CreditCardOptions
                    {
                        Number   = cardNumber,
                        ExpYear  = cardExpYear,
                        ExpMonth = cardExpMonth,
                        Cvc      = cardCvc
                    }
                };

                var   tokenService = new TokenService();
                Token token        = tokenService.Create(tokenOptions);

                var stripeCustomer = GetStripeCustomer();

                var cardOptions = new CardCreateOptions
                {
                    Source = token.Id
                };

                var  service = new CardService();
                Card card    = service.Create(stripeCustomer.Id, cardOptions);

                using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
                {
                    var paymentMehtod = new AccountPaymentMethod()
                    {
                        Id                       = Guid.NewGuid(),
                        AccountId                = _accountId,
                        PaymentMethod            = (byte)PaymentMethods.CreditCard,
                        TokenId                  = token.Id,
                        CreditCardBrand          = token.Card.Brand,
                        CreditCardLast4          = token.Card.Last4,
                        CreditCardExpMonth       = token.Card.ExpMonth,
                        CreditCardExYear         = token.Card.ExpYear,
                        UsedFor                  = usedFor,
                        ReferencePaymentMethodId = card.Id,
                        CreatedOn                = DateTime.UtcNow
                    };

                    dbContext.AccountPaymentMethods.Add(paymentMehtod);
                    dbContext.SaveChanges();

                    return(paymentMehtod);
                }
            }
            catch (StripeException e)
            {
                switch (e.StripeError.ErrorType)
                {
                case "card_error":
                    Console.WriteLine("Code: " + e.StripeError.Code);
                    Console.WriteLine("Message: " + e.StripeError.Message);
                    break;

                case "api_connection_error":
                    Console.WriteLine("Code: " + e.StripeError.Code);
                    Console.WriteLine("Message: " + e.StripeError.Message);
                    break;

                case "api_error":
                    Console.WriteLine("Code: " + e.StripeError.Code);
                    Console.WriteLine("Message: " + e.StripeError.Message);
                    break;

                case "authentication_error":
                    Console.WriteLine("Code: " + e.StripeError.Code);
                    Console.WriteLine("Message: " + e.StripeError.Message);
                    break;

                case "invalid_request_error":
                    Console.WriteLine("Code: " + e.StripeError.Code);
                    Console.WriteLine("Message: " + e.StripeError.Message);
                    break;

                case "rate_limit_error":
                    Console.WriteLine("Code: " + e.StripeError.Code);
                    Console.WriteLine("Message: " + e.StripeError.Message);
                    break;

                case "validation_error":
                    Console.WriteLine("Code: " + e.StripeError.Code);
                    Console.WriteLine("Message: " + e.StripeError.Message);
                    break;

                default:
                    Console.WriteLine("Code: " + e.StripeError.Code);
                    Console.WriteLine("Message: " + e.StripeError.Message);
                    break;
                }

                return(null);
            }
        }
        public ServiceOperationResult UpdateAvailability(Guid aircraftAvailabilityId, Guid aircraftId, int?reroutingRadius,
                                                         List <AircraftAvailabilityLocationDto> departureLocations,
                                                         List <AircraftAvailabilityLocationDto> arrivalLocations, List <AircraftAvailabilityPeriodDto> availabileDates,
                                                         decimal?pricePerHour, decimal?minimumAcceptablePrice, bool sellCharterSeat)
        {
            using (FlyJetsDbContext dbContext = new FlyJetsDbContext(_config))
            {
                var operationResult = new ServiceOperationResult();
                operationResult.IsSuccessfull = true;

                var availability = dbContext.AircraftsAvailability
                                   .FirstOrDefault(av => av.Id == aircraftAvailabilityId);

                if (availability == null)
                {
                    operationResult.Errors = new List <ErrorCodes>()
                    {
                        ErrorCodes.NotFound
                    };
                    operationResult.IsSuccessfull = false;

                    return(operationResult);
                }

                availability.AircraftId   = aircraftId;
                availability.PricePerHour = pricePerHour;
                availability.MinimumAcceptablePricePerTrip = minimumAcceptablePrice;
                availability.SellCharterSeat = sellCharterSeat;
                availability.ReroutingRadius = reroutingRadius;

                var oldLocations = dbContext.AircraftAvailabilityLocations
                                   .Where(loc => loc.AircraftAvailabilityId == aircraftAvailabilityId)
                                   .ToList();

                foreach (var location in oldLocations)
                {
                    dbContext.Entry(location).State = EntityState.Deleted;
                }

                availability.Locations = new List <AircraftAvailabilityLocation>();

                if (reroutingRadius.HasValue)
                {
                    var homebaseLoc = (from aircraft in dbContext.Aircrafts
                                       join homebase in dbContext.LocationsTree on aircraft.HomeBaseId equals homebase.Id
                                       where aircraft.Id == aircraftId
                                       select new { Lat = homebase.Lat, Lng = homebase.Lng })
                                      .First();

                    var reroutingLocations = _locationService.GetLocationsWithinXMiles(homebaseLoc.Lat.Value, homebaseLoc.Lng.Value,
                                                                                       reroutingRadius.Value, (byte)LocationsTypes.Airport);

                    foreach (var reroutingLocation in reroutingLocations)
                    {
                        var newLoc = new AircraftAvailabilityLocation()
                        {
                            Id = Guid.NewGuid(),
                            AircraftAvailabilityId = availability.Id,
                            LocationTreeId         = reroutingLocation.Id,
                            IsForDeparture         = true,
                            Rerouting = true
                        };

                        availability.Locations.Add(newLoc);
                    }
                }

                foreach (var departureLocation in departureLocations)
                {
                    var newLoc = new AircraftAvailabilityLocation()
                    {
                        Id = Guid.NewGuid(),
                        AircraftAvailabilityId = availability.Id,
                        LocationTreeId         = departureLocation.LocationTreeId,
                        IsForDeparture         = true,
                        Rerouting = false
                    };

                    availability.Locations.Add(newLoc);
                }

                foreach (var arrivalLocation in arrivalLocations)
                {
                    var newLoc = new AircraftAvailabilityLocation()
                    {
                        Id = Guid.NewGuid(),
                        AircraftAvailabilityId = availability.Id,
                        LocationTreeId         = arrivalLocation.LocationTreeId,
                        IsForDeparture         = false,
                        Rerouting = false
                    };

                    availability.Locations.Add(newLoc);
                }

                var oldPeriods = dbContext.AircraftsAvailabilityPeriods
                                 .Where(p => p.AircraftAvailabilityId == aircraftAvailabilityId)
                                 .ToList();

                foreach (var period in oldPeriods)
                {
                    dbContext.Entry(period).State = EntityState.Deleted;
                }

                availability.Periods = new List <AircraftAvailabilityPeriod>();

                foreach (var availableDate in availabileDates)
                {
                    availability.Periods.Add(new AircraftAvailabilityPeriod()
                    {
                        Id = Guid.NewGuid(),
                        AircraftAvailabilityId = availability.Id,
                        From = availableDate.From,
                        To   = availableDate.To
                    });
                }

                dbContext.SaveChanges();

                return(operationResult);
            }
        }