81 Commits
Models ... main

Author SHA1 Message Date
Dimitar Byalkov
10f998206f Documentation 2021-03-20 22:28:28 +02:00
Dimitar Byalkov
a9fbb7dcec Version 1.0.0 2021-03-20 22:20:41 +02:00
thermalthrottle
8b64e45539 Merge branch 'main' of https://github.com/CapitalRhino/luminous-sales 2021-03-20 22:19:44 +02:00
thermalthrottle
409d8c0b0c Interface comments and refactoring 2021-03-20 22:18:49 +02:00
Dimitar Byalkov
59418caf04 Update AdminView.cs 2021-03-20 22:07:00 +02:00
thermalthrottle
93ec3b009a Controllers updates 2021-03-20 22:03:55 +02:00
thermalthrottle
df56840812 Merge branch 'main' of https://github.com/CapitalRhino/luminous-sales 2021-03-20 22:01:21 +02:00
thermalthrottle
1dafdeee43 ProductController added name item adding 2021-03-20 21:59:40 +02:00
thermalthrottle
efed3461f2 StockController comments 2021-03-20 21:56:06 +02:00
Dimitar Byalkov
df8b814e65 Views fixes 2021-03-20 21:38:51 +02:00
batgo6o
027c1c9b0f DealController comments 2021-03-20 20:41:19 +02:00
Aneliya Konarcheva
fc9ff26137 comment about manager view 2021-03-20 19:16:50 +02:00
Dimitar Byalkov
4f26a747c0 Comments 2021-03-20 18:53:30 +02:00
thermalthrottle
1adc2aac9e Updates Comments 2021-03-20 18:30:12 +02:00
thermalthrottle
f559479200 Deal and Stock Controllers update 2021-03-20 17:27:23 +02:00
Dimitar Byalkov
e404892b4a Small changes 2021-03-20 17:11:27 +02:00
Dimitar Byalkov
e3b1409b69 Big Logo 2021-03-20 17:09:18 +02:00
thermalthrottle
5da8b71fe0 Bug Fixes 2021-03-20 14:33:21 +02:00
thermalthrottle
0b8babd520 Bug Fixes 2021-03-20 12:55:59 +02:00
thermalthrottle
45742a32a4 Merge branch 'main' of https://github.com/CapitalRhino/luminous-sales 2021-03-20 12:12:49 +02:00
Dimitar Byalkov
25ac717b56 Views, Add Time in Deal & Stock 2021-03-20 12:12:28 +02:00
thermalthrottle
bec08c5851 Added unit tests 2021-03-20 11:04:58 +02:00
thermalthrottle
bb4f2b4f16 Initial Registration Update 2021-03-20 10:21:11 +02:00
thermalthrottle
a59fd53cc6 roles update 2021-03-20 10:14:51 +02:00
thermalthrottle
e89ec0c212 ROleController update 2021-03-20 10:04:06 +02:00
thermalthrottle
2d44c67621 added comments and rolecontroller updates 2021-03-20 10:01:52 +02:00
Dimitar Byalkov
17fbd10d03 Presentaion, Views, CLI 2021-03-19 16:58:06 +02:00
Aneliya Konarcheva
cb1206661f commit last changes 2021-03-19 15:57:07 +02:00
Dimitar Byalkov
8cf5c93a98 AdminView 1 2021-03-19 14:39:00 +02:00
Aneliya Konarcheva
98f3e87441 manager view commition 2021-03-19 14:25:23 +02:00
Aneliya Konarcheva
a4c097a8ca manager view 2021-03-19 12:38:30 +02:00
thermalthrottle
d516d33a38 Display update 2021-03-19 10:58:04 +02:00
Dimitar Byalkov
701be834cf Display fundamentals 2021-03-19 09:51:42 +02:00
thermalthrottle
7507023d11 Merge branch 'main' of https://github.com/CapitalRhino/luminous-sales 2021-03-19 09:34:43 +02:00
thermalthrottle
729441fda7 UserController Update 2021-03-19 09:34:00 +02:00
Dimitar Byalkov
8506673a91 Display InitialSetup 2021-03-19 01:39:47 +02:00
thermalthrottle
9a4fa93aad User Management updates 2021-03-19 01:19:59 +02:00
Dimitar Byalkov
6ed05ff82f DealController, code style 2021-03-19 00:59:46 +02:00
Aneliya Konarcheva
a6fb81d1eb stock ctrl 2021-03-19 00:07:55 +02:00
thermalthrottle
dbee01a94a StockController update 2021-03-18 23:59:05 +02:00
thermalthrottle
de738b7801 Controllers Update 2021-03-18 23:56:49 +02:00
Aneliya Konarcheva
128a243133 stock controller 2021-03-18 23:42:49 +02:00
thermalthrottle
9fd0d965d9 Product Context 2021-03-18 22:24:12 +02:00
Dimitar Byalkov
bdd0d5256f DateTime replaced Timestamp, StockController methods 2021-03-18 21:42:28 +02:00
thermalthrottle
541b001d31 Product Context 2021-03-18 21:25:10 +02:00
Aneliya Konarcheva
b5a035249e commiting stock controller 2021-03-18 18:13:46 +02:00
thermalthrottle
dbfbed4b5d User Controller updates 2021-03-18 16:55:20 +02:00
thermalthrottle
3c69124650 Business update 2021-03-18 14:57:00 +02:00
thermalthrottle
7aac7f999f Models Updated 2021-03-18 13:08:18 +02:00
batgo6o
9f7dcd71d5 Models Update 2021-03-17 22:02:52 +02:00
batgo6o
3b673f153e Changes in validator 2021-03-15 16:38:02 +02:00
batgo6o
cbb3b404c0 Added Validator and User Controller 2021-03-15 16:31:45 +02:00
Aneliya Konarcheva
e77b76688c commiting add stock 2021-03-15 16:57:09 +02:00
batgo6o
8a091496f3 Added CredentialChecker 2021-03-15 13:43:21 +02:00
batgo6o
2af190c291 Business Logic update 2021-03-14 13:29:42 +02:00
batgo6o
5924ee0dd9 Updated refrences 2021-03-14 11:16:35 +02:00
batgo6o
2b23d51c3e Merge branch 'Tests' 2021-03-14 10:18:05 +02:00
batgo6o
8578b62989 Added constructors and base classses to Models 2021-03-14 10:17:13 +02:00
Dimitar Byalkov
d2374e4f26 Merge branch 'Tests' into main
# Conflicts:
#	LuminousSales/Business/Business.csproj
#	LuminousSales/Business/DealsBusiness.cs
#	LuminousSales/Business/PermissionsBusiness.cs
#	LuminousSales/Business/ProductBusiness.cs
#	LuminousSales/Business/RolesBusiness.cs
#	LuminousSales/Business/RolesToPermissionBusiness.cs
#	LuminousSales/Business/StocksBusiness.cs
#	LuminousSales/Business/UsersBusiness.cs
#	LuminousSales/Business/UsersToRolesBusiness.cs
#	LuminousSales/LuminousSales/Data/DealContext.cs
#	LuminousSales/LuminousSales/Data/PermissionContext.cs
#	LuminousSales/LuminousSales/Data/ProductContext.cs
#	LuminousSales/LuminousSales/Data/RoleContext.cs
#	LuminousSales/LuminousSales/Data/RolesToPermissionContext.cs
#	LuminousSales/LuminousSales/Data/StockContext.cs
#	LuminousSales/LuminousSales/Data/UserContext.cs
#	LuminousSales/LuminousSales/Data/UsersToRolesContext.cs
#	LuminousSales/LuminousSales/LuminousSales.csproj
#	LuminousSales/Models/LuminousContext.cs
#	LuminousSales/Models/Models.csproj
#	LuminousSales/Models/Models/Deal.cs
2021-03-11 13:00:51 +02:00
batgo6o
b45909ab63 EF Models created 2021-03-11 01:47:22 +02:00
Aneliya Konarcheva
a97dd1c2cc visual studio is drunk 2021-03-10 22:32:21 +02:00
Aneliya Konarcheva
781a2873fd commiting many errors 2021-03-10 21:02:51 +02:00
Aneliya Konarcheva
08fd6e67e8 commiting errors 2021-03-10 12:15:21 +02:00
Aneliya Konarcheva
4b1b438381 commiting many errors 2021-03-10 11:55:03 +02:00
Aneliya Konarcheva
ea95b4ad6b commiting recent changes 2021-03-07 13:53:10 +02:00
Aneliya Konarcheva
f8ee73f50b commit new library 2021-03-07 13:09:15 +02:00
Aneliya Konarcheva
76f84a6afa commited manu changes 2021-03-07 12:25:58 +02:00
batgo6o
03740b08bc Fixed DbContext 2021-03-07 12:14:15 +02:00
Aneliya Konarcheva
6de2d1db6a commit changes 2 2021-03-07 12:07:45 +02:00
Aneliya Konarcheva
982ff0da15 commit changes 1 2021-03-07 11:59:17 +02:00
Aneliya Konarcheva
b2215cdd8f commit changes 2021-03-07 11:45:59 +02:00
Aneliya Konarcheva
04f5e9e455 Merge branch 'Models' into main 2021-03-07 11:35:49 +02:00
Aneliya Konarcheva
58f470ffbc private atributes 2021-03-07 11:17:43 +02:00
Aneliya Konarcheva
ee776460b2 methods buy and sell 2021-03-07 10:24:48 +02:00
Aneliya Konarcheva
219b0483f6 product business 2021-03-07 10:13:23 +02:00
Aneliya Konarcheva
39e9737476 class product 2021-03-07 10:04:51 +02:00
Aneliya Konarcheva
54e64cbb87 change 2021-03-07 09:46:54 +02:00
Dimitar Byalkov
8e0e5ad34a Merge pull request #1 from CapitalRhino/business-logic
Business logic
2021-03-07 09:44:07 +02:00
Aneliya Konarcheva
5a0c5411a8 commit changes 2021-03-06 21:10:40 +02:00
ani-konarcheva
438bffb502 commit Americans 2021-03-06 10:46:11 +02:00
Dimitar Byalkov
0692b6671b EntityFramework 2021-03-06 10:38:21 +02:00
50 changed files with 4081 additions and 293 deletions

BIN
Documentation.docx Normal file

Binary file not shown.

BIN
Documentation.pdf Normal file

Binary file not shown.

BIN
Luminous Sales.pptx Normal file

Binary file not shown.

View File

@@ -1,11 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.12" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.12" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Models\Data.csproj" />
</ItemGroup>
</Project> </Project>

View File

@@ -0,0 +1,23 @@
using Models;
using Models.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Business.Business.UserManagment
{
/// <summary>
/// Controller interface.
/// </summary>
interface IController<T>
{
ICollection<T> GetAll();
T Get(int id);
T Get(string name);
ICollection<T> GetByApproximateName(string name);
void UpdateName(int id, string newName);
void UpdateName(string oldName, string newName);
void Delete(int id);
void Delete(string name);
}
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Business.Business.Interfaces
{
/// <summary>
/// Interface used only for read-only Controllers such as RoleController
/// </summary>
interface IReadOnlyController<T>
{
ICollection<T> GetAll();
T Get(int id);
T Get(string name);
ICollection<T> GetByApproximateName(string name);
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Business.Business.Sales
{
/// <summary>
/// Interface used for Sale Controllers such as DealController and StockController
/// </summary>
interface ISalesController<T>
{
ICollection<T> GetAll();
T Get(int id);
ICollection<T> GetByTime(DateTime startTime, DateTime endTime);
void Add(int productId, double Amount, DateTime time);
void Add(string productName, double Amount, DateTime time);
void Delete(int id);
}
}

View File

@@ -0,0 +1,257 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Business.Business.UserManagment;
using Models;
using Models.Models;
namespace Business.Business.Sales
{
public class DealController : ISalesController<Deal>
{
private LuminousContext context;
private User currentUser;
private ProductController productctrl;
private UserController userctrl;
/// <summary>
/// Constructor that accepts a user object
/// </summary>
/// <remarks>
/// User object is used for role checking
/// </remarks>
public DealController(User currentUser)
{
this.currentUser = currentUser;
this.context = new LuminousContext();
this.productctrl = new ProductController(currentUser);
this.userctrl = new UserController(currentUser);
}
/// <summary>
/// Constructor that accepts custom context, ProductController, UserController and a user object
/// </summary>
/// <remarks>
/// Mainly Used for Unit Teststing
/// </remarks>
/// <remarks>
/// User object is used for role checking
/// </remarks>
public DealController(User currentUser, LuminousContext context, ProductController productctrl, UserController userctrl)
{
this.currentUser = currentUser;
this.context = context;
this.productctrl = productctrl;
this.userctrl = userctrl;
}
/// <summary>
/// Gets All Deals
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <returns>
/// Returns a ICollection of all Deals.
/// </returns>
public ICollection<Deal> GetAll()
{
return context.Deal.ToList();
}
/// <summary>
/// Searches a deal by given Id.
/// </summary>
/// <remarks>
/// Requires Manager role or better.
/// </remarks>
/// <returns>
/// Returns an object of the role with the given Id.
/// </returns>
public Deal Get(int id)
{
if (currentUser != null || currentUser.RoleId > 1)
{
return context.Deal.Find(id);
}
else
{
throw new ArgumentException("Insufficient Roles");
}
}
/// <summary>
/// Gets deals between time periods.
/// </summary>
/// <remarks>
/// Requires Manager role or better.
/// </remarks>
/// <returns>
/// Returns a collection of all the deal in the criteria.
/// </returns>
public ICollection<Deal> GetByTime(DateTime startTime, DateTime endTime)
{
if (currentUser.RoleId > 1)
{
return context.Deal.Where(x => x.Time <= endTime && x.Time >= startTime).ToList();
}
else
{
throw new ArgumentException("Insufficient role!");
}
}
/// <summary>
/// Gets deals made by certain user.
/// </summary>
/// <remarks>
/// Accepts user id for getting the user.
/// Requires Manager role or better.
/// </remarks>
/// <returns>
/// Returns an Collection of all the deals in the criteria.
/// </returns>
public ICollection<Deal> GetByUser(int id)
{
if (currentUser != null || currentUser.RoleId > 1)
{
var user = userctrl.Get(id);
if (user != null)
{
return GetAll().Where(u => u.UserId == user.Id).ToList();
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient role!");
}
}
/// <summary>
/// Gets deals made by certain user.
/// </summary>
/// <remarks>
/// Accepts username for getting the user.
/// Requires Manager role or better.
/// </remarks>
/// <returns>
/// Returns an Collection of all the deals in the criteria.
/// </returns>
public ICollection<Deal> GetByUser(string username)
{
if (currentUser != null || currentUser.RoleId > 1)
{
var user = userctrl.Get(username);
if (user != null)
{
return GetAll().Where(u => u.UserId == user.Id).ToList();
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient role!");
}
}
/// <summary>
/// Adds Deal to the database.
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <remarks>
/// Accepts product id for getting the product, amount sold and time of transaction.
/// </remarks>
public void Add(int productId, double Amount, DateTime time)
{
if (Amount > 0)
{
var deal = new Deal(currentUser.Id, productId, Amount, time);
productctrl.RemoveAmount(productId, Amount);
context.Deal.Add(deal);
context.SaveChanges();
}
else
{
throw new ArgumentException("Amount cannot be negative");
}
}
/// <summary>
/// Adds Deal to the database.
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <remarks>
/// Accepts product name for getting the product, amount sold and time of transaction.
/// </remarks>
public void Add(string productName, double Amount, DateTime time)
{
if (Amount > 0)
{
productctrl = new ProductController(currentUser);
var productId = productctrl.Get(productName).Id;
var deal = new Deal(currentUser.Id, productId, Amount, time);
productctrl.RemoveAmount(productId, Amount);
context.Deal.Add(deal);
context.SaveChanges();
}
else
{
throw new ArgumentException("Amount cannot be negative");
}
}
/// <summary>
/// Deletes Deal from the database.
/// </summary>
/// <remarks>
/// Requires Manager Role or better.
/// </remarks>
/// <remarks>
/// Accepts deal id for getting the product
/// </remarks>
public void Delete(int id)
{
if (currentUser != null || currentUser.RoleId > 1)
{
var deal = Get(id);
if (deal != null)
{
productctrl.AddAmount(deal.ProductId, deal.Amount);
context.Deal.Remove(deal);
context.SaveChanges();
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient role!");
}
}
}
}

View File

@@ -0,0 +1,477 @@
using Business.Business.UserManagment;
using Models;
using Models.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Business.Business.Sales
{
public class ProductController : IController<Product>
{
private LuminousContext context;
private User currentUser;
/// <summary>
/// Constructor that accepts a user object
/// </summary>
/// <remarks>
/// User object is used for role checking
/// </remarks>
public ProductController(User currenUser)
{
this.currentUser = currenUser;
this.context = new LuminousContext();
}
/// <summary>
/// Constructor that accepts custom context and a user object
/// </summary>
/// <remarks>
/// Custom context is mainly used for Unit Testing
/// </remarks>
/// <remarks>
/// User object is used for role checking
/// </remarks>
public ProductController(User currenUser, LuminousContext context)
{
this.currentUser = currenUser;
this.context = context;
}
/// <summary>
/// Gets All Products
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <returns>
/// Returns a ICollection of all products.
/// </returns>
public ICollection<Product> GetAll()
{
return context.Product.ToList();
}
/// <summary>
/// Searches a product by given Id.
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <returns>
/// Returns an object of the role with the given Id.
/// </returns>
public Product Get(int id)
{
var item = context.Product.Find(id);
if (item != null)
{
return item;
}
else
{
throw new ArgumentException("Product Id not found!");
}
}
/// <summary>
/// Searches a product by given name
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <returns>
/// Returns an object of the role with the given name.
/// </returns>
public Product Get(string name)
{
var item = context.Product.FirstOrDefault(p => p.Name == name);
if (item != null)
{
return item;
}
else
{
throw new ArgumentException("Product name not found!");
}
}
/// <summary>
/// Searches a product by a given substring
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <returns>
/// Returns an ICollection of all roles that contain the given substring in their name.
/// </returns>
public ICollection<Product> GetByApproximateName(string name)
{
var items = context.Product.Where(u => u.Name.Contains(name)).ToList();
if (items.Any())
{
return items;
}
else
{
throw new ArgumentException("No products added in the database!");
}
}
/// <summary>
/// Adds an product in the database
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts an item name and price.
/// </remarks>
public void AddItem(string name, double price)
{
if (currentUser.RoleId == 3)
{
if (!GetAll().Where(p => p.Name == name).Any())
{
if (price > 0)
{
var product = new Product(name, price);
context.Product.Add(product);
context.SaveChanges();
}
else
{
throw new ArgumentException("Price cannot be negative");
}
}
else
{
throw new ArgumentException("Item with the given name already exists!");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Updates the name of the given product
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts the id for getting the product.
/// </remarks>
public void UpdateName(int id, string newName)
{
if (currentUser.RoleId == 3)
{
var product = Get(id);
if (product != null)
{
if (!GetAll().Where(p => p.Name == newName).Any())
{
product.Name = newName;
context.SaveChanges();
}
else
{
throw new ArgumentException("Item with the given name already exists!");
}
}
else
{
throw new ArgumentException("Product id not valid!");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Updates the name of the given product
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts the current name for getting the product.
/// </remarks>
public void UpdateName(string oldName, string newName)
{
if (currentUser.RoleId == 3)
{
var product = Get(oldName);
if (product != null)
{
if (!GetAll().Where(p => p.Name == newName).Any())
{
product.Name = newName;
context.SaveChanges();
}
else
{
throw new ArgumentException("Item with the given name already exists!");
}
}
else
{
throw new ArgumentException("Product name not valid!");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Updates the price of the given product
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts the id for getting the product.
/// </remarks>
public void UpdatePrice(int id, double price)
{
if (currentUser.RoleId == 3)
{
var product = Get(id);
if (product != null)
{
if (price > 0)
{
product.Price = price;
context.SaveChanges();
}
else
{
throw new ArgumentException("Price cannot be negative");
}
}
else
{
throw new ArgumentException("Product id not valid!");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Updates the price of the given product.
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts the name for getting the product.
/// </remarks>
public void UpdatePrice(string name, double price)
{
if (currentUser.RoleId == 3)
{
var product = Get(name);
if (product != null)
{
if (price > 0)
{
product.Price = price;
context.SaveChanges();
}
else
{
throw new ArgumentException("Price cannot be negative");
}
}
else
{
throw new ArgumentException("Product name not valid!");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Adds to the amount of a given product.
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <remarks>
/// Accepts the product id for getting the product and amount to add
/// </remarks>
public void AddAmount(int productId ,double Amount)
{
var product = Get(productId);
if (product != null)
{
product.AmountInStock += Amount;
context.SaveChanges();
}
else
{
throw new ArgumentException("Product id not valid!");
}
}
/// <summary>
/// Adds to the amount of a given product.
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <remarks>
/// Accepts the product name for getting the product and amount to add
/// </remarks>
public void AddAmount(string productName, double Amount)
{
var product = Get(productName);
if (product != null)
{
product.AmountInStock += Amount;
context.SaveChanges();
}
else
{
throw new ArgumentException("Product name not valid!");
}
}
/// <summary>
/// Subtracts to the amount of a given product.
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <remarks>
/// Accepts the product id for getting the product and amount to substract
/// </remarks>
public void RemoveAmount(int productId, double Amount)
{
var product = Get(productId);
if (product != null)
{
product.AmountInStock -= Amount;
context.SaveChanges();
}
else
{
throw new ArgumentException("Product id not valid!");
}
}
/// <summary>
/// Subtracts to the amount of a given product.
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <remarks>
/// Accepts the product name for getting the product and amount to substract
/// </remarks>
public void RemoveAmount(string productName, double Amount)
{
var product = Get(productName);
if (product != null)
{
product.AmountInStock -= Amount;
context.SaveChanges();
}
else
{
throw new ArgumentException("Product id not valid!");
}
}
/// <summary>
/// Deletes the given product.
/// </summary>
/// <remarks>
/// Requires Admin Role
/// </remarks>
/// <remarks>
/// Accepts an product for getting the product.
/// </remarks>
public void Delete(int id)
{
if (currentUser.RoleId == 3)
{
var user = Get(id);
if (user != null)
{
context.Product.Remove(user);
context.SaveChanges();
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Deletes the given product
/// </summary>
/// <remarks>
/// Requires Admin role
/// </remarks>
/// <remarks>
/// Accepts an name for getting the product
/// </remarks>
public void Delete(string name)
{
if (currentUser.RoleId == 3)
{
var user = Get(name);
if (user != null)
{
context.Product.Remove(user);
context.SaveChanges();
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
}
}

View File

@@ -0,0 +1,285 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Business.Business.UserManagment;
using Microsoft.EntityFrameworkCore;
using Models;
using Models.Models;
namespace Business.Business.Sales
{
public class StockController : ISalesController<Stock>
{
private LuminousContext context;
private User currentUser;
private ProductController productctrl;
private UserController userctrl;
/// <summary>
/// Constructor that accepts a user object
/// </summary>
/// <remarks>
/// User object is used for role checking
/// </remarks>
public StockController(User currentUser)
{
this.currentUser = currentUser;
this.context = new LuminousContext();
this.productctrl = new ProductController(currentUser);
this.userctrl = new UserController(currentUser);
}
/// <summary>
/// Constructor that accepts custom context, ProductController, UserController and a user object
/// </summary>
/// <remarks>
/// Mainly Used for Unit Teststing
/// </remarks>
/// <remarks>
/// User object is used for role checking
/// </remarks>
public StockController(User currentUser, LuminousContext context ,ProductController productctrl, UserController userctrl)
{
this.currentUser = currentUser;
this.context = context;
this.productctrl = productctrl;
this.userctrl = userctrl;
}
/// <summary>
/// Gets All Stocks
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <returns>
/// Returns a ICollection of all Stocks.
/// </returns>
public ICollection<Stock> GetAll()
{
if (currentUser != null || currentUser.RoleId > 1)
{
return context.Stock.ToList();
}
else
{
throw new ArgumentException("Cannot return all stocks!");
}
}
/// <summary>
/// Searches a stocks session by given Id.
/// </summary>
/// <remarks>
/// Requires Manager role or better.
/// </remarks>
/// <returns>
/// Returns an object of the stock with the given Id.
/// </returns>
public Stock Get(int id)
{
if (currentUser != null || currentUser.RoleId > 1)
{
return context.Stock.Find(id);
}
else
{
throw new ArgumentException("Insufficient Roles");
}
}
/// <summary>
/// Gets stocks between time periods.
/// </summary>
/// <remarks>
/// Requires Manager role or better.
/// </remarks>
/// <returns>
/// Returns a collection of all the stocks in the criteria.
/// </returns>
public ICollection<Stock> GetByTime(DateTime startTime, DateTime endTime)
{
if (currentUser != null || currentUser.RoleId > 1)
{
return context.Stock.Where(x => x.Time <= endTime && x.Time >= startTime).ToList();
}
else
{
throw new ArgumentException("Insufficient role!");
}
}
/// <summary>
/// Gets stocks made by certain user.
/// </summary>
/// <remarks>
/// Accepts user id for getting the user.
/// Requires Admin role.
/// </remarks>
/// <returns>
/// Returns an Collection of all the stocks in the criteria.
/// </returns>
public ICollection<Stock> GetByUser(int id)
{
if (currentUser != null || currentUser.RoleId == 3)
{
var user = userctrl.Get(id);
if (user != null)
{
return GetAll().Where(u => u.UserId == user.Id).ToList();
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient role!");
}
}
/// <summary>
/// Gets stocks made by certain user.
/// </summary>
/// <remarks>
/// Accepts username for getting the user.
/// Requires Admin role.
/// </remarks>
/// <returns>
/// Returns an Collection of all the stocks in the criteria.
/// </returns>
public ICollection<Stock> GetByUser(string username)
{
if (currentUser != null || currentUser.RoleId == 3)
{
var user = userctrl.Get(username);
if (user != null)
{
return GetAll().Where(u => u.UserId == user.Id).ToList();
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient role!");
}
}
/// <summary>
/// Adds Stock to the database.
/// </summary>
/// <remarks>
/// Requires Manager role or better.
/// </remarks>
/// <remarks>
/// Accepts product id for getting the product, amount sold and time of transaction.
/// </remarks>
public void Add(int productId, double Amount, DateTime time)
{
if (currentUser.RoleId > 1)
{
if (Amount > 0)
{
var stock = new Stock(currentUser.Id, productId, Amount, time);
productctrl.AddAmount(productId, Amount);
context.Stock.Add(stock);
context.SaveChanges();
}
else
{
throw new ArgumentException("Amount cannot be negative");
}
}
else
{
throw new ArgumentException("Insufficient role!");
}
}
/// <summary>
/// Adds Stock to the database.
/// </summary>
/// <remarks>
/// Requires Manager role or better.
/// </remarks>
/// <remarks>
/// Accepts product name for getting the product, amount sold and time of transaction.
/// </remarks>
public void Add(string productName, double Amount, DateTime time)
{
if (currentUser.RoleId > 1)
{
if (Amount > 0)
{
productctrl = new ProductController(currentUser);
var productId = productctrl.Get(productName).Id;
var stock = new Stock(currentUser.Id, productId, Amount, time);
productctrl.AddAmount(productId, Amount);
context.Stock.Add(stock);
context.SaveChanges();
}
else
{
throw new ArgumentException("Amount cannot be negative");
}
}
else
{
throw new ArgumentException("Insufficient role!");
}
}
/// <summary>
/// Deletes Deal from the database.
/// </summary>
/// <remarks>
/// Requires Manager Role or better.
/// </remarks>
/// <remarks>
/// Accepts stock id for getting the product
/// </remarks>
public void Delete(int id)
{
if (currentUser.RoleId == 3 )
{
var stock = Get(id);
if (stock != null)
{
productctrl.RemoveAmount(stock.ProductId, stock.Amount);
context.Stock.Remove(stock);
context.SaveChanges();
}
else
{
throw new ArgumentException("Stock Id not found!");
}
}
else
{
throw new ArgumentException("Insufficient role!");
}
}
}
}

View File

@@ -0,0 +1,169 @@
using Business.Business.Interfaces;
using Models;
using Models.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Business.Business.UserManagment.Controllers
{
public class RoleController : IReadOnlyController<Role>
{
private LuminousContext context;
private User currentUser;
/// <summary>
/// Empty Constructor.
/// </summary>
/// <remarks>
/// Used for Initialiation of the roles in the database.
/// </remarks>
public RoleController()
{
this.context = new LuminousContext();
}
public RoleController(LuminousContext context)
{
this.context = context;
}
/// <summary>
/// Constructor that accepts a user object.
/// </summary>
/// <remarks>
/// User object is used for role checking.
/// </remarks>
public RoleController(User currentUser)
{
this.context = new LuminousContext();
this.currentUser = currentUser;
}
/// <summary>
/// Constructor that accepts custom context and a user object.
/// </summary>
/// <remarks>
/// Custom context is mainly used for Unit Testing.
/// </remarks>
/// <remarks>
/// User object is used for role checking.
/// </remarks>
public RoleController(User currentUser, LuminousContext context)
{
this.context = context;
this.currentUser = currentUser;
}
/// <summary>
/// Creates the roles.
/// </summary>
/// <remarks>
/// Requires no special roles. Not even an registered user.
/// </remarks>
/// <remarks>
/// Almost every method of each class checks if the user has suffficient roles for the task.
/// </remarks>
public void CreateInitialRoles()
{
var Cashier = new Role("Cashier");
var Manager = new Role("Manager");
var Admin = new Role("Admin");
context.Role.AddRange(Cashier, Manager, Admin);
context.SaveChanges();
}
/// <summary>
/// Gets All Roles.
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <returns>
/// Returns a ICollection of all roles.
/// </returns>
public ICollection<Role> GetAll()
{
if (currentUser.RoleId == 3)
{
return context.Role.ToList();
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Searches the role by given Id
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <returns>
/// Returns an object of the role with the given Id.
/// </returns>
public Role Get(int id)
{
if (currentUser.RoleId == 3)
{
return context.Role.Find(id);
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Searches the role by given name
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <returns>
/// Returns an object of the role with the given name.
/// </returns>
public Role Get(string name)
{
if (currentUser.RoleId == 3)
{
return context.Role.FirstOrDefault(u => u.Name == name);
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Searches the role by a given substring
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <returns>
/// Returns an ICollection of all roles that contain the given substring in their name.
/// </returns>
public ICollection<Role> GetByApproximateName(string substring)
{
if (currentUser.RoleId == 3)
{
return context.Role.Where(u => u.Name.Contains(substring)).ToList();
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
}
}

View File

@@ -0,0 +1,665 @@
using Business.Business.UserManagment.Controllers;
using Models;
using Models.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Business.Business.UserManagment
{
public class UserController : IController<User>
{
private LuminousContext context;
private RoleController rolectrl;
private User currentUser;
/// <summary>
/// Empty Constructor
/// </summary>
/// <remarks>
/// Used for Initialiation of the roles in the database
/// </remarks>
public UserController()
{
this.context = new LuminousContext();
}
/// <summary>
/// Constructor that accepts a user object
/// </summary>
/// <remarks>
/// User object is used for role checking
/// </remarks>
public UserController(User currentUser)
{
this.currentUser = currentUser;
this.context = new LuminousContext();
this.rolectrl = new RoleController(currentUser);
}
// <summary>
/// Constructor that accepts custom context, rolectrl and a user object
/// </summary>
/// <remarks>
/// Custom context is mainly used for Unit Testing
/// </remarks>
/// <remarks>
/// Custom context is mainly used for Unit Testing
/// User object is used for role checking
/// </remarks>
public UserController(User currentUser, LuminousContext context, RoleController rolectrl)
{
this.currentUser = currentUser;
this.context = context;
this.rolectrl = rolectrl;
}
/// <summary>
/// Gets All Users
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <returns>
/// Returns a ICollection of all users.
/// </returns>
public ICollection<User> GetAll()
{
if (currentUser != null || currentUser.RoleId == 3)
{
return context.User.ToList();
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Checks if there's a user in the database
/// </summary>
/// <remarks>
/// Can be used with an empty constructor
/// </remarks>
public bool CheckIfUserEverCreated()
{
if (context.User.ToList().Any())
{
return true;
}
return false;
}
/// <summary>
/// Searches the user by given Id
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// </summary>
/// <returns>
/// Returns an object of the user with the given Id
/// </returns>
public User Get(int id)
{
if (currentUser != null || currentUser.RoleId == 3)
{
return context.User.Find(id);
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Searches the user by given name
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <returns>
/// Returns an object of the user with the given name.
/// </returns>
public User Get(string name)
{
if (currentUser != null || currentUser.RoleId == 3)
{
return context.User.FirstOrDefault(u => u.Name == name);
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Searches the user by a given substring
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <returns>
/// Returns an ICollection of all users that contain the given substring in their name.
/// </returns>
public ICollection<User> GetByApproximateName(string substring)
{
if (currentUser != null || currentUser.RoleId == 3)
{
return context.User.Where(u => u.Name.Contains(substring)).ToList();
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Checks if the password is valid
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <remarks>
/// Password is used to log in the user.
/// </remarks>
/// <returns>
/// Returns an object of the found user.
/// </returns>
public User ValidatePassword(string password)
{
var user = context.User.FirstOrDefault(x => x.Password == password);
if (user == null)
{
throw new ArgumentException("Invalid User!");
}
return user;
}
/// <summary>
/// Registers an user
/// </summary>
/// <remarks>
/// Requires no special roles.
/// </remarks>
/// <remarks>
/// Used for the creation of the initial user, so it assigns admin role by default.
/// </remarks>
public void RegisterItem(string name, string password)
{
var user = new User(name, password, 3);
context.User.Add(user);
context.SaveChanges();
}
/// <summary>
/// Registers an user
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts an role id so it can assign a role to the user.
/// </remarks>
public void RegisterItem(string name, string password, int roleId)
{
if (currentUser != null || currentUser.RoleId == 3)
{
if (GetAll().Where(u => u.Name == name).Any())
{
throw new ArgumentException("The username is already taken!");
}
else if (GetAll().Where(u => u.Password == password).Any())
{
throw new ArgumentException("The password is already taken"!);
}
else
{
var foundRole = rolectrl.Get(roleId);
if (foundRole != null)
{
var user = new User(name, password, roleId);
context.User.Add(user);
context.SaveChanges();
}
else
{
throw new ArgumentException("Role not found!");
}
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Registers an user
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts an role name so it can assign a role to the user.
/// </remarks>
public void RegisterItem(string name, string password, string roleName)
{
if (currentUser != null || currentUser.RoleId == 3)
{
if (GetAll().Where(u => u.Name == name).Any())
{
throw new ArgumentException("The username is already taken!");
}
else if (GetAll().Where(u => u.Password == password).Any())
{
throw new ArgumentException("The password is already taken"!);
}
else
{
var foundRole = rolectrl.Get(roleName);
if (foundRole != null)
{
var user = new User(name, password, foundRole.Id);
context.User.Add(user);
context.SaveChanges();
}
else
{
throw new ArgumentException("Role not found!");
}
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Updates the username of the given user
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts an id for getting the user.
/// </remarks>
public void UpdateName(int id, string newName)
{
if (currentUser != null || currentUser.Id == 3)
{
var user = Get(id);
if (user != null)
{
if (user.Name != newName)
{
user.Name = newName;
context.SaveChanges();
}
else
{
throw new ArgumentException("Usernames match. Please choose another username!");
}
}
else
{
throw new ArgumentException("No user with such id");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Updates the username of the given user
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts the current name for getting the user.
/// </remarks>
public void UpdateName(string oldName, string newName)
{
if (currentUser != null || currentUser.RoleId == 3)
{
if (oldName != newName)
{
var user = Get(oldName);
if (user != null)
{
user.Name = newName;
context.SaveChanges();
}
else
{
throw new ArgumentException("No user with such name!");
}
}
else
{
throw new ArgumentException("Usernames match. Please use another username!");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Updates the password of the given user
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts an id for getting the user.
/// </remarks>
public void UpdatePassword(int id, string newPassword)
{
if (currentUser != null || currentUser.RoleId == 3)
{
var user = Get(id);
if (user != null)
{
if (user.Password != newPassword)
{
user.Password = newPassword;
context.SaveChanges();
}
else
{
throw new ArgumentException("Passwords match! Please use another password!");
}
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Updates the password of the given user
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts the name for getting the user.
/// </remarks>
public void UpdatePassword(string name, string newPassword)
{
if (currentUser != null || currentUser.RoleId == 3)
{
var user = Get(name);
if (user != null)
{
if (user.Password != newPassword)
{
user.Password = newPassword;
context.SaveChanges();
}
else
{
throw new ArgumentException("Passwords match! Please use another password!");
}
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Updates the role of the given user
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts an user id for getting the user.
/// Accepts an role id for getting the role.
/// </remarks>
public void UpdateRole(int id, int RoleId)
{
if (currentUser != null || currentUser.RoleId == 3)
{
var user = Get(id);
if (user != null)
{
var foundRole = rolectrl.Get(RoleId);
if (foundRole != null)
{
user.RoleId = RoleId;
context.SaveChanges();
}
else
{
throw new ArgumentException("Role not found!");
}
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Updates the role of the given user
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts an user id for getting the user.
/// Accepts an role name for getting the role.
/// </remarks>
public void UpdateRole(int id, string roleName)
{
if (currentUser != null || currentUser.RoleId == 3)
{
var user = Get(id);
if (user != null)
{
var foundRole = rolectrl.Get(roleName);
if (foundRole != null)
{
user.RoleId = foundRole.Id;
context.SaveChanges();
}
else
{
throw new ArgumentException("Role not found!");
}
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Updates the role of the given user
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts an username for getting the user.
/// Accepts an role id for getting the role.
/// </remarks>
public void UpdateRole(string name, int roleId)
{
if (currentUser != null || currentUser.RoleId == 3)
{
var user = Get(name);
if (user != null)
{
var foundRole = rolectrl.Get(roleId);
if (foundRole != null)
{
user.RoleId = roleId;
context.SaveChanges();
}
else
{
throw new ArgumentException("Role not found!");
}
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Updates the role of the given user
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts an username for getting the user.
/// Accepts an role name for getting the role.
/// </remarks>
public void UpdateRole(string name, string roleName)
{
if (currentUser != null || currentUser.RoleId == 3)
{
var user = Get(name);
if (user != null)
{
var foundRole = rolectrl.Get(roleName);
if (foundRole != null)
{
user.RoleId = foundRole.Id;
context.SaveChanges();
}
else
{
throw new ArgumentException("Role not found!");
}
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Deletes the given user
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts an user id for getting the user.
/// </remarks>
public void Delete(int id)
{
if (currentUser != null || currentUser.RoleId == 3)
{
var user = Get(id);
if (user != null)
{
context.User.Remove(user);
context.SaveChanges();
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
/// <summary>
/// Deletes the given user
/// </summary>
/// <remarks>
/// Requires Admin role.
/// </remarks>
/// <remarks>
/// Accepts an username for getting the user.
/// </remarks>
public void Delete(string name)
{
if (currentUser != null || currentUser.RoleId == 3)
{
var user = Get(name);
if (user != null)
{
context.User.Remove(user);
context.SaveChanges();
}
else
{
throw new ArgumentException("User not found");
}
}
else
{
throw new ArgumentException("Insufficient Role!");
}
}
}
}

View File

@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.12">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Business\Business.csproj" />
<ProjectReference Include="..\Models\Data.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,63 @@
using Business.Business.UserManagment;
using Business.Business.UserManagment.Controllers;
using System;
using System.Collections.Generic;
using System.Text;
namespace Display
{
public class InitialSetup
{
public InitialSetup()
{
}
/// <summary>
/// Asks the user for credentials used for the first user - administrator.
/// </summary>
public static void InitialUserInput(out string userName, out string password)
{
try
{
Console.Write("Enter username: ");
userName = Console.ReadLine();
Console.Write("Enter password: ");
password = Console.ReadLine();
}
catch (Exception e)
{
userName = string.Empty;
password = string.Empty;
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Registers the initial user as an admin.
/// </summary>
/// <param name="uc">Current UserController</param>
public static void InitialRegistration(UserController uc)
{
try
{
if (uc.CheckIfUserEverCreated())
{
}
else
{
RoleController rc = new RoleController();
rc.CreateInitialRoles();
string userName, password;
InitialUserInput(out userName, out password);
uc.RegisterItem(userName, password);
Console.WriteLine("Registration succesful!");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

View File

@@ -0,0 +1,83 @@
using Business.Business.UserManagment;
using Display.Views;
using Models;
using Models.Models;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace Display
{
public class Program
{
static void Main()
{
User currentUser = new User();
var uc = new UserController();
try
{
BigLogo();
InitialSetup.InitialRegistration(uc);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
bool isRunning = true;
while (isRunning)
{
try
{
Console.Write("Enter password: ");
currentUser = uc.ValidatePassword(Console.ReadLine());
if (currentUser != null)
{
isRunning = false;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
try
{
uc = new UserController(currentUser);
var view = new BaseView(currentUser);
switch (currentUser.RoleId)
{
case 1:
view = new CashierView(currentUser);
break;
case 2:
view = new ManagerView(currentUser);
break;
case 3:
view = new AdminView(currentUser);
break;
default:
break;
}
view.ActionHandle();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Logo splash screen
/// </summary>
private static void BigLogo()
{
Console.WriteLine(" _ _ _____ _ ");
Console.WriteLine(" | | (_) / ____| | | ");
Console.WriteLine(" | | _ _ _ __ ___ _ _ __ ___ _ _ ___ | (___ __ _| | ___ ___ ");
Console.WriteLine(" | | | | | | '_ ` _ \\| | '_ \\ / _ \\| | | / __| \\___ \\ / _` | |/ _ / __|");
Console.WriteLine(" | |___| |_| | | | | | | | | | | (_) | |_| \\__ \\ ____) | (_| | | __\\__ \\");
Console.WriteLine(" |______\\__,_|_| |_| |_|_|_| |_|\\___/ \\__,_|___/ |_____/ \\__,_|_|\\___|___/");
Console.WriteLine("Luminous Sales v1.0.0 by A. Konarcheva, D. Byalkov & D. Todorov 2021");
Console.WriteLine();
}
}
}

View File

@@ -0,0 +1,597 @@
using Business.Business.Sales;
using Business.Business.UserManagment;
using Models.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Display.Views
{
public class AdminView : ManagerView
{
User currentUser;
/// <summary>
/// Constructor that accepts a user object.
/// <summary>
public AdminView(User currentUser) : base(currentUser)
{
this.currentUser = currentUser;
}
/// <summary>
/// Shows the avaliable to the user commands.
/// </summary>
/// <remarks>
/// The main menu. Inherited from ManagerView and adds Admin-specific menu.
/// </remarks>
public override void ShowAvaliableCommands()
{
base.ShowAvaliableCommands();
Console.WriteLine("3. Administration");
}
/// <summary>
/// Asks the user to choose which group of action to use.
/// </summary>
/// <remarks>
/// A choice is given by entering a number from the given list.
/// Inherited from ManagerView and expanded with the Admin menu.
/// </remarks>
public override void ActionHandle()
{
try
{
while (true)
{
Console.Clear();
ShowAvaliableCommands();
Console.Write("> ");
int input = int.Parse(Console.ReadLine());
if (input == 0)
{
Environment.Exit(0);
}
else if (input == 1)
{
SaleHandle();
}
else if (input == 2)
{
ManageHandle();
}
else if (input == 3)
{
AdminHandle();
}
else Console.WriteLine("Invalid operation");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Selection menu with admin actions.
/// </summary>
/// <remarks>
/// Requires role level 3 (Admin).
/// </remarks>
public void AdminHandle()
{
bool running = true;
while (running)
{
Console.WriteLine();
Console.WriteLine("=== ADMINISTRATION ===");
Console.WriteLine("0. Back");
Console.WriteLine();
Console.WriteLine("User Managment");
Console.WriteLine("1. List all users");
Console.WriteLine("2. Get user by id or name");
Console.WriteLine("3. List users by name");
Console.WriteLine("4. Register user");
Console.WriteLine("5. Update role");
Console.WriteLine("6. Update username");
Console.WriteLine("7. Update password");
Console.WriteLine("8. Delete user");
Console.WriteLine();
Console.WriteLine("Product Managment");
Console.WriteLine("9. Add product");
Console.WriteLine("10. List all products");
Console.WriteLine("11. Delete product");
Console.WriteLine("12. Update product price");
Console.WriteLine("13. Add amount of a product");
Console.WriteLine("14. Remove amount of a product");
Console.Write("> ");
try
{
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
GetAllUsers();
break;
case 2:
GetUser();
break;
case 3:
GetByApproximateName();
break;
case 4:
RegisterItem();
break;
case 5:
UpdateRole();
break;
case 6:
UpdateName();
break;
case 7:
UpdatePassword();
break;
case 8:
DeleteUser();
break;
case 9:
AddItem();
break;
case 10:
GetAllItems();
break;
case 11:
DeleteProduct();
break;
case 12:
UpdateProductPrice();
break;
case 13:
AddProductAmount();
break;
case 14:
RemoveProductAmount();
break;
case 0:
running = false;
break;
default:
Console.WriteLine("Invalid Option!");
break;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
/// <summary>
/// Lists all products from the database.
/// </summary>
private void GetAllItems()
{
try
{
ProductController productctrl = new ProductController(currentUser);
Console.WriteLine("Getting all items...");
Console.WriteLine("ID - Name - Amount - Price");
foreach (var item in productctrl.GetAll())
{
Console.WriteLine($"{item.Id} - {item.Name} - {item.AmountInStock} - {item.Price} ");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Lists all registered users from the database.
/// </summary>
public void GetAllUsers()
{
try
{
UserController userctl = new UserController(currentUser);
Console.WriteLine("Getting all users...");
Console.WriteLine("User ID - Username - Role");
foreach (var item in userctl.GetAll())
{
Console.WriteLine($"{item.Id} - {item.Name} - {item.Role.Name} ");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Lists info about a user using their ID or name from the database.
/// </summary>
public void GetUser()
{
try
{
UserController userctl = new UserController(currentUser);
Console.WriteLine("Getting user...");
Console.Write("Get user by ID or Name: ");
string input = Console.ReadLine();
int.TryParse(input, out int inputId);
if (inputId != 0)
{
Console.WriteLine(userctl.Get(inputId));
}
else
{
Console.WriteLine(userctl.Get(input));
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Lists all users who match the search term from the database.
/// </summary>
public void GetByApproximateName()
{
try
{
UserController userctl = new UserController(currentUser);
Console.WriteLine("Getting by name...");
Console.Write("Enter name: ");
string input = Console.ReadLine();
foreach (var item in userctl.GetByApproximateName(input))
{
Console.WriteLine($"{item.Id} {item.Name} {item.Role.Name}");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Registers a user using the provided data.
/// </summary>
public void RegisterItem()
{
try
{
UserController userctl = new UserController(currentUser);
Console.WriteLine("Registering user...");
Console.Write("Enter username: ");
string username = Console.ReadLine();
Console.Write("Enter password: ");
string password = Console.ReadLine();
Console.WriteLine("Avaliable roles: 1 - Cashier, 2 - Manager, 3 - Admin");
Console.Write("Enter role ID or name: ");
string role = Console.ReadLine();
bool result = int.TryParse(role, out int roleId);
if (role == null)
{
userctl.RegisterItem(username, password);
Console.WriteLine("Registered user successfully");
}
else if (result)
{
userctl.RegisterItem(username, password, roleId);
Console.WriteLine("Registered user successfully");
}
else
{
userctl.RegisterItem(username, password, role);
Console.WriteLine("Registered user successfully");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Changes the role given to a specific user.
/// </summary>
/// <remarks>
/// Asks for a user's ID or name and the new role ID or name.
/// </remarks>
public void UpdateRole()
{
try
{
UserController userctl = new UserController(currentUser);
Console.WriteLine("Updating role...");
Console.Write("Enter username or user ID: ");
string username = Console.ReadLine();
Console.Write("Enter new role ID or name: ");
string role = Console.ReadLine();
bool userResult = int.TryParse(username, out int userId);
bool roleResult = int.TryParse(role, out int roleId);
if (userResult && roleResult)
{
userctl.UpdateRole(userId, roleId);
}
else if (userResult && !roleResult)
{
userctl.UpdateRole(userId, role);
}
else if (!userResult && roleResult)
{
userctl.UpdateRole(username, roleId);
}
else
{
userctl.UpdateRole(username, role);
}
Console.WriteLine("Updated role successfully");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Renames a user.
/// </summary>
public void UpdateName()
{
try
{
UserController userctl = new UserController(currentUser);
Console.WriteLine("Updating username...");
Console.Write("Enter username or ID: ");
string user = Console.ReadLine();
Console.Write("Enter new username: ");
string username = Console.ReadLine();
bool result = int.TryParse(user, out int userId);
if (result)
{
userctl.UpdateName(userId, username);
Console.WriteLine("Updated username successfully");
}
else
{
userctl.UpdateName(user, username);
Console.WriteLine("Updated username successfully");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Changes a users' password.
/// </summary>
public void UpdatePassword()
{
try
{
UserController userctl = new UserController(currentUser);
Console.WriteLine("Updating password...");
Console.Write("Enter username or ID: ");
string user = Console.ReadLine();
Console.Write("Enter new password: ");
string username = Console.ReadLine();
bool result = int.TryParse(user, out int userId);
if (result)
{
userctl.UpdatePassword(userId, username);
Console.WriteLine("Updated password successfully");
}
else
{
userctl.UpdatePassword(user, username);
Console.WriteLine("Updated password successfully");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Deletes a user from the database.
/// </summary>
public void DeleteUser()
{
try
{
UserController userctl = new UserController(currentUser);
Console.WriteLine("Deleting user...");
Console.Write("Enter username or ID: ");
string user = Console.ReadLine();
bool result = int.TryParse(user, out int userId);
if (result)
{
userctl.Delete(userId);
Console.WriteLine("Deleted successfully");
}
else
{
userctl.Delete(user);
Console.WriteLine("Deleted successfully");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Adds a product to the database.
/// </summary>
public void AddItem()
{
ProductController productctrl = new ProductController(currentUser);
try
{
Console.WriteLine("Adding item to database...");
Console.Write("Enter product name: ");
string product = Console.ReadLine();
Console.Write("Enter price: ");
double price = double.Parse(Console.ReadLine());
productctrl.AddItem(product, price);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Deletes a product from the database.
/// </summary>
public void DeleteProduct()
{
ProductController productctrl = new ProductController(currentUser);
try
{
Console.WriteLine("Delete item to database...");
Console.Write("Enter product ID or name: ");
string product = Console.ReadLine();
bool result = int.TryParse(product, out int productId);
if (result)
{
productctrl.Delete(productId);
Console.WriteLine("Deleted successfully");
}
else
{
productctrl.Delete(product);
Console.WriteLine("Deleted successfully");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Updates a product's price from the database.
/// </summary>
public void UpdateProductPrice()
{
ProductController productctrl = new ProductController(currentUser);
try
{
Console.WriteLine("Updating item in database...");
Console.Write("Enter product ID or name: ");
string product = Console.ReadLine();
Console.Write("Enter new price: ");
double price = double.Parse(Console.ReadLine());
bool result = int.TryParse(product, out int productId);
if (result)
{
productctrl.UpdatePrice(product, price);
Console.WriteLine("Deleted successfully");
}
else
{
productctrl.UpdatePrice(productId, price);
Console.WriteLine("Deleted successfully");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Updates a product's name from the database.
/// </summary>
public void UpdateProductName()
{
ProductController productctrl = new ProductController(currentUser);
try
{
Console.WriteLine("Updating item in database...");
Console.Write("Enter product ID or name: ");
string product = Console.ReadLine();
Console.Write("Enter new name: ");
string name = Console.ReadLine();
bool result = int.TryParse(product, out int productId);
if (result)
{
productctrl.UpdateName(product, name);
Console.WriteLine("Deleted successfully");
}
else
{
productctrl.UpdateName(productId, name);
Console.WriteLine("Deleted successfully");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Adds amount to a product's amount from the database.
/// </summary>
public void AddProductAmount()
{
ProductController productctrl = new ProductController(currentUser);
try
{
Console.WriteLine("Updating item in database...");
Console.Write("Enter product ID or name: ");
string product = Console.ReadLine();
Console.Write("Add amount: ");
double amount = double.Parse(Console.ReadLine());
bool result = int.TryParse(product, out int productId);
if (result)
{
productctrl.AddAmount(product, amount);
Console.WriteLine("Deleted successfully");
}
else
{
productctrl.AddAmount(productId, amount);
Console.WriteLine("Deleted successfully");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Removes amount to a product's amount from the database.
/// </summary>
public void RemoveProductAmount()
{
ProductController productctrl = new ProductController(currentUser);
try
{
Console.WriteLine("Updating item in database...");
Console.Write("Enter product ID or name: ");
string product = Console.ReadLine();
Console.Write("Remove amount: ");
double amount = double.Parse(Console.ReadLine());
bool result = int.TryParse(product, out int productId);
if (result)
{
productctrl.RemoveAmount(product, amount);
Console.WriteLine("Deleted successfully");
}
else
{
productctrl.RemoveAmount(productId, amount);
Console.WriteLine("Deleted successfully");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

View File

@@ -0,0 +1,204 @@
using Business.Business.Sales;
using Models.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Display.Views
{
public class BaseView
{
internal ProductController productctrl;
private DealController dealctrl;
internal User currentUser;
/// <summary>
/// Constructor that accepts a user object.
/// <summary>
/// <remarks>
/// User object is used for stock and deal checking.
/// Initialises stock and deal controllers.
/// </remarks>
public BaseView(User currentUser)
{
this.currentUser = currentUser;
this.dealctrl = new DealController(currentUser);
this.productctrl = new ProductController(currentUser);
}
/// <summary>
/// Shows all available commands.
/// </summary>
/// <remarks>
/// Includes only the basic functions of the program.
/// The main menu.
/// </remarks>
public virtual void ShowAvaliableCommands()
{
Console.WriteLine();
Console.WriteLine("=== MAIN MENU ===");
Console.WriteLine("0. Exit");
Console.WriteLine();
Console.WriteLine("1. Sales");
}
/// <summary>
/// Asks the user to choose which group of action to use.
/// </summary>
/// <remarks>
/// A choice is given by entering a number from the given list.
/// It's expanded by its inheritors.
/// </remarks>
public virtual void ActionHandle()
{
try
{
while (true)
{
Console.Clear();
ShowAvaliableCommands();
Console.Write("> ");
int input = int.Parse(Console.ReadLine());
if (input == 0)
{
Environment.Exit(0);
}
else if (input == 1)
{
SaleHandle();
}
else Console.WriteLine("Invalid operation");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Selection menu with base actions.
/// </summary>
public void SaleHandle()
{
bool running = true;
while (running)
{
Console.WriteLine();
Console.WriteLine("=== SALES ===");
Console.WriteLine("0. Back");
Console.WriteLine();
Console.WriteLine("Deal Managment");
Console.WriteLine("1. Search");
Console.WriteLine("2. Sale");
Console.Write("> ");
try
{
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
SearchItem();
break;
case 2:
SaleItem();
break;
case 0:
running = false;
break;
default:
Console.WriteLine("Invalid Option!");
break;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
/// <summary>
/// Lists all products which match the search term from the database.
/// </summary>
private void SearchItem()
{
try
{
productctrl = new ProductController(currentUser);
Console.Write("Search item: ");
string search = Console.ReadLine();
Console.WriteLine("Product ID - Name - Price - Amount");
foreach (var item in productctrl.GetByApproximateName(search).ToList())
{
Console.WriteLine($"{item.Id} - {item.Name} - {item.Price} - {item.AmountInStock}");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Sells products. Asks which product and the quantity sold. Prints a summary in the end.
/// </summary>
private void SaleItem()
{
try
{
productctrl = new ProductController(currentUser);
List<Product> check = new List<Product>();
bool endTyped = false;
while (!endTyped)
{
Console.Write("Enter item id or name (\"end\" to finish): ");
string itemInput = Console.ReadLine();
if (itemInput.ToLower() != "end")
{
int itemId;
if (int.TryParse(itemInput, out itemId))
{
var productToAdd = productctrl.Get(itemId);
Console.Write("Amount: ");
double amount = double.Parse(Console.ReadLine());
dealctrl.Add(itemId, amount, DateTime.Now);
check.Add(productToAdd);
}
else
{
var productToAdd = productctrl.Get(itemInput);
Console.Write("Amount: ");
double amount = double.Parse(Console.ReadLine());
dealctrl.Add(itemInput, amount, DateTime.Now);
check.Add(productToAdd);
}
}
else
{
endTyped = true;
Console.WriteLine();
Console.WriteLine("Check");
double sum = 0;
check.Reverse();
var lastdeals = dealctrl.GetAll().OrderByDescending(x => x.Id).ToArray();
for (int i = check.Count - 1; i >= 0; i--)
{
sum += check[i].Price * lastdeals[i].Amount;
int rowNum = i + 1;
Console.WriteLine($"{rowNum}. {check[i].Name} - {check[i].Price}x{lastdeals[i].Amount}");
}
Console.WriteLine($"Total: {sum}");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

View File

@@ -0,0 +1,16 @@
using Models.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Display.Views
{
public class CashierView : BaseView
{
public CashierView(User currentUser) : base(currentUser)
{
}
}
}

View File

@@ -0,0 +1,303 @@
using System;
using System.Collections.Generic;
using System.Text;
using Business.Business.Sales;
using Models.Models;
namespace Display.Views
{
public class ManagerView : BaseView
{
StockController stockctrl;
DealController dealctrl;
/// <summary>
/// Constructor that accepts a user object.
/// <summary>
/// <remarks>
/// User object is used for stock and deal checking.
/// Initialises stock and deal controllers.
/// </remarks>
public ManagerView(User currentUser):base(currentUser)
{
stockctrl = new StockController(currentUser);
dealctrl = new DealController(currentUser);
}
/// <summary>
/// Shows all available commands.
/// </summary>
/// <remarks>
/// Inherits all available commands from the base view.
/// The main menu.
/// </remarks>
public override void ShowAvaliableCommands()
{
base.ShowAvaliableCommands();
Console.WriteLine("2. Stock");
}
/// <summary>
/// Asks the user to choose which group of action to use.
/// </summary>
/// <remarks>
/// If user inputs the digit 1, returns selling handles.
/// If user inputs the digit 2, returns managing handles.
/// If user inputs something else, the operation is invalid.
/// </remarks>
public override void ActionHandle()
{
try
{
while (true)
{
ShowAvaliableCommands();
Console.Write("> ");
int input = int.Parse(Console.ReadLine());
if (input == 0)
{
Environment.Exit(0);
}
else if (input == 1)
{
SaleHandle();
}
else if (input == 2)
{
ManageHandle();
}
else Console.WriteLine("Invalid operation");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Selection menu with manager actions.
/// </summary>
/// <remarks>
/// Requires role level 2 (Manager).
/// </remarks>
public void ManageHandle()
{
bool running = true;
while (running)
{
Console.WriteLine();
Console.WriteLine("=== STOCK ===");
Console.WriteLine("0. Back");
Console.WriteLine();
Console.WriteLine("Stock Managment");
Console.WriteLine("1. List all stocks");
Console.WriteLine("2. Get stock by ID");
Console.WriteLine("3. List stocks by time");
Console.WriteLine("4. Add stock");
Console.WriteLine("5. Delete");
Console.WriteLine("6. List deals by user");
Console.Write("> ");
try
{
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
GetAll();
break;
case 2:
Get();
break;
case 3:
GetByTime();
break;
case 4:
Add();
break;
case 5:
Delete();
break;
case 6:
GetByUser();
break;
case 0:
running = false;
break;
default:
Console.WriteLine("Invalid Option!");
break;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
/// <summary>
/// Lists all information about stock from the database.
/// </summary>
public void GetAll()
{
try
{
Console.WriteLine("Getting all stock...");
Console.WriteLine("ID - Product ID - Amount - Time");
foreach (var item in stockctrl.GetAll())
{
Console.WriteLine($"{item.Id} - {item.ProductId} - {item.Amount} - {item.Time}");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Lists all registered information about stocks from the database.
/// </summary>
public void Get()
{
try
{
Console.Write("Enter stock id: ");
int id = int.Parse(Console.ReadLine());
var result = stockctrl.Get(id);
Console.WriteLine("ID - Product ID - Amount - Time");
Console.WriteLine($"{result.Id} - {result.ProductId} - {result.Amount} - {result.Time}");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Gets stock by its start time and end time.
/// </summary>
/// <remarks>
/// Inputs start time and end time.
/// Lists all information about stocks from the database in real time.
/// </remarks>
public void GetByTime()
{
try
{
Console.WriteLine("Getting stock by time...");
Console.Write("Enter start time: ");
DateTime startTime = DateTime.Parse(Console.ReadLine());
Console.Write("Enter end time: ");
DateTime endTime = DateTime.Parse(Console.ReadLine());
Console.WriteLine("ID - Product ID - Amount - Time");
foreach (var item in stockctrl.GetByTime(startTime, endTime))
{
Console.WriteLine($"{item.Id} - {item.ProductId} - {item.Amount} - {item.Time}");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Adding a stock using the product id or name.
/// </summary>
/// <remarks>
/// Entering product name and amount.
/// If the result is true, returns a stock with product id, amount and a real time.
/// Else returns a stock with product name, amount and a real time.
/// </remarks>
public void Add()
{
try
{
Console.WriteLine("Adding stock by product id or name...");
Console.Write("Enter product ID or name: ");
string product = Console.ReadLine();
Console.Write("Enter stock amount: ");
double amount = double.Parse(Console.ReadLine());
bool result = int.TryParse(product, out int productId);
if (result)
{
stockctrl.Add(productId, amount, DateTime.Now);
}
else
{
stockctrl.Add(product, amount, DateTime.Now);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Deletes a stock from the database.
/// </summary>
public void Delete()
{
try
{
Console.WriteLine("Deleting stock...");
Console.Write("Enter stock id: ");
int id = int.Parse(Console.ReadLine());
stockctrl.Delete(id);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Gets deals by the user who made them.
/// </summary>
/// <remarks>
/// Inputs username or user ID.
/// Lists all deals made by a user from the database.
/// </remarks>
public void GetByUser()
{
try
{
Console.WriteLine("Getting stock by time...");
Console.Write("Enter username or user ID: ");
string input = Console.ReadLine();
int.TryParse(input, out int inputId);
ICollection<Deal> output;
if (inputId != 0)
{
output = dealctrl.GetByUser(inputId);
}
else
{
output = dealctrl.GetByUser(input);
}
Console.WriteLine("Deal ID - Product ID - Amount - Time");
foreach (var item in output)
{
Console.WriteLine($"{item.Id} - {item.ProductId} - {item.Amount} - {item.Time}");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

View File

@@ -3,9 +3,13 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16 # Visual Studio Version 16
VisualStudioVersion = 16.0.31019.35 VisualStudioVersion = 16.0.31019.35
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LuminousSales", "LuminousSales\LuminousSales.csproj", "{0B102226-3EAB-4DA3-9C1F-4053E4FA2232}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Data", "Models\Data.csproj", "{40C482BF-B9C4-4460-BB1C-5A90959D1838}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Models", "Models\Models.csproj", "{40C482BF-B9C4-4460-BB1C-5A90959D1838}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Business", "Business\Business.csproj", "{E1661853-3081-4C40-8E68-C063B3BC88A4}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Display", "Display\Display.csproj", "{61E060C5-4360-4880-9ED7-6A139C988F0F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LuminousTests", "LuminousTests\LuminousTests.csproj", "{8475489D-3593-43D0-A6E2-006A732B982A}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -13,14 +17,22 @@ Global
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0B102226-3EAB-4DA3-9C1F-4053E4FA2232}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0B102226-3EAB-4DA3-9C1F-4053E4FA2232}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0B102226-3EAB-4DA3-9C1F-4053E4FA2232}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0B102226-3EAB-4DA3-9C1F-4053E4FA2232}.Release|Any CPU.Build.0 = Release|Any CPU
{40C482BF-B9C4-4460-BB1C-5A90959D1838}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {40C482BF-B9C4-4460-BB1C-5A90959D1838}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{40C482BF-B9C4-4460-BB1C-5A90959D1838}.Debug|Any CPU.Build.0 = Debug|Any CPU {40C482BF-B9C4-4460-BB1C-5A90959D1838}.Debug|Any CPU.Build.0 = Debug|Any CPU
{40C482BF-B9C4-4460-BB1C-5A90959D1838}.Release|Any CPU.ActiveCfg = Release|Any CPU {40C482BF-B9C4-4460-BB1C-5A90959D1838}.Release|Any CPU.ActiveCfg = Release|Any CPU
{40C482BF-B9C4-4460-BB1C-5A90959D1838}.Release|Any CPU.Build.0 = Release|Any CPU {40C482BF-B9C4-4460-BB1C-5A90959D1838}.Release|Any CPU.Build.0 = Release|Any CPU
{E1661853-3081-4C40-8E68-C063B3BC88A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E1661853-3081-4C40-8E68-C063B3BC88A4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E1661853-3081-4C40-8E68-C063B3BC88A4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E1661853-3081-4C40-8E68-C063B3BC88A4}.Release|Any CPU.Build.0 = Release|Any CPU
{61E060C5-4360-4880-9ED7-6A139C988F0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{61E060C5-4360-4880-9ED7-6A139C988F0F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{61E060C5-4360-4880-9ED7-6A139C988F0F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{61E060C5-4360-4880-9ED7-6A139C988F0F}.Release|Any CPU.Build.0 = Release|Any CPU
{8475489D-3593-43D0-A6E2-006A732B982A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8475489D-3593-43D0-A6E2-006A732B982A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8475489D-3593-43D0-A6E2-006A732B982A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8475489D-3593-43D0-A6E2-006A732B982A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace LuminousSales.Business
{
public class DealsBusiness
{
private DealContext dealContext;
}
}

View File

@@ -1,11 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace LuminousSales.Business
{
public class PermissionsBusiness
{
private PermissionContext permissionContext;
}
}

View File

@@ -1,66 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LuminousSales.Data;
using LuminousSales.Data.Model;
namespace LuminousSales.Business
{
public class ProductBusiness
{
private ProductContext productContext;
public List<Product> GetAll()
{
using (productContext = new ProductContext())
{
return productContext.Products.ToList();
}
}
public Product Get(int id)
{
using (productContext = new ProductContext())
{
return productContext.Products.Find(id);
}
}
public void Buy(Product product)
{
using (productContext = new ProductContext())
{
productContext.Products.Add(product);
productContext.SaveChanges();
}
}
public void Update(Product product)
{
using (productContext = new ProductContext())
{
var item = productContext.Products.Find(product.Id);
if (item != null)
{
productContext.Entry(item).CurrentValues.SetValues(product);
productContext.SaveChanges();
}
}
}
public void Sell(int id)
{
using (productContext = new ProductContext())
{
var product = productContext.Products.Find(id);
if (product != null)
{
productContext.Products.Remove(product);
productContext.SaveChanges();
}
}
}
}
}

View File

@@ -1,11 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace LuminousSales.Business
{
public class RolesBusiness
{
private RoleContext roleContext;
}
}

View File

@@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace LuminousSales.Business
{
public class RolesToPermissionBusiness
{
private RolesToPermissionContext rolesToPermissionContext;
}
}

View File

@@ -1,11 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace LuminousSales.Business
{
public class StocksBusiness
{
private StockContext stockContext;
}
}

View File

@@ -1,11 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace LuminousSales.Business
{
public class UsersBusiness
{
private UserContext userContext;
}
}

View File

@@ -1,11 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace LuminousSales.Business
{
public class UsersToRolesBusiness
{
private UsersToRolesContext usersToRolesContext;
}
}

View File

@@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace LuminousSales.Data.Model
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int AmountInStock { get; set; }
}
}

View File

@@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Text;
using LuminousSales.Data.Model;
namespace LuminousSales.Data
{
public class ProductContext : DbContext
{
public ProductContext():base("name = ProductContext")
{
}
public DbSet<Product> Products { get; set; }
}
}

View File

@@ -1,12 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EntityFramework" Version="6.4.4" />
</ItemGroup>
</Project>

View File

@@ -1,15 +0,0 @@
using System;
namespace LuminousSales
{
public class Program
{
static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine());
Console.WriteLine(a);
}
}
}

View File

@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Moq" Version="4.16.1" />
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.16.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Business\Business.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,89 @@
using NUnit.Framework;
using Moq;
using Models.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Models;
using Business.Business.UserManagment;
using Business.Business.UserManagment.Controllers;
using System;
namespace LuminousUnitTests
{
public class Tests
{
private UserController userctrl;
private RoleController rolectrl;
private Mock<LuminousContext> testContext;
private Mock<DbSet<User>> UserMock;
private Mock<DbSet<Role>> RoleMock;
private IQueryable<User> testUsers;
private IQueryable<Role> testRoles;
[SetUp]
public void Setup()
{
UserMock = new Mock<DbSet<User>>();
RoleMock = new Mock<DbSet<Role>>();
testUsers = new List<User>
{
new User(){ Name = "Admin", Password = "adm123", RoleId = 1},
new User(){ Name = "Goso", Password = "goso123", RoleId = 2},
new User(){ Name = "Pesho", Password = "peso123", RoleId = 3},
}.AsQueryable();
testRoles = new List<Role>
{
new Role { Name = "Cashier"},
new Role { Name = "Manager"},
new Role { Name = "Admin" }
}.AsQueryable();
UserMock.As<IQueryable<User>>().Setup(m => m.Provider).Returns(testUsers.Provider);
UserMock.As<IQueryable<User>>().Setup(m => m.Expression).Returns(testUsers.Expression);
UserMock.As<IQueryable<User>>().Setup(m => m.ElementType).Returns(testUsers.ElementType);
UserMock.As<IQueryable<User>>().Setup(m => m.GetEnumerator()).Returns(testUsers.GetEnumerator());
RoleMock.As<IQueryable<Role>>().Setup(m => m.Provider).Returns(testRoles.Provider);
RoleMock.As<IQueryable<Role>>().Setup(m => m.Expression).Returns(testRoles.Expression);
RoleMock.As<IQueryable<Role>>().Setup(m => m.ElementType).Returns(testRoles.ElementType);
RoleMock.As<IQueryable<Role>>().Setup(m => m.GetEnumerator()).Returns(testRoles.GetEnumerator());
testContext = new Mock<LuminousContext>();
testContext.Setup(s => s.User).Returns(UserMock.Object);
testContext.Setup(s => s.Role).Returns(RoleMock.Object);
rolectrl = new RoleController(testContext.Object);
userctrl = new UserController(testUsers.ToList()[2], testContext.Object, rolectrl);
}
[Test]
public void UsersController_GetAll()
{
List<User> users = userctrl.GetAll().ToList();
List<User> testUsersList = testUsers.ToList();
Assert.AreEqual(users.Count, testUsers.Count());
for (int i = 0; i < users.Count; i++)
{
Assert.AreEqual(users[i].Name, testUsersList[i].Name);
Assert.AreEqual(users[i].Password, testUsersList[i].Password);
Assert.AreEqual(users[i].RoleId, testUsersList[i].RoleId);
}
}
[Test]
public void UserController_AddItem()
{
rolectrl.CreateInitialRoles();
RoleMock.Verify(m => m.AddRange(It.IsAny<Role[]>()));
testContext.Verify(m => m.SaveChanges());
userctrl.RegisterItem("Penka", "penka123", 3);
UserMock.Verify(m => m.Add(It.IsAny<User>()));
testContext.Verify(m => m.SaveChanges());
}
public void UserController_DeleteUser()
{
userctrl.Delete(1);
UserMock.Verify(m => m.Remove(It.IsAny<User>()));
}
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Data
{
public static class Configuration
{
public const string ConnectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=LuminousSales;Integrated Security=True;";
}
}

View File

@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Migrations\20210318105825_init.cs" />
<Compile Remove="Migrations\20210318105825_init.Designer.cs" />
<Compile Remove="Migrations\20210318192056_DateTimeUpdate.cs" />
<Compile Remove="Migrations\20210318192056_DateTimeUpdate.Designer.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.12">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="3.1.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.12" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.12">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
</Project>

View File

@@ -1,23 +1,45 @@
using Microsoft.EntityFrameworkCore; using Data;
using Microsoft.EntityFrameworkCore;
using Models.Models; using Models.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Models namespace Models
{ {
class LuminousContext : DbContext public class LuminousContext : DbContext
{ {
public LuminousContext(): base("name=LuminousContext") public LuminousContext()
{ {
} }
public DbSet<User> User { get; set; }
public DbSet<Role> Role { get; set; }
public DbSet<Permission> Permission { get; set; }
public DbSet<Product> Product { get; set; }
public DbSet<Deal> Deal{ get; set; }
public DbSet<Stock> Stock { get; set; }
public LuminousContext(DbContextOptions options) : base(options)
{
}
public virtual DbSet<User> User { get; set; }
public virtual DbSet<Role> Role { get; set; }
public virtual DbSet<Product> Product { get; set; }
public virtual DbSet<Deal> Deal { get; set; }
public virtual DbSet<Stock> Stock { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer(Configuration.ConnectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasIndex(user => new { user.Name, user.Password })
.IsUnique(true);
modelBuilder.Entity<Role>()
.HasIndex(role => new { role.Name })
.IsUnique(true);
modelBuilder.Entity<Product>()
.HasIndex(product => new { product.Name })
.IsUnique(true);
}
} }
} }

View File

@@ -0,0 +1,193 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Models;
namespace Data.Migrations
{
[DbContext(typeof(LuminousContext))]
[Migration("20210318193112_init")]
partial class init
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.12")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Models.Models.Deal", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<double>("Amount")
.HasColumnType("float");
b.Property<int>("ProductId")
.HasColumnType("int");
b.Property<DateTime>("Time")
.HasColumnType("datetime2");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ProductId");
b.HasIndex("UserId");
b.ToTable("Deal");
});
modelBuilder.Entity("Models.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<double>("AmountInStock")
.HasColumnType("float");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Product");
});
modelBuilder.Entity("Models.Models.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Role");
});
modelBuilder.Entity("Models.Models.Stock", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<double>("Amount")
.HasColumnType("float");
b.Property<int>("ProductId")
.HasColumnType("int");
b.Property<DateTime>("Time")
.HasColumnType("datetime2");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ProductId");
b.HasIndex("UserId");
b.ToTable("Stock");
});
modelBuilder.Entity("Models.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("RoleId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("Name", "Password")
.IsUnique();
b.ToTable("User");
});
modelBuilder.Entity("Models.Models.Deal", b =>
{
b.HasOne("Models.Models.Product", "Products")
.WithMany()
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Models.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Models.Models.Stock", b =>
{
b.HasOne("Models.Models.Product", "Products")
.WithMany()
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Models.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Models.Models.User", b =>
{
b.HasOne("Models.Models.Role", "Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,177 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Data.Migrations
{
public partial class init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Product",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false),
Price = table.Column<double>(nullable: false),
AmountInStock = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Product", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Role",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Role", x => x.Id);
});
migrationBuilder.CreateTable(
name: "User",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false),
Password = table.Column<string>(nullable: false),
RoleId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_User", x => x.Id);
table.ForeignKey(
name: "FK_User_Role_RoleId",
column: x => x.RoleId,
principalTable: "Role",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Deal",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<int>(nullable: false),
ProductId = table.Column<int>(nullable: false),
Amount = table.Column<double>(nullable: false),
Time = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Deal", x => x.Id);
table.ForeignKey(
name: "FK_Deal_Product_ProductId",
column: x => x.ProductId,
principalTable: "Product",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Deal_User_UserId",
column: x => x.UserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Stock",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<int>(nullable: false),
ProductId = table.Column<int>(nullable: false),
Amount = table.Column<double>(nullable: false),
Time = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Stock", x => x.Id);
table.ForeignKey(
name: "FK_Stock_Product_ProductId",
column: x => x.ProductId,
principalTable: "Product",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Stock_User_UserId",
column: x => x.UserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Deal_ProductId",
table: "Deal",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Deal_UserId",
table: "Deal",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Product_Name",
table: "Product",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Role_Name",
table: "Role",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Stock_ProductId",
table: "Stock",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Stock_UserId",
table: "Stock",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_User_RoleId",
table: "User",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_User_Name_Password",
table: "User",
columns: new[] { "Name", "Password" },
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Deal");
migrationBuilder.DropTable(
name: "Stock");
migrationBuilder.DropTable(
name: "Product");
migrationBuilder.DropTable(
name: "User");
migrationBuilder.DropTable(
name: "Role");
}
}
}

View File

@@ -0,0 +1,191 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Models;
namespace Data.Migrations
{
[DbContext(typeof(LuminousContext))]
partial class LuminousContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.12")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Models.Models.Deal", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<double>("Amount")
.HasColumnType("float");
b.Property<int>("ProductId")
.HasColumnType("int");
b.Property<DateTime>("Time")
.HasColumnType("datetime2");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ProductId");
b.HasIndex("UserId");
b.ToTable("Deal");
});
modelBuilder.Entity("Models.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<double>("AmountInStock")
.HasColumnType("float");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Product");
});
modelBuilder.Entity("Models.Models.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("Role");
});
modelBuilder.Entity("Models.Models.Stock", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<double>("Amount")
.HasColumnType("float");
b.Property<int>("ProductId")
.HasColumnType("int");
b.Property<DateTime>("Time")
.HasColumnType("datetime2");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ProductId");
b.HasIndex("UserId");
b.ToTable("Stock");
});
modelBuilder.Entity("Models.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("RoleId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("Name", "Password")
.IsUnique();
b.ToTable("User");
});
modelBuilder.Entity("Models.Models.Deal", b =>
{
b.HasOne("Models.Models.Product", "Products")
.WithMany()
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Models.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Models.Models.Stock", b =>
{
b.HasOne("Models.Models.Product", "Products")
.WithMany()
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Models.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Models.Models.User", b =>
{
b.HasOne("Models.Models.Role", "Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,41 @@
using Models.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Data.Base
{
public abstract class BaseSales
{
protected BaseSales()
{
}
protected BaseSales(int UserId, int ProductId, double Amount, DateTime Time)
{
this.UserId = UserId;
this.ProductId = ProductId;
this.Amount = Amount;
this.Time = Time;
}
[Key]
public int Id { get; set; }
[Required]
[ForeignKey("User")]
public int UserId { get; set; }
[Required]
public virtual User User { get; set; }
[Required]
[ForeignKey("Product")]
public int ProductId { get; set; }
[Required]
public virtual Product Products { get; set; }
[Required]
public double Amount { get; set; }
// [DataType(DataType.DateTime)]
[Required]
public DateTime Time { get; set; }
}
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Data.Base
{
public abstract class BaseUserManagmentEntity
{
public BaseUserManagmentEntity(){}
protected BaseUserManagmentEntity(string Name)
{
this.Name = Name;
}
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
}

View File

@@ -1,15 +1,12 @@
using Models.Models.Interfaces; using Data.Base;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Models.Models namespace Models.Models
{ {
public class Deal : IBaseSalesProperties public class Deal : BaseSales
{ {
public User User { get; set; } public Deal() : base(){}
public ICollection<Product> ProductsADeal { get; set; } public Deal(int UserId, int ProductId, double Amount, DateTime Time) : base(UserId, ProductId, Amount, Time) { }
public double Amount { get; set; }
[Timestamp]
public byte[] Time { get; set; }
} }
} }

View File

@@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Models.Models.Interfaces
{
public interface IBaseProperties
{
int Id { get; set; }
string Name { get; set; }
}
}

View File

@@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Models.Models.Interfaces
{
interface IBaseSalesProperties
{
User User { get; set; }
ICollection<Product> ProductsADeal { get; set;}
double Amount { get; set; }
public byte[] Time { get; set; }
}
}

View File

@@ -1,11 +0,0 @@
using Models.Models.Interfaces;
namespace Models.Models
{
public class Permission : IBaseProperties
{
public int Id { get; set; }
public string Name { get; set; }
}
}

View File

@@ -1,12 +1,30 @@
using Models.Models.Interfaces; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Models.Models namespace Models.Models
{ {
public class Product : IBaseProperties public class Product
{ {
public Product(){}
public Product(string Name, double Price)
{
this.Name = Name;
this.Price = Price;
this.AmountInStock = 0;
}
public Product(string Name, double Price, double AmountInStock)
{
this.Name = Name;
this.Price = Price;
this.AmountInStock = AmountInStock;
}
[Key]
public int Id { get; set; } public int Id { get; set; }
[Required]
public string Name { get; set; } public string Name { get; set; }
[Required]
public double Price { get; set; } public double Price { get; set; }
public double AvailableInStock { get; set; } [Required]
public double AmountInStock { get; set; }
} }
} }

View File

@@ -1,14 +1,13 @@
using Models.Models.Interfaces; using Data.Base;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Models.Models namespace Models.Models
{ {
public class Role : IBaseProperties public class Role : BaseUserManagmentEntity
{ {
public int Id { get; set; } public Role() : base(){}
public string Name { get; set; } public Role(string Name) : base(Name){}
public ICollection<User> UsersWithTheRole { get; set; }
public ICollection<Permission> RolesPermissions{ get; set; }
} }
} }

View File

@@ -1,17 +1,14 @@
using Models.Models.Interfaces; using Data.Base;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text; using System.Text;
namespace Models.Models namespace Models.Models
{ {
class Stock : IBaseSalesProperties public class Stock : BaseSales
{ {
public User User { get; set; } public Stock() : base(){}
public ICollection<Product> ProductsADeal { get; set; } public Stock(int UserId, int ProductId, double Amount, DateTime Time) : base(UserId, ProductId, Amount, Time){}
public double Amount { get; set; }
[Timestamp]
public byte[] Time { get; set; }
} }
} }

View File

@@ -1,17 +1,25 @@
using Models.Models.Interfaces; using Data.Base;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text; using System.Text;
namespace Models.Models namespace Models.Models
{ {
public class User : IBaseProperties public class User : BaseUserManagmentEntity
{ {
public int Id { get; set; } public User() : base() { }
public string Name { get; set; } public User(string Name, string Password, int RoleId) : base(Name)
public string Passcode { get; set; } {
public Role Role { get; set; } this.Password = Password;
public ICollection<Deal> ItemsSoldByUser{ get; set; } this.RoleId = RoleId;
public ICollection<Product> ItemsStockedByUser { get; set; } }
[Required]
public string Password { get; set; }
[Required]
[ForeignKey("Role")]
public int RoleId { get; set; }
public virtual Role Role { get; set; }
} }
} }