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

Close #28 Khurshid/organization controller #54

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
198 changes: 198 additions & 0 deletions webapp/Controllers/OrganizationsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using webapp.Data;
using webapp.Entity;
using webapp.Extensions;
using webapp.ViewModel;
using webapp.ViewModels;

namespace webapp.Controllers;


[Authorize]
public class OrganizationsController : Controller
{
private readonly ILogger _logger;
private readonly AppDbContext _ctx;
private readonly UserManager<AppUser> _userm;

public OrganizationsController(
AppDbContext context,
UserManager<AppUser> usermanager,
ILogger<OrganizationsController> logger)
{

_ctx = context;
_userm = usermanager;
_logger = logger;
}

[HttpGet]
public IActionResult Index()
{
return View();
}

[HttpGet]

public async Task<IActionResult> List(int page = 1, int limit = 10)
{
var existingOrgs = await _ctx.Organizations
.Skip((page - 1) * limit)
.Take(limit)
.Select(u => new OrganizationViewModel
{
Id = u.Id,
Name = u.Name,
Phone = u.Phone,
Email = u.Email,
Address = u.Address,
}).ToListAsync();

var totalOrganizations = existingOrgs.Count();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bu xato. Paginationni ishdan chiqaradi.

var totalOrganizations = await _ctx.Organizations.CountAsync();

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bajarildi


return View(new PaginatedListViewModel<OrganizationViewModel>()
{
Items = existingOrgs,
TotalItems = (uint)totalOrganizations,
TotalPages = (uint)Math.Ceiling(totalOrganizations / (double)limit),
CurrentPage = (uint)page,
Limit = (uint)limit
});
}

[HttpGet]
public IActionResult New() => View(new CreateOrganizationViewModel());

[HttpPost]
public async Task<IActionResult> Create(CreateOrganizationViewModel model)
{
if(!ModelState.IsValid)
{
_logger.LogInformation($"Model validation failed for {JsonSerializer.Serialize(model)}");
// return BadRequest("Organization properties are not valid.");
return View();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return View(model);

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bajarildi

}

var user = await _userm.GetUserAsync(User);

var org = new Organization()
{
Id = Guid.NewGuid(),
Name = model.Name,
Address = model.Address,
Phone = model.Phone,
Email = model.Email,
OwnerId = user.Id
};
Comment on lines +80 to +88
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Organization(model.Name, model.Address, model.Phone, model.Email, user.Id);

Organization entity ichida default constructorni obsolete qilib qo'yish kerak.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hop


try
{
await _ctx.Organizations.AddAsync(org);
await _ctx.SaveChangesAsync();
_logger.LogInformation($"New organization added with ID: {org.Id}");
_logger.LogInformation($"New EmployeeOrganization added with ID: {user.Id}");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2- loggin kerak emas.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hop


return RedirectToAction(nameof(Created));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Created degan Action yoqku bizda?

Copy link
Contributor Author

@KhurshidUmid KhurshidUmid Feb 17, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

show ga qilib quydim


}
catch (Exception e)
{
_logger.LogError($"Error occured while creating organization:\n{e.Message}");
return StatusCode(500, new { errorMessage = e.Message });
}
}

[HttpGet]
public async Task<IActionResult> Update(Guid id)
{
var existingOrg = await _ctx.Organizations.FirstOrDefaultAsync(o => o.Id == id);
if(existingOrg != default)
{
return View(existingOrg.ToOrganizationViewModel());
}
else
{
return RedirectToAction(nameof(Created));
}
}

[HttpPost("{id}/update")]
public async Task<IActionResult> UpdateModel(Guid id, UpdateOrganizationViewModel model)
{
if(!ModelState.IsValid)
{
_logger.LogInformation($"Model validation failed for {JsonSerializer.Serialize(model)}");
return RedirectToAction("Created");
}

var existingOrg = await _ctx.Organizations.FirstOrDefaultAsync(o => o.Id == id);
if(existingOrg == null)
{
return NotFound();
}

try
{
existingOrg.Address = model.Address;
existingOrg.Phone = model.Phone;
existingOrg.Email = model.Email;
existingOrg.Name = model.Name;

await _ctx.SaveChangesAsync();

_logger.LogInformation($"Organization updated with ID: {existingOrg.Id}");

return RedirectToAction(nameof(Created));

}
catch (Exception e)
{
_logger.LogError($"Error occured while updating organization:\n{e.Message}");
return StatusCode(500, new { errorMessage = e.Message });
}
}

[HttpPost("{id}/delete")]
public async Task <IActionResult> Delete(Guid id)
{
if (!await _ctx.Organizations.AnyAsync(p => p.Id == id))
{
return NotFound();
}

var org = await _ctx.Organizations.FirstOrDefaultAsync(y => y.Id == id);

try
{
_ctx.Organizations.Remove(org);

await _ctx.SaveChangesAsync();

_logger.LogInformation($"Organization deleted with ID: {org.Id}");

return RedirectToAction("list");
}
catch (Exception e)
{
_logger.LogError($"Error occured while updating organization:\n{e.Message}");
return StatusCode(500, new { errorMessage = e.Message });
}
}

[HttpGet("{id}/show")]
public async Task <IActionResult> Show(Guid id)
{
if (!await _ctx.Organizations.AnyAsync(c => c.Id == id))
{
return NotFound();
}

var org = await _ctx.Organizations.FirstOrDefaultAsync(p => p.Id == id);

return View(org.ToOrganizationViewModel());
}
}
2 changes: 1 addition & 1 deletion webapp/Entity/Contact.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ public class Contact

public Guid OwnerId { get; set; }

public virtual AppUser Owner { get; set; }
public virtual AppUser Owner { get; set; }
}
3 changes: 1 addition & 2 deletions webapp/Entity/InvoiceItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,10 @@ public class InvoiceItem
[Required]
public double Rate { get; set; }

[Required]
[Required]
public string Currency { get; set; }

public Guid InvoiceId { get; set; }

public virtual Invoice Invoice { get; set; }

}
29 changes: 29 additions & 0 deletions webapp/Extensions/OrganizationExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using webapp.Entity;
using webapp.ViewModels;

namespace webapp.Extensions
{
public static class OrganizationExtensions
{
public static OrganizationViewModel ToOrganizationModel(this Organization entity)
{
return new OrganizationViewModel()
{
Id = entity.Id,
Name = entity.Name
};
}
public static OrganizationViewModel ToOrganizationViewModel(this Organization entity)
{
return new OrganizationViewModel()
{
Id = entity.Id,
Name = entity.Name,
Address = entity.Address,
Phone = entity.Phone,
Email = entity.Email
};
}

}
}
3 changes: 2 additions & 1 deletion webapp/Extensions/ToViewModels.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using webapp.Entity;
using webapp.ViewModel;
using webapp.ViewModels;

namespace webapp.Extensions;
public static class ToViewModels
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ContactEntityExtensions.cs

@KhurshidUmid siz OrganizationExtensions.cs class ga hamma kodizni ko'chirasiz.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bu kecha bajarilgan

Expand Down Expand Up @@ -38,5 +39,5 @@ public static NewContactViewModel ToNewContactViewModel(this Contact entity)
Owner=entity.Owner,
Phone=entity.Phone
};
}
}
}
30 changes: 30 additions & 0 deletions webapp/ViewModel/CreateOrganizationViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace webapp.ViewModels;

public class CreateOrganizationViewModel
{
[Required(ErrorMessage = "To'liq nomni kiritish shart!")]
[Display(Name = "Korxona nomi")]
public string Name { get; set; }

[Required(ErrorMessage = "Email manzilini kiritish shart!")]
[EmailAddress(ErrorMessage = "Email manzil formati noto'g'ri.")]
[DisplayName("Email manzili")]
public string Email { get; set; }

[Required(ErrorMessage = "Telefon raqam kiritish shart!")]
[RegularExpression(
@"^[\+]?(998[-\s\.]?)([0-9]{2}[-\s\.]?)([0-9]{3}[-\s\.]?)([0-9]{2}[-\s\.]?)([0-9]{2}[-\s\.]?)$",
ErrorMessage = "Telefon raqam formati noto'g'ri.")]
[DisplayName("Telefon raqami")]
public string Phone { get; set; }

[Required(ErrorMessage = "Addressni kiritish!")]
[MinLength(10, ErrorMessage = "Addressni to'liq kiritish shart.")]
[DisplayName("Korxona manzili")]
public string Address { get; set; }


}
33 changes: 33 additions & 0 deletions webapp/ViewModel/OrganizationViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace webapp.ViewModels
{
public class OrganizationViewModel
{
public Guid Id { get; set; }

[Required(ErrorMessage = "To'liq nomni kiritish shart!")]
[Display(Name = "Korxona nomi")]
public string Name { get; set; }

[Required(ErrorMessage = "Email manzilini kiritish shart!")]
[EmailAddress(ErrorMessage = "Email manzil formati noto'g'ri.")]
[DisplayName("Email manzili")]
public string Email { get; set; }

[Required(ErrorMessage = "Telefon raqam kiritish shart!")]
[RegularExpression(
@"^[\+]?(998[-\s\.]?)([0-9]{2}[-\s\.]?)([0-9]{3}[-\s\.]?)([0-9]{2}[-\s\.]?)([0-9]{2}[-\s\.]?)$",
ErrorMessage = "Telefon raqam formati noto'g'ri.")]
[DisplayName("Telefon raqami")]
public string Phone { get; set; }

[Required(ErrorMessage = "Addressni kiritish!")]
[MinLength(10, ErrorMessage = "Addressni to'liq kiritish shart.")]
[DisplayName("Korxona manzili")]
public string Address { get; set; }

}
}
12 changes: 12 additions & 0 deletions webapp/ViewModel/PaginatedListViewModelBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace webapp.ViewModel
{
public class PaginatedListViewModel<T>
{
public List<T> Items { get; set; }
public uint CurrentPage { get; set; }
public uint Limit { get; set; }
public uint TotalPages { get; set; }
public uint TotalItems { get; set; }
}

}
31 changes: 31 additions & 0 deletions webapp/ViewModel/UpdateOrganizationViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace webapp.ViewModels
{
public class UpdateOrganizationViewModel
{
public Guid Id { get; set; }

[Required(ErrorMessage = "To'liq nomni kiritish shart!")]
[Display(Name = "Korxona nomi")]
public string Name { get; set; }

[Required(ErrorMessage = "Email manzilini kiritish shart!")]
[EmailAddress(ErrorMessage = "Email manzil formati noto'g'ri.")]
[DisplayName("Email manzili")]
public string Email { get; set; }

[Required(ErrorMessage = "Telefon raqam kiritish shart!")]
[RegularExpression(
@"^[\+]?(998[-\s\.]?)([0-9]{2}[-\s\.]?)([0-9]{3}[-\s\.]?)([0-9]{2}[-\s\.]?)([0-9]{2}[-\s\.]?)$",
ErrorMessage = "Telefon raqam formati noto'g'ri.")]
[DisplayName("Telefon raqami")]
public string Phone { get; set; }

[Required(ErrorMessage = "Addressni kiritish!")]
[MinLength(10, ErrorMessage = "Addressni to'liq kiritish shart.")]
[DisplayName("Korxona manzili")]
public string Address { get; set; }
}
}
2 changes: 2 additions & 0 deletions webapp/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
"ConnectionStrings": {

"DefaultConnection": ""

},
"Logging": {
"LogLevel": {
Expand Down