NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using IntranetPortal.AppEntities.Moods;
using IntranetPortal.EmployeeMoods;
using IntranetPortal.EmployeeMoods.Dtos;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using Volo.Abp;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;
using System.Linq;
using System.Text.RegularExpressions;
using IntranetPortal.Responses;
using Volo.Abp.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
using System.IO;
using Volo.Abp.Application.Dtos;
using IntranetPortal.AppEntities;
using IntranetPortal.AppEntities.UserProfiles;

namespace IntranetPortal.AppServices.EmployeeMoods
{
[Authorize]
public class EmployeeMoodAppService : IntranetPortalAppService, IEmployeeMoodAppService
{
private readonly IRepository<Mood, Guid> _moodRepository;
private readonly IRepository<EmployeeMood, Guid> _employeeMoodRepository;
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly IRepository<IdentityUser, Guid> _identityUserRepository;
private readonly IConfiguration _configuration;
private readonly IRepository<Department, Guid> _departmentRepository;
private readonly IRepository<UserProfile, Guid> _userProfileRepository;
private readonly IRepository<Designation, Guid> _designationRepository;


public EmployeeMoodAppService(
IRepository<Mood, Guid> moodRepository,
IRepository<EmployeeMood, Guid> employeeMoodRepository,
IUnitOfWorkManager unitOfWorkManager,
IRepository<IdentityUser, Guid> identityUserRepository,
IConfiguration configuration,
IRepository<Department, Guid> departmentRepository,
IRepository<UserProfile, Guid> userProfileRepository,
IRepository<Designation, Guid> designationRepository)
{
_moodRepository = moodRepository;
_employeeMoodRepository = employeeMoodRepository;
_unitOfWorkManager = unitOfWorkManager;
_identityUserRepository = identityUserRepository;
_configuration = configuration;
_departmentRepository = departmentRepository;
_userProfileRepository = userProfileRepository;
_designationRepository = designationRepository;
}

public async Task<CreateMoodDto> CreateMoodAsync(CreateMoodInputDto input)
{
try
{
Logger.LogInformation($"CreateMood requested by User:{CurrentUser.Id}");

using (var uow = _unitOfWorkManager.Begin())
{
var moodQuery = await _moodRepository.GetQueryableAsync();

var urlRegex = @"^(?:http(s)?://)?[w.-]+(?:.[w.-]+)+[w-._~:/?#[]@!$&'()*+,;=.]+$";


if (await _moodRepository.AnyAsync(x => x.Name.ToLower() == input.Name.ToLower()))
{
throw new UserFriendlyException("A mood with same name already exists!");
}

if (string.IsNullOrWhiteSpace(input.Name))
{
throw new UserFriendlyException("Name cannot be empty!");
}

if (!Regex.IsMatch(input.IconUrl, urlRegex, RegexOptions.IgnoreCase))
{
throw new UserFriendlyException("Please enter a valid url.", "400");
}


var inputResult = new Mood
{
Name = input.Name,
IconUrl = input.IconUrl,
IsActive = input.IsActive
};

await _moodRepository.InsertAsync(inputResult);

if (await _moodRepository.CountAsync() == 0)
{
inputResult.OrderNumber = 1;
}
else
{
var maxOrderNumber = await _moodRepository.MaxAsync(x => x.OrderNumber);
inputResult.OrderNumber = maxOrderNumber + 1;
}

var result = new CreateMoodDto
{
Name = inputResult.Name,
IconUrl = inputResult.IconUrl,
IsActive = inputResult.IsActive,
OrderNumber = inputResult.OrderNumber
};

await uow.CompleteAsync();
Logger.LogInformation($"CreateMood responded for User:{CurrentUser.Id}");
return result;
}
}
catch(Exception ex)
{
Logger.LogException(ex);
throw new UserFriendlyException($"An exception was caught. {ex}");
}
}

public async Task<UpdateMoodDto> UpdateMoodAsync(UpdateMoodInputDto input)
{
try
{
Logger.LogInformation($"UpdateMood requested by User:{CurrentUser.Id}");

using (var uow = _unitOfWorkManager.Begin())
{

var urlRegex = @"^(?:http(s)?://)?[w.-]+(?:.[w.-]+)+[w-._~:/?#[]@!$&'()*+,;=.]+$";

var moodQuery = await _moodRepository.GetQueryableAsync();

var moodToUpdate = await _moodRepository.FindAsync(input.MoodId);


if (string.IsNullOrWhiteSpace(input.Name))
{
throw new UserFriendlyException("Name cannot be empty!");
}

if (!Regex.IsMatch(input.IconUrl, urlRegex, RegexOptions.IgnoreCase))
{
throw new UserFriendlyException("Please enter a valid url.", "400");
}


if (moodToUpdate != null)
{
//NEW VALUES SET
moodToUpdate.Name = input.Name;
moodToUpdate.IconUrl = input.IconUrl;
moodToUpdate.IsActive = input.IsActive;

var updatedMoodResult = await _moodRepository.UpdateAsync(moodToUpdate);

var result = new UpdateMoodDto
{
Name = moodToUpdate.Name,
IconUrl = moodToUpdate.IconUrl,
OrderNumber = moodToUpdate.OrderNumber,
IsActive = moodToUpdate.IsActive
};

uow.CompleteAsync();
Logger.LogInformation($"UpdateMood responded for User:{CurrentUser.Id}");

return result;
}
else
{
throw new UserFriendlyException($"Mood with ID {input.MoodId} not found.");
}
}

}
catch (Exception ex)
{
Logger.LogException(ex);
throw new UserFriendlyException($"An exception was caught. {ex}");
}
}

public async Task<List<GetActiveMoodDto>> GetActiveMoodsAsync()
{
try
{
Logger.LogInformation($"GetActiveMood requested by User:{CurrentUser.Id}");

var activeMoods = (await _moodRepository.GetQueryableAsync()).Where(x => x.IsActive == true).ToList();

List<GetActiveMoodDto> result = new List<GetActiveMoodDto>();

foreach(var activeMood in activeMoods)
{
result.Add(new GetActiveMoodDto
{
MoodId = activeMood.Id,
MoodName = activeMood.Name,
IconUrl = activeMood.IconUrl,
IsActive = activeMood.IsActive,
OrderNumber = activeMood.OrderNumber
});
}

Logger.LogInformation($"GetActiveMood responded for User:{CurrentUser.Id}");

result = result.OrderBy(x => x.OrderNumber).ToList();
return result;


}
catch (Exception ex)
{
Logger.LogException(ex);
throw new UserFriendlyException($"An exception was caught. {ex}");
}
}

public async Task<ResponseDto> DeleteMoodAsync(Guid id)
{
try
{
Logger.LogInformation($"Delete Mood requested by user {CurrentUser.Id}");
Logger.LogDebug($"Delete Mood requested for mood {(CurrentUser.Id, id)}");

using (var uow = _unitOfWorkManager.Begin())
{
var moodQuery = await _moodRepository.FindAsync(id);

if (moodQuery != null)
{
await _moodRepository.DeleteAsync(moodQuery);
Logger.LogInformation($"Deleted Successfully", "200");
}
else
{
throw new UserFriendlyException("There is no any moods with the given Id");
}
await uow.CompleteAsync();
Logger.LogInformation($"Delete Document responded for user {CurrentUser.Id}");
return new ResponseDto { Code = 200, Success = true, Message = "Deleted Successfully" };
}
}
catch (Exception ex)
{
Logger.LogError(ex, nameof(DeleteMoodAsync));
throw new UserFriendlyException("${ex}");
}
}

public async Task<GetMyMoodTodayDto> GetMyMoodForToday()
{
try
{
Logger.LogInformation($"GetMoods requested by user {CurrentUser.Id}");
Logger.LogDebug($"GetMoods requested for moods list {CurrentUser.Id}");

var today = new DateTime(2021,01,01);

var moodQuery = await _moodRepository.GetQueryableAsync();
var employeeMoodsQuery = (await _employeeMoodRepository.GetQueryableAsync()).Where(x => x.AbpUserId == CurrentUser.Id
&& x.CreationTime.Date == today.Date);
var designationQuery = await _designationRepository.GetQueryableAsync();
var departmentQuery = await _departmentRepository.GetQueryableAsync();
var userProfileQuery = await _userProfileRepository.GetQueryableAsync();
var userQuery = (await _identityUserRepository.GetQueryableAsync()).Where(x => x.Id == CurrentUser.Id);

var result = (from user in userQuery
join userPro in userProfileQuery on user.Id equals userPro.AbpUserId
join designation in designationQuery on userPro.DesignationId equals designation.Id
join department in departmentQuery on userPro.DepartmentId equals department.Id
join employeeMood in employeeMoodsQuery on user.Id equals employeeMood.AbpUserId
join moods in moodQuery on employeeMood.MoodId equals moods.Id
select new GetMyMoodTodayDto
{
MoodId = moods.Id,
EmployeeId = user.Id,
EmployeeFullName = user.Name + " " + userPro.MiddleName + " " + user.Surname,
MoodName = moods.Name,
MoodIconUrl = moods.IconUrl,
DepartmentId = department.Id,
DepartmentName = department.Name,
DesignationId = designation.Id,
DesignationName = designation.Name
}).FirstOrDefault();


Logger.LogInformation($"GetMyMood responded for User:{CurrentUser.Id}");

return result;

}
catch (Exception ex)
{
Logger.LogException(ex);
throw new UserFriendlyException($"An exception was caught. {ex}");

}
}

public async Task<GetMoodDto> GetMoodByIdAsync(Guid id)
{
try
{
Logger.LogInformation($"GetMoodById requested by user {CurrentUser.Id}");

var moods = await _moodRepository.FindAsync(id);

if(moods == null)
{
throw new UserFriendlyException("Moood not found");
}

var result = new GetMoodDto
{
Id = moods.Id,
Name = moods.Name,
IconUrl = moods.IconUrl,
OrderNumber = moods.OrderNumber,
IsActive = moods.IsActive
};

return result;
}
catch(Exception ex)
{
Logger.LogException(ex);
throw new UserFriendlyException($"An exception was caught. {ex}");
}
}

public async Task<ResponseDto> SetEmployeeMoodAsync(SetEmployeeMoodInputDto input)
{
try
{
Logger.LogInformation($"SetMood requested by user {CurrentUser.Id}");
Logger.LogDebug($"SetMood requested to set moods by employee{CurrentUser.Id}");

using(var uow = _unitOfWorkManager.Begin())
{
var today = DateTime.Today;
var loggedInUser = await _identityUserRepository.GetAsync(x =>x.Id == CurrentUser.Id);

var employee = (await _employeeMoodRepository.GetQueryableAsync()).Where(x =>x.AbpUserId == loggedInUser.Id
&& today.Date == x.CreationTime.Date);

var result = new EmployeeMood
{
MoodId = input.MoodId,
AbpUserId = loggedInUser.Id
};

if(employee.Count() == 0 )
{
await _employeeMoodRepository.InsertAsync(result);
}
else
{
throw new UserFriendlyException("Duplicate Mood selection is not available");
}

await uow.CompleteAsync();
Logger.LogInformation($"SetEmployeeMood responded for user {CurrentUser.Id}");

return new ResponseDto { Code = 200, Success = true, Message = "Employee Mood Set Successfully" };
}
}
catch (Exception ex)
{
Logger.LogException(ex);
throw new UserFriendlyException($"An exception was caught. {ex}");
}
}

public async Task<PagedResultDto<GetEmployeeMoodCountDto>> GetEmployeesMoodsCountForTodayAsync()
{
try
{
Logger.LogInformation($"GetEmployeesMoodForToday requested by user {CurrentUser.Id}");
Logger.LogDebug($"GetEmployeesMoodForToday requested to get moods of employee{CurrentUser.Id}");


var everyMood = await _moodRepository.GetQueryableAsync();
var moodsOfEmployee = await _employeeMoodRepository.GetQueryableAsync();
var employeesMood = (await _employeeMoodRepository.GetQueryableAsync()).Select(x => x.MoodId).ToList();

var result = (from moods in everyMood
join employeeMoods in moodsOfEmployee on moods.Id equals employeeMoods.MoodId

select new GetEmployeeMoodCountDto
{
MoodId = moods.Id,
MoodName = moods.Name,
IconUrl = moods.IconUrl
}).GroupBy(x => x.MoodId).Select(group => new GetEmployeeMoodCountDto
{
MoodId =group.Key,
Count = group.Count(),
MoodName = group.First().MoodName,
IconUrl = group.First().IconUrl
}).OrderByDescending(x => x.Count).ToList();

var totalCount = result.Count();

return new PagedResultDto<GetEmployeeMoodCountDto>(totalCount, result);


}
catch (Exception ex)
{
Logger.LogException(ex);
throw new UserFriendlyException($"An exception was caught. {ex}");
}
}

public async Task<string> UploadMoodLogo(IFormFile logo)
{
try
{
if (logo is null)
{
throw new UserFriendlyException("Logo file is required");
}
var whitelistedExtensions = _configuration["App:WhitelistedExtentionsForEmployeeMoodLogos"].Split(',');
var fileExtension = Path.GetExtension(logo.FileName).TrimStart('.').ToLower();

if (!whitelistedExtensions.Contains(fileExtension))
{
throw new UserFriendlyException("File extension is not allowed");

}

var basePath = _configuration["App:EmployeeMoodLogoBaseLocation"];
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}

var randomizedLogoName = Path.GetFileNameWithoutExtension(logo.FileName) + Guid.NewGuid() + Path.GetExtension(logo.FileName);

var filePath = Path.Combine(basePath, randomizedLogoName);
using var fileStream = new FileStream(filePath, FileMode.Create);
await logo.CopyToAsync(fileStream);

Logger.LogInformation($"UploadMoodLogo responded for User:{CurrentUser.Id}");
return randomizedLogoName;


}
catch (Exception ex)
{
Logger.LogException(ex);
throw new UserFriendlyException($"An exception was caught. {ex}");
}
}

}
}

     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.