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

Refactor Code Nicolas Alarcon Kopelmann #59

Open
wants to merge 2 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
38 changes: 38 additions & 0 deletions Sat.Recruitment.Api/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Sat.Recruitment.Api.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sat.Recruitment.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly ITokenService _tokenService;

public AuthController(ITokenService tokenService)
{
_tokenService = tokenService;
}

[HttpPost("login")]
public IActionResult Login(string userName, string password)
{
if (!Autenticate(userName, password))
{
return Unauthorized();
}
var token = _tokenService.TokenGen(userName);
return Ok(new { token });
}

private bool Autenticate(string userName, string password)
{
return true;
}
}
}
199 changes: 29 additions & 170 deletions Sat.Recruitment.Api/Controllers/UsersController.cs
Original file line number Diff line number Diff line change
@@ -1,202 +1,61 @@
using Microsoft.AspNetCore.Mvc;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

using Sat.Recruitment.Api.Models;
using Sat.Recruitment.Api.Requests.Commands;
using Sat.Recruitment.Api.Requests.Queries;
using Sat.Recruitment.Api.Services;
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]")]
[Authorize]
public partial class UsersController : ControllerBase
{

private readonly List<User> _users = new List<User>();
public UsersController()
private readonly IMediator _mediator;

public UsersController(IMediator mediator)
{
_mediator = mediator;
}

[HttpPost]
[Route("/create-user")]
public async Task<Result> CreateUser(string name, string email, string address, string phone, string userType, string money)
public async Task<IActionResult> CreateUser(AddUserCommand addUsercommand)
{
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 result = await _mediator.Send(addUsercommand);

if (!isDuplicated)
{
Debug.WriteLine("User Created");

return new Result()
{
IsSuccess = true,
Errors = "User Created"
};
}
else
{
Debug.WriteLine("The user is duplicated");

return new Result()
{
IsSuccess = false,
Errors = "The user is duplicated"
};
}
return CreatedAtAction(nameof(GetUser), new { id = result.Id }, result);
}
catch
catch (Exception ex)
{
Debug.WriteLine("The user is duplicated");
return new Result()
{
IsSuccess = false,
Errors = "The user is duplicated"
};
return BadRequest(ex.ToString());
}
}

return new Result()
[HttpGet("{id}")]
public async Task<IActionResult> GetUser(int id)
{
var user = await _mediator.Send(new GetUserQuery { Id = id });

if (user == null)
{
IsSuccess = true,
Errors = "User Created"
};
}
return NotFound();
}

//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";
return Ok(user);
}
}
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.

73 changes: 73 additions & 0 deletions Sat.Recruitment.Api/DbContext/MyDbContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Sat.Recruitment.Api.Models;
using Sat.Recruitment.Api.Services;

namespace Sat.Recruitment.Api.DbContext
{
public class MyDbContext : Microsoft.EntityFrameworkCore.DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}

public DbSet<User> User { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Entity<User>()
.HasDiscriminator<UserType>("UserType")
.HasValue<Premium>(UserType.Premium)
.HasValue<Normal>(UserType.Normal)
.HasValue<SuperUser>(UserType.SuperUser);

//modelBuilder.Entity<User>(entity =>
//{
// entity.ToTable("users");

// entity.HasKey(e => e.Id);

// entity.Property(e => e.Id)
// .HasColumnName("id")
// .ValueGeneratedOnAdd();

// entity.Property(e => e.Name)
// .HasColumnName("name")
// .HasMaxLength(100)
// .IsRequired();

// entity.Property(e => e.Email)
// .HasColumnName("email")
// .HasMaxLength(100)
// .IsRequired();

// entity.Property(e => e.Address)
// .HasColumnName("address")
// .HasMaxLength(200)
// .IsRequired();

// entity.Property(e => e.Phone)
// .HasColumnName("phone")
// .HasMaxLength(20)
// .IsRequired();

// entity.Property(e => e.UserType)
// .HasColumnName("usertype")
// .HasMaxLength(20)
// .IsRequired();

// entity.Property(u => u.Money)
// .HasColumnName("money")
// .HasColumnType("decimal(18,2)")
// .IsRequired();
//});
}

}
}
Loading