Authorization, Shipments - Batch/Print views.

This commit is contained in:
Stoyan Zlatev
2023-04-05 15:05:33 +02:00
parent fdfb42da9e
commit 220308088f
41 changed files with 909 additions and 86 deletions
@@ -36,6 +36,27 @@
}
}
public IEnumerable<T> AsEnumerable<T>(string query, Func<ISqlReader, T> reader)
{
using (var sqlConnection = new SqlConnection(this.connectionString))
{
sqlConnection.OpenWithErrorHandling();
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.CommandText = query;
using (var sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
yield return reader(new SqlReader(sqlDataReader));
}
}
}
}
}
public T FirstOrDefault<T>(string query, Action<IParameterCollection> parameters, Func<ISqlReader, T> reader)
{
var firstOrDefaultResult = default(T);
@@ -94,5 +115,34 @@
return scalarResult;
}
public bool Transaction(string query, Action<IParameterCollection> parameters)
{
var canCommitTransaction = true;
using (var sqlConnection = new SqlConnection(this.connectionString))
{
sqlConnection.OpenWithErrorHandling((sender, args) => canCommitTransaction = false);
using (var sqlTransaction = sqlConnection.BeginTransaction())
{
using (var sqlCommand = sqlConnection.CreateCommand())
{
sqlCommand.Transaction = sqlTransaction;
sqlCommand.CommandText = query;
parameters(new ParameterCollection(sqlCommand.Parameters));
sqlCommand.ExecuteNonQuery();
}
if (canCommitTransaction)
{
sqlTransaction.Commit();
}
}
}
return canCommitTransaction;
}
}
}
@@ -4,6 +4,7 @@
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
@@ -16,11 +17,16 @@
return services;
}
internal static void OpenWithErrorHandling(this SqlConnection sqlConnection)
internal static void OpenWithErrorHandling(this SqlConnection sqlConnection, SqlInfoMessageEventHandler messageHandler = null)
{
sqlConnection.FireInfoMessageEventOnUserErrors = true;
sqlConnection.InfoMessage += SqlConnectionInfoMessage;
if (messageHandler != null)
{
sqlConnection.InfoMessage += messageHandler;
}
sqlConnection.Open();
}
@@ -7,8 +7,12 @@
{
IEnumerable<T> AsEnumerable<T>(string query, Action<IParameterCollection> parameters, Func<ISqlReader, T> reader);
IEnumerable<T> AsEnumerable<T>(string query, Func<ISqlReader, T> reader);
T FirstOrDefault<T>(string query, Action<IParameterCollection> parameters, Func<ISqlReader, T> reader);
T ScalarTransaction<T>(string query, Action<IParameterCollection> parameters);
bool Transaction(string query, Action<IParameterCollection> parameters);
}
}
@@ -0,0 +1,190 @@
namespace LaaProductionWeb.Services
{
using LaaProductionWeb.Data.Interfaces;
using LaaProductionWeb.Services.Interfaces;
using LaaProductionWeb.Services.Models;
using System.Collections.Generic;
using System.Linq;
public class AccountService : IAccountService
{
private readonly IDbContext dbContext;
public AccountService(IDbContext dbContext)
=> this.dbContext = dbContext;
public WindowsUser GetOrCreateWindowsUser(string primarySID, string domainName, string userName)
{
var user = this.dbContext.FirstOrDefault($@"
DECLARE @userId INT;
SELECT @userId = [Account].[WindowsUsers].[UserId]
FROM [Account].[WindowsUsers]
WHERE [Account].[WindowsUsers].[PrimarySID] = @{nameof(primarySID)}
IF @userId IS NULL
INSERT INTO [Account].[WindowsUsers] (
[PrimarySID]
, [DomainName]
, [UserName])
OUTPUT [Inserted].[UserId]
VALUES (@{nameof(primarySID)}
, @{nameof(domainName)}
, @{nameof(userName)})
ELSE SELECT @userId",
parameters => parameters
.Add(nameof(primarySID), primarySID)
.Add(nameof(domainName), domainName)
.Add(nameof(userName), userName),
reader => new WindowsUser
{
UserId = reader.GetValue<int>(0)
})
?? new WindowsUser();
user.Roles = this
.GetUserRoles(user.UserId)
.Select(x => x.RoleName);
return user;
}
public PermissionsModel GetPermissionModelForUser(int userId, string role)
{
var roleModel = this.GetRoleForUser(role);
return new PermissionsModel
{
UserId = userId,
Role = roleModel
};
}
public UserRole GetRoleForUser(string role)
=> this.dbContext.FirstOrDefault($@"
SELECT [Account].[Roles].[RoleId]
, [Account].[Roles].[RoleName]
, [Account].[Roles].[DisplayName]
, [Account].[UsersRoles].[Approved]
FROM [Account].[Roles]
LEFT JOIN [Account].[UsersRoles]
ON [Account].[UsersRoles].[RoleId] = [Account].[Roles].[RoleId]
WHERE [Account].[Roles].[RoleName] = @{nameof(role)}",
parameters => parameters.Add(nameof(role), role),
reader => new UserRole
{
RoleId = reader.GetValue<int>(0),
RoleName = reader.GetString(1),
DisplayName = reader.GetString(2),
Pending = reader.GetValue<bool?>(3),
}) ?? new UserRole();
public IEnumerable<UserRole> GetUserRoles(int userId)
=> this.dbContext.AsEnumerable($@"
SELECT [Account].[Roles].[RoleId]
, [Account].[Roles].[RoleName]
, [Account].[Roles].[DisplayName]
FROM [Account].[Roles]
JOIN [Account].[UsersRoles]
ON [Account].[UsersRoles].[RoleId] = [Account].[Roles].[RoleId]
AND [Account].[UsersRoles].[UserId] = @{nameof(userId)}
AND [Account].[UsersRoles].[Approved] = 1",
parameters => parameters.Add(nameof(userId), userId),
reader => new UserRole
{
RoleId = reader.GetValue<int>(0),
RoleName = reader.GetString(1),
DisplayName = reader.GetString(2),
});
public List<UserPermissions> GetUsersWithPendingRoles()
=> this.dbContext.AsEnumerable($@"
SELECT [Account].[Users].[UserId]
, [Account].[Users].[FirstName] + ' ' + [Account].[Users].[LastName]
, [Account].[Roles].[RoleId]
, [Account].[Roles].[RoleName]
, [Account].[UsersRoles].[Approved]
FROM [Account].[UsersRoles]
JOIN [Account].[Roles] ON [Account].[Roles].[RoleId] = [Account].[UsersRoles].[RoleId]
JOIN [Account].[Users] ON [Account].[Users].[UserId] = [Account].[UsersRoles].[UserId]
WHERE [Account].[UsersRoles].[Approved] = 0",
reader => new
{
UserId = reader.GetValue<int>(0),
DisplayName = reader.GetString(1),
RoleId = reader.GetValue<int>(2),
RoleName = reader.GetString(3),
Approved = reader.GetValue<bool>(4)
})
.GroupBy(x => new UserPermissions
{
UserId = x.UserId,
DisplayName = x.DisplayName
}, UserPermissionsComparer.Current)
.Select(x => new UserPermissions
{
UserId = x.Key.UserId,
DisplayName = x.Key.DisplayName,
Roles = x
.AsEnumerable()
.Select(r => new RoleModel
{
RoleId = r.RoleId,
RoleName = r.RoleName,
Approved = r.Approved
})
.ToList()
})
.ToList();
public void RequestPermissions(PermissionsModel model)
{
this.dbContext.Transaction($@"
INSERT INTO [Auftrag].[Account].[Users] (
[UserId]
, [FirstName]
, [LastName])
VALUES (@{nameof(model.UserId)}
, @{nameof(model.FirstName)}
, @{nameof(model.LastName)})",
parameters => parameters
.Add(nameof(model.UserId), model.UserId)
.Add(nameof(model.FirstName), model.FirstName)
.Add(nameof(model.LastName), model.LastName));
model.Role.Pending = this.dbContext.Transaction($@"
INSERT INTO [Auftrag].[Account].[UsersRoles] (
[UserId]
, [RoleId])
VALUES (@{nameof(model.UserId)}
, @{nameof(model.Role.RoleId)})",
parameters => parameters
.Add(nameof(model.UserId), model.UserId)
.Add(nameof(model.Role.RoleId), model.Role.RoleId));
}
public void SaveUserPermissions(IEnumerable<UserPermissions> usersPermissions)
{
foreach (var user in usersPermissions)
{
foreach (var role in user.Roles)
{
this.dbContext.Transaction(
role.Deleted
? $@"DELETE FROM [Account].[UsersRoles]
WHERE [Account].[UsersRoles].[UserId] = @{nameof(user.UserId)}
AND [Account].[UsersRoles].[RoleId] = @{nameof(role.RoleId)}"
: $@"UPDATE [Account].[UsersRoles]
SET [Approved] = @{nameof(role.Approved)}
WHERE [Account].[UsersRoles].[UserId] = @{nameof(user.UserId)}
AND [Account].[UsersRoles].[RoleId] = @{nameof(role.RoleId)}",
parameters => parameters
.Add(nameof(user.UserId), user.UserId)
.Add(nameof(role.RoleId), role.RoleId)
.Add(nameof(role.Approved), role.Approved));
}
}
}
}
}
@@ -0,0 +1,23 @@
namespace LaaProductionWeb.Services.Interfaces
{
using LaaProductionWeb.Services.Models;
using System.Collections.Generic;
public interface IAccountService : ITransient
{
WindowsUser GetOrCreateWindowsUser(string primarySID, string domainName, string userName);
PermissionsModel GetPermissionModelForUser(int userId, string role);
IEnumerable<UserRole> GetUserRoles(int userId);
List<UserPermissions> GetUsersWithPendingRoles();
UserRole GetRoleForUser(string role);
void RequestPermissions(PermissionsModel model);
void SaveUserPermissions(IEnumerable<UserPermissions> usersPermissions);
}
}
@@ -7,6 +7,8 @@
public interface IProtocolService : ITransient
{
bool DeleteFile(int fileId);
string FileContent(int? fileId);
OrderClientModel FindOrder(int orderId);
@@ -57,10 +57,17 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AccountService.cs" />
<Compile Include="Interfaces\IAccountService.cs" />
<Compile Include="Interfaces\IOrdersService.cs" />
<Compile Include="Interfaces\IProtocolService.cs" />
<Compile Include="Interfaces\IShipmentsService.cs" />
<Compile Include="Interfaces\ITransient.cs" />
<Compile Include="Models\PalletPosition.cs" />
<Compile Include="Models\RoleModel.cs" />
<Compile Include="Models\UserRole.cs" />
<Compile Include="Models\UserPermissions.cs" />
<Compile Include="Models\WindowsUser.cs" />
<Compile Include="Models\BatchPrintModel.cs" />
<Compile Include="Models\OrderClientModel.cs" />
<Compile Include="Models\OrderInfoModel.cs" />
@@ -69,6 +76,7 @@
<Compile Include="Models\OrderScanModel.cs" />
<Compile Include="Models\OrdersFoundModel.cs" />
<Compile Include="Models\PalletsBatchModel.cs" />
<Compile Include="Models\PermissionsModel.cs" />
<Compile Include="Models\Result.cs" />
<Compile Include="Models\SerialNr.cs" />
<Compile Include="Models\ShipmentModel.cs" />
@@ -19,14 +19,14 @@
public int ProductionOrderNr
=> this.batchModel.ProductionOrderNr;
public int PositionNr
=> this.batchModel.PositionNr;
public IEnumerable<PalletPosition> Positions
=> this.batchModel.Positions;
public int TotlalItemsCount
=> this.batchModel.TotlalItemsCount;
public string ItemsType
=> this.batchModel.ItemsType;
public int ItemsCount
=> this.batchModel.ItemsCount;
public SerialNr[] Items
=> this.batchModel
@@ -0,0 +1,11 @@
namespace LaaProductionWeb.Services.Models
{
public class PalletPosition
{
public int PositionNr { get; set; }
public string Description { get; set; }
public int ItemsCount { get; set; }
}
}
@@ -2,6 +2,7 @@
{
using System;
using System.Collections.Generic;
using System.Linq;
public class PalletsBatchModel
{
@@ -11,15 +12,17 @@
public int ProductionOrderNr { get; set; }
public int PositionNr { get; set; }
public int TotlalItemsCount { get; set; }
public string ItemsType { get; set; }
public string AdditionalText { get; set; }
public int ItemsCount
=> this.Positions.Sum(x => x.ItemsCount);
public IEnumerable<SerialNr> Items { get; set; }
= Array.Empty<SerialNr>();
public IEnumerable<PalletPosition> Positions { get; set; }
= Array.Empty<PalletPosition>();
}
}
@@ -0,0 +1,19 @@
namespace LaaProductionWeb.Services.Models
{
using System.ComponentModel.DataAnnotations;
public class PermissionsModel
{
public int UserId { get; set; }
[Display(Name = "Vorname")]
[Required(ErrorMessage = "Die Vorname ist erforderlich.")]
public string FirstName { get; set; }
[Display(Name = "Name")]
[Required(ErrorMessage = "Die Name ist erforderlich.")]
public string LastName { get; set; }
public UserRole Role { get; set; }
}
}
@@ -0,0 +1,13 @@
namespace LaaProductionWeb.Services.Models
{
public class RoleModel
{
public int RoleId { get; set; }
public string RoleName { get; set; }
public bool Approved { get; set; }
public bool Deleted { get; set; }
}
}
@@ -16,6 +16,8 @@
public int Nr { get; set; }
public int PositionNr { get; set; }
public int? PalletNr { get; set; }
public string ClientNr { get; set; }
@@ -28,7 +28,7 @@
public int? PositionNr { get; set; }
public bool HasOrder
=> this.orderModel != null;
=> this.orderModel != null && this.orderModel.OrderNr > 0;
public OrderModel OrderModel
=> this.orderModel
@@ -0,0 +1,25 @@
namespace LaaProductionWeb.Services.Models
{
using System.Collections.Generic;
public class UserPermissions
{
public int UserId { get; set; }
public string DisplayName { get; set; }
public List<RoleModel> Roles { get; set; }
}
public class UserPermissionsComparer : IEqualityComparer<UserPermissions>
{
public bool Equals(UserPermissions x, UserPermissions y)
=> x?.UserId == y?.UserId;
public int GetHashCode(UserPermissions obj)
=> obj?.UserId ?? default(int);
public static UserPermissionsComparer Current
= new UserPermissionsComparer();
}
}
@@ -0,0 +1,13 @@
namespace LaaProductionWeb.Services.Models
{
public class UserRole
{
public int RoleId { get; set; }
public string RoleName { get; set; }
public string DisplayName { get; set; }
public bool? Pending { get; set; }
}
}
@@ -0,0 +1,12 @@
namespace LaaProductionWeb.Services.Models
{
using System;
using System.Collections.Generic;
public class WindowsUser
{
public int UserId { get; set; } = -1;
public IEnumerable<string> Roles { get; set; } = Array.Empty<string>();
}
}
@@ -15,6 +15,15 @@
public ProtocolService(IDbContext dbContext)
=> this.dbContext = dbContext;
public bool DeleteFile(int fileId)
=> this.dbContext.ScalarTransaction<int>($@"
DELETE FROM [File]
WHERE [FileId] = @{nameof(fileId)};
DELETE FROM [FilesOrders]
OUTPUT [Deleted].[FileId]
WHERE [FileId] = @{nameof(fileId)};",
parameters: parameters => parameters.Add(nameof(fileId), fileId)) > 0;
public string FileContent(int? fileId)
{
var fileContent = this.dbContext.FirstOrDefault(
@@ -23,13 +32,14 @@
FROM [dbo].[File]
WHERE [dbo].[File].[FileId] = @{nameof(fileId)}",
parameters: parameters => parameters.Add(nameof(fileId), fileId),
reader: reader => reader.GetBytes(0));
reader: reader => reader.GetBytes(0)) ?? Array.Empty<byte>();
return string.Format("data:application/pdf;base64,{0}", Convert.ToBase64String(fileContent));
}
public OrderClientModel FindOrder(int orderId)
=> this.dbContext.FirstOrDefault(
{
var orderClientModel = this.dbContext.FirstOrDefault(
query: $@"
SELECT DISTINCT
[APG].[AuftragNr]
@@ -57,7 +67,21 @@
ClientId = reader.GetValue<int>(1),
ClientName = reader.GetString(2),
Positions = reader.GetString(3).Trim().Trim(',')
}) ?? new OrderClientModel();
});
if (orderClientModel != null && orderId > 0)
{
orderClientModel.FileId = this.dbContext.FirstOrDefault($@"
SELECT [FileId]
FROM [FilesOrders]
WHERE [OrderId] = @{nameof(orderId)}
AND [Usage] = 'PROTOCOL'",
parameters: parameters => parameters.Add(nameof(orderId), orderId),
reader: reader => reader.GetValue<int>(0));
}
return orderClientModel ?? new OrderClientModel();
}
public IEnumerable<KeyValuePair<int, string>> FindOrdersById(int orderno)
=> this.dbContext.AsEnumerable($@"
@@ -83,18 +83,17 @@
, REPLACE(RTRIM(LTRIM([AuftragPositionSerienNr].[KundeneigeneSerienNr])), ' ', '') -- 2
, [PalettenScan].[PalettenNr] -- 3
, CAST(CASE WHEN [PalettenScan].[ID] IS NULL THEN 0 ELSE 1 END AS BIT) -- 4
, [PalettenScan].[PositionNr] -- 5
FROM [AuftragPositionSerienNr]
LEFT JOIN [PalettenScan]
ON [PalettenScan].[AuftragNr] = [AuftragPositionSerienNr].[AuftragNr]
AND [PalettenScan].[PositionNr] = [AuftragPositionSerienNr].[PositionNr]
AND [PalettenScan].[SerienNr] = REPLACE(RTRIM(LTRIM([AuftragPositionSerienNr].[KundeneigeneSerienNr])), ' ', '')
WHERE [AuftragPositionSerienNr].[AuftragNr] = @{nameof(model.OrderNr)}
AND [AuftragPositionSerienNr].[PositionNr] = @{nameof(model.PositionNr)}
AND ([PalettenScan].[PalettenNr] = @{nameof(model.PalletNr)}
OR [PalettenScan].[PalettenNr] IS NULL)",
parameters: parameters => parameters
.Add(nameof(model.OrderNr), model.OrderNr)
.Add(nameof(model.PositionNr), model.PositionNr)
.Add(nameof(model.PalletNr), model.PalletNr),
reader: reader => new SerialNr
{
@@ -102,30 +101,30 @@
Nr = reader.GetValue<int>(1),
ClientNr = reader.GetString(2),
PalletNr = reader.GetValue<short>(3),
IsScaned = reader.GetValue<bool>(4)
IsScaned = reader.GetValue<bool>(4),
PositionNr = reader.GetValue<int>(5),
})
.OrderByDescending(x => x.IsScaned)
.ThenBy(x => x.ClientNr);
public PalletsBatchModel LoadBatchModel(OrderScanModel model)
{
const string orderNr = nameof(model.OrderNr);
const string posNr = nameof(model.PositionNr);
const string palNr = nameof(model.PalletNr);
var batchModel = this.dbContext.FirstOrDefault(
query: $@"
SELECT TOP 1
[Auftrag].[AuftragNr] -- 0
, [Auftrag].[FertigungsauftragNr] -- 1
, [Auftrag].[PositionNr] -- 2
, [Auftrag].[Menge] -- 3
, [Kunde].[Name] -- 4
, [IdentNr].[Typ] -- 5
, [IdentNr].[Typzusatz] -- 6
, [IdentNr].[Nennweite] -- 7
, [Auftrag].[ZusatzText] -- 8
, [Auftrag].[Menge] -- 2
, [Kunde].[Name] -- 3
, [Auftrag].[ZusatzText] -- 4
FROM [AlleAuftragPositionen] AS [Auftrag]
JOIN [Kunde] ON [Kunde].[KundenNr] = [Auftrag].[KundenNr]
JOIN [IdentNr] ON [IdentNr].[IdentNr] = [Auftrag].[IdentNr]
WHERE [Auftrag].[AuftragNr] = @{nameof(model.OrderNr)}
AND [Auftrag].[PositionNr] = @{nameof(model.PositionNr)}
WHERE [Auftrag].[AuftragNr] = @{orderNr}
AND [Auftrag].[PositionNr] = @{posNr}
ORDER BY [Auftrag].[FertigungsauftragNr] DESC",
parameters: parameters => parameters
.Add(nameof(model.OrderNr), model.OrderNr)
@@ -134,26 +133,59 @@
{
OrderNr = reader.GetValue<int>(0),
ProductionOrderNr = reader.GetValue<int>(1),
PositionNr = reader.GetValue<short>(2),
TotlalItemsCount = reader.GetValue<int>(3),
ClientName = reader.GetValue<string>(4),
ItemsType = string.Join(" ", new[]
{
reader.GetString(5),
reader.GetString(6),
reader.GetString(7),
}.Where(x => !string.IsNullOrWhiteSpace(x))),
AdditionalText = reader.GetValue<string>(8),
}) ?? new PalletsBatchModel();
TotlalItemsCount = reader.GetValue<int>(2),
ClientName = reader.GetValue<string>(3),
AdditionalText = reader.GetValue<string>(4),
})
?? new PalletsBatchModel();
if (batchModel.OrderNr > 0)
{
batchModel.Items = this.LoadBatchItems(model);
batchModel.Positions = this.LoadBatchPositions(model, orderNr, palNr);
}
return batchModel;
}
private IEnumerable<PalletPosition> LoadBatchPositions(OrderScanModel model, string orderNr, string palNr)
=> this.dbContext.AsEnumerable($@"
SELECT DISTINCT
[Auftrag].[PositionNr]
, COUNT(1)
, [Identnr].[Typ]
, [Identnr].[Typzusatz]
, [Identnr].[Nennweite]
FROM [Identnr]
JOIN [AlleAuftragPositionen] AS [Auftrag]
ON [Auftrag].[IdentNr] = [Identnr].[IdentNr]
JOIN [PalettenScan]
ON [PalettenScan].[AuftragNr] = [Auftrag].[AuftragNr]
AND [PalettenScan].[PositionNr] = [Auftrag].[PositionNr]
AND [PalettenScan].[PalettenNr] = @{palNr}
WHERE [Auftrag].[AuftragNr] = @{orderNr}
GROUP BY [Auftrag].[PositionNr]
, [Identnr].[Typ]
, [Identnr].[Typzusatz]
, [Identnr].[Nennweite]
ORDER BY [Auftrag].[PositionNr] ",
parameters => parameters
.Add(orderNr, model.OrderNr)
.Add(palNr, model.PalletNr),
positionReader => new PalletPosition
{
PositionNr = positionReader.GetValue<short>(0),
ItemsCount = positionReader.GetValue<int>(1),
Description = string
.Join(" ", new[]
{
positionReader.GetString(2),
positionReader.GetString(3),
positionReader.GetString(4),
}
.Where(x => !string.IsNullOrWhiteSpace(x)))
});
public Result UpdateBatchModel(OrderScanModel model)
{
if (!string.IsNullOrWhiteSpace(model.SerialNr))
@@ -117,4 +117,12 @@ table.table table.table {
.text-teal {
color: var(--bs-teal);
}
.btn.btn-link:hover {
text-decoration: underline !important;
}
.bg-whitesmoke {
background-color: whitesmoke !important
}
@@ -0,0 +1,23 @@
namespace LaaProductionWeb.App_Infrastructure
{
using System.Security.Claims;
using System.Web.Mvc;
public class AllowedRolesAttribute : AuthorizeAttribute
{
public AllowedRolesAttribute(params string[] roles)
=> this.Roles = string.Join(",", roles);
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.User is ClaimsPrincipal claimsPrincipal)
{
filterContext.Result = new RedirectResult($"/Account/Authorize?role={this.Roles}");
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
}
@@ -0,0 +1,48 @@
namespace LaaProductionWeb.App_Infrastructure
{
using LaaProductionWeb.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web.Mvc;
public class AuthorizationFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.User is ClaimsPrincipal claimsPrincipal)
{
this.GetWindowsUser(claimsPrincipal, out string primarySID, out string domainName, out string userName);
var accountService = ServiceProvider.Current.GetService<IAccountService>();
var windowsUser = accountService.GetOrCreateWindowsUser(primarySID, domainName, userName);
var claims = new List<Claim> { new Claim(ClaimTypes.NameIdentifier, $"{windowsUser.UserId}") };
foreach (var role in windowsUser.Roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var claimsIdentity = new ClaimsIdentity(claims, nameof(ClaimsPrincipal), ClaimTypes.Name, ClaimTypes.Role);
claimsPrincipal.AddIdentity(claimsIdentity);
}
}
private void GetWindowsUser(ClaimsPrincipal claimsPrincipal, out string primarySID, out string domainName, out string userName)
{
var nameTokens = claimsPrincipal
.FindFirst(ClaimTypes.Name)
?.Value
?.ToLower()
?.Split(new[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries)
?? Array.Empty<string>();
primarySID = claimsPrincipal.FindFirst(ClaimTypes.PrimarySid)?.Value;
domainName = nameTokens.FirstOrDefault();
userName = nameTokens.LastOrDefault();
}
}
}
@@ -4,6 +4,8 @@
using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Web.Mvc;
public static class ControllersExtensions
@@ -32,5 +34,25 @@
return serviceProvider;
}
public static int NameIdentifier(this IPrincipal principal)
{
if (principal is ClaimsPrincipal claimsPrincipal)
{
var nameIdentifier = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (int.TryParse($"{nameIdentifier}", out int userId))
{
return userId;
}
}
return -1;
}
public static T NameIdentifier<T>(this ViewContext viewContext)
{
return default(T);
}
}
}
@@ -0,0 +1,12 @@
namespace LaaProductionWeb.App_Infrastructure
{
using System.Web.Mvc;
public class ExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.Result = new RedirectResult("/");
}
}
}
@@ -0,0 +1,39 @@
namespace LaaProductionWeb.App_Infrastructure
{
using Microsoft.Extensions.DependencyInjection;
using System;
public class ServiceProvider
{
private readonly IServiceProvider services;
private ServiceProvider(IServiceProvider services)
=> this.services = services;
public T GetService<T>() where T : class
{
if (this.services.GetService<T>() is T service)
{
return service;
}
return default(T);
}
public static ServiceProvider Current { get; private set; }
internal static void SetServiceProvider(IServiceProvider serviceProvider)
=> Current = new ServiceProvider(serviceProvider);
}
public static class ServiceProviderExtensions
{
public static IServiceProvider RegisterServiceProvider(this IServiceProvider serviceProvider)
{
ServiceProvider.SetServiceProvider(serviceProvider);
return serviceProvider;
}
}
}
@@ -1,12 +1,15 @@
namespace LaaProductionWeb
{
using LaaProductionWeb.App_Infrastructure;
using System.Web.Mvc;
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new ExceptionFilter());
filters.Add(new AuthorizationFilter());
}
}
}
@@ -12,7 +12,8 @@
=> new ServiceCollection()
.ConfigureServices()
.BuildServiceProvider()
.BuildControllerFactory();
.BuildControllerFactory()
.RegisterServiceProvider();
static IServiceCollection ConfigureServices(this IServiceCollection services)
{
@@ -0,0 +1,61 @@
namespace LaaProductionWeb.Controllers
{
using LaaProductionWeb.App_Infrastructure;
using LaaProductionWeb.Services.Interfaces;
using LaaProductionWeb.Services.Models;
using System.Collections.Generic;
using System.Web.Mvc;
[Authorize]
public class AccountController : Controller
{
private readonly IAccountService accountService;
public AccountController(IAccountService accountService)
=> this.accountService = accountService;
[HttpGet]
public ActionResult Authorize(string role)
{
var userId = this.User.NameIdentifier();
var permissionsModel = this.accountService
.GetPermissionModelForUser(userId, role);
return this.View(model: permissionsModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Authorize(PermissionsModel model)
{
if (this.ModelState.IsValid)
{
this.accountService.RequestPermissions(model);
}
return this.View(model);
}
[HttpGet]
[AllowedRoles("Admin")]
public ActionResult Permissions()
{
var model = this.accountService.GetUsersWithPendingRoles();
return this.View(model);
}
[HttpPost]
[AllowedRoles("Admin")]
[ValidateAntiForgeryToken]
public ActionResult Permissions(List<UserPermissions> model)
{
this.accountService.SaveUserPermissions(model);
model = this.accountService.GetUsersWithPendingRoles();
return this.View(model);
}
}
}
@@ -1,11 +1,12 @@
namespace LaaProductionWeb.Controllers
{
using LaaProductionWeb.App_Infrastructure;
using LaaProductionWeb.Services.Interfaces;
using LaaProductionWeb.Services.Models;
using System.Web.Mvc;
[Authorize]
[AllowedRoles("Protocol")]
public class ProtocolController : Controller
{
public const string FilePDF = nameof(FilePDF);
@@ -20,6 +21,11 @@
{
var orderClientModel = this.protocolService.FindOrder(orderId);
if (orderClientModel.FileId > 0)
{
return this.RedirectToAction(nameof(Document), orderClientModel);
}
return this.View(orderClientModel);
}
@@ -28,7 +34,11 @@
{
var files = this.Request.Files;
if (files.Count > 0)
if (model.OrderId is null || model.OrderId <= 0)
{
this.TempData[FilePDF] = $"Bitte Auftrag auswählen.";
}
else if (files.Count > 0)
{
var file = this.Request.Files.Get(0);
@@ -66,6 +76,15 @@
return this.View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteFile(int fileId, int orderId)
{
this.protocolService.DeleteFile(fileId);
return this.RedirectToAction(nameof(this.Index), new { orderId });
}
public ActionResult Clients(string search = null)
{
var clientsOrders = this.protocolService.FindOrdersByClient(search);
@@ -1,5 +1,6 @@
namespace LaaProductionWeb.Controllers
{
using LaaProductionWeb.App_Infrastructure;
using LaaProductionWeb.Services.Interfaces;
using LaaProductionWeb.Services.Models;
@@ -12,7 +13,7 @@
using SystemFile = System.IO.File;
[Authorize]
[AllowedRoles("Shipment")]
public class ShipmentsController : Controller
{
private readonly IShipmentsService shipmentsService;
@@ -131,13 +131,18 @@
</ItemGroup>
<ItemGroup>
<Compile Include="App_Infrastructure\ApplicationSettings.cs" />
<Compile Include="App_Infrastructure\AuthorizationFilter.cs" />
<Compile Include="App_Infrastructure\ControllerFactory.cs" />
<Compile Include="App_Infrastructure\ControllersExtensions.cs" />
<Compile Include="App_Infrastructure\ExceptionFilter.cs" />
<Compile Include="App_Infrastructure\AllowedRolesAttribute.cs" />
<Compile Include="App_Infrastructure\ServiceProvider.cs" />
<Compile Include="App_Start\BundleConfig.cs" />
<Compile Include="App_Start\FilterConfig.cs" />
<Compile Include="App_Start\RouteConfig.cs" />
<Compile Include="App_Start\ServicesConfig.cs" />
<Compile Include="App_Start\WebApiConfig.cs" />
<Compile Include="Controllers\AccountController.cs" />
<Compile Include="Controllers\HomeController.cs" />
<Compile Include="Controllers\ProtocolController.cs" />
<Compile Include="Controllers\SearchController.cs" />
@@ -168,6 +173,9 @@
<ItemGroup>
<None Include="packages.config" />
<Content Include="Views\Shared\_PrintLayout.cshtml" />
<Content Include="Views\Account\Authorize.cshtml" />
<Content Include="Views\Account\UserRole.cshtml" />
<Content Include="Views\Account\Permissions.cshtml" />
</ItemGroup>
<ItemGroup>
<Content Include="App_Content\font\fonts\bootstrap-icons.woff" />
@@ -198,6 +206,7 @@
<Name>LaaProductionWeb.Services</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup />
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
@@ -0,0 +1,35 @@
@model PermissionsModel
@using LaaProductionWeb.Services.Models
<div class="d-flex justify-content-center align-items-center h-100">
@if (this.Model.Role.Pending is null)
{
<div class="col-md-3 card p-5">
<form action="/Account/Authorize" method="post" autocomplete="off">
@this.Html.AntiForgeryToken()
@this.Html.HiddenFor(x => x.UserId)
@this.Html.Partial(nameof(UserRole), this.Model.Role, new ViewDataDictionary { { "namePattern", $"{nameof(this.Model.Role)}.{{0}}" } })
<h5 class="mb-3">Ihnen fehlt die Berechtigung – '@this.Model.Role.DisplayName'.</h5>
<div class="form-floating mb-3">
@this.Html.TextBoxFor(x => x.FirstName, new { @class = "form-control", placeholder = "Vorname" })
@this.Html.LabelFor(x => x.FirstName, new { @class = "text-secondary" })
@this.Html.ValidationMessageFor(x => x.FirstName, string.Empty, new { @class = "small text-danger" })
</div>
<div class="form-floating mb-3">
@this.Html.TextBoxFor(x => x.LastName, new { @class = "form-control", placeholder = "Vorname" })
@this.Html.LabelFor(x => x.LastName, new { @class = "text-secondary" })
@this.Html.ValidationMessageFor(x => x.LastName, string.Empty, new { @class = "small text-danger" })
</div>
<button type="submit" class="btn btn-primary py-3 w-100">Berechtigung anfordern</button>
</form>
</div>
}
else
{
<div class="col-md-3 card p-5 border-success">
<h1 class="text-center text-success"><i class="bi bi-shield-exclamation"></i></h1>
<h6 class="text-center text-success">Ihre anfrage für die berechtigung – '@this.Model.Role.DisplayName' ist in bearbeitung ...</h6>
</div>
}
</div>
@@ -0,0 +1,60 @@
@model List<LaaProductionWeb.Services.Models.UserPermissions>
@if (this.Model.Any())
{
<form action="/Account/Permissions" method="post" autocomplete="off">
@this.Html.AntiForgeryToken()
<ul class="list-group list-group-flush mb-3">
@{
var usersCount = this.Model.Count;
for (int userIndex = 0; userIndex < usersCount; userIndex++)
{
var user = this.Model[userIndex];
var hiddenUserId = $"[{userIndex}].{nameof(user.UserId)}";
var hiddenUserName = $"[{userIndex}].{nameof(user.DisplayName)}";
<li class="list-group-item">
<input type="hidden" name="@hiddenUserId" value="@user.UserId" />
<input type="hidden" name="@hiddenUserName" value="@user.DisplayName" />
<h5>@user.DisplayName</h5>
</li>
<li class="list-group-item">
<table>
<thead>
<tr>
<th class="text-secondary white-space-nowrap small px-3">Role Id</th>
<th class="text-secondary white-space-nowrap small px-3">Role Name</th>
<th class="text-secondary white-space-nowrap small px-3">Is Approved</th>
<th class="text-secondary white-space-nowrap small px-3">Is Deleted</th>
</tr>
</thead>
<tbody>
@{
var rolesCount = user.Roles.Count;
for (int roleIndex = 0; roleIndex < rolesCount; roleIndex++)
{
var role = user.Roles[roleIndex];
var hiddenRoleId = $"[{userIndex}].{nameof(user.Roles)}[{roleIndex}].{nameof(role.RoleId)}";
var hiddenRoleName = $"[{userIndex}].{nameof(user.Roles)}[{roleIndex}].{nameof(role.RoleName)}";
var roleApproved = $"[{userIndex}].{nameof(user.Roles)}[{roleIndex}].{nameof(role.Approved)}";
var roleDeleted = $"[{userIndex}].{nameof(user.Roles)}[{roleIndex}].{nameof(role.Deleted)}";
<tr>
<td class="px-3">@role.RoleId <input type="hidden" name="@hiddenRoleId" value="@role.RoleId" /></td>
<td class="px-3">@role.RoleName <input type="hidden" name="@hiddenRoleName" value="@role.RoleName" /></td>
<td class="px-3">@this.Html.CheckBox(roleApproved, role.Approved, new { @class = "form-check-input" })</td>
<td class="px-3">@this.Html.CheckBox(roleDeleted, role.Deleted, new { @class = "form-check-input" })</td>
</tr>
}
}
</tbody>
</table>
</li>
}
}
</ul>
<button type="submit" class="btn btn-primary py-2 px-5 ms-3">Änderungen speichern</button>
</form>
}
@@ -0,0 +1,14 @@
@model LaaProductionWeb.Services.Models.UserRole
@{
var namePattern = "{0}";
if (this.ViewData.TryGetValue(nameof(namePattern), out object value))
{
namePattern = $"{value}";
}
}
@this.Html.Hidden(string.Format(namePattern, nameof(this.Model.RoleId)), this.Model.RoleId)
@this.Html.Hidden(string.Format(namePattern, nameof(this.Model.RoleName)), this.Model.RoleName)
@this.Html.Hidden(string.Format(namePattern, nameof(this.Model.DisplayName)), this.Model.DisplayName)
@@ -53,7 +53,7 @@
{
<tr>
<td class="va-middle">@item.PosNr</td>
<td class="va-middle white-space-nowrap px-5">@item.SerialNr</td>
<td class="va-middle white-space-nowrap">@item.SerialNr</td>
<td class="text-center">
<bi class="@testPassed(item.HeliumTest)"></bi>
</td>
@@ -2,12 +2,13 @@
@using LaaProductionWeb.Services.Models
<form>
<form action="/Protocol/DeleteFile" method="post" class="nav justify-content-end bg-whitesmoke">
@this.Html.AntiForgeryToken()
@this.Html.HiddenFor(x => x.FileId)
@this.Html.HiddenFor(x => x.OrderId)
@this.Html.HiddenFor(x => x.ClientId)
@this.Html.HiddenFor(x => x.ClientName)
@this.Html.HiddenFor(x => x.Positions)
<button class="btn btn-link text-danger nav-link">
<i class="bi bi-trash"></i> Delete
</button>
</form>
<div class="container-fluid h-100 p-0">
@@ -13,7 +13,7 @@
</tr>
<tr>
<td class="py-1 white-space-nowrap va-middle"><label for="client_name">Client</label></td>
<td class="p-1 dropdown">
<td class="p-1 dropdown w-75">
<input id="client_name" class="form-control border-0 rounded-0" value="@this.Model.ClientName" />
<ul class="dropdown-menu mt-2 w-100" id="client_name_options">
<li class="text-secondary bg-light text-normal">Search by client name</li>
@@ -22,7 +22,7 @@
</tr>
<tr>
<td class="py-1 white-space-nowrap va-middle"><label for="order_no">Order No.</label></td>
<td class="p-1">
<td class="p-1 w-75">
<input id="order_no" class="form-control border-0 rounded-0" value="@this.Model.OrderId" />
<ul class="dropdown-menu mt-2 w-100" id="order_no_options">
<li class="text-secondary bg-light text-normal">Search by order no.</li>
@@ -31,7 +31,7 @@
</tr>
<tr class="border-bottom-0">
<td class="py-1 white-space-nowrap va-middle">Positions</td>
<td class="p-1">
<td class="p-1 w-75">
<div class="form-control border-0 rounded-0">
@if (string.IsNullOrWhiteSpace(this.Model.Positions))
{
@@ -61,7 +61,7 @@
</div>
@if (this.TempData.TryGetValue(ProtocolController.FilePDF, out object errorMessage))
{
<div class="text-danger small">
<div class="text-danger small fw-normal">
@($"{errorMessage}")
</div>
}
@@ -17,7 +17,7 @@
</tr>
<tr>
<td class="py-1 white-space-nowrap va-middle"><label for="client_name">Client</label></td>
<td class="p-1 dropdown">
<td class="p-1 w-75">
<div class="form-control border-0 rounded-0">
@if (string.IsNullOrWhiteSpace(this.Model.ClientName))
{
@@ -32,7 +32,7 @@
</tr>
<tr>
<td class="py-1 white-space-nowrap va-middle"><label for="order_no">Order No.</label></td>
<td class="p-1">
<td class="p-1 w-75">
<div class="form-control border-0 rounded-0">
@if (this.Model.OrderId is null)
{
@@ -47,7 +47,7 @@
</tr>
<tr class="border-bottom-0">
<td class="py-1 white-space-nowrap va-middle">Positions</td>
<td class="p-1">
<td class="p-1 w-75">
<div class="form-control border-0 rounded-0">
@if (string.IsNullOrWhiteSpace(this.Model.Positions))
{
@@ -63,7 +63,7 @@
</table>
</th>
<th class="text-center va-middle w-auto p-3">
<img src="~/App_Content/svg/sensus_xylem_logo.svg" width="210" class="mx-5" />
<img src="~/App_Content/svg/sensus_xylem_logo.svg" width="130" class="mx-5" />
</th>
</tr>
</thead>
@@ -6,22 +6,37 @@
<div class="d-flex justify-content-center">
<div id="batch" class="print-page border rounded shadow-sm mt-5 p-5">
<div class="table-responsive">
<table>
<table class="table table-borderless table-striped">
<tr>
<th colspan="2" class="fs-5">Paletten Begleitschein</th>
<th colspan="2" class="fs-5">@this.Model.ClientName</th>
</tr>
<tr>
<td class="py-0 pe-3 white-space-nowrap">Kunden-Auftrag/Pos.Nr.</td>
<td class="py-0 pe-3">@this.Model.OrderNr/@this.Model.PositionNr</td>
<td class="py-0 pe-3 white-space-nowrap">Fertigungsauftrags-Nr.</td>
<td class="py-0 pe-3">@this.Model.ProductionOrderNr</td>
<th class="py-0 white-space-nowrap">Kunden-Auftrag</th>
<td class="py-0">@this.Model.OrderNr</td>
<th class="py-0 white-space-nowrap">Fertigungsauftrags-Nr.</th>
<td class="py-0">@this.Model.ProductionOrderNr</td>
</tr>
@{
var isFirst = true;
foreach (var position in this.Model.Positions)
{
<tr>
<th class="py-0">@(isFirst ? "Position Nr" : string.Empty)</th>
<td class="py-0">@position.PositionNr</td>
<th class="py-0">@(isFirst ? "Bezeichnung" : string.Empty)</th>
<td class="py-0">@position.Description</td>
</tr>
isFirst = false;
}
}
<tr>
<td class="py-0 pe-3 white-space-nowrap">Auftragsmenge</td>
<td class="py-0 pe-3">@this.Model.TotlalItemsCount</td>
<td class="py-0 pe-3 white-space-nowrap">Typ</td>
<td class="py-0 pe-3">@this.Model.ItemsType</td>
<th class="py-0 white-space-nowrap">Palettemenge</th>
<td class="py-0">@this.Model.ItemsCount</td>
<th class="py-0 white-space-nowrap">Auftragsmenge</th>
<td class="py-0">@this.Model.TotlalItemsCount</td>
</tr>
</table>
<table class="table table-borderless table-striped">
@@ -42,7 +57,7 @@
{
<tr class="is_scaned_@(item.IsScaned ? 1 : 0)">
<td class="va-middle @(item.IsScaned ? null : "text-secondary")">@(count++).</td>
<td class="va-middle w-100 @(item.IsScaned ? null : "text-secondary")">@item.BarcodeNr</td>
<td class="va-middle w-100 @(item.IsScaned ? null : "text-secondary")">(@item.PositionNr) @item.BarcodeNr</td>
<td class="va-middle w-100 text-center">
<svg class="barcode"
jsbarcode-format="auto"
@@ -52,7 +67,7 @@
jsbarcode-lineColor="@(item.IsScaned ? "black" : "#ced4da")"
jsbarcode-height="50"
jsbarcode-margin="0"
jsbarcode-textmargin="0"
jsbarcode-textMargin="0"
jsbarcode-fontoptions="bold">
</svg>
</td>
@@ -31,14 +31,12 @@
</button>
</div>
</form>
@if (this.IsPost || this.Model.HasOrder)
{
@{
this.Html.RenderAction(nameof(ShipmentsController.Scan), this.Model.OrderScanModel);
}
</div>
<div class="col-md-9 h-100 scrollable-sm pb-5">
@if (this.IsPost || this.Model.HasOrder)
{
@{
this.Html.RenderAction(nameof(ShipmentsController.Batch), this.Model.OrderScanModel);
}
</div>
@@ -18,16 +18,31 @@
<th colspan="2" class="fs-4">@this.Model.ClientName</th>
</tr>
<tr>
<td class="py-0 white-space-nowrap">Kunden-Auftrag/Pos.Nr.</td>
<td class="py-0 fw-normal">@this.Model.OrderNr/@this.Model.PositionNr</td>
<td class="py-0 white-space-nowrap">Kunden-Auftrag</td>
<td class="py-0 fw-normal">@this.Model.OrderNr</td>
<td class="py-0 white-space-nowrap">Fertigungsauftrags-Nr.</td>
<td class="py-0 fw-normal">@this.Model.ProductionOrderNr</td>
</tr>
@{
var isFirst = true;
foreach (var position in this.Model.Positions)
{
<tr>
<td class="py-0">@(isFirst ? "Position Nr" : string.Empty)</td>
<td class="py-0 fw-normal">@position.PositionNr</td>
<td class="py-0">@(isFirst ? "Bezeichnung" : string.Empty)</td>
<td class="py-0 fw-normal">@position.Description</td>
</tr>
isFirst = false;
}
}
<tr>
<td class="py-0 white-space-nowrap">Palettenmenge</td>
<td class="py-0 fw-normal">@this.Model.ItemsCount</td>
<td class="py-0 white-space-nowrap">Auftragsmenge</td>
<td class="py-0 fw-normal">@this.Model.TotlalItemsCount</td>
<td class="py-0 white-space-nowrap">Typ</td>
<td class="py-0 fw-normal">@this.Model.ItemsType</td>
</tr>
</thead>
</table>
@@ -35,10 +50,10 @@
</tr>
<tr>
<th class="small">No.</th>
<th class="small">Serial No.</th>
<th class="small">Pos.</th>
<th class="small"></th>
<th class="small">No.</th>
<th class="small">Serial No.</th>
<th class="small">Pos.</th>
<th class="small"></th>
</tr>
</thead>
@@ -49,26 +64,28 @@
var item = items[i];
<tr>
<td class="va-middle">@(i + 1)</td>
<td class="va-middle">@item.BarcodeNr</td>
<td class="va-middle">
<td class="fs-5">@(i + 1).</td>
<td class="fs-5">@item.PositionNr</td>
<td class="py-0">
<svg class="barcode"
jsbarcode-height="50"
jsbarcode-height="70"
jsbarcode-format="auto"
jsbarcode-displayValue="false"
jsbarcode-displayValue="true"
jsbarcode-textMargin="0"
jsbarcode-background="transparent"
jsbarcode-value="@item.BarcodeNr" />
</td>
@if (ni < itemsLength)
{
var nitem = items[ni];
<td class="va-middle">@(ni + 1)</td>
<td class="va-middle">@nitem.BarcodeNr</td>
<td class="va-middle">
<td class="fs-5" >@(ni + 1).</td>
<td class="fs-5">@nitem.PositionNr</td>
<td class="py-0">
<svg class="barcode"
jsbarcode-height="50"
jsbarcode-height="70"
jsbarcode-format="auto"
jsbarcode-displayValue="false"
jsbarcode-displayValue="true"
jsbarcode-textMargin="0"
jsbarcode-background="transparent"
jsbarcode-value="@nitem.BarcodeNr" />
</td>