Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fork.paramo.sebastian.zunini #44

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
199 changes: 28 additions & 171 deletions Sat.Recruitment.Api/Controllers/UsersController.cs
Original file line number Diff line number Diff line change
@@ -1,202 +1,59 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Sat.Recruitment.Api.ViewModel;
using Sat.Recruitment.Domain.Contracts.Services;
using Sat.Recruitment.Domain.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Sat.Recruitment.Api.Controllers
{
public class Result
{
public bool IsSuccess { get; set; }
public string Errors { get; set; }
}

[ApiController]
[Route("[controller]")]
public partial class UsersController : ControllerBase
public class UsersController : ControllerBase
{
private readonly IMapper _mapper;
private readonly IUserService _userService;
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

private readonly List<User> _users = new List<User>();
public UsersController()
public UsersController(IMapper mapper, IUserService userService)
{
_userService = userService;
_mapper = mapper;
}

[HttpPost]
[Route("/create-user")]
public async Task<Result> CreateUser(string name, string email, string address, string phone, string userType, string money)

public async Task<ActionResult> CreateUser([FromBody] UserViewModel userViewModel)
{
var errors = "";

ValidateErrors(name, email, address, phone, ref errors);

if (errors != null && errors != "")
return new Result()
{
IsSuccess = false,
Errors = errors
};

var newUser = new User
{
Name = name,
Email = email,
Address = address,
Phone = phone,
UserType = userType,
Money = decimal.Parse(money)
};

if (newUser.UserType == "Normal")
{
if (decimal.Parse(money) > 100)
{
var percentage = Convert.ToDecimal(0.12);
//If new user is normal and has more than USD100
var gif = decimal.Parse(money) * percentage;
newUser.Money = newUser.Money + gif;
}
if (decimal.Parse(money) < 100)
{
if (decimal.Parse(money) > 10)
{
var percentage = Convert.ToDecimal(0.8);
var gif = decimal.Parse(money) * percentage;
newUser.Money = newUser.Money + gif;
}
}
}
if (newUser.UserType == "SuperUser")
{
if (decimal.Parse(money) > 100)
{
var percentage = Convert.ToDecimal(0.20);
var gif = decimal.Parse(money) * percentage;
newUser.Money = newUser.Money + gif;
}
}
if (newUser.UserType == "Premium")
{
if (decimal.Parse(money) > 100)
{
var gif = decimal.Parse(money) * 2;
newUser.Money = newUser.Money + gif;
}
}


var reader = ReadUsersFromFile();

//Normalize email
var aux = newUser.Email.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);

var atIndex = aux[0].IndexOf("+", StringComparison.Ordinal);

aux[0] = atIndex < 0 ? aux[0].Replace(".", "") : aux[0].Replace(".", "").Remove(atIndex);

newUser.Email = string.Join("@", new string[] { aux[0], aux[1] });

while (reader.Peek() >= 0)
{
var line = reader.ReadLineAsync().Result;
var user = new User
{
Name = line.Split(',')[0].ToString(),
Email = line.Split(',')[1].ToString(),
Phone = line.Split(',')[2].ToString(),
Address = line.Split(',')[3].ToString(),
UserType = line.Split(',')[4].ToString(),
Money = decimal.Parse(line.Split(',')[5].ToString()),
};
_users.Add(user);
}
reader.Close();
try
{
var isDuplicated = false;
foreach (var user in _users)
if (!ModelState.IsValid)
{
if (user.Email == newUser.Email
||
user.Phone == newUser.Phone)
{
isDuplicated = true;
}
else if (user.Name == newUser.Name)
{
if (user.Address == newUser.Address)
{
isDuplicated = true;
throw new Exception("User is duplicated");
}

}
return BadRequest(ModelState);
}
var user = _mapper.Map<User>(userViewModel);

if (!isDuplicated)
if (await _userService.ExistsAsync(user))
{
Debug.WriteLine("User Created");

return new Result()
{
IsSuccess = true,
Errors = "User Created"
};
log.Error("User Duplicated" + JsonConvert.SerializeObject(user));
return StatusCode(StatusCodes.Status409Conflict, "The user is already in the list");
}
else
{
Debug.WriteLine("The user is duplicated");

return new Result()
{
IsSuccess = false,
Errors = "The user is duplicated"
};
await _userService.AddAsync(user);
return Ok("User Created");
}
}
catch
catch (Exception ex)
{
Debug.WriteLine("The user is duplicated");
return new Result()
{
IsSuccess = false,
Errors = "The user is duplicated"
};
log.Error(ex.Message, ex);
return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error, please contact IT Team");
}

return new Result()
{
IsSuccess = true,
Errors = "User Created"
};
}

//Validate errors
private void ValidateErrors(string name, string email, string address, string phone, ref string errors)
{
if (name == null)
//Validate if Name is null
errors = "The name is required";
if (email == null)
//Validate if Email is null
errors = errors + " The email is required";
if (address == null)
//Validate if Address is null
errors = errors + " The address is required";
if (phone == null)
//Validate if Phone is null
errors = errors + " The phone is required";
}
}
public class User
{
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string UserType { get; set; }
public decimal Money { get; set; }
}

}
18 changes: 0 additions & 18 deletions Sat.Recruitment.Api/Controllers/UsersController2.cs

This file was deleted.

14 changes: 14 additions & 0 deletions Sat.Recruitment.Api/Maps/UserProfile.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using AutoMapper;
using Sat.Recruitment.Api.ViewModel;
using Sat.Recruitment.Domain.Model;

namespace Sat.Recruitment.Api.Maps
{
public class UserProfile : Profile
{
public UserProfile()
{
CreateMap<UserViewModel, User>();
}
}
}
14 changes: 6 additions & 8 deletions Sat.Recruitment.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sat.Recruitment.Api
{
public class Program
Expand All @@ -20,8 +14,12 @@ public static void Main(string[] args)
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
{
webBuilder.UseStartup<Startup>();
});
})
.ConfigureLogging(builder =>
{
builder.AddLog4Net("log4net.config");
});
}
}
4 changes: 2 additions & 2 deletions Sat.Recruitment.Api/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"launchUrl": "User",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Sat.Recruitment.Api": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"launchUrl": "User",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
Expand Down
25 changes: 22 additions & 3 deletions Sat.Recruitment.Api/Sat.Recruitment.Api.csproj
Original file line number Diff line number Diff line change
@@ -1,18 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="log4net" Version="2.0.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.32" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.32">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.32" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.32">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="6.1.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.6.3" />
</ItemGroup>

<ItemGroup>
<None Update="Files\Users.txt">
<ProjectReference Include="..\Sat.Recruitment.Domain\Sat.Recruitment.Domain.csproj" />
<ProjectReference Include="..\Sat.Recruitment.Repository.EF\Sat.Recruitment.Repository.EF.csproj" />
</ItemGroup>

<ItemGroup>
<Content Update="log4net.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</Content>
</ItemGroup>


Expand Down
Loading