public bool SetSubscriptionWithPromo(string UserCode, int IdPlan, string AppToken, string TagPromo) { //verificar existencia de la app token //obtiene ID de producto int idProduct = productsRepository.GetProductId(AppToken); if (idProduct == 0) { throw new Contract.Exceptions.ProductsNotFoundException("No se encontró un producto con el ProductToken " + AppToken, null); } //obtener usuario segun el app token y external code var user = usersRepository.GetUser(UserCode, idProduct); if (user == null) { throw new Contract.Exceptions.UserNotFoundException("No se encontró un usuario con el UserCode " + UserCode, null); } //voy a buscar la promo var promo = this.promosRepository.GetPromo(idProduct, TagPromo); //si el tag es nulo o vacio, elimino if (String.IsNullOrEmpty(TagPromo)) { promo = null; } //por si esta mal configurada la promo if (promo != null && promo.FreeDays == null) { promo.FreeDays = 0; } //voy a buscar el profile por defecto var profile = this.profilesRepository.GetStandardFreeSuscription(user.IdUser); if (profile != null) { IdPlan = profile.IdProfile; } /* * if (promo == null) { * //throw new Contract.Exceptions.PromoNotFoundException("No se encontró promocion con Tag " + TagPromo, null); * //genero promo en blanco para que peuda leer más adelante * * * }*/ //verificar si existe una suscripcion actual. Si existe se cambia el IDPERFIL. var sub = subscriptionsRepository.GetUserCurrentSubscription(user.IdUser); if (sub == null) { //Si no existe, se crea la suscripcion. Repository.EntityFramework.Subscriptions subs = new Repository.EntityFramework.Subscriptions { Active = true, DateCreated = DateTime.Now, ExternalCode = "", IdProfile = IdPlan, IdUser = user.IdUser, IsCurrent = true, RenewalDay = DateTime.Now.Day //LastRenewal = DateTime.Now.AddDays(addDays) }; //si hay promo, le seteo los datos. if (promo != null) { subs.IdProfile = promo.IdProfileActivePromo; //le setea el perfil que debe ir con la promo, independiente del que se envia por el servicio subs.PromoActive = true; subs.PromoStarted = DateTime.Now; subs.PromoEnd = DateTime.Now.AddDays((int)promo.FreeDays); subs.PromoFreeDays = promo.FreeDays; subs.IdPromo = promo.IdPromo; } //guardo la nueva subscripcion subscriptionsRepository.NewSubscription(subs); } else { //si existe, se setea el nuevo perfil y se asigna la promo subscriptionsRepository.SetSubscriptionProfileWithPromo(sub.IdSubscription, IdPlan, promo); } return(true); }
/// <summary> /// Will set or update all related to change one profile. Need to be gobernated by transaction /// in order to keep consistency. Whatever profile is free or premium, requires create subscription /// Subscription links profile with user /// </summary> /// <param name="idProfile">ID new profile to be setted</param> /// <param name="idUser">ID user (freemium)</param> /// <param name="idClient">ID user MASTER</param> /// <param name="idProduct">ID product</param> /// <returns></returns> public bool SetProfileUser(int idProfile, int idUser, int idClient, int idProduct) { try { // User exists if (idUser != 0) { // Find for subscription var subscription = GetUserCurrentSubscription(idUser); // Will check if profile is the same or not if (subscription.IdProfile == idProfile) { this.lastError = "El perfil enviado es el mismo al actual del usuario"; return(false); } // STEP A1: If it exists, will check for UserDimensions (trying to delete them) var userDimensions = db.UsersDimensions.Where(e => e.IdSubscription == subscription.IdSubscription); foreach (EntityFramework.UsersDimensions oUserDimension in userDimensions) { db.UsersDimensions.Remove(oUserDimension); } // STEP A2: Update user to new profile subscription.IdProfile = idProfile; // STEP A3: Recreate UserDimensions if new profile has consumible dimensions // Get dimensions by profile List <EntityFramework.Dimensions> dimensions = db.Dimensions.Where(e => e.ProfilesDimensions.Any(j => j.IdProfile == idProfile)).ToList(); if (dimensions.Count > 0) { foreach (var oDimension in dimensions) { // STEP A4: Check if dimension type is consumible if (oDimension.IdDimensionType == (int)DimensionTypeEnum.CONSUMIBLE) { int idDimension = oDimension.IdDimension; // Create new UserDimension var userdimension = new EntityFramework.UsersDimensions(); userdimension.IdDimension = idDimension; userdimension.DateCreated = DateTime.Now; userdimension.DateLastUpdate = DateTime.Now; userdimension.IdSubscription = subscription.IdSubscription; userdimension.Active = true; // Find value between profile and dimension var profileDimension = db.ProfilesDimensions.Where(e => e.IdProfile == idProfile && e.IdDimension == idDimension).FirstOrDefault(); // Set default value userdimension.CurrentValue = profileDimension.Value; db.UsersDimensions.Add(userdimension); } } } // Commit db.SaveChanges(); } else { // If it doesn't exist, will set profile to user using (EntityFramework.FriPriEntities context = new EntityFramework.FriPriEntities()) { if (context.Database.Connection.State != ConnectionState.Open) { context.Database.Connection.Open(); } using (var transaction = context.Database.BeginTransaction()) { try { // Create user EntityFramework.Users newClient = new Repository.EntityFramework.Users { Active = true, ExternalCode = idClient.ToString(), // ID user master IdProduct = idProduct }; context.Users.Add(newClient); context.SaveChanges(); // Create subscription EntityFramework.Subscriptions newSubscription = new Repository.EntityFramework.Subscriptions { Active = true, DateCreated = DateTime.Now, ExternalCode = "", IdProfile = idProfile, IdUser = newClient.IdUser, IsCurrent = true, RenewalDay = DateTime.Now.Day, LastRenewal = DateTime.Now }; context.Subscriptions.Add(newSubscription); context.SaveChanges(); // Get dimensions by profile List <EntityFramework.Dimensions> dimensions = context.Dimensions.Where(e => e.ProfilesDimensions.Any(j => j.IdProfile == idProfile)).ToList(); if (dimensions.Count > 0) { foreach (var oDimension in dimensions) { // STEP A4: Check if dimension type is consumible if (oDimension.IdDimensionType == (int)DimensionTypeEnum.CONSUMIBLE) { int idDimension = oDimension.IdDimension; // Create new UserDimension var userdimension = new EntityFramework.UsersDimensions(); userdimension.IdDimension = idDimension; userdimension.DateCreated = DateTime.Now; userdimension.DateLastUpdate = DateTime.Now; userdimension.IdSubscription = newSubscription.IdSubscription; userdimension.Active = true; // Find value between profile and dimension var profileDimension = context.ProfilesDimensions.Where(e => e.IdProfile == idProfile && e.IdDimension == idDimension).FirstOrDefault(); // Set default value userdimension.CurrentValue = profileDimension.Value; context.UsersDimensions.Add(userdimension); } } context.SaveChanges(); transaction.Commit(); } } catch (Exception e) { transaction.Rollback(); this.lastError = e.Message; return(false); } finally { if (context.Database.Connection.State == ConnectionState.Open) { context.Database.Connection.Close(); } } } } // using } // end general if-else return(true); } catch (Exception) { return(false); } }
// -------------------------------------------------- DEPRECATED LOGIC -------------------------------------------------- public Subscriptions Get(string ProductToken, string UserCode) { //obtiene ID de producto int idProduct = productsRepository.GetProductId(ProductToken); if (idProduct == 0) { throw new Contract.Exceptions.ProductsNotFoundException("No se encontró un producto con el ProductToken " + ProductToken, null); } //obtiene datos del usuario var user = usersRepository.GetUser(UserCode, idProduct); if (user == null) { throw new Contract.Exceptions.UserNotFoundException("No se encontró un usuario con el UserCode " + UserCode, null); } if (user.Active == false) { throw new Contract.Exceptions.UserInactiveException("El usuario indicado no se encuentra Activo en la plataforma", null); } //obtiene datos del perfil del usuario respecto al producto var subscription = subscriptionsRepository.GetUserCurrentSubscription(user.IdUser); //perfil segun suscripcion Repository.EntityFramework.Profiles profile; if (subscription == null) { //si no tiene suscripcion, le crea una en el estándar de suscrito sin suscripción. profile = profilesRepository.GetStandardFreeSuscription(user.IdUser); if (profile == null) { throw new Contract.Exceptions.StandardProfileNotFoundException("El producto no tiene un perfil estándar para cuando el usuario está registrado pero no está suscrito a ningún perfil. Usuario: " + UserCode, null); } //setea suscripción vacía subscription = new Repository.EntityFramework.Subscriptions(); } else { profile = subscription.Profiles; if (profile == null) { //si no tiene suscripcion, le crea una en el estándar de suscrito sin suscripción. profile = profilesRepository.GetStandardFreeSuscription(user.IdUser); if (profile == null) { throw new Contract.Exceptions.StandardProfileNotFoundException("El producto no tiene un perfil estándar para cuando el usuario está registrado pero no está suscrito a ningún perfil. Usuario: " + UserCode, null); } } } List <UsersDimensions> dimensiones = new List <UsersDimensions>(); foreach (var item in subscription.UsersDimensions) { dimensiones.Add(new UsersDimensions() { IdDimension = (int)item.IdDimension, Dimension = item.Dimensions.Description, CurrentValue = (decimal)item.CurrentValue, TagName = item.Dimensions.TagName }); } //genera objeto de salida return(new Subscriptions { IdSubscription = subscription.IdSubscription, ExternalCode = subscription.ExternalCode, DateCreated = subscription.DateCreated, RenewalDay = subscription.RenewalDay, LastRenewal = subscription.LastRenewal, //IdUser = subscription.IdUser, //no debe ir dentro de lo que se expone como servicio. es de uso interno. Se utiliza el user de abajo como objeto IsCurrent = subscription.IsCurrent, Users = new Users { Active = user.Active, Email = user.Email, ExternalCode = user.ExternalCode }, Profiles = new Profiles { ProfileId = profile.IdProfile, Active = profile.Active, Description = profile.Description, Name = profile.Name, TagName = profile.TagName, Paid = profile.Paid }, PromoFreeDays = subscription.PromoFreeDays, PromoStarted = subscription.PromoStarted, PromoEnd = subscription.PromoEnd, PromoActive = subscription.PromoActive, IdPromo = subscription.IdPromo, Dimensions = dimensiones }); }