Ejemplo n.º 1
0
        public static void LogsInsertAction(string message, bool send = true)
        {
            using (var db = new UniversalGymEntities())
            {
                Log log = new Log
                {
                    InsertDate = DateTime.UtcNow,
                    LogMessage = message,
                    IsError    = false
                };
                db.Logs.Add(log);

                db.SaveChanges();

                if (send)
                {
                    var body = "Action: "
                               + "Id: "
                               + log.LogId
                               + Environment.NewLine
                               + "Date: "
                               + log.InsertDate
                               + Environment.NewLine
                               + "LogMessage: "
                               + log.LogMessage
                               + Environment.NewLine
                               + Environment.NewLine;

                    SlackHelper.sendActionChannel(body);
                }
            }
        }
        public static BasicResponse resetUserPasswordEmailImplementation(ResetPasswordEmailRequest request)
        {
            if (String.IsNullOrWhiteSpace(request.email))
            {
                return(new BasicResponse {
                    message = "Please enter an email.", status = 601, success = false
                });
            }

            using (var db = new UniversalGymEntities())
            {
                var user = db.Users.SingleOrDefault(f => f.Email == request.email);
                if (user == null)
                {
                    return(new BasicResponse {
                        message = "User not found.", status = 404, success = false
                    });
                }

                var forgotPasswordBody = String.Format("Someone forgot a password :/ -- {0}", request.email);
                EmailNoTemplateHelper.SendEmail("User forgot password", "*****@*****.**", forgotPasswordBody);

                user.CurrentToken = Guid.NewGuid().ToString();
                db.SaveChanges();

                var link = Constants.PedalWebUrl + "user.html#/resetPassword/" + user.UserId + "/" + user.CurrentToken;;
                EmailTemplateHelper.SendEmail("Reset Password Link - Pedal", request.email, link, user.FirstName, "reset_password.html");

                return(new BasicResponse {
                    message = "User email sent successfully", status = 3, success = true
                });
            }
        }
        public static BasicResponse updateProfileImplementation(UpdateProfileRequest request)
        {
            if (request == null || String.IsNullOrWhiteSpace(request.authToken) || request.accountId == null)
            {
                return(new BasicResponse
                {
                    message = "User not found.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.firstName))
            {
                return(new BasicResponse
                {
                    message = "Please enter a first name.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.lastName))
            {
                return(new BasicResponse
                {
                    message = "Please enter a last name.",
                    status = 404,
                    success = false,
                });
            }

            using (var db = new UniversalGymEntities())
            {
                var user = db.Users.SingleOrDefault(a => a.CurrentToken == request.authToken && a.UserId == request.accountId);
                if (user == null)
                {
                    return(new BasicResponse
                    {
                        message = "User not found.",
                        status = 404,
                        success = false,
                    });
                }


                user.FirstName = request.firstName;
                user.LastName  = request.lastName;
                db.SaveChanges();
            }
            return(new BasicResponse {
                message = "Profile was successfully changed.", status = 200, success = true
            });
        }
        public static BasicResponse deletePhotoImplementation(UpdateCoverPhotoRequest request)
        {
            if (request == null || String.IsNullOrWhiteSpace(request.authToken) || request.accountId == null)
            {
                return(new addGymHoursResponse {
                    status = 401, success = false, message = "Gym not found"
                });
            }

            using (var db = new UniversalGymEntities())
            {
                if (request.authToken == null)
                {
                    return(new BasicResponse
                    {
                        message = "Gym not found.",
                        status = 404,
                        success = false,
                    });
                }

                var gym = db.Gyms.SingleOrDefault(a => a.CurrentToken == request.authToken && a.GymId == request.accountId);
                if (gym == null)
                {
                    return(new BasicResponse
                    {
                        message = "Gym not found.",
                        status = 404,
                        success = false,
                    });
                }

                var picture = db.GymPhotoGalleries.First(w => w.GymPhotoGalleryId == request.pictureId);
                if (picture.IsCoverPhoto)
                {
                    return(new BasicResponse
                    {
                        message = "Please set another photo as the cover.",
                        status = 404,
                        success = false,
                    });
                }
                deletePhotoFromBlob(picture.Photo);

                db.GymPhotoGalleries.Remove(picture);
                db.SaveChanges();
                return(new BasicResponse {
                    status = 200,
                    success = true,
                    message = "Photo Gallery removed"
                });
            }
        }
Ejemplo n.º 5
0
        public static GymSearchListResponse searchByLocationImplementation(SearchGymRequest request)
        {
            var location = System.Data.Entity.Spatial.DbGeography.FromText(String.Format("POINT({0} {1})", request.longitude, request.latitude));

            GymSearchListResponse rv;

            using (var db = new UniversalGymEntities())
            {
                var searchRequest = new Data.SearchRequest
                {
                    SearchDate             = DateTime.Now,
                    Position               = location,
                    UniqueDeviceIdentifier = request.uniqueDeviceId,
                };

                var user = db.Users.SingleOrDefault(a => a.CurrentToken == request.authToken && a.UserId == request.accountId);
                if (user != null)
                {
                    searchRequest.UserId = user.UserId;
                }


                db.SearchRequests.Add(searchRequest);
                db.SaveChanges();

                var searchText = "DeviceId: "
                                 + request.uniqueDeviceId
                                 + Environment.NewLine;
                if (searchRequest.User != null)
                {
                    searchText = searchText
                                 + "User: "
                                 + searchRequest.User.Email;
                }

                SlackHelper.sendSearchChannel(searchText, request.latitude.ToString(), request.longitude.ToString());


                var gyms = db.Gyms.Where(w => w.Position != null).OrderBy(o => o.Position.Distance(location));
                rv = GymSearchListHelper.createGymSearchListResponse(gyms, location.Latitude, location.Longitude);
                if (user != null)
                {
                    rv.credits = user.Credits;
                }
                else
                {
                    rv.credits = 0;
                }
            }
            return(rv);
        }
Ejemplo n.º 6
0
        public static BasicResponse removeGymHoursImplementation(removeGymHoursRequest request)
        {
            using (var db = new UniversalGymEntities())
            {
                if (request == null || String.IsNullOrWhiteSpace(request.authToken) || request.accountId == null)
                {
                    return(new BasicResponse
                    {
                        message = "Gym not found.",
                        status = 404,
                        success = false,
                    });
                }

                var gym = db.Gyms.SingleOrDefault(a => a.CurrentToken == request.authToken && a.GymId == request.accountId);
                if (gym == null)
                {
                    return(new BasicResponse
                    {
                        message = "Gym not found.",
                        status = 404,
                        success = false,
                    });
                }

                var gymHour = db.GymSchedules.First(w => w.GymScheduleId == request.gymHourId);
                if (gymHour == null)
                {
                    return(new BasicResponse
                    {
                        message = "Time schedule not found.",
                        status = 404,
                        success = false,
                    });
                }

                db.GymSchedules.Remove(gymHour);
                db.SaveChanges();
                return(new BasicResponse {
                    status = 200, success = true, message = "Successfully Removed"
                });
            }
        }
        public static BasicResponse suspendSubscriptionImplementation(BaseRequest request)
        {
            if (request == null || String.IsNullOrWhiteSpace(request.authToken) || request.accountId == null)
            {
                return(new BasicResponse
                {
                    message = "User not found.",
                    status = 404,
                    success = false,
                });
            }

            using (var db = new UniversalGymEntities())
            {
                var user = db.Users.SingleOrDefault(a => a.CurrentToken == request.authToken && a.UserId == request.accountId);
                if (user == null)
                {
                    return(new BasicResponse
                    {
                        message = "User not found.",
                        status = 404,
                        success = false,
                    });
                }

                if (String.IsNullOrWhiteSpace(user.StripeUrl))
                {
                    return(new BasicResponse {
                        message = "User is missing billing information.", status = 901, success = false
                    });
                }

                new StripeSubscription().RemoveCustomerFromSubscription(user.StripeUrl);
                user.hasActiveSubscription = false;

                db.SaveChanges();

                return(new BasicResponse {
                    message = "Subscription was successfully cancelled.", status = 200, success = true
                });
            }
        }
Ejemplo n.º 8
0
        public static BasicResponse updateBankInfoImplementation(BankAccountInfoRequest request)
        {
            //validate incoming data
            if (String.IsNullOrWhiteSpace(request.stripeToken))
            {
                return(new BasicResponse {
                    message = "Bank Routing Number or Account Number was not valid.", status = 601, success = false
                });
            }

            if (request == null || String.IsNullOrWhiteSpace(request.authToken) || request.accountId == null)
            {
                return(new BasicResponse
                {
                    message = "Gym not found.",
                    status = 404,
                    success = false,
                });
            }

            using (var db = new UniversalGymEntities())
            {
                var gym = db.Gyms.SingleOrDefault(a => a.CurrentToken == request.authToken && a.GymId == request.accountId);
                if (gym == null)
                {
                    return(new BasicResponse
                    {
                        message = "Gym not found.",
                        status = 404,
                        success = false,
                    });
                }

                var recipId = new StripeAch().CreateRecipient(gym.ContactInfo.Email, gym.GymName, "account for " + gym.GymName, request.stripeToken);
                gym.StripeUrl = recipId;
                db.SaveChanges();
                return(new BasicResponse {
                    status = 200, success = true, message = "Success!"
                });
            }
        }
Ejemplo n.º 9
0
        // decides whether to create new customer or update them
        public static string HandleCustomer(string cardToken, Data.User user)
        {
            var rv = "";

            if (String.IsNullOrWhiteSpace(user.StripeUrl))
            {
                // create new customer
                rv = new StripeCustomer().CreateCustomer(user.Email, user.FirstName + " " + user.LastName, cardToken);
                new StripeSubscription().AddCustomerToSubscription(rv);
                using (var db = new UniversalGymEntities())
                {
                    user.StripeUrl             = rv;
                    user.hasActiveSubscription = true;
                    user.hasCreditCard         = true;
                    db.SaveChanges();
                }
            }
            else
            {
                // update customer
                rv = new StripeCustomer().UpdateCustomer(user.StripeUrl, cardToken);


                // if user suspended account and is reenabling it right now
                using (var db = new UniversalGymEntities())
                {
                    if (user.hasActiveSubscription != true)
                    {
                        new StripeSubscription().AddCustomerToSubscription(rv);
                        user.hasActiveSubscription = true;
                        user.hasCreditCard         = true;

                        db.SaveChanges();
                    }
                }
            }

            return(rv);
        }
        public static BasicResponse updateSelectedCoverPhotoImplementation(UpdateCoverPhotoRequest request)
        {
            if (request == null || String.IsNullOrWhiteSpace(request.authToken) || request.accountId == null)
            {
                return(new BasicResponse
                {
                    message = "Gym not found.",
                    status = 404,
                    success = false,
                });
            }

            using (var db = new UniversalGymEntities())
            {
                var gym = db.Gyms.SingleOrDefault(a => a.CurrentToken == request.authToken && a.GymId == request.accountId);
                if (gym == null)
                {
                    return(new BasicResponse
                    {
                        message = "Gym not found.",
                        status = 404,
                        success = false,
                    });
                }

                var photoes = db.GymPhotoGalleries.Where(w => w.GymId == gym.GymId);
                foreach (var photo in photoes)
                {
                    // set all others to false
                    photo.IsCoverPhoto = photo.GymPhotoGalleryId == request.pictureId;
                }
                db.SaveChanges();
                return(new BasicResponse {
                    status = 200, success = true, message = "Success!"
                });
            }
        }
        public static GymDataResponse CreateGymDataResponse(int gymId, bool genNewToken)
        {
            using (var db = new UniversalGymEntities())
            {
                var gym = db.Gyms.First(f => f.GymId == gymId);

                var baseRefUrl = "";
                if (genNewToken)
                {
                    gym.CurrentToken = Guid.NewGuid().ToString();
                    db.SaveChanges();
                }



                //gym photo
                var gymPhotoList = db.GymPhotoGalleries
                                   .Where(w => w.GymId == gymId)
                                   .OrderByDescending(o => o.IsCoverPhoto)
                                   .Select(s => new PictureObject
                {
                    url     = s.Photo,
                    isCover = s.IsCoverPhoto,
                    id      = s.GymPhotoGalleryId,
                }).ToList();
                var gymPhotos         = gymPhotoList.Any() ? gymPhotoList : new List <PictureObject> {
                };
                var hasRightGymPhotos = false;
                if (gymPhotos.Count <= 8 && gymPhotos.Count >= 3)
                {
                    hasRightGymPhotos = true;
                }


                //gym schedules
                var gymSchedulesList = db.GymSchedules
                                       .Where(w => w.GymId == gymId)
                                       .OrderBy(w => w.TypeWeekDay.Order)
                                       .ThenBy(n => n.StartTime)
                                       .Select(s => new Schedule
                {
                    day       = s.TypeWeekDay.TypeDescription,
                    startTime = new gymHour
                    {
                        hour   = s.StartTime.Hour,
                        minute = s.StartTime.Minute,
                    },
                    endTime = new gymHour
                    {
                        hour   = s.EndTime.Hour,
                        minute = s.EndTime.Minute,
                    },
                    id = s.GymScheduleId,
                }).ToList();
                var gymSchedules      = gymSchedulesList.Any() ? gymSchedulesList : new List <Schedule> {
                };
                var hasRightSchedules = false;
                if (gymSchedules.Count > 0)
                {
                    hasRightSchedules = true;
                }

                var startingPaymentDate   = "";
                var endingPaymentDate     = "";
                var currentPaymentBalance = 0;
                var collectPaymentBalance = 0;

                if (gym.IsApproved && !gym.badData)
                {
                    // equal to same time as endingpaymentdate of last invoice
                    startingPaymentDate = "";

                    // starting date + 14 days?
                    endingPaymentDate = "";

                    // all gympass costs in above time frame
                    currentPaymentBalance = 0;

                    // all previous gym invoices with isCollected set to false
                    collectPaymentBalance = 0;
                }


                return(new GymDataResponse
                {
                    address = gym.ContactInfo1.Address.StreetLine1,
                    token = gym.CurrentToken,
                    city = gym.ContactInfo1.Address.City,
                    state = gym.ContactInfo1.Address.TypeState.StateAbbreviation,
                    zip = gym.ContactInfo1.Address.Zip,
                    isApproved = gym.IsApproved,
                    contactName = gym.OwnerName,
                    contactPhone = gym.ContactInfo.Phone,
                    contactEmail = gym.ContactInfo.Email,
                    gymPhone = gym.ContactInfo1.Phone,
                    description = gym.GymInfo,
                    gymId = gym.GymId,
                    gymUrl = gym.Url,
                    scheduleUrl = gym.ScheduleUrl,
                    gymName = gym.GymName,
                    status = 200,
                    success = true,
                    message = "Success!",
                    price = gym.CreditDollarValue.ToString(),
                    pictures = gymPhotos,
                    hasAccount = !String.IsNullOrWhiteSpace(gym.StripeUrl),
                    schedules = gymSchedules,
                    hasRightHours = hasRightSchedules,
                    hasRightGymPhotos = hasRightGymPhotos,
                    rightGymPhotosMessage = "Please upload 3 to 8 photos of your gym.",
                    rightHourMessage = "Please input gym hours.",
                    startingPaymentDate = startingPaymentDate,
                    endingPaymentDate = endingPaymentDate,
                    currentPaymentBalance = currentPaymentBalance,
                    collectPaymentBalance = collectPaymentBalance,
                });
            }
        }
        public static UpdateCardResponse UpdateCardInfo(CreditCardDataRequest request, StripeAction stripeAction)
        {
            //validate incoming data
            if (String.IsNullOrWhiteSpace(request.token))
            {
                return(new UpdateCardResponse {
                    message = "Missing token.", status = 601, success = false
                });
            }

            if (request == null || String.IsNullOrWhiteSpace(request.authToken) || request.accountId == null)
            {
                return(new UpdateCardResponse
                {
                    message = "User not found.",
                    status = 404,
                    success = false,
                });
            }


            using (var db = new UniversalGymEntities())
            {
                var user = db.Users.SingleOrDefault(a => a.CurrentToken == request.authToken && a.UserId == request.accountId);
                if (user == null)
                {
                    return(new UpdateCardResponse
                    {
                        message = "User not found.",
                        status = 404,
                        success = false,
                    });
                }

                var message = "";
                // temporarily add credits to frontend so user immediately sees money
                var shouldAddCredits = false;

                // empty stripe url means new customer
                if (String.IsNullOrWhiteSpace(user.StripeUrl))
                {
                    message          = "Card added successfully.";
                    shouldAddCredits = true;
                }

                // has active subscription already means updating card
                if (user.hasActiveSubscription)
                {
                    message          = "Card updated successfully.";
                    shouldAddCredits = false;
                }
                // does not have active subscription means re-activating card
                else
                {
                    message          = "Card re-activated successfully.";
                    shouldAddCredits = true;
                }



                user.StripeUrl = stripeAction(request.token, user);
                db.SaveChanges();

                return(new UpdateCardResponse {
                    message = message,
                    status = 200,
                    success = true,
                    shouldAddCredits = shouldAddCredits
                });
            }
        }
Ejemplo n.º 13
0
        public static BasicResponse deleteGymImplementation(deleteGymRequest request)
        {
            if (!Constants.isApiStaging)
            {
                return(new BasicResponse()
                {
                    success = false, status = 404, message = ""
                });
            }

            if (request.authToken != Constants.MarketingToken)
            {
                return new BasicResponse()
                       {
                           success = false, status = 404, message = "Wrong Token"
                       }
            }
            ;

            using (var db = new UniversalGymEntities())
            {
                var gym = db.Gyms.FirstOrDefault(cs => cs.GymId == request.gymId);

                if (gym == null)
                {
                    return(new BasicResponse {
                        message = "Gym not found!", status = 404, success = false
                    });
                }

                // delete gym invoices TODO
                // delete gym pass TODO


                // delete gym photogallery
                if (gym.GymPhotoGalleries != null)
                {
                    db.GymPhotoGalleries.RemoveRange(gym.GymPhotoGalleries);
                }

                // delete address of public contact
                if (gym.ContactInfo1.Address != null)
                {
                    db.Addresses.Remove(gym.ContactInfo1.Address);
                }

                // delete public contact
                if (gym.ContactInfo1 != null)
                {
                    db.ContactInfoes.Remove(gym.ContactInfo1);
                }

                // delete address of owner contact
                if (gym.ContactInfo.Address != null)
                {
                    db.Addresses.Remove(gym.ContactInfo.Address);
                }

                // delete owner contact
                if (gym.ContactInfo != null)
                {
                    db.ContactInfoes.Remove(gym.ContactInfo);
                }

                // delete gym
                db.Gyms.Remove(gym);
                db.SaveChanges();
            }

            return(new BasicResponse()
            {
                success = true, status = 200, message = "Success"
            });
        }
    }
        public static addGymHoursResponse addGymHoursImplementation(addGymHoursRequest request)
        {
            using (var db = new UniversalGymEntities())
            {
                if (request == null || String.IsNullOrWhiteSpace(request.authToken) || request.accountId == null)
                {
                    return(new addGymHoursResponse {
                        status = 401, success = false, message = "Gym not found"
                    });
                }
                else if (String.IsNullOrWhiteSpace(request.day))
                {
                    return(new addGymHoursResponse {
                        status = 401, success = false, message = "Please select a day"
                    });
                }
                else if (request.startTime == null)
                {
                    return(new addGymHoursResponse {
                        status = 401, success = false, message = "Please select a start time"
                    });
                }
                else if (request.endTime == null)
                {
                    return(new addGymHoursResponse {
                        status = 401, success = false, message = "Please select an end time"
                    });
                }


                var gym = db.Gyms.SingleOrDefault(a => a.CurrentToken == request.authToken && a.GymId == request.accountId);
                if (gym == null)
                {
                    return(new addGymHoursResponse
                    {
                        message = "Gym not found.",
                        status = 404,
                        success = false,
                    });
                }

                var weekDay = db.TypeWeekDays.SingleOrDefault(s => s.TypeDescription == request.day);

                if (weekDay == null)
                {
                    return(new addGymHoursResponse {
                        status = 401, success = false, message = "Day not valid"
                    });
                }

                var startTime = new DateTime();
                var endTime   = new DateTime();

                if (request.startTime.hour == 24)
                {
                    // next day at 0 hour
                    startTime = new DateTime(1990, 11, 20, 0, request.startTime.minute, 0, 0);
                }
                else
                {
                    startTime = new DateTime(1990, 11, 19, request.startTime.hour, request.startTime.minute, 0, 0);
                }

                if (request.endTime.hour == 24)
                {
                    // next day at 0 hour

                    endTime = new DateTime(1990, 11, 20, 0, 0, 0, 0);
                }
                else
                {
                    endTime = new DateTime(1990, 11, 19, request.endTime.hour, request.endTime.minute, 0, 0);
                }

                if (startTime >= endTime)
                {
                    return(new addGymHoursResponse {
                        status = 401, success = false, message = "The start time has to come before the end time"
                    });
                }

                // non-intersection between two dates = if (A1 > B2 || B1 > A2)
                // so intersection is the opposite !
                var overlapSchedules = db.GymSchedules.Any(s => s.GymId == request.accountId &&
                                                           s.TypeWeekDayId == weekDay.TypeWeekDayId &&
                                                           (!(s.StartTime >= endTime || startTime >= s.EndTime)));
                if (overlapSchedules)
                {
                    return(new addGymHoursResponse
                    {
                        message = "Schedule overlaps with another existing schedule.",
                        status = 404,
                        success = false,
                    });
                }


                var gymHours = new Data.GymSchedule
                {
                    TypeWeekDayId = weekDay.TypeWeekDayId,
                    StartTime     = startTime,
                    EndTime       = endTime,
                    GymId         = gym.GymId,
                };
                db.GymSchedules.Add(gymHours);
                db.SaveChanges();


                return(new addGymHoursResponse {
                    status = 200, success = true, message = "Gym hours added!", gymHourId = gymHours.GymScheduleId
                });
            }
        }
Ejemplo n.º 15
0
        public static AllDataResponse CreateAllDataResponse(int userId, bool genNewToken)
        {
            using (var db = new UniversalGymEntities())
            {
                var userItem = db.Users.First(f => f.UserId == userId);

                var baseRefUrl = "";
                if (genNewToken)
                {
                    userItem.CurrentToken = Guid.NewGuid().ToString();
                    db.SaveChanges();
                }

                var user = new UserResponse
                {
                    userId                = userId,
                    firstName             = userItem.FirstName,
                    lastName              = userItem.LastName,
                    email                 = userItem.Email,
                    referalBaseUrl        = baseRefUrl,
                    referalCode           = userItem.ReferalUrl,
                    hasActiveSubscription = userItem.hasActiveSubscription,
                    credits               = userItem.Credits,
                    stripeUserId          = (userItem.StripeUrl ?? "").ToString(),
                    hasCreditCard         = userItem.hasCreditCard,
                    purchasedGyms         = new List <GymResponse>(),
                };

                var userPasses = db.GymPasses.Include("Gym").Where(w => w.UserId == userId).OrderByDescending(o => o.ServerTimeDateBought).ToList().Take(15);

                foreach (var userPass in userPasses)
                {
                    var temp = new Responses.GymResponse
                    {
                        name        = userPass.Gym.GymName,
                        description = userPass.Gym.GymInfo,
                        gymId       = userPass.GymId,
                        pictureUrl  = GymSearchListHelper.getPictureUrl(userPass.Gym.GymPhotoGalleries),
                        price       = userPass.Gym.PriceToCharge,
                        city        = userPass.Gym.ContactInfo.Address.City,
                        state       = userPass.Gym.ContactInfo.Address.TypeState.StateAbbreviation,
                        gymUrl      = userPass.Gym.Url ?? "",
                        isActive    = userPass.Gym.IsActive,
                        address     = userPass.Gym.ContactInfo.Address.StreetLine1 + " " + userPass.Gym.ContactInfo.Address.StreetLine2 + "," +
                                      userPass.Gym.ContactInfo.Address.City + ","
                                      + userPass.Gym.ContactInfo.Address.TypeState.StateAbbreviation + "," + userPass.Gym.ContactInfo.Address.Zip,
                        phone = userPass.Gym.ContactInfo.Phone,


                        timeBought                 = userPass.LocalDateBought,
                        displayTimeBought          = userPass.LocalDateBought.ToString("MMM d, yyyy").ToUpper(),
                        localGymDateTimeExpiration = userPass.LocalDateExpired.ToString("MMM d, yyyy").ToUpper(),
                        latitude  = userPass.Gym.Position.Latitude ?? 0,
                        longitude = userPass.Gym.Position.Longitude ?? 0,
                        // user position not known so miles not known
                        // it isn't needed to be known here though
                        miles = 0,
                    };
                    user.purchasedGyms.Add(temp);
                }


                // TODO: ONCE TIMEZONE IS SAVED, FILTER OUT EXPIRED PASSES


                return(new AllDataResponse {
                    user = user, message = "Success!", success = true, status = 3, authToken = userItem.CurrentToken
                });
            }
        }
Ejemplo n.º 16
0
        public static GymDataResponse gymRegisterImplementation(RegisterGymRequest request)
        {
            if (String.IsNullOrWhiteSpace(request.gymName))
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please enter a gym name"
                });
            }
            else if (String.IsNullOrWhiteSpace(request.gymPhone))
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please enter a gym phone number"
                });
            }

            else if (String.IsNullOrWhiteSpace(request.contactName))
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please enter a contact name"
                });
            }
            else if (String.IsNullOrWhiteSpace(request.contactEmail))
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please enter an email"
                });
            }
            else if (String.IsNullOrWhiteSpace(request.contactPhone))
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please enter a phone number"
                });
            }
            else if (String.IsNullOrWhiteSpace(request.website))
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please enter a website"
                });
            }
            else if (String.IsNullOrWhiteSpace(request.address))
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please enter a street"
                });
            }
            else if (String.IsNullOrWhiteSpace(request.city))
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please enter a city"
                });
            }
            else if (String.IsNullOrWhiteSpace(request.state))
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please enter a state or province"
                });
            }
            else if (String.IsNullOrWhiteSpace(request.zip))
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please enter a zip code"
                });
            }
            else if (String.IsNullOrWhiteSpace(request.priceTier))
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please select one given of the price tiers"
                });
            }
            else if (String.IsNullOrWhiteSpace(request.password) || request.password.Length < 6)
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please enter a password greater than 5 characters"
                });
            }
            else if (String.IsNullOrWhiteSpace(request.website))
            {
                return(new GymDataResponse {
                    success = false, status = 200, message = "Please enter a website"
                });
            }
            if (MembershipHelper.emailAlreadyExists(request.contactEmail, Constants.GymRole))
            {
                return(new GymDataResponse {
                    success = false, status = 10, message = "Email already taken."
                });
            }


            var newGymGuid = MembershipHelper.createMembership(request.contactEmail, request.password, Constants.GymRole);

            using (var db = new UniversalGymEntities())
            {
                var state = db.TypeStates.FirstOrDefault(f => f.StateAbbreviation.ToLower() == request.state.ToLower()) ??
                            db.TypeStates.First(f => f.StateAbbreviation == "00");

                var address = new Data.Address()
                {
                    StreetLine1 = request.address,
                    City        = request.city,
                    Zip         = request.zip,
                    TypeStateId = state.TypeStateId
                };
                db.Addresses.Add(address);
                var publicContactInfo = new Data.ContactInfo
                {
                    AddressId = address.AddressId,
                    Phone     = request.gymPhone,
                };
                db.ContactInfoes.Add(publicContactInfo);
                db.SaveChanges();
                var ownerContactInfo = new Data.ContactInfo
                {
                    Email = request.contactEmail,
                    Phone = request.contactPhone,
                };
                db.ContactInfoes.Add(ownerContactInfo);
                db.SaveChanges();

                var gym = new Data.Gym
                {
                    CreditDollarValue = Constants.returnGymPay(request.priceTier),
                    PriceToCharge     = Constants.returnGymPrice(request.priceTier),
                    GymName           = request.gymName,
                    IsApproved        = false,
                    OwnerName         = request.contactName,
                    Url = request.website.Contains("://") ? request.website : "http://" + request.website,
                    PublicContactInfoId = publicContactInfo.ContactInfoId,
                    OwnerContactInfoId  = ownerContactInfo.ContactInfoId,
                    GymInfo             = "",
                    GymGuid             = newGymGuid,
                    ApplicationDate     = DateTime.UtcNow,
                    IsActive            = true,
                };


                db.Gyms.Add(gym);
                var target   = request.address + " " + request.state + " " + request.zip;
                var geocoded = Geocoder.GeoCodeAddress(target);
                if (geocoded != null)
                {
                    gym.Position = System.Data.Entity.Spatial.DbGeography.FromText(geocoded.GetPointString());
                    db.SaveChanges();

                    var newgymBody = "Gym Registration"
                                     + Environment.NewLine
                                     + "Gym Name: "
                                     + gym.GymName
                                     + Environment.NewLine
                                     + "Location: "
                                     + request.address
                                     + Environment.NewLine
                                     + "City: "
                                     + request.city
                                     + Environment.NewLine
                                     + "State: "
                                     + request.state
                                     + Environment.NewLine
                                     + "Zip Code: "
                                     + request.zip
                                     + Environment.NewLine
                                     + "Gym Phone"
                                     + request.gymPhone
                                     + Environment.NewLine
                                     + "Contact Name: "
                                     + request.contactName
                                     + Environment.NewLine
                                     + "Contact Email: "
                                     + request.contactEmail
                                     + Environment.NewLine
                                     + "Contact Phone: "
                                     + request.contactPhone
                                     + Environment.NewLine
                                     + "Website: "
                                     + gym.Url
                                     + Environment.NewLine;

                    SlackHelper.sendGymSignupChannel(newgymBody, geocoded.Latitude.ToString(), geocoded.Longitude.ToString());
                    // add gym id
                    var gymId = gym.GymId;
                    var link  = Constants.PedalWebUrl + "gym.html#/login";

                    EmailTemplateHelper.SendEmail("Welcome to Pedal!", request.contactEmail, link, request.gymName, "gym_signup.html");
                }
                else
                {
                    db.ContactInfoes.Remove(gym.ContactInfo);
                    db.ContactInfoes.Remove(gym.ContactInfo1);

                    var supportText = "Gym Registration - Location not found!"
                                      + Environment.NewLine
                                      + "Gym Name: "
                                      + gym.GymName
                                      + Environment.NewLine
                                      + "Location: "
                                      + request.address
                                      + Environment.NewLine
                                      + "City: "
                                      + request.city
                                      + Environment.NewLine
                                      + "State: "
                                      + request.state
                                      + Environment.NewLine
                                      + "Zip Code: "
                                      + request.zip
                                      + Environment.NewLine
                                      + "Gym Phone"
                                      + request.gymPhone
                                      + Environment.NewLine
                                      + "Contact Name: "
                                      + request.contactName
                                      + Environment.NewLine
                                      + "Contact Email: "
                                      + request.contactEmail
                                      + Environment.NewLine
                                      + "Contact Phone: "
                                      + request.contactPhone
                                      + Environment.NewLine
                                      + "Website: "
                                      + gym.Url
                                      + Environment.NewLine;

                    SlackHelper.sendSupportChannel(supportText);

                    EmailNoTemplateHelper.SendEmail("Gym Registration Problem", "*****@*****.**", supportText);

                    return(new GymDataResponse {
                        success = false, status = 200, message = "Location could not be found. The Pedal team has been notified to look into this."
                    });
                }


                return(gymDataHelper.CreateGymDataResponse(gym.GymId, true));
            }
        }
Ejemplo n.º 17
0
        public static void LogsInsertError(Exception exception)
        {
            using (var db = new UniversalGymEntities())
            {
                Log log = new Log
                {
                    InsertDate = DateTime.UtcNow,
                    IsError    = true
                };

                log.LogMessage = "";
                if (exception.Message != null)
                {
                    log.LogMessage = log.LogMessage
                                     + "Error: "
                                     + exception.Message;
                }
                else if (exception.StackTrace != null)
                {
                    log.LogMessage = log.LogMessage
                                     + "| stacktrace : "
                                     + exception.StackTrace;
                }
                else if (exception.InnerException != null)
                {
                    log.LogMessage = log.LogMessage + "inner:";

                    if (exception.InnerException.Message != null)
                    {
                        log.LogMessage = log.LogMessage
                                         + " "
                                         + exception.Message;
                    }
                    else if (exception.InnerException.StackTrace != null)
                    {
                        log.LogMessage = log.LogMessage
                                         + " "
                                         + exception.StackTrace;
                    }
                }

                db.Logs.Add(log);

                db.SaveChanges();



                var lastLogs = db.Logs.OrderByDescending(o => o.LogId).Take(6).ToArray();
                var body     = "Exception: " + Environment.NewLine;
                foreach (Log lastLog in lastLogs)
                {
                    body = body
                           + "Id: "
                           + lastLog.LogId
                           + Environment.NewLine
                           + "Date: "
                           + lastLog.InsertDate
                           + Environment.NewLine
                           + "LogMessage: "
                           + lastLog.LogMessage
                           + Environment.NewLine
                           + Environment.NewLine;
                }

                SlackHelper.sendErrorChannel(body);

                /*EmailNoTemplateHelper.SendEmail(
                 *  "Exception Found",
                 *  "*****@*****.**",
                 *  body);*/
            }
        }
Ejemplo n.º 18
0
        public static BasicResponse airbnbRegisterImplementation(AirbnbRegisterRequest request)
        {
            if (String.IsNullOrWhiteSpace(request.email))
            {
                return(new BasicResponse
                {
                    message = "Please enter an email.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.firstName))
            {
                return(new BasicResponse
                {
                    message = "Please enter a first name.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.lastName))
            {
                return(new BasicResponse
                {
                    message = "Please enter a last name.",
                    status = 404,
                    success = false,
                });
            }


            if (MembershipHelper.emailAlreadyExists(request.email, Constants.UserRole))
            {
                return(new BasicResponse {
                    message = "Email is already taken", status = 10, success = false
                });
            }
            else if (String.IsNullOrWhiteSpace(request.password) || request.password.Length < 6)
            {
                return(new BasicResponse {
                    message = "Please enter a password at least 6 characters long", status = 10, success = false
                });
            }



            if (!request.password.Equals(request.confirmPassword))
            {
                return(new BasicResponse
                {
                    message = "Passwords do not match",
                    status = 404,
                    success = false,
                });
            }

            var newUserGuid = MembershipHelper.createMembership(request.email, request.password, Constants.UserRole);
            var userId      = 0;

            using (var db = new UniversalGymEntities())
            {
                var newCode = UserCode.GenerateDistinctCode(db);
                var user    = new User
                {
                    FirstName             = request.firstName,
                    LastName              = request.lastName,
                    ReferalUrl            = newCode,
                    UserGuid              = newUserGuid,
                    Email                 = request.email.ToLower(),
                    hasActiveSubscription = true,
                    hasCreditCard         = false,
                    joinDate              = DateTime.Now,
                    Credits               = 0,
                };
                db.Users.Add(user);
                db.SaveChanges();
                userId = user.UserId;



                var newuserbody = "User Signup"
                                  + Environment.NewLine
                                  + "Email: "
                                  + user.Email
                                  + Environment.NewLine
                                  + "Name: "
                                  + user.FirstName
                                  + user.LastName
                                  + Environment.NewLine
                                  + "Airbnb Host: https://www.airbnb.com/users/show/"
                                  + request.airbnbHostId;



                SlackHelper.sendUserSignupChannel(newuserbody);
            }

            EmailTemplateHelper.SendEmail("Welcome to Pedal", request.email, "http://pedal.com", request.firstName, "user_signup.html");

            return(new BasicResponse
            {
                message = "Account created! Just download the Pedal Fitness app and login!",
                status = 200,
                success = true,
            });
        }
Ejemplo n.º 19
0
        public static AllDataResponse appSignUpImplementation(AppSignUpRequest request)
        {
            if (String.IsNullOrWhiteSpace(request.email))
            {
                return(new AllDataResponse
                {
                    message = "Please enter an email.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.firstName))
            {
                return(new AllDataResponse
                {
                    message = "Please enter a first name.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.lastName))
            {
                return(new AllDataResponse
                {
                    message = "Please enter a last name.",
                    status = 404,
                    success = false,
                });
            }



            if (MembershipHelper.emailAlreadyExists(request.email, Constants.UserRole))
            {
                return(new AllDataResponse {
                    message = "Email is already taken", status = 10, success = false
                });
            }
            else if (String.IsNullOrWhiteSpace(request.password) || request.password.Length < 6)
            {
                return(new AllDataResponse {
                    message = "Please enter a password at least 6 characters long", status = 10, success = false
                });
            }

            var newUserGuid = MembershipHelper.createMembership(request.email, request.password, Constants.UserRole);
            var userId      = 0;

            using (var db = new UniversalGymEntities())
            {
                var newCode = UserCode.GenerateDistinctCode(db);
                var user    = new User
                {
                    FirstName             = request.firstName,
                    LastName              = request.lastName,
                    ReferalUrl            = newCode,
                    UserGuid              = newUserGuid,
                    Email                 = request.email.ToLower(),
                    hasActiveSubscription = false,
                    hasCreditCard         = false,
                    joinDate              = DateTime.Now,
                    Credits               = 0,
                };
                db.Users.Add(user);
                db.SaveChanges();
                userId = user.UserId;



                var newuserbody = "User Signup"
                                  + Environment.NewLine
                                  + "Email: "
                                  + user.Email
                                  + Environment.NewLine
                                  + "Name: "
                                  + user.FirstName
                                  + user.LastName;

                SlackHelper.sendUserSignupChannel(newuserbody);
            }

            EmailTemplateHelper.SendEmail("Welcome to Pedal", request.email, "http://pedal.com", request.firstName, "user_signup.html");

            return(allDataHelper.CreateAllDataResponse(userId, true));
        }
        public static BasicResponse updateGymInfoImplementation(UpdateGymInfoRequest request)
        {
            if (request == null || String.IsNullOrWhiteSpace(request.authToken) || request.accountId == null)
            {
                return(new BasicResponse
                {
                    message = "Gym not found.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.data.address))
            {
                return(new BasicResponse
                {
                    message = "Please enter an address.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.data.city))
            {
                return(new BasicResponse
                {
                    message = "Please enter a city.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.data.contactName))
            {
                return(new BasicResponse
                {
                    message = "Please enter a contact name.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.data.contactPhone))
            {
                return(new BasicResponse
                {
                    message = "Please enter a contact phone number.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.data.gymName))
            {
                return(new BasicResponse
                {
                    message = "Please enter a gym name.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.data.gymPhone))
            {
                return(new BasicResponse
                {
                    message = "Please enter a gym phone number.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.data.gymUrl))
            {
                return(new BasicResponse
                {
                    message = "Please enter a gym url.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.data.state))
            {
                return(new BasicResponse
                {
                    message = "Please enter a state.",
                    status = 404,
                    success = false,
                });
            }

            if (String.IsNullOrWhiteSpace(request.data.zip))
            {
                return(new BasicResponse
                {
                    message = "Please enter a zip code.",
                    status = 404,
                    success = false,
                });
            }

            using (var db = new UniversalGymEntities())
            {
                var gym = db.Gyms.SingleOrDefault(a => a.CurrentToken == request.authToken && a.GymId == request.accountId);
                if (gym == null)
                {
                    return(new BasicResponse
                    {
                        message = "Gym not found.",
                        status = 404,
                        success = false,
                    });
                }


                var state = db.TypeStates.FirstOrDefault(f => f.StateAbbreviation.ToLower() == request.data.state.ToLower()) ??
                            db.TypeStates.First(f => f.StateAbbreviation == "00");
                gym.ContactInfo1.Address.TypeStateId = state.TypeStateId;
                gym.ContactInfo1.Address.City        = request.data.city;
                gym.ContactInfo1.Address.Zip         = request.data.zip;
                gym.ContactInfo.Phone  = request.data.contactPhone;
                gym.ContactInfo1.Phone = request.data.gymPhone;
                gym.GymName            = request.data.gymName;
                gym.GymInfo            = request.data.description;
                gym.OwnerName          = request.data.contactName;
                var url = request.data.gymUrl;
                if (!String.IsNullOrWhiteSpace(url))
                {
                    gym.Url = new UriBuilder(url).Uri.ToString();
                }
                db.SaveChanges();


                db.SaveChanges();

                var target   = request.data.address + " " + request.data.state + " " + request.data.zip;
                var geocoded = Geocoder.GeoCodeAddress(target);

                if (geocoded != null)
                {
                    gym.Position = System.Data.Entity.Spatial.DbGeography.FromText(geocoded.GetPointString());
                    db.SaveChanges();
                }

                return(new BasicResponse()
                {
                    success = true, status = 200, message = "Success!"
                });
            }
        }
Ejemplo n.º 21
0
        public static GymSearchListResponse searchGymsByCityImplementation(SearchGymRequest request)
        {
            GymSearchListResponse rv;

            using (var db = new UniversalGymEntities())
            {
                var searchRequest = new Data.SearchRequest
                {
                    SearchDate             = DateTime.Now,
                    UniqueDeviceIdentifier = request.uniqueDeviceId,
                };

                if (request.longitude != 0 && request.latitude != 0)
                {
                    searchRequest.Position = System.Data.Entity.Spatial.DbGeography.FromText(String.Format("POINT({0} {1})", request.longitude, request.latitude));
                }



                if (!request.city.Equals("NULL"))
                {
                    searchRequest.Request = request.city;
                }

                if (!request.state.Equals("NULL"))
                {
                    searchRequest.Request = searchRequest.Request + " " + request.state ?? "NO STATE";
                }

                var user = db.Users.SingleOrDefault(a => a.CurrentToken == request.authToken && a.UserId == request.accountId);
                if (user != null)
                {
                    searchRequest.UserId = user.UserId;
                }


                db.SearchRequests.Add(searchRequest);
                db.SaveChanges();



                // convert city, state to lat, long
                var target   = searchRequest.Request;
                var geocoded = Geocoder.GeoCodeAddress(target);
                if (geocoded != null)
                {
                    var cityLocation = System.Data.Entity.Spatial.DbGeography.FromText(
                        String.Format("POINT({0} {1})",
                                      geocoded.Longitude,
                                      geocoded.Latitude));


                    var gyms = db.Gyms.Where(w => w.Position != null).OrderBy(o => o.Position.Distance(cityLocation));
                    rv = GymSearchListHelper.createGymSearchListResponse(gyms, cityLocation.Latitude, cityLocation.Longitude);
                    if (user != null)
                    {
                        rv.credits = user.Credits;
                    }
                    else
                    {
                        rv.credits = 0;
                    }

                    var searchText = "DeviceId: "
                                     + request.uniqueDeviceId
                                     + Environment.NewLine;
                    if (searchRequest.User != null)
                    {
                        searchText = searchText
                                     + "User: "******"Request: "
                                 + searchRequest.Request;

                    SlackHelper.sendSearchChannel(searchText, request.latitude.ToString(), request.longitude.ToString());
                }
                else
                {
                    var searchText = "";
                    if (searchRequest.User != null)
                    {
                        searchText = searchText
                                     + "User: "******"Request: "
                                 + searchRequest.Request;

                    SlackHelper.sendSearchChannelNotFound(searchText);

                    rv = new GymSearchListResponse {
                        success = false,
                        status  = 400,
                        message = "Could not find location"
                    };
                    if (user != null)
                    {
                        rv.credits = user.Credits;
                    }
                    else
                    {
                        rv.credits = 0;
                    }
                }
            }
            return(rv);
        }
        public static PurchaseGymResponse purchaseGymImplementation(PurchaseDayPassRequest request)
        {
            if (request == null || String.IsNullOrWhiteSpace(request.authToken) || request.accountId == null)
            {
                return(new PurchaseGymResponse
                {
                    message = "User not found.",
                    status = 404,
                    success = false,
                });
            }

            using (var db = new UniversalGymEntities())
            {
                var user = db.Users.SingleOrDefault(a => a.CurrentToken == request.authToken && a.UserId == request.accountId);
                if (user == null)
                {
                    return(new PurchaseGymResponse
                    {
                        message = "User not found.",
                        status = 404,
                        success = false,
                    });
                }

                if (String.IsNullOrWhiteSpace(user.StripeUrl))
                {
                    return(new PurchaseGymResponse {
                        message = "Please add a credit card.", status = 703, success = false
                    });
                }
                var gym = db.Gyms.SingleOrDefault(w => w.GymId == request.gymId);
                if (gym == null)
                {
                    return(new PurchaseGymResponse {
                        message = "Gym does not exist.", status = 701, success = false
                    });
                }

                var creditsUsed    = new CreditUse(db).UseCredit(user, gym.PriceToCharge);
                var amountToCharge = gym.PriceToCharge - creditsUsed;

                if (amountToCharge > 0)
                {
                    new StripeCharge().ChargeCardForPass(user.StripeUrl, amountToCharge, gym.GymName);
                }
                var locationString = "location=" + gym.Position.Latitude + ", " + gym.Position.Longitude;

                DateTime origin          = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                TimeSpan diff            = DateTime.UtcNow.ToUniversalTime() - origin;
                var      timeStamp       = Math.Floor(diff.TotalSeconds);
                var      timeStampString = "timestamp=" + timeStamp;
                var      googleUrl       = "https://maps.googleapis.com/maps/api/timezone/json?key=" + Constants.GoogleApiKey + "&" + timeStampString + "&" + locationString;

                Uri          uri              = new Uri(googleUrl);
                WebRequest   webRequest       = WebRequest.Create(uri);
                WebResponse  response         = webRequest.GetResponse();
                StreamReader streamReader     = new StreamReader(response.GetResponseStream());
                String       responseData     = streamReader.ReadToEnd();
                var          outObject        = JsonConvert.DeserializeObject <GoogleTimeZoneResponse>(responseData);
                DateTime     gymLocalDateTime = DateTime.UtcNow.AddSeconds(Convert.ToDouble(outObject.dstOffset) + Convert.ToDouble(outObject.rawOffset));

                var gymLocalEndOfDay = new DateTime(gymLocalDateTime.Year, gymLocalDateTime.Month, gymLocalDateTime.Day, 0, 0, 0, 000);
                gymLocalEndOfDay = gymLocalEndOfDay.AddDays(1);

                var item = new GymPass
                {
                    UserId               = user.UserId,
                    GymId                = request.gymId,
                    LocalDateBought      = gymLocalDateTime,
                    LocalDateExpired     = gymLocalEndOfDay,
                    CreditsUsed          = creditsUsed,
                    ServerTimeDateBought = DateTime.Now,
                    AmountCharged        = amountToCharge,
                    GymPassCost          = gym.CreditDollarValue,
                };
                db.GymPasses.Add(item);
                db.SaveChanges();

                var passText = "Pass Purchase"
                               + Environment.NewLine
                               + "User: "******"Gym: "
                               + item.Gym.GymName
                               + Environment.NewLine
                               + "Phone Number: "
                               + item.Gym.ContactInfo.Phone
                               + Environment.NewLine
                               + "LocalDateBought: "
                               + item.LocalDateBought
                               + Environment.NewLine
                               + "+ Credits Used: "
                               + intToMoney(item.CreditsUsed)
                               + Environment.NewLine
                               + "+ Amount Charged: "
                               + intToMoney(item.AmountCharged)
                               + Environment.NewLine
                               + "- Gym Pass Cost: "
                               + intToMoney(item.GymPassCost);

                SlackHelper.sendPassChannel(passText, item.Gym.Position.Latitude.ToString(), item.Gym.Position.Longitude.ToString());


                return(new PurchaseGymResponse
                {
                    message = "Pass Activated.",
                    status = 200,
                    success = true,
                    newCreditValue = user.Credits,
                    localGymDateTimeBought = gymLocalDateTime.ToString("MMM d, yyyy").ToUpper(),
                    localGymDateTimeExpiration = gymLocalEndOfDay.ToString("MMM d, yyyy").ToUpper()
                });
            }
        }
        public static UploadPictureResponse uploadPhotoImplementation(Stream file, string token, string accountId)
        {
            if (String.IsNullOrWhiteSpace(token))
            {
                return(new UploadPictureResponse
                {
                    message = "Gym not found.",
                    status = 404,
                    success = false,
                });
            }

            int accountIdAsInt;

            if (String.IsNullOrWhiteSpace(accountId) || !Int32.TryParse(accountId, out accountIdAsInt))
            {
                return(new UploadPictureResponse
                {
                    message = "Gym not found.",
                    status = 404,
                    success = false,
                });
            }


            var parser = new MultipartParser(file);

            using (var db = new UniversalGymEntities())
            {
                var gym = db.Gyms.SingleOrDefault(a => a.CurrentToken == token && a.GymId == accountIdAsInt);
                if (gym == null)
                {
                    new UploadPictureResponse
                    {
                        message = "Gym not found.",
                        status  = 404,
                        success = false,
                    };
                }

                if (gym.GymPhotoGalleries.Count >= 8)
                {
                    return(new UploadPictureResponse {
                        message = "You can only upload up to 8 images.", status = 404, success = false
                    });
                }

                if (parser.Success)
                {
                    // Make sure really is image and the kind we want
                    string[] supportedMimeTypes = { "images/png", "image/png", "image/jpeg", "images/jpeg", "image/jpg", "images/jpg" };

                    if (!supportedMimeTypes.Contains(parser.ContentType.ToString().ToLower()))
                    {
                        return(new UploadPictureResponse {
                            message = "Image needs to be .png or .jpg", status = 404, success = false
                        });
                    }

                    var megabyte      = 1024;
                    var fileSizeLimit = megabyte * 2;
                    if (parser.FileContents.Length < fileSizeLimit)
                    {
                        return(new UploadPictureResponse {
                            message = "Image too large", status = 404, success = false
                        });
                    }


                    var picture = new Data.GymPhotoGallery
                    {
                        GymId        = gym.GymId,
                        IsCoverPhoto = false
                    };
                    db.GymPhotoGalleries.Add(picture);


                    var filename = gym.GymId + "_" + Guid.NewGuid();

                    var storageAccount = CloudStorageAccount.Parse(Constants.BlobStorageConnectionString);

                    CloudBlobClient    blobClient    = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer blobContainer = blobClient.GetContainerReference(Constants.GymPicturesBlobContainerName);

                    CloudBlockBlob blob = blobContainer.GetBlockBlobReference(filename);
                    blob.Properties.ContentType = parser.ContentType;
                    blob.UploadFromByteArrayAsync(parser.FileContents, 0, parser.FileContents.Length);

                    //  the magical url to the picture
                    var url = blob.Uri.ToString();

                    picture.Photo = url;

                    // if no other photos, set isCoverPhoto to true
                    var hasCoverPhoto = db.GymPhotoGalleries.SingleOrDefault(a => a.GymId == gym.GymId && a.IsCoverPhoto == true);
                    if (hasCoverPhoto == null)
                    {
                        picture.IsCoverPhoto = true;
                    }

                    db.SaveChanges();

                    var uploadedPhoto = new pictureResult
                    {
                        url          = picture.Photo,
                        pictureId    = picture.GymPhotoGalleryId,
                        isCoverPhoto = picture.IsCoverPhoto,
                    };

                    // return back new url
                    return(new UploadPictureResponse {
                        status = 200, picture = uploadedPhoto, success = true, message = "Success!"
                    });
                }
                else
                {
                    return(new UploadPictureResponse {
                        status = 500, success = false, message = "Not able to parse file"
                    });
                }
            }
        }