Skip to content

Commit

Permalink
revision 6
Browse files Browse the repository at this point in the history
  • Loading branch information
Dhiogo Acioli committed Sep 23, 2022
1 parent 04c8fd1 commit 77da95a
Show file tree
Hide file tree
Showing 15 changed files with 211 additions and 181 deletions.
2 changes: 0 additions & 2 deletions src/VerusDate.Api/Core/Interfaces/IRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ public interface IRepository
{
Task<T> Get<T>(string id, string partitionKeyValue, CancellationToken cancellationToken) where T : CosmosBase;

Task<T> Get<T>(QueryDefinition query, string partitionKeyValue, CancellationToken cancellationToken) where T : class;

Task<List<T>> Query<T>(Expression<Func<T, bool>> predicate, string partitionKeyValue, CosmosType Type, CancellationToken cancellationToken) where T : CosmosBase;

Task<List<T>> Query<T>(QueryDefinition query, CancellationToken cancellationToken) where T : CosmosBaseQuery;
Expand Down
40 changes: 12 additions & 28 deletions src/VerusDate.Api/Mediator/Queries/Profile/ProfileGetViewCommand.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.Cosmos;
using System.Text;
using System;
using System.Threading;
using System.Threading.Tasks;
using VerusDate.Api.Core.Interfaces;
using VerusDate.Shared.Core;
using VerusDate.Shared.Helper;
using VerusDate.Shared.Model;

namespace VerusDate.Api.Mediator.Queries.Profile
Expand Down Expand Up @@ -37,35 +37,19 @@ public ProfileGetViewHandler(IRepository repo)

public async Task<ProfileView> Handle(ProfileGetViewCommand request, CancellationToken cancellationToken)
{
var SQL = new StringBuilder();
var profile = await _repo.Get<ProfileView>(request.GetId(request.IdUserView), request.IdUserView, cancellationToken);

SQL.Append("SELECT ");
SQL.Append(" c.key as id ");
SQL.Append(" , c.modality, c.nickName, c.description, c.location, c.languages, c.currentSituation, c.intentions, c.biologicalSex, c.genderIdentity, c.sexualOrientation "); //basic
SQL.Append(" , c.zodiac, c.height, c.raceCategory, c.bodyMass "); //bio
SQL.Append(" , c.drink, c.smoke, c.diet, c.haveChildren, c.wantChildren, c.educationLevel, c.careerCluster, c.religion, c.travelFrequency "); //lifestyle
SQL.Append(" , c.moneyPersonality, c.splitTheBill, c.relationshipPersonality, c.myersBriggsTypeIndicator, c.loveLanguage, c.sexPersonality "); //personality
SQL.Append(" , c.food, c.vacation, c.sports, c.leisureActivities, c.musicGenre, c.movieGenre, c.tvGenre, c.readingGenre "); //interests
SQL.Append(" , c.neurodiversity, c.disabilities "); //others
SQL.Append(" , c.preference ");
SQL.Append(" , c.badge ");
SQL.Append(" , c.photo ");
SQL.Append(" , c.reports ");
SQL.Append(" , TRUNC(DateTimeDiff('month',c.birthDate,GetCurrentDateTime())/12) Age ");
SQL.Append(" , c.dtLastLogin >= DateTimeAdd('d',-1,GetCurrentDateTime()) ? 1 ");
SQL.Append(" : c.dtLastLogin >= DateTimeAdd('d',-7,GetCurrentDateTime()) ? 2 ");
SQL.Append(" : c.dtLastLogin >= DateTimeAdd('m',-1,GetCurrentDateTime()) ? 3 ");
SQL.Append(" : 4 ");
SQL.Append(" as ActivityStatus ");
//SQL.Append(" , ROUND(ST_DISTANCE({'type': 'Point', 'coordinates':[@latitude, @longitude]},{'type': 'Point', 'coordinates':[c.basic.latitude, c.basic.longitude]}) / @valueCalDistance) as Distance ");
SQL.Append("FROM ");
SQL.Append(" c ");
SQL.Append("WHERE ");
SQL.Append($" c.id = '{request.Type}:{request.IdUserView}'");
profile.Age = profile.BirthDate.GetAge();
profile.BirthDate = DateTime.MinValue;

var query = new QueryDefinition(SQL.ToString());
profile.ActivityStatus = Shared.Enum.ActivityStatus.Today;

return await _repo.Get<ProfileView>(query, request.IdUserView, cancellationToken);
if (profile.DtLastLogin >= DateTime.UtcNow.AddDays(-1)) profile.ActivityStatus = Shared.Enum.ActivityStatus.Today;
else if (profile.DtLastLogin >= DateTime.UtcNow.AddDays(-7)) profile.ActivityStatus = Shared.Enum.ActivityStatus.Week;
else if (profile.DtLastLogin >= DateTime.UtcNow.AddMonths(-1)) profile.ActivityStatus = Shared.Enum.ActivityStatus.Month;
else profile.ActivityStatus = Shared.Enum.ActivityStatus.Disabled;

return profile;
}
}
}
44 changes: 21 additions & 23 deletions src/VerusDate.Api/Repository/CosmosRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ public class CosmosRepository : IRepository
{
public Container Container { get; private set; }

private const double ru_limit_get = 2;
private const double ru_limit_query = 4;
private const double ru_limit_save = 30; //15
private const double ru_limit_get = 1.5;
private const double ru_limit_query = 3;
private const double ru_limit_save = 15;

public CosmosRepository(IConfiguration config)
{
Expand Down Expand Up @@ -80,26 +80,6 @@ public async Task<T> Get<T>(string id, string partitionKeyValue, CancellationTok
}
}

public async Task<T> Get<T>(QueryDefinition query, string partitionKeyValue, CancellationToken cancellationToken) where T : class
{
using var iterator = Container.GetItemQueryIterator<T>(query, requestOptions: CosmosRepositoryExtensions.GetDefaultOptions(partitionKeyValue));
double count = 0;

if (iterator.HasMoreResults)
{
var response = await iterator.ReadNextAsync(cancellationToken);

count += response.RequestCharge;
if (count > ru_limit_query) throw new NotificationException($"RU limit exceeded get ({response.RequestCharge})");

return response.Resource.FirstOrDefault();
}
else
{
return null;
}
}

public async Task<List<T>> Query<T>(Expression<Func<T, bool>> predicate, string partitionKeyValue, CosmosType Type, CancellationToken cancellationToken) where T : CosmosBase
{
IQueryable<T> query;
Expand Down Expand Up @@ -203,4 +183,22 @@ public async Task<bool> Delete<T>(T item, CancellationToken cancellationToken) w
//composite indexes
//https://docs.microsoft.com/pt-br/learn/modules/customize-indexes-azure-cosmos-db-sql-api/3-evaluate-composite-indexes
}

public static class CosmosRepositoryExtensions
{
public static QueryRequestOptions GetDefaultOptions(string partitionKeyValue)
{
if (string.IsNullOrEmpty(partitionKeyValue))
return null;
else
return new QueryRequestOptions()
{
PartitionKey = new PartitionKey(partitionKeyValue),
//https://learn.microsoft.com/en-us/training/modules/measure-index-azure-cosmos-db-sql-api/4-measure-query-cost
MaxItemCount = 10, //max itens per page
//https://learn.microsoft.com/en-us/training/modules/measure-index-azure-cosmos-db-sql-api/2-enable-indexing-metrics
PopulateIndexMetrics = false //enable only when analysing metrics
};
}
}
}
15 changes: 0 additions & 15 deletions src/VerusDate.Api/Repository/CosmosRepositoryExtensions.cs

This file was deleted.

16 changes: 9 additions & 7 deletions src/VerusDate.Shared/Core/CustomAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@ namespace VerusDate.Shared.Core
public class CustomAttribute : Attribute
{
public string Name { get; set; }

public string Description { get; set; }

public string Group { get; set; }

public string Prompt { get; set; }

public string FieldInfo { get; set; }

/// <summary>
/// format: Title 1|Description 1|Title 2|Description 2
/// </summary>
public string Tips { get; set; }

/// <summary>
/// Translations resource file
/// </summary>
Expand Down Expand Up @@ -65,11 +66,12 @@ public static CustomAttribute GetCustomAttribute(this MemberInfo mi, bool transl
{
var rm = new ResourceManager(attr.ResourceType.FullName ?? "", attr.ResourceType.Assembly);

if (!string.IsNullOrEmpty(attr.Name)) attr.Name = rm.GetString(attr.Name) ?? attr.Name + " (error)";
if (!string.IsNullOrEmpty(attr.Description)) attr.Description = rm.GetString(attr.Description) ?? attr.Description + " (error)";
if (!string.IsNullOrEmpty(attr.Name)) attr.Name = rm.GetString(attr.Name) ?? attr.Name + " (incomplete translation)";
if (!string.IsNullOrEmpty(attr.Description)) attr.Description = rm.GetString(attr.Description) ?? attr.Description + " (incomplete translation)";
if (!string.IsNullOrEmpty(attr.Group)) attr.Group = rm.GetString(attr.Group);
if (!string.IsNullOrEmpty(attr.Prompt)) attr.Prompt = rm.GetString(attr.Prompt).Replace(@"\n", Environment.NewLine);
if (!string.IsNullOrEmpty(attr.FieldInfo)) attr.FieldInfo = rm.GetString(attr.FieldInfo) ?? attr.FieldInfo + " (error)";
if (!string.IsNullOrEmpty(attr.FieldInfo)) attr.FieldInfo = rm.GetString(attr.FieldInfo)?.Replace(@"\n", Environment.NewLine) ?? attr.FieldInfo.Replace(@"\n", Environment.NewLine) + " (incomplete translation)";
if (!string.IsNullOrEmpty(attr.Tips)) attr.Tips = rm.GetString(attr.Tips) ?? attr.Tips + " (incomplete translation)";
}

return attr;
Expand Down
21 changes: 15 additions & 6 deletions src/VerusDate.Shared/Model/Profile/ProfileModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,17 @@ public ProfileModel() : base(CosmosType.Profile)
[Custom(Name = "Height_Name", ResourceType = typeof(Resources.Model.ProfileBioModel))]
public Height? Height { get; set; }

[Custom(Name = "Neurodiversity_Name", ResourceType = typeof(Resources.Model.ProfileBioModel))]
//https://www.gottman.com/blog/two-different-brains-in-love-conflict-resolution-in-neurodiverse-relationships/
[Custom(
Name = "Neurodiversity_Name",
FieldInfo = " Relacionamentos românticos neurodiversos incluem pelo menos um ou mais parceiros neurodivergentes. A neurodiversidade refere-se à variação nas diferenças neurológicas que ocorrem naturalmente em todos os humanos, com 15-20% das pessoas caindo na categoria de neurodivergentes. Os maiores conflitos nos relacionamentos neurodiversos se resumem à dificuldade que os indivíduos têm em entender as diferenças na forma como cada parceiro processa as informações. Para que seus relacionamentos neurodiversos prosperem, é importante se concentrar em entender as diferenças em como você e seu parceiro processam informações e como isso afeta sua capacidade de entender um ao outro.",
Tips = "Compreenda e honre as diferenças|Consulte o seu médico ou terapeuta. É importante que você e seu parceiro aprendam como ambos processam informações, honram essas diferenças e aprendem a definir expectativas realistas em torno delas.|Faça um inventário|Faça um inventário com seu parceiro sobre as coisas com as quais vocês dois lutam. Está interrompendo? Tirar conclusões precipitadas? Sobrecarga sensorial? Desligar? Faça um plano sobre como lidar com isso antes que eles apareçam. Talvez um parceiro possa tentar ouvir com mais atenção, enquanto o outro trabalha para entender que isso pode ser difícil para o parceiro.|Trabalhe em uma comunicação clara e não defensiva|Estabeleça como meta se comunicar direta e claramente quando se trata de tópicos que podem se transformar em conflito. Implemente start-ups suaves e dê ao seu parceiro o benefício da dúvida. Algumas pessoas se saem melhor com conversas telefônicas com tempo limitado, videochamadas ou cartas escritas em vez de conversas cara a cara. Lembre-se de que, desde que o relacionamento não seja abusivo, não há “jeito certo” ou “jeito errado”, simplesmente duas maneiras diferentes de ver as coisas.|Compreender o papel das questões sensoriais|Se você é o parceiro neurodivergente, reconheça suas próprias sensibilidades à luz, som, toque, cheiro, sabor e sentido para poder comunicá-las ao seu parceiro. Se você é o parceiro neurotípico, entenda como isso pode afetar o sistema nervoso do seu parceiro e como sua capacidade de gerenciá-los está comprometida. Honrar e atender a essas necessidades básicas de regulação do sistema nervoso pode desempenhar um papel enorme no desenvolvimento da intimidade e na aproximação do relacionamento.",
ResourceType = typeof(Resources.Model.ProfileBioModel))]
public Neurodiversity? Neurodiversity { get; set; }

[Custom(Name = "Disabilities_Name", ResourceType = typeof(Resources.Model.ProfileBioModel))]
//https://medium.com/@emily_rj/10-things-to-know-before-dating-someone-with-a-disability-6bf6eb8ae196
//We all desire and deserve to have meaningful relationships where we feel loved and appreciated. This need is felt by people with disabilities too. Some people may be surprised by this because they assume people with disabilities do not date, marry, or desire intimate relationships. But, this isn’t true. In fact, there is no difference between people with disabilities need and desire for healthy and happy relationships and those of non-disabled people.
[Custom(Name = "Disabilities_Name", FieldInfo = "Todos nós desejamos e merecemos ter relacionamentos significativos onde nos sentimos amados e apreciados. Essa necessidade também é sentida por pessoas com deficiência. Algumas pessoas podem se surpreender com isso porque assumem que pessoas com deficiência não namoram, casam ou desejam relacionamentos íntimos. Mas, isso não é verdade. De fato, não há diferença entre a necessidade e o desejo de pessoas com deficiência por relacionamentos saudáveis e felizes e os de pessoas sem deficiência.", ResourceType = typeof(Resources.Model.ProfileBioModel))]
public IReadOnlyList<Disability> Disabilities { get; set; } = Array.Empty<Disability>();

#endregion BIO
Expand All @@ -99,14 +106,16 @@ public ProfileModel() : base(CosmosType.Profile)
[Custom(Name = "WantChildren_Name", ResourceType = typeof(Resources.Model.ProfileLifestyleModel))]
public WantChildren? WantChildren { get; set; }

//The intention of this evaluation is not to judge the paths that each one takes in life, but to statistically group people who have different potentials in their professional life or most of the time have decided to lead a life focused only on studies/research.
[Custom(Name = "EducationLevel_Name", FieldInfo = "A intenção desta avaliação não é julgar os caminhos que cada um toma na vida, mas estatisticamente agrupar pessoas que tem potenciais diferentes na sua vida profissional ou na maioria das vezes decidiu levar uma vida voltada apenas para os estudos/pesquisas.", ResourceType = typeof(Resources.Model.ProfileLifestyleModel))]
//The intention of this field is not to judge the paths chosen by each or the opportunities they had in life, but statistically speaking, partners who have similar levels of education tend to have the same potential for growth in personal/professional life or even have a similar lifestyle (for those who decided to dedicate themselves exclusively to studies/research). Or, if they have different levels of education, one partner may feel intimidated towards the other.
[Custom(Name = "EducationLevel_Name", FieldInfo = "A intenção deste campo não é julgar os caminhos escolhidos por cada um ou as oportunidades que tiveram na vida, mas estatisticamente falando, os parceiros que possuem níveis de escolaridade semelhantes tendem a ter os mesmos potenciais de crescimento na vida pessoal/profissional ou até mesmo ter um estilo de vida semelhante (para quem decidiu dedicar-se exclusivamente aos estudos/pesquisa). Ou, no caso de terem niveis de escolaridade diferentes, um dos parceiros poderá se sentir intimidado em relação ao outro.", ResourceType = typeof(Resources.Model.ProfileLifestyleModel))]
public EducationLevel? EducationLevel { get; set; }

[Custom(Name = "CareerCluster_Name", ResourceType = typeof(Resources.Model.ProfileLifestyleModel))]
//First, let's make it clear that having different careers does not mean that there will be conflicts in the relationship, but the idea is that in most cases these conflicts can be mitigated precisely because both partners better understand the context of the situation. It could be: irregular working hours, pressure to deliver a result, being a public person, need to travel constantly or move to another state/country (it's easier to have access to the same opportunities), etc.
[Custom(Name = "CareerCluster_Name", FieldInfo = "Primeiramente, vamos deixar claro que ter carreiras diferentes, não significa que poderão existir conflitos no relacionamento, mas a idéia é que na maioria das vezes esses conflitos poderão ser amenizados justamente porque ambos os parceiros entendem melhor o contexto da situação. Podendo ser: horários de trabalho irregulares, pressão para entregar algum resultado, ser uma pessoa pública, necessidade de viajar constantemente ou se mudar de estado/país (é mais fácil terem acesso as mesmas oportunidades), etc.", ResourceType = typeof(Resources.Model.ProfileLifestyleModel))]
public CareerCluster? CareerCluster { get; set; }

[Custom(Name = "Religion_Name", ResourceType = typeof(Resources.Model.ProfileLifestyleModel))]
//Although some research indicates that religious beliefs are not a key factor in relationship success, this can greatly reduce conflicts in partners' communication/thinking or even in relationships with friends and family. Depending on the country/religion/culture, there may be many restrictions on relationships between people of different religions.
[Custom(Name = "Religion_Name", FieldInfo = "Apesar de que algumas pesquisas indiquem que crenças religiosas não é um fator chave no sucesso do relacionamento, isso pode diminuir bastante conflitos na comunicação/forma de pensar dos parceiros ou até mesmo no relacionamento com amigos e familiares. A depender do país/religião/cultura, poderá existir muitas restrições quanto a relacionamentos entre pessoas de religiões diferentes.", ResourceType = typeof(Resources.Model.ProfileLifestyleModel))]
public Religion? Religion { get; set; }

[Custom(Name = "Travel Frequency")]
Expand Down
6 changes: 3 additions & 3 deletions src/VerusDate.Shared/Resources/Enum/Drink.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 77da95a

Please sign in to comment.