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
215 changes: 215 additions & 0 deletions webapp/Controllers/OrganizationsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
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 user = await _userm.GetUserAsync(User);
if(user == null)
{
return Unauthorized();
}
Copy link
Member

Choose a reason for hiding this comment

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

Bu actionda user ishlatilmagani uchun bu shart emas. Unauthorizedni esa tepadagi attribute o'zi qaytaradi shundoq ham

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 createdOrgs = await _ctx.Organizations
Copy link
Member

Choose a reason for hiding this comment

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

existingOrgs

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

.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();
if (createdOrgs == null)
{
return NotFound();
}

Copy link
Member

Choose a reason for hiding this comment

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

Yoq, prosta bironta ham Oranizationsiz qaytarilaveradi. NotFound faqat izlangan ma'lumot topilmaganda qaytariladi.

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 totalOrganizations = createdOrgs.Count();

return View(new OrganizationsListViewModel()
{
Organizations = createdOrgs,
totalOrganizationsCount = totalOrganizations,
totalPages = (int)Math.Ceiling(totalOrganizations / (double)limit),
Page = page,
Limit = limit
Copy link
Member

Choose a reason for hiding this comment

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

Just PaginatedListViewModel.cs from ViewModels folder.

  • Just supply the Items type for generic class. For this action, it's OrganizationViewModel

Copy link
Member

Choose a reason for hiding this comment

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

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

});
}




Copy link
Member

Choose a reason for hiding this comment

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

extra spaces

[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.LogWarning($"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.ToOrgModel());
}
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.LogWarning($"Error occured while updating organization:\n{e.Message}");
Copy link
Member

Choose a reason for hiding this comment

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

LogError()

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 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.LogWarning($"Error occured while updating organization:\n{e.Message}");
Copy link
Member

Choose a reason for hiding this comment

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

LogError()

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 StatusCode(500, new { errorMessage = e.Message });
}
}

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

Choose a reason for hiding this comment

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

This action should go upto right before Create action.

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


[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);
if (org == default)
{
return NotFound();
}
Copy link
Member

Choose a reason for hiding this comment

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

You dont need this since you already have AnyAsync above.

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(org.ToOrgModel());
Copy link
Member

Choose a reason for hiding this comment

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

*.ToOrganizationViewModel()

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

}
}
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; }

}
1 change: 1 addition & 0 deletions webapp/Entity/Organization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ public class Organization
public virtual AppUser Owner { get; set; }

public virtual ICollection<Invoice> Invoices { get; set; }

Comment on lines 30 to +31
Copy link
Member

Choose a reason for hiding this comment

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

chopamiz

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Invoices qolsinmi?

}
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 ToOrgModel(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; }

}
}
18 changes: 18 additions & 0 deletions webapp/ViewModel/OrganizationsListViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using webapp.ViewModels;

namespace webapp.ViewModel
{
public class OrganizationsListViewModel
{
public int Page { get; set; }

public int Limit { get; set; }

public int totalPages { get; set; }

public int totalOrganizationsCount { get; set; }

public List<OrganizationViewModel> Organizations { get; set; }

}
}
Loading