project structure and namespaces

This commit is contained in:
Stoyan Zlatev
2023-06-19 15:43:55 +02:00
parent 2624dd7c87
commit 5446342fbd
198 changed files with 310 additions and 528 deletions
@@ -0,0 +1,105 @@
namespace LaaProduction.Services
{
using LaaProductionSQL.Interfaces;
using LaaProduction.Services.Interfaces;
using LaaProduction.Services.Models;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
public class AccountService : IAccountService
{
private readonly ISQLConnection sqlConnection;
public AccountService(ISQLConnection sqlConnection)
=> this.sqlConnection = sqlConnection;
public Employee FindEmployee(short userId)
=> this.sqlConnection
.CreateCommand($@"
SELECT [Vorname] + ' ' + [Name]
FROM [Mitarbeiter]
WHERE [MitarbeiterNr] = @{nameof(userId)}")
.SetParameter(nameof(userId), userId)
.FirstOrDefault(x => new Employee
{
Name = x.GetString().Trim(),
Permissions = this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT [Recht]
FROM [MitarbeiterRechte]
WHERE [MitarbeiterNr] = @{nameof(userId)}")
.SetParameter(nameof(userId), userId)
.ExecuteReader(p => p.GetString())
});
public IEnumerable<string> FindUserFunctions(short appId, string username, string password)
=> this.sqlConnection
.CreateCommand($@"
SELECT [SF].[Function]
FROM [Mitarbeiter] AS [U]
JOIN [UsersFunctions] AS [UF]
ON [UF].[UserId] = [U].[MitarbeiterNr]
JOIN [SoftwareFunctions] AS [SF]
ON [SF].[Id] = [UF].[SoftwareFunctionId]
WHERE [U].[Benutzername] = @{nameof(username)}
AND [U].[PasswordHash] = @{nameof(password)}
AND [SF].[AppId] = @{nameof(appId)}")
.SetParameter(nameof(username), username)
.SetParameter(nameof(password), password)
.SetParameter(nameof(appId), appId)
.ExecuteReader(x => x.GetString());
public short Login(string username, string password)
=> this.sqlConnection
.CreateCommand($@"
SELECT TOP 1 [MitarbeiterNr]
FROM [Mitarbeiter]
WHERE [Benutzername] LIKE @{nameof(username)}
AND [PasswordHash] LIKE @{nameof(password)}")
.SetParameter(nameof(username), username)
.SetParameter(nameof(password), password)
.FirstOrDefault(reader => reader.GetSmallint());
public int ResetPassword(string username)
=> this.sqlConnection
.CreateCommand($@"
UPDATE [Mitarbeiter]
SET [PasswordHash] = NULL
WHERE [Benutzername] = @{nameof(username)}")
.SetParameter(nameof(username), username)
.ExecuteNonQuery();
public int ResetPassword(string username, string password)
=> this.sqlConnection
.CreateCommand($@"
UPDATE [Mitarbeiter]
SET [PasswordHash] = @{nameof(password)}
WHERE [Benutzername] = @{nameof(username)}")
.SetParameter(nameof(username), username)
.SetParameter(nameof(password), password)
.ExecuteNonQuery();
}
public static class AccountExtensions
{
public static string ComputeHash(this HashAlgorithm hashAlgorithm, string value)
{
if (!string.IsNullOrWhiteSpace(value))
{
var bytes = Encoding.UTF8.GetBytes(value);
var hash = hashAlgorithm.ComputeHash(bytes);
var base64 = Convert.ToBase64String(hash);
return base64;
}
return value;
}
public static string ComputeHash(this string value)
=> SHA256.Create().ComputeHash(value);
}
}
@@ -0,0 +1,79 @@
namespace LaaProduction.Services
{
using LaaProductionSQL.Interfaces;
using LaaProduction.Services.Interfaces;
using LaaProduction.Services.Models;
public class ApprovalsService : IApprovalsService
{
private readonly ISQLConnection sqlConnection;
public ApprovalsService(ISQLConnection sqlConnection)
=> this.sqlConnection = sqlConnection;
public Result Add(ProductionApproval approval)
{
var message = string.Empty;
var rowsAffected = this.sqlConnection
.CreateCommand($@"
INSERT INTO [ProductionSkipAndLifeTimeInfo] (
[OrderNumber]
, [PcbId]
, [SkipRadioParametersCheck]
, [OverrideFwCheck]
, [OverrideLutCheck]
, [RequiredLifeTimeYearsAssembly]
, [RequiredLifeTimeYearsShipping]
, [KitronProductionDate]
, [MaxDrainedBatteryLoadPercent]
, [MaxStorageMonths]
, [ApprovalDate]
, [ApproverName]
, [ApprovalComment])
VALUES (@{nameof(approval.OrderNr)}
, @{nameof(approval.PcbId)}
, @{nameof(approval.SkipRadioCheck)}
, @{nameof(approval.OverrideFwCheck)}
, @{nameof(approval.OverrideLutCheck)}
, @{nameof(approval.RequiredLifeTimeYearsAssembly)}
, @{nameof(approval.RequiredLifeTimeYearsShipping)}
, @{nameof(approval.KitronProductionDate)}
, @{nameof(approval.MaxDrainedBatteryLoadPercent)}
, @{nameof(approval.MaxStorageMonths)}
, @{nameof(approval.ApprovalDate)}
, @{nameof(approval.ApproverName)}
, @{nameof(approval.ApprovalComment)})")
.SetParameter(nameof(approval.OrderNr), approval.OrderNr)
.SetParameter(nameof(approval.PcbId), approval.PcbId)
.SetParameter(nameof(approval.SkipRadioCheck), approval.SkipRadioCheck)
.SetParameter(nameof(approval.OverrideFwCheck), approval.OverrideFwCheck)
.SetParameter(nameof(approval.OverrideLutCheck), approval.OverrideLutCheck)
.SetParameter(nameof(approval.RequiredLifeTimeYearsAssembly), approval.RequiredLifeTimeYearsAssembly)
.SetParameter(nameof(approval.RequiredLifeTimeYearsShipping), approval.RequiredLifeTimeYearsShipping)
.SetParameter(nameof(approval.KitronProductionDate), approval.KitronProductionDate)
.SetParameter(nameof(approval.MaxDrainedBatteryLoadPercent), approval.MaxDrainedBatteryLoadPercent)
.SetParameter(nameof(approval.MaxStorageMonths), approval.MaxStorageMonths)
.SetParameter(nameof(approval.ApprovalDate), approval.ApprovalDate)
.SetParameter(nameof(approval.ApproverName), approval.ApproverName)
.SetParameter(nameof(approval.ApprovalComment), approval.ApprovalComment)
.ExecuteNonQuery();
Result result = rowsAffected == 1;
if (result)
{
result.WithMessage("Die Genehmigung wurde erfolgreich hinzugefügt.");
}
else if (string.IsNullOrWhiteSpace(message))
{
result.WithMessage("Die Genehmigung wurde nicht hinzugefügt.");
}
else
{
result.WithMessage(message);
}
return result;
}
}
}
@@ -0,0 +1,19 @@
namespace LaaProduction.Services.Interfaces
{
using LaaProduction.Services.Models;
using System.Collections.Generic;
public interface IAccountService
{
Employee FindEmployee(short userId);
IEnumerable<string> FindUserFunctions(short appId, string username, string password);
short Login(string username, string password);
int ResetPassword(string username, string password);
int ResetPassword(string username);
}
}
@@ -0,0 +1,9 @@
namespace LaaProduction.Services.Interfaces
{
using LaaProduction.Services.Models;
public interface IApprovalsService
{
Result Add(ProductionApproval approval);
}
}
@@ -0,0 +1,13 @@
namespace LaaProduction.Services.Interfaces
{
using LaaProduction.Services.Models;
using System.Threading.Tasks;
public interface IHttpService
{
Task<HttpResponseModel> GetAsync(string path);
Task<HttpResponseModel> OptionsAsync(string path);
}
}
@@ -0,0 +1,9 @@
namespace LaaProduction.Services.Interfaces
{
using System;
public interface ILoggerService
{
void Log(Action<LoggerService.LogModel> logModel);
}
}
@@ -0,0 +1,13 @@
namespace LaaProduction.Services.Interfaces
{
using LaaProduction.Services.Models;
public interface IOrdersService
{
OrdersFoundModel FindOrders(string search);
OrderPositions FindPositions(string id);
ProductionOrders FindProductionOrders(string productionNr);
}
}
@@ -0,0 +1,27 @@
namespace LaaProduction.Services.Interfaces
{
using LaaProduction.Services.Models;
using LaaProduction.Services.Models.Reports;
using System.Collections.Generic;
using System.IO;
public interface IProtocolService
{
bool DeleteFile(int fileId);
string FileContent(int? fileId);
OrderClientModel FindOrder(int orderId);
IEnumerable<KeyValuePair<int, string>> FindOrdersById(int orderno);
IEnumerable<KeyValuePair<int, string>> FindOrdersByClient(string clientName);
IEnumerable<TestStatus> LoadTestStatus(int orderId);
bool OrderCompleted(int orderNr);
int SaveFile(Stream fileStream, int clientId, int orderId);
}
}
@@ -0,0 +1,21 @@
namespace LaaProduction.Services.Interfaces
{
using LaaProduction.Services.Models.Reports;
using System.Collections.Generic;
public interface IReportService
{
CordonelPressureSensorModel LoadCordonelPressureSensorReport(CordonelPressureSensorModel model = null);
HeliumReportModel LoadHeliumPressureReport(HeliumReportModel model = null);
IEnumerable<HeliumPressurePoint> LoadHeliumPressureResults(int testId);
byte[] LoadHeliumPressureReportAsCSV(HeliumReportModel model);
KottmannReportModel LoadKottmannPressureReport(KottmannReportModel model = null);
byte[] LoadKottmannPressureReportAsCSV(KottmannReportModel model);
}
}
@@ -0,0 +1,13 @@
namespace LaaProduction.Services.Interfaces
{
using LaaProduction.Services.Models;
using System.Collections.Generic;
public interface ISearchService
{
IEnumerable<WildcardResult> Find(WildcardInputModel model);
IEnumerable<string> Options();
}
}
@@ -0,0 +1,20 @@
namespace LaaProduction.Services.Interfaces
{
using LaaProduction.Services.Models;
using System.Collections.Generic;
public interface IShipmentsService
{
OrderScanModel DeletePalletEntry(int id);
byte[] LoadBatchBuffer(OrderScanModel model);
PalletsBatchModel LoadBatchModel(OrderScanModel model);
OrderScanModel LoadPallets(OrderScanModel model);
IEnumerable<MissingItem> MissingItems();
Result UpdateBatchModel(OrderScanModel model);
}
}
@@ -0,0 +1,42 @@
namespace LaaProduction.Services.Interfaces
{
using LaaProduction.Services.Models.Software;
using System;
using System.Collections.Generic;
public interface ISoftwareService
{
void AddFunction(short appId, string name);
void DeleteFunction(int funcId);
short FindAndUpdateSoftware(string windowsUser, string software, IEnumerable<string> functions);
IEnumerable<SoftwareFunction> GetAllSoftwareFunctions();
IEnumerable<SoftwareFunction> GetSoftwareFunctions(short appId);
IEnumerable<string> GetSoftwareFunctions(short appId, short userId);
SoftwareOverview GetSoftwareOverview(short appId);
IEnumerable<Software> GetSoftwareVersions(short appId);
IEnumerable<SoftwareOverview> GetSoftwares();
IEnumerable<SoftwareUser> GetUsers(string username = null);
IEnumerable<SoftwareUser> GetUsersWithFunctions(int id = -1, string username = null);
int ResetPassword(short userId);
int ResetPassword(short userId, string password);
void UpdateFunction(int funcId, string name);
void UpdateUsersFunctions(Action<UserFunctions> mapper);
void UpdateUsersFunctions(Action<FunctionUsers> mapper);
void UpdatePasswordHashes();
}
}
@@ -0,0 +1,122 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{FF167011-431A-41A7-A7DB-560E08860388}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>LaaProduction.Services</RootNamespace>
<AssemblyName>LaaProduction.Services</AssemblyName>
<TargetFrameworkVersion>v4.8.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="LaaProductionSQL, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\LaaProductionSQL.1.0.0\lib\netstandard2.0\LaaProductionSQL.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\Program Files\dotnet\sdk\NuGetFallbackFolder\newtonsoft.json\11.0.2\lib\netstandard2.0\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AccountService.cs" />
<Compile Include="ApprovalsService.cs" />
<Compile Include="Interfaces\IAccountService.cs" />
<Compile Include="Interfaces\IApprovalsService.cs" />
<Compile Include="Interfaces\IHttpService.cs" />
<Compile Include="Interfaces\ILoggerService.cs" />
<Compile Include="Interfaces\IOrdersService.cs" />
<Compile Include="Interfaces\IProtocolService.cs" />
<Compile Include="Interfaces\IReportService.cs" />
<Compile Include="Interfaces\ISearchService.cs" />
<Compile Include="Interfaces\IShipmentsService.cs" />
<Compile Include="Interfaces\ISoftwareService.cs" />
<Compile Include="LoggerService.cs" />
<Compile Include="Models\Employee.cs" />
<Compile Include="Models\HttpResponseModel.cs" />
<Compile Include="Models\MissingItem.cs" />
<Compile Include="Models\Reports\CordonelPressureSensorFilter.cs" />
<Compile Include="Models\Reports\CordonelPressureSensorItem.cs" />
<Compile Include="Models\Reports\CordonelPressureSensorModel.cs" />
<Compile Include="Models\Reports\HeliumPressurePoint.cs" />
<Compile Include="Models\Reports\HeliumReportFilter.cs" />
<Compile Include="Models\Reports\KottmannReportFilter.cs" />
<Compile Include="Models\Reports\KottmannReportItem.cs" />
<Compile Include="Models\Reports\PropertyType.cs" />
<Compile Include="Models\Reports\ReportFilterProperty.cs" />
<Compile Include="Models\Reports\HeliumReportItem.cs" />
<Compile Include="Models\Reports\HeliumReportModel.cs" />
<Compile Include="Models\Reports\ReportModelExtensions.cs" />
<Compile Include="Models\Reports\KottmannReportModel.cs" />
<Compile Include="Models\OrderIdentity.cs" />
<Compile Include="Models\PalletPosition.cs" />
<Compile Include="Models\ProductionApproval.cs" />
<Compile Include="Models\ProductionOrders.cs" />
<Compile Include="Models\BatchPrintModel.cs" />
<Compile Include="Models\OrderClientModel.cs" />
<Compile Include="Models\OrderInfoModel.cs" />
<Compile Include="Models\OrderModel.cs" />
<Compile Include="Models\OrderPositions.cs" />
<Compile Include="Models\OrderScanModel.cs" />
<Compile Include="Models\OrdersFoundModel.cs" />
<Compile Include="Models\PalletsBatchModel.cs" />
<Compile Include="Models\Reports\ReportFilter.cs" />
<Compile Include="Models\Result.cs" />
<Compile Include="Models\Search\SearchWildcardModel.cs" />
<Compile Include="Models\Search\WildcardInputModel.cs" />
<Compile Include="Models\Search\WildcardResult.cs" />
<Compile Include="Models\SerialNr.cs" />
<Compile Include="Models\ShipmentModel.cs" />
<Compile Include="Models\Reports\SqlExpression.cs" />
<Compile Include="Models\Reports\TestStatus.cs" />
<Compile Include="Models\Software\FunctionUsers.cs" />
<Compile Include="Models\Software\Software.cs" />
<Compile Include="Models\Software\SoftwareFunction.cs" />
<Compile Include="Models\Software\SoftwareOverview.cs" />
<Compile Include="Models\Software\SoftwareUser.cs" />
<Compile Include="Models\Software\UserFunctions.cs" />
<Compile Include="OrdersService.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ProtocolService.cs" />
<Compile Include="ReportService.cs" />
<Compile Include="SearchService.cs" />
<Compile Include="ShipmentsService.cs" />
<Compile Include="SoftwareService.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,54 @@
namespace LaaProduction.Services
{
using LaaProductionSQL.Interfaces;
using LaaProduction.Services.Interfaces;
using System;
public class LoggerService : ILoggerService
{
private readonly ISQLConnection sqlConnection;
public LoggerService(ISQLConnection sqlConnection)
=> this.sqlConnection = sqlConnection;
public class Actions
{
public const string RUN = nameof(RUN);
}
public class LogModel
{
public long Id { get; internal set; }
public DateTime Date { get; internal set; }
= DateTime.Now;
public string User { get; set; }
public string Action { get; set; }
public string Data { get; set; }
}
public void Log(Action<LogModel> logModel)
{
var model = new LogModel();
logModel?.Invoke(model);
this.sqlConnection
.CreateCommand($@"
INSERT INTO [SoftwareFunctionsLog] (
[User]
, [Action]
, [Data])
VALUES (@{nameof(model.User)}
, @{nameof(model.Action)}
, @{nameof(model.Data)})")
.SetParameter(nameof(model.User), model.User)
.SetParameter(nameof(model.Action), model.Action)
.SetParameter(nameof(model.Data), model.Data)
.ExecuteNonQuery();
}
}
}
@@ -0,0 +1,33 @@
namespace LaaProduction.Services.Models
{
using System.Collections.Generic;
using System.Linq;
public class BatchPrintModel
{
private readonly PalletsBatchModel batchModel;
public BatchPrintModel(PalletsBatchModel batchModel)
=> this.batchModel = batchModel;
public string ClientName
=> this.batchModel.Customer;
public int OrderNr
=> this.batchModel.OrderNr;
public int PalletNr
=> this.batchModel
.Positions
?.FirstOrDefault()
?.Items
?.FirstOrDefault()
?.PalletNr ?? 0;
public int ProductionOrderNr
=> this.batchModel.ProductionOrderNr;
public IEnumerable<PalletPosition> Positions
=> this.batchModel.Positions;
}
}
@@ -0,0 +1,16 @@
namespace LaaProduction.Services.Models
{
using System;
using System.Collections.Generic;
public class Employee
{
public string Name { get; set; }
public bool IsValid
=> !string.IsNullOrWhiteSpace(this.Name);
public IEnumerable<string> Permissions { get; set; }
= Array.Empty<string>();
}
}
@@ -0,0 +1,23 @@
namespace LaaProduction.Services.Models
{
using Newtonsoft.Json;
public class HttpResponseModel
{
public bool Succeeded { get; internal set; }
public string Content { get; internal set; }
public string Error { get; internal set; }
public T Deserialize<T>() where T : new ()
{
if (!string.IsNullOrWhiteSpace(this.Content))
{
return JsonConvert.DeserializeObject<T>(this.Content);
}
return new T();
}
}
}
@@ -0,0 +1,21 @@
namespace LaaProduction.Services.Models
{
using System;
public class MissingItem
{
public DateTime EntryDate { get; set; }
public int OrderNr { get; set; }
public int PosNr { get; set; }
public int SerialNr { get; set; }
public string CustomSerial { get; set; }
public string Term { get; set; }
public string Type { get; set; }
}
}
@@ -0,0 +1,19 @@
namespace LaaProduction.Services.Models
{
public class OrderClientModel
{
public int? OrderId { get; set; }
public int? ClientId { get; set; }
public string ClientName { get; set; }
public string Positions { get; set; }
public int? FileId { get; set; }
public string FileContent { get; set; }
public string Responsible { get; set; }
}
}
@@ -0,0 +1,13 @@
namespace LaaProduction.Services.Models
{
public class OrderIdentity
{
public int OrderNr { get; set; }
public int PositionNr { get; set; }
public int SerialNr { get; set; }
public string CustomerSerialNr { get; set; }
}
}
@@ -0,0 +1,32 @@
namespace LaaProduction.Services.Models
{
using System.Collections.Generic;
public class OrderInfoModel
{
public int OrderNr { get; set; }
public int ProductionOrderNr { get; set; }
public string Customer { get; set; }
public string Nr
=> this.OrderNr > 0
? $"{this.OrderNr}"
: this.ProductionOrderNr > 0
? $"{this.ProductionOrderNr}"
: default(string);
public static readonly OrderInfoComparer Comparer
= new OrderInfoComparer();
public class OrderInfoComparer : IEqualityComparer<OrderInfoModel>
{
public bool Equals(OrderInfoModel x, OrderInfoModel y)
=> x?.OrderNr == y?.OrderNr;
public int GetHashCode(OrderInfoModel obj)
=> obj?.OrderNr ?? default(int);
}
}
}
@@ -0,0 +1,21 @@
namespace LaaProduction.Services.Models
{
using System.ComponentModel.DataAnnotations;
public class OrderModel
{
public readonly string ScanTitle = "Scanvorgang";
public readonly string BtnSerialNr = "Serien-Nr. hinzufügen";
[Required]
public int? OrderNr { get; set; }
[Display(Name = "Positions-Nr. auswählen")]
public int? PositionNr { get; set; }
[Required]
[Display(Name = "Serien-Nr. scanen oder eingeben")]
public string SerialNr { get; set; }
}
}
@@ -0,0 +1,19 @@
namespace LaaProduction.Services.Models
{
using System.Collections;
using System.Collections.Generic;
public class OrderPositions : IEnumerable<int>
{
private readonly IEnumerable<int> positions;
public OrderPositions(IEnumerable<int> positions)
=> this.positions = positions;
public IEnumerator<int> GetEnumerator()
=> this.positions.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
=> this.GetEnumerator();
}
}
@@ -0,0 +1,53 @@
namespace LaaProduction.Services.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
public class OrderScanModel : OrderModel
{
public string Host { get; set; }
public string Place { get; set; }
public int PalletsCount { get; set; }
[Display(Name = "Paletten-Nr.")]
public int? PalletNr { get; set; }
public IEnumerable<int> Positions { get; set; }
= Array.Empty<int>();
public IDictionary<int, bool> Pallets { get; set; }
= new Dictionary<int, bool> { { 1, false } };
public string PrintUrl
=> $"~/Shipments/Print?ordernr={this.OrderNr}&positionnr={this.PositionNr}&palletnr={this.PalletNr}";
public string PalletUrl(int? palletNr)
=> $"~/Shipments/Pallet?ordernr={this.OrderNr}&positionnr={this.PositionNr}&palletnr={palletNr}";
internal void UpdatePallets(IEnumerable<KeyValuePair<int, bool>> pallets)
{
this.Pallets = pallets.ToDictionary(x => x.Key, x => x.Value);
if (this.PalletNr is null || this.PalletNr == 0)
{
if (pallets.Any(x => x.Value))
{
this.PalletNr = Math.Max(pallets
.Where(x => x.Value)
.OrderByDescending(x => x.Key)
.FirstOrDefault().Key, 1);
}
else
{
this.PalletNr = Math.Max(pallets
.OrderByDescending(x => x.Key)
.FirstOrDefault().Key, 1);
}
}
}
}
}
@@ -0,0 +1,22 @@
namespace LaaProduction.Services.Models
{
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class OrdersFoundModel : IEnumerable<OrderInfoModel>
{
private readonly IEnumerable<OrderInfoModel> orders;
public OrdersFoundModel(IEnumerable<OrderInfoModel> orders)
=> this.orders = orders;
public IEnumerator<OrderInfoModel> GetEnumerator()
=> this.orders
.Distinct(OrderInfoModel.Comparer)
.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
=> this.GetEnumerator();
}
}
@@ -0,0 +1,19 @@
namespace LaaProduction.Services.Models
{
using System;
using System.Collections.Generic;
public class PalletPosition
{
public int PositionNr { get; set; }
public string Description { get; set; }
public int ItemsCount { get; set; }
public int TotalItemsCount { get; set; }
public IEnumerable<SerialNr> Items { get; set; }
= Array.Empty<SerialNr>();
}
}
@@ -0,0 +1,19 @@
namespace LaaProduction.Services.Models
{
using System;
using System.Collections.Generic;
public class PalletsBatchModel
{
public string Customer { get; set; }
public int OrderNr { get; set; }
public int ProductionOrderNr { get; set; }
public string AdditionalText { get; set; }
public IEnumerable<PalletPosition> Positions { get; set; }
= Array.Empty<PalletPosition>();
}
}
@@ -0,0 +1,38 @@
namespace LaaProduction.Services.Models
{
using System;
using System.ComponentModel.DataAnnotations;
public class ProductionApproval
{
public int Id { get; set; }
public int? OrderNr { get; set; }
public int? PcbId { get; set; }
public bool SkipRadioCheck { get; set; }
public int? OverrideFwCheck { get; set; }
public int? OverrideLutCheck { get; set; }
public int? RequiredLifeTimeYearsAssembly { get; set; }
public int? RequiredLifeTimeYearsShipping { get; set; }
public DateTime? KitronProductionDate { get; set; }
public double? MaxDrainedBatteryLoadPercent { get; set; }
public int? MaxStorageMonths { get; set; }
public DateTime ApprovalDate { get; set; }
public string ApproverName { get; set; }
[Required]
[MinLength(10)]
public string ApprovalComment { get; set; }
}
}
@@ -0,0 +1,19 @@
namespace LaaProduction.Services.Models
{
using System.Collections;
using System.Collections.Generic;
public class ProductionOrders : IEnumerable<int>
{
private readonly IEnumerable<int> productionOrders;
public ProductionOrders(IEnumerable<int> productionOrders)
=> this.productionOrders = productionOrders;
public IEnumerator<int> GetEnumerator()
=> this.productionOrders.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
=> this.GetEnumerator();
}
}
@@ -0,0 +1,24 @@
namespace LaaProduction.Services.Models.Reports
{
public class CordonelPressureSensorFilter : ReportFilter
{
public CordonelPressureSensorFilter()
{
var model = default(CordonelPressureSensorItem);
this.Add(model.Text(x => x.AuftragNr, this.Count));
this.Add(model.Text(x => x.PosNr, this.Count));
this.Add(model.Text(x => x.SerialNr, this.Count));
this.Add(model.Text(x => x.CustomerSerialNr, this.Count));
this.Add(model.Text(x => x.IdentNr, this.Count));
this.Add(model.Text(x => x.PcbId, this.Count));
this.Add(model.Text(x => x.TypeI, this.Count));
this.Add(model.Text(x => x.TypeII, this.Count));
this.Add(model.Text(x => x.Nennweite, this.Count));
this.Add(model.Text(x => x.Baulaenge, this.Count));
this.Add(model.Text(x => x.AVGPressure, this.Count));
this.Add(model.Boolean(x => x.TestPassed, this.Count));
this.Add(model.DateTime(x => x.TestDate, this.Count, -1));
}
}
}
@@ -0,0 +1,61 @@
namespace LaaProduction.Services.Models.Reports
{
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class CordonelPressureSensorItem
{
[Display(Name = "Auftrag Nr")]
[Column("[APS].[AuftragNr]")]
public int? AuftragNr { get; set; }
[Display(Name = "Position Nr")]
[Column("[APS].[PositionNr]")]
public short? PosNr { get; set; }
[Display(Name = "Serial Nr")]
[Column("[APS].[SerienNr]")]
public int? SerialNr { get; set; }
[Display(Name = "Kundenserial Nr")]
[Column("[APS].[KundeneigeneSerienNr]")]
public string CustomerSerialNr { get; set; }
[Display(Name = "IdentNr")]
[Column("[ID].[IdentNr]")]
public int? IdentNr { get; set; }
[Display(Name = "PcbId")]
[Column("[CPSTR].[PcbId]")]
public int PcbId { get; set; }
[Display(Name = "Typ")]
[Column("[ID].[Typ]")]
public string TypeI { get; set; }
[Display(Name = "Zusatz")]
[Column("[ID].[Typzusatz]")]
public string TypeII { get; set; }
[Display(Name = "Nennweite")]
[Column("[ID].[Nennweite]")]
public int? Nennweite { get; set; }
[Display(Name = "Baulänge")]
[Column("[ID].[Baulaenge]")]
public int? Baulaenge { get; set; }
[Display(Name = "AVG Pressure")]
[Column("[CPSTR].[AvgPressureInBar]")]
public float AVGPressure { get; set; }
[Display(Name = "Test passed")]
[Column("[CPSTR].[TestPassed]")]
public bool TestPassed { get; set; }
[Display(Name = "Test Date")]
[Column("[CPSTR].[TestDate]")]
public DateTime TestDate { get; set; }
}
}
@@ -0,0 +1,21 @@
namespace LaaProduction.Services.Models.Reports
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
public class CordonelPressureSensorModel
{
public CordonelPressureSensorFilter Filter { get; set; }
= new CordonelPressureSensorFilter();
public IEnumerable<CordonelPressureSensorItem> Items { get; set; }
= Array.Empty<CordonelPressureSensorItem>();
public static implicit operator CordonelPressureSensorModel(CordonelPressureSensorFilter filter)
=> new CordonelPressureSensorModel { Filter = filter };
public string Display(Expression<Func<CordonelPressureSensorItem, object>> expression)
=> ReportModelExtensions.Display(expression);
}
}
@@ -0,0 +1,11 @@
namespace LaaProduction.Services.Models.Reports
{
public class HeliumPressurePoint
{
public int TestId { get; set; }
public int PointNr { get; set; }
public decimal Result { get; set; }
}
}
@@ -0,0 +1,30 @@
namespace LaaProduction.Services.Models.Reports
{
public partial class HeliumReportFilter : ReportFilter
{
public HeliumReportFilter()
{
var model = default(HeliumReportItem);
this.Add(model.Text(x => x.FertigungNr, this.Count));
this.Add(model.Text(x => x.AuftragNr, this.Count));
this.Add(model.Text(x => x.PositionNr, this.Count));
this.Add(model.Text(x => x.SerialNr, this.Count));
this.Add(model.Text(x => x.IdentNr, this.Count));
this.Add(model.Text(x => x.HeId, this.Count));
this.Add(model.Text(x => x.HeTestId, this.Count));
this.Add(model.Text(x => x.PcbId, this.Count));
this.Add(model.Text(x => x.Nennweite, this.Count));
this.Add(model.Text(x => x.Baulaenge, this.Count));
this.Add(model.Text(x => x.Typ, this.Count));
this.Add(model.Text(x => x.Druck, this.Count));
this.Add(model.Text(x => x.Temperatur, this.Count));
this.Add(model.Text(x => x.HeLakeRate, this.Count));
this.Add(model.Text(x => x.HeTestPressure, this.Count));
this.Add(model.Boolean(x => x.IsValid, this.Count));
this.Add(model.Text(x => x.Text, this.Count));
this.Add(model.DateTime(x => x.TestDate, this.Count, -1));
this.Add(model.Text(x => x.Tester, this.Count));
}
}
}
@@ -0,0 +1,85 @@
namespace LaaProduction.Services.Models.Reports
{
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class HeliumReportItem
{
[Display(Name = "Auftrag Nr.")]
[Column("[POS].[AuftragNr]")]
public int AuftragNr { get; set; }
[Display(Name = "Fertigung Nr.")]
[Column("[PT].[CordonelPressureTest_FertigungsAuftragsNr]")]
public int FertigungNr { get; set; }
[Display(Name = "Pos.")]
[Column("[POS].[PositionNr]")]
public short PositionNr { get; set; }
[Display(Name = "Serial Nr.")]
[Column("[PCB2SN].[MapPcbIdToSerialNumber_SerialNumber]")]
public int SerialNr { get; set; }
[Display(Name = "Ident Nr.")]
[Column("[ID].[IdentNr]")]
public int IdentNr { get; set; }
[Display(Name = "He Id")]
[Column("[PT_HE].[CordonelPressureTestHe_Id]")]
public int HeId { get; set; }
[Display(Name = "He TestId")]
[Column("[PT_HE].[CordonelPressureTestHe_TestID]")]
public int HeTestId { get; set; }
[Display(Name = "Pcb Id")]
[Column("[PT].[CordonelPressureTest_PcbId]")]
public int PcbId { get; set; }
[Display(Name = "Nennweite")]
[Column("[ID].[Nennweite]")]
public int? Nennweite { get; set; }
[Display(Name = "Baulänge")]
[Column("[ID].[Baulaenge]")]
public int? Baulaenge { get; set; }
[Display(Name = "Typ")]
[Column("[ID].[Typ]")]
public string Typ { get; set; }
[Display(Name = "Druck")]
[Column("[ID].[Druck]")]
public int? Druck { get; set; }
[Display(Name = "°C")]
[Column("[ID].[Temperatur]")]
public int? Temperatur { get; set; }
[Display(Name = "Lake Rate")]
[Column("[PT_HE].[CordonelPressureTestHe_LeakRate]")]
public string HeLakeRate { get; set; }
[Display(Name = "He Druck")]
[Column("[PT_HE].[CordonelPressureTestHe_TestPressure]")]
public string HeTestPressure { get; set; }
[Display(Name = "Valid")]
[Column("[PT].[CordonelPressureTest_Valid]")]
public bool IsValid { get; set; }
[Display(Name = "Text")]
[Column("[PT].[CordonelPressureTest_Text]")]
public string Text { get; set; }
[Display(Name = "Datum")]
[Column("[PT].[CordonelPressureTest_Date]")]
public DateTimeOffset TestDate { get; set; }
[Display(Name = "Tester")]
[Column("[PT_HE].[CordonelPressureTestHe_TesterName]")]
public string Tester { get; set; }
}
}
@@ -0,0 +1,21 @@
namespace LaaProduction.Services.Models.Reports
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
public class HeliumReportModel
{
public HeliumReportFilter Filter { get; set; }
= new HeliumReportFilter();
public IEnumerable<HeliumReportItem> Items { get; set; }
= Array.Empty<HeliumReportItem>();
public static implicit operator HeliumReportModel(HeliumReportFilter filter)
=> new HeliumReportModel { Filter = filter };
public string Display(Expression<Func<HeliumReportItem, object>> expression)
=> ReportModelExtensions.Display(expression);
}
}
@@ -0,0 +1,23 @@
namespace LaaProduction.Services.Models.Reports
{
public class KottmannReportFilter : ReportFilter
{
public KottmannReportFilter()
{
var model = default(KottmannReportItem);
this.Add(model.Text(x => x.FertigungsNr, this.Count));
this.Add(model.Text(x => x.SerialNr, this.Count));
this.Add(model.Text(x => x.PcbId, this.Count));
this.Add(model.Text(x => x.Typ, this.Count));
this.Add(model.Text(x => x.Nennweite, this.Count));
this.Add(model.Text(x => x.Baulaenge, this.Count));
this.Add(model.Text(x => x.StartDruck, this.Count));
this.Add(model.Text(x => x.EndDruck, this.Count));
this.Add(model.Text(x => x.DruckZeit, this.Count));
this.Add(model.Boolean(x => x.Dicht, this.Count, -1));
this.Add(model.DateTime(x => x.Datum, this.Count, -1));
this.Add(model.DateTime(x => x.Bemerkung, this.Count, -1));
}
}
}
@@ -0,0 +1,57 @@
namespace LaaProduction.Services.Models.Reports
{
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class KottmannReportItem
{
[Display(Name = "Fertigung Nr.")]
[Column("[DP].[FertigungsauftragNr]")]
public int? FertigungsNr { get; set; }
[Display(Name = "Serial Nr.")]
[Column("[PCB2SN].[MapPcbIdToSerialNumber_SerialNumber]")]
public int SerialNr { get; set; }
[Display(Name = "Pcb Id")]
[Column("[PT].[CordonelPressureTest_PcbId]")]
public int PcbId { get; set; }
[Display(Name = "Nennweite")]
[Column("[ID].[Nennweite]")]
public int? Nennweite { get; set; }
[Display(Name = "Baulaenge")]
[Column("[ID].[Baulaenge]")]
public int? Baulaenge { get; set; }
[Display(Name = "Typ")]
[Column("[ID].[Typ]")]
public string Typ { get; set; }
[Display(Name = "Start Druck")]
[Column("[DP].[StartDruck]")]
public double StartDruck { get; set; }
[Display(Name = "End Druck")]
[Column("[DP].[EndDruck]")]
public double EndDruck { get; set; }
[Display(Name = "Zeit")]
[Column("[DP].[Pruefzeit]")]
public int DruckZeit { get; set; }
[Display(Name = "Dicht")]
[Column("[DP].[Dicht]")]
public bool Dicht { get; set; }
[Display(Name = "Datum")]
[Column("[DP].[Datum]")]
public DateTime Datum { get; set; }
[Display(Name = "Bemerkung")]
[Column("[DP].[Bemerkung]")]
public string Bemerkung { get; internal set; }
}
}
@@ -0,0 +1,21 @@
namespace LaaProduction.Services.Models.Reports
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
public class KottmannReportModel
{
public KottmannReportFilter Filter { get; set; }
= new KottmannReportFilter();
public IEnumerable<KottmannReportItem> Items { get; set; }
= Array.Empty<KottmannReportItem>();
public static implicit operator KottmannReportModel(KottmannReportFilter filter)
=> new KottmannReportModel { Filter = filter };
public string Display(Expression<Func<KottmannReportItem, object>> expression)
=> ReportModelExtensions.Display(expression);
}
}
@@ -0,0 +1,9 @@
namespace LaaProduction.Services.Models.Reports
{
public enum PropertyType
{
Text,
Date,
Bool
}
}
@@ -0,0 +1,100 @@
namespace LaaProduction.Services.Models.Reports
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public class ReportFilter : List<ReportFilterProperty>
{
internal SqlExpression OrderBy()
{
var sqlExpression = new SqlExpression();
foreach (var property in this)
{
if (property.OrderBy == 1)
{
sqlExpression.Add($"{property.Column}");
}
else if (property.OrderBy == -1)
{
sqlExpression.Add($"{property.Column} DESC");
}
}
return sqlExpression.BuildOrderBy(", ");
}
internal SqlExpression Where()
{
var sqlExpression = new SqlExpression();
foreach (var property in this)
{
if (string.IsNullOrWhiteSpace(property.Like))
{
continue;
}
if (property.Type == PropertyType.Date)
{
if (!string.IsNullOrWhiteSpace(property.Like))
{
var dateTokens = property
.Like
.Split(new[] { '-' })
.Select(x => DateTimeOffset.TryParse($"{x}".Trim(), new CultureInfo("de"), DateTimeStyles.None, out DateTimeOffset date)
? (DateTimeOffset?)date
: null)
.ToArray();
if (dateTokens.Length >= 1)
{
var date1 = dateTokens.FirstOrDefault();
if (date1 != null)
{
var date = date1.Value;
var propertyName = $"{property.Property}_{property.Index}_From";
var propertyValue = new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
sqlExpression.Add($"{property.Column} >= @{propertyName}", propertyName, propertyValue);
}
}
if (dateTokens.Length >= 2)
{
var date2 = dateTokens.LastOrDefault();
if (date2 != null)
{
var date = date2.Value.AddDays(1);
var propertyName = $"{property.Property}_{property.Index}_To";
var propertyValue = new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
sqlExpression.Add($"{property.Column} <= @{propertyName}", propertyName, propertyValue);
}
}
}
}
else if (property.Type == PropertyType.Bool)
{
var propertyName = $"{property.Property}_{property.Index}";
var propertyValue = int.TryParse(property.Like, out int bit) ? bit : 0;
sqlExpression.Add($"{property.Column} = @{propertyName}", propertyName, property.Like);
}
else
{
var propertyName = $"{property.Property}_{property.Index}";
var propertyValue = $"%{property.Like}%";
sqlExpression.Add($"{property.Column} LIKE @{propertyName}", propertyName, propertyValue);
}
}
return sqlExpression.BuildWhere(" AND ");
}
}
}
@@ -0,0 +1,39 @@
namespace LaaProduction.Services.Models.Reports
{
public class ReportFilterProperty
{
public int Index { get; set; }
public PropertyType Type { get; set; }
public string Property { get; set; }
public string Column { get; set; }
public string Like { get; set; }
public int OrderBy { get; set; }
public string TypeName
=> $"Filter[{this.Index}].{nameof(this.Type)}";
public string IndexName
=> $"Filter[{this.Index}].{nameof(this.Index)}";
public string PropertyName
=> $"Filter[{this.Index}].{nameof(this.Property)}";
public string ColumnName
=> $"Filter[{this.Index}].{nameof(this.Column)}";
public string LikeName
=> $"Filter[{this.Index}].{nameof(this.Like)}";
public string OrderByName
=> $"Filter[{this.Index}].{nameof(this.OrderBy)}";
public string OrderById
=> $"Filter_{this.Index}_{nameof(this.OrderBy)}";
}
}
@@ -0,0 +1,61 @@
namespace LaaProduction.Services.Models.Reports
{
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq.Expressions;
using System.Reflection;
public static class ReportModelExtensions
{
public static ReportFilterProperty Text<T>(this T model, Expression<Func<T, object>> expression, int index, int orderBy = 0)
=> model.Property(expression, index, PropertyType.Text, orderBy);
public static ReportFilterProperty DateTime<T>(this T model, Expression<Func<T, object>> expression, int index, int orderBy = 0)
=> model.Property(expression, index, PropertyType.Date, orderBy);
public static ReportFilterProperty Boolean<T>(this T model, Expression<Func<T, object>> expression, int index, int orderBy = 0)
=> model.Property(expression, index, PropertyType.Bool, orderBy);
public static ReportFilterProperty Property<T>(this T model, Expression<Func<T, object>> expression, int index, PropertyType propertyType, int orderBy)
{
var memberInfo = default(MemberInfo);
if (expression.Body is MemberExpression memberExpression)
{
memberInfo = memberExpression.Member;
}
else if (expression.Body is UnaryExpression unaryExpression && unaryExpression.Operand is MemberExpression operandExpression)
{
memberInfo = operandExpression.Member;
}
return new ReportFilterProperty
{
Column = memberInfo?.GetCustomAttribute<ColumnAttribute>()?.Name,
Property = memberInfo?.Name,
OrderBy = orderBy,
Index = index,
Type = propertyType
};
}
public static string Display<T>(Expression<Func<T, object>> expression)
{
var memberInfo = default(MemberInfo);
if (expression.Body is MemberExpression memberExpression)
{
memberInfo = memberExpression.Member;
}
else if (expression.Body is UnaryExpression unaryExpression && unaryExpression.Operand is MemberExpression operandExpression)
{
memberInfo = operandExpression.Member;
}
return memberInfo
?.GetCustomAttribute<DisplayAttribute>()
?.Name;
}
}
}
@@ -0,0 +1,41 @@
namespace LaaProduction.Services.Models.Reports
{
using System.Collections.Generic;
public class SqlExpression
{
private readonly ICollection<string> expressions
= new List<string>();
public string Query { get; set; }
public IDictionary<string, object> Parameters { get; set; }
= new Dictionary<string, object>();
internal void Add(string expression)
=> this.expressions.Add(expression);
internal void Add(string expression, string propertyName, object propertyValue)
{
this.Parameters[propertyName] = propertyValue;
this.expressions.Add(expression);
}
internal SqlExpression BuildOrderBy(string delimiter)
{
this.Query = string.Join(delimiter, this.expressions);
return this;
}
internal SqlExpression BuildWhere(string delimiter)
{
this.Query = this.expressions.Count > 0
? string.Join(delimiter, this.expressions)
: "1 = 1";
return this;
}
}
}
@@ -0,0 +1,17 @@
namespace LaaProduction.Services.Models.Reports
{
public class TestStatus
{
public string PosNr { get; set; }
public string SerialNr { get; set; }
public bool? HeliumTest { get; set; }
public bool? PressureTest { get; set; }
public bool? MetroTest { get; set; }
public bool? RadioTest { get; set; }
}
}
@@ -0,0 +1,39 @@
namespace LaaProduction.Services.Models
{
public class Result
{
private readonly bool succeeded;
private string message;
private Result(bool succeeded = true)
{
this.succeeded = succeeded;
this.message = string.Empty;
}
private Result(string message = default(string))
{
this.message = message;
this.succeeded = string.IsNullOrWhiteSpace(message);
}
public void WithMessage(string message)
=> this.message = message;
public override string ToString()
=> this.message;
public static implicit operator Result(bool succeeded)
=> new Result(succeeded);
public static implicit operator Result(string message)
=> new Result(message);
public static implicit operator bool(Result result)
=> result.succeeded;
public static implicit operator string(Result result)
=> result.ToString();
}
}
@@ -0,0 +1,16 @@
namespace LaaProduction.Services.Models.Search
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class SearchWildcardModel
{
[Display(Name = "Radioadress | PcbId | SerienNr | KundenSerienNr")]
public string Token { get; set; }
[Display(Name = "Select fields")]
public IDictionary<string, bool> Fields { get; set; }
public IEnumerable<IDictionary<string, object>> Results { get; set; }
}
}
@@ -0,0 +1,38 @@
namespace LaaProduction.Services.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
public class WildcardInputModel
{
private string token;
private IEnumerable<string> fields = Array.Empty<string>();
[Required]
[StringLength(50, MinimumLength = 1)]
[RegularExpression("^[0-9 a-z-A-Z]+$")]
public string Token
{
get => this.token;
set => this.token = value?.Replace(" ", "")?.Trim();
}
public string Fields
{
get => string.Join(",", this.fields);
set => this.fields = $"{value}".Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}
internal IEnumerable<string> GetRequiredFields(IEnumerable<string> allFields)
{
if (this.fields.Any())
{
return allFields.Where(x => this.fields.Contains(x, StringComparer.OrdinalIgnoreCase));
}
return allFields;
}
}
}
@@ -0,0 +1,8 @@
namespace LaaProduction.Services.Models
{
using System.Collections.Generic;
public class WildcardResult : Dictionary<string, object>
{
}
}
@@ -0,0 +1,19 @@
namespace LaaProduction.Services.Models
{
public class SerialNr
{
public int Id { get; set; }
public int Serial { get; set; }
public int PositionNr { get; set; }
public int? PalletNr { get; set; }
public string CustomerSerial { get; set; }
public bool IsScanned { get; set; }
public string BarcodeNr => this.CustomerSerial ?? $"{this.Serial}";
}
}
@@ -0,0 +1,36 @@
namespace LaaProduction.Services.Models
{
using System.ComponentModel.DataAnnotations;
public class ShipmentModel
{
public readonly string BtnSubmit = "Auftrag suchen";
private readonly int? palletNr;
private readonly int? positionNr;
public ShipmentModel() { }
public ShipmentModel(OrderScanModel orderModel)
{
if (orderModel != null)
{
this.OrderNr = orderModel.OrderNr;
this.positionNr = orderModel.PositionNr;
this.palletNr = orderModel.PalletNr;
}
}
[Required(ErrorMessage = "Auftrags-Nr. ist erforderlich!")]
[Display(Name = "Auftrags-Nr. scanen oder eingeben")]
public int? OrderNr { get; set; }
public OrderScanModel OrderScanModel
=> new OrderScanModel
{
OrderNr = this.OrderNr,
PalletNr = this.palletNr,
PositionNr = this.positionNr
};
}
}
@@ -0,0 +1,11 @@
namespace LaaProduction.Services.Models.Software
{
using System.Collections.Generic;
public class FunctionUsers
{
public int FunctionId { get; set; }
public IEnumerable<short> Users { get; set; }
}
}
@@ -0,0 +1,29 @@
namespace LaaProduction.Services.Models.Software
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class Software
{
public int Id { get; set; }
public short AppId { get; set; }
[StringLength(50)]
public string FullName { get; set; }
public int MajorV { get; set; }
public int MinorV { get; set; }
public int BuildV { get; set; }
public DateTime ValidTo { get; set; }
[StringLength(150)]
public string Description { get; set; }
public IEnumerable<SoftwareFunction> Functions { get; set; }
}
}
@@ -0,0 +1,11 @@
namespace LaaProduction.Services.Models.Software
{
public class SoftwareFunction
{
public int Id { get; set; }
public short AppId { get; set; }
public string Function { get; set; }
}
}
@@ -0,0 +1,13 @@
namespace LaaProduction.Services.Models.Software
{
public class SoftwareOverview
{
public short AppId { get; set; }
public string Name { get; set; }
public int Versions { get; set; }
public int Functions { get; set; }
}
}
@@ -0,0 +1,19 @@
namespace LaaProduction.Services.Models.Software
{
public class SoftwareUser
{
public short Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username { get; set; }
public int FunctionsCount { get; set; }
public bool HasPassword { get; set; }
public string Functions { get; set; }
}
}
@@ -0,0 +1,12 @@
namespace LaaProduction.Services.Models.Software
{
using System;
using System.Collections.Generic;
public class UserFunctions
{
public short UserId { get; set; }
public IEnumerable<int> Functions { get; set; }
}
}
@@ -0,0 +1,72 @@
namespace LaaProduction.Services
{
using LaaProductionSQL.Interfaces;
using LaaProduction.Services.Interfaces;
using LaaProduction.Services.Models;
public class OrdersService : IOrdersService
{
private readonly ISQLConnection sqlConnection;
public OrdersService(ISQLConnection sqlConnection)
=> this.sqlConnection = sqlConnection;
public OrdersFoundModel FindOrders(string search)
{
var ordersFound = this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT
[AlleAuftragPositionen].[AuftragNr] -- 0
, [AlleAuftragPositionen].[FertigungsauftragNr] -- 1
, [Kunde].[Name] -- 2
FROM [AlleAuftragPositionen]
LEFT JOIN [Kunde] ON [Kunde].[KundenNr] = [AlleAuftragPositionen].[KundenNr]
WHERE [AlleAuftragPositionen].[Versand_Ist_datum] IS NOT NULL
AND [AlleAuftragPositionen].[AuftragNr] LIKE @{nameof(search)}
ORDER BY [AlleAuftragPositionen].[AuftragNr]
, [AlleAuftragPositionen].[FertigungsauftragNr]
, [Kunde].[Name]")
.SetParameter(nameof(search), $"%{search}%")
.ExecuteReader(reader => new OrderInfoModel
{
OrderNr = reader.GetInt(),
ProductionOrderNr = reader.GetInt(),
Customer = reader.GetString(),
});
return new OrdersFoundModel(ordersFound);
}
public OrderPositions FindPositions(string orderNr)
{
var positionsFound = this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT
[AlleAuftragPositionen].[PositionNr] -- 0
FROM [AlleAuftragPositionen]
WHERE [AlleAuftragPositionen].[AuftragNr] = @{nameof(orderNr)}
OR [AlleAuftragPositionen].[FertigungsauftragNr] = @{nameof(orderNr)}
ORDER BY [AlleAuftragPositionen].[PositionNr]")
.SetParameter(nameof(orderNr), orderNr)
.ExecuteReader(reader => (int)reader.GetSmallint());
return new OrderPositions(positionsFound);
}
public ProductionOrders FindProductionOrders(string productionNr)
{
var ordersFound = this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT
[AlleAuftragPositionen].[FertigungsauftragNr] -- 1
FROM [AlleAuftragPositionen]
WHERE [AlleAuftragPositionen].[Versand_Ist_datum] IS NOT NULL
AND [AlleAuftragPositionen].[AuftragNr] LIKE @{nameof(productionNr)}
ORDER BY [AlleAuftragPositionen].[FertigungsauftragNr]")
.SetParameter(nameof(productionNr), $"{productionNr}%")
.ExecuteReader(reader => reader.GetInt());
return new ProductionOrders(ordersFound);
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LaaProduction.Services")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LaaProduction.Services")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff167011-431a-41a7-a7db-560e08860388")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,249 @@
namespace LaaProduction.Services
{
using LaaProductionSQL.Interfaces;
using LaaProduction.Services.Interfaces;
using LaaProduction.Services.Models;
using LaaProduction.Services.Models.Reports;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public class ProtocolService : IProtocolService
{
private readonly ISQLConnection sqlConnection;
public ProtocolService(ISQLConnection sqlConnection)
=> this.sqlConnection = sqlConnection;
public bool DeleteFile(int fileId)
=> this.sqlConnection
.CreateCommand($@"
DELETE FROM [File]
WHERE [FileId] = @{nameof(fileId)};
DELETE FROM [FilesOrders]
OUTPUT [Deleted].[FileId]
WHERE [FileId] = @{nameof(fileId)};")
.SetParameter(nameof(fileId), fileId)
.ExecuteScalar(x => x.GetInt()) > 0;
public string FileContent(int? fileId)
{
var fileContent = this.sqlConnection
.CreateCommand($@"
SELECT [dbo].[File].[FileContent]
FROM [dbo].[File]
WHERE [dbo].[File].[FileId] = @{nameof(fileId)}")
.SetParameter(nameof(fileId), fileId)
.FirstOrDefault(reader => reader.GetBytes())
?? Array.Empty<byte>();
return string.Format("data:application/pdf;base64,{0}", Convert.ToBase64String(fileContent));
}
public OrderClientModel FindOrder(int orderId)
{
var orderClientModel = this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT
[APG].[AuftragNr]
, [K].[KundenNr]
, [K].[Name]
, ISNULL((SELECT CAST([Positions].[PositionNr] AS VARCHAR) + ', '
FROM (SELECT DISTINCT TOP 1000 [PositionNr]
FROM [AuftragPositionSerienNr]
WHERE [AuftragNr] = [APG].[AuftragNr]
ORDER BY [PositionNr]) AS [Positions]
FOR XML PATH('')), '') AS [Positions]
FROM [AuftragPosition_Gesamt] AS [APG]
JOIN [Auftrag_Gesamt] AS [AG]
ON [AG].[AuftragNr] = [APG].[AuftragNr]
JOIN [IdentNr] AS [IN]
ON [IN].[IdentNr] = [APG].[Identnr]
AND [IN].[Typ] = 'GNS'
JOIN [Kunde] AS [K]
ON [K].[KundenNr] = [AG].[KundenNr]
WHERE [APG].[AuftragNr] = @{nameof(orderId)}")
.SetParameter(nameof(orderId), orderId)
.FirstOrDefault(reader => new OrderClientModel
{
OrderId = reader.GetInt(),
ClientId = reader.GetInt(),
ClientName = reader.GetString(),
Positions = reader.GetString().Trim().Trim(',')
});
if (orderClientModel != null && orderId > 0)
{
orderClientModel.FileId = this.sqlConnection
.CreateCommand($@"
SELECT [FileId]
FROM [FilesOrders]
WHERE [OrderId] = @{nameof(orderId)}
AND [Usage] = 'PROTOCOL'")
.SetParameter(nameof(orderId), orderId)
.FirstOrDefault(reader => reader.GetValue<int?>());
}
return orderClientModel ?? new OrderClientModel();
}
public IEnumerable<KeyValuePair<int, string>> FindOrdersById(int orderno)
=> this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT
[APG].[AuftragNr]
, [K].[Name]
FROM [AuftragPosition_Gesamt] AS [APG]
JOIN [Auftrag_Gesamt] AS [AG]
ON [AG].[AuftragNr] = [APG].[AuftragNr]
JOIN [IdentNr] AS [IN]
ON [IN].[IdentNr] = [APG].[Identnr]
AND [IN].[Typ] = 'GNS'
JOIN [Kunde] AS [K]
ON [K].[KundenNr] = [AG].[KundenNr]
WHERE [APG].[AuftragNr] LIKE @{nameof(orderno)}")
.SetParameter(nameof(orderno), $"%{orderno}%")
.ExecuteReader(reader => new KeyValuePair<int, string>(
key: reader.GetInt(),
value: reader.GetString()));
public IEnumerable<KeyValuePair<int, string>> FindOrdersByClient(string clientName)
=> this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT
[APG].[AuftragNr]
, [K].[Name]
FROM [AuftragPosition_Gesamt] AS [APG]
JOIN [Auftrag_Gesamt] AS [AG]
ON [AG].[AuftragNr] = [APG].[AuftragNr]
JOIN [IdentNr] AS [IN]
ON [IN].[IdentNr] = [APG].[Identnr]
AND [IN].[Typ] = 'GNS'
JOIN [Kunde] AS [K]
ON [K].[KundenNr] = [AG].[KundenNr]
WHERE [K].[Name] LIKE @{nameof(clientName)}")
.SetParameter(nameof(clientName), $"%{clientName}%")
.ExecuteReader(reader => new KeyValuePair<int, string>(
key: reader.GetInt(),
value: reader.GetString()));
public IEnumerable<TestStatus> LoadTestStatus(int orderId)
=> this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT
[APS].[PositionNr] AS [PosNr] -- 0
, ISNULL([APS].[KundeneigeneSerienNr], [APS].[SerienNr]) AS [SerialNr] -- 1
, [CPT].[CordonelPressureTest_Valid] AS [3TightnessTest] -- 2
, [DP].[Dicht] AS [4PressureAndTightness] -- 3
, MAX([APS].[StatusFertigung]) AS [5Metrologicaltesting] -- 4
, [CRRH].[Result] AS [6ConfigComparisonAndRadiotest] -- 5
FROM [AuftragPositionSerienNr] AS [APS]
LEFT JOIN [Genesis_Meter] AS [GM] ON [GM].[Seriennummer] = [APS].[SerienNr]
LEFT JOIN [MapPcbIdToSerialNumber] AS [PCB] ON [PCB].[MapPcbIdToSerialNumber_SerialNumber] = [GM].[Seriennummer]
LEFT JOIN [Cordonel_Radio_RSSI_History] AS [CRRH] ON [CRRH].[RadioAdress] = [GM].[Adresse] - 10000000000
AND [CRRH].[IsLast] = 1
AND [CRRH].[Result] = 1
LEFT JOIN [Druckpruefung] AS [DP] ON [DP].[FabNr] = [PCB].[MapPcbIdToSerialNumber_PcbId]
AND [DP].[Dicht] = 1
LEFT JOIN [Cordonel_PressureTest] AS [CPT] ON [CPT].[CordonelPressureTest_PcbId] = [PCB].[MapPcbIdToSerialNumber_PcbId]
AND [CPT].[CordonelPressureTest_Valid] = 1
WHERE [APS].[AuftragNr] = @{nameof(orderId)}
GROUP BY [APS].[PositionNr]
, [APS].[SerienNr]
, [APS].[KundeneigeneSerienNr]
, [CPT].[CordonelPressureTest_Valid]
, [DP].[Dicht]
, [CRRH].[Result]
ORDER BY [APS].[PositionNr]
, ISNULL([APS].[KundeneigeneSerienNr], [APS].[SerienNr])")
.SetParameter(nameof(orderId), orderId)
.ExecuteReader(reader => new TestStatus
{
PosNr = $"{reader.GetSmallint()}",
SerialNr = reader.GetString(),
HeliumTest = reader.GetValue<bool?>(),
PressureTest = reader.GetValue<bool?>(),
MetroTest = this.MetrologicalValue(reader.GetValue<byte?>()),
RadioTest = reader.GetValue<bool?>(),
});
public bool OrderCompleted(int orderId)
{
var sumResults = this.sqlConnection
.CreateCommand($@"
SELECT CAST(CASE WHEN ISNULL([CPT].[CordonelPressureTest_Valid], 1) = 1 THEN 0 ELSE 1 END AS INT)
+ CAST(CASE WHEN ISNULL([DP].[Dicht], 1) = 1 THEN 0 ELSE 1 END AS INT)
+ ISNULL(MAX([APS].[StatusFertigung]) - 30, 0)
+ CAST(CASE WHEN ISNULL([CRRH].[Result], 1) = 1 THEN 0 ELSE 1 END AS INT)
FROM [AuftragPositionSerienNr] AS [APS]
LEFT JOIN [Genesis_Meter] AS [GM] ON [GM].[Seriennummer] = [APS].[SerienNr]
LEFT JOIN [MapPcbIdToSerialNumber] AS [PCB] ON [PCB].[MapPcbIdToSerialNumber_SerialNumber] = [GM].[Seriennummer]
LEFT JOIN [Cordonel_Radio_RSSI_History] AS [CRRH] ON [CRRH].[RadioAdress] = [GM].[Adresse] - 10000000000
AND [CRRH].[IsLast] = 1
AND [CRRH].[Result] = 1
LEFT JOIN [Druckpruefung] AS [DP] ON [DP].[FabNr] = [PCB].[MapPcbIdToSerialNumber_PcbId]
AND [DP].[Dicht] = 1
LEFT JOIN [Cordonel_PressureTest] AS [CPT] ON [CPT].[CordonelPressureTest_PcbId] = [PCB].[MapPcbIdToSerialNumber_PcbId]
AND [CPT].[CordonelPressureTest_Valid] = 1
WHERE [APS].[AuftragNr] = @{nameof(orderId)}
GROUP BY [APS].[PositionNr]
, [APS].[SerienNr]
, [APS].[KundeneigeneSerienNr]
, [CPT].[CordonelPressureTest_Valid]
, [DP].[Dicht]
, [CRRH].[Result]")
.SetParameter(nameof(orderId), orderId)
.ExecuteReader(reader => reader.GetInt())
.Sum(x => x);
return sumResults == 0;
}
public int SaveFile(Stream fileStream, int clientId, int orderId)
{
var fileName = $"{clientId}_{orderId}.pdf";
var fileContent = this.GetBuffer(fileStream);
return this.sqlConnection
.CreateCommand($@"
INSERT INTO [dbo].[File] (
[FileName]
, [FileContent])
OUTPUT @{nameof(orderId)}, [Inserted].[FileId], 'PROTOCOL'
INTO [dbo].[FilesOrders]([OrderId], [FileId], [Usage])
OUTPUT [Inserted].[FileId]
VALUES (@{nameof(fileName)}
, @{nameof(fileContent)})")
.SetParameter(nameof(orderId), orderId)
.SetParameter(nameof(fileName), fileName)
.SetParameter(nameof(fileContent), fileContent)
.ExecuteScalar(x => x.GetInt());
}
private byte[] GetBuffer(Stream fileStream)
{
var fileContent = new byte[fileStream.Length];
using (var memoryStream = new MemoryStream())
{
fileStream.CopyTo(memoryStream);
fileContent = memoryStream.ToArray();
}
return fileContent;
}
private bool? MetrologicalValue(byte? value)
{
if (value is null)
{
return null;
}
return value == 30;
}
}
}
@@ -0,0 +1,393 @@
namespace LaaProduction.Services
{
using LaaProductionSQL.Interfaces;
using LaaProduction.Services.Interfaces;
using LaaProduction.Services.Models.Reports;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public partial class ReportService : IReportService
{
private readonly ISQLConnection sqlConnection;
public ReportService(ISQLConnection sqlConnection)
=> this.sqlConnection = sqlConnection;
public CordonelPressureSensorModel LoadCordonelPressureSensorReport(CordonelPressureSensorModel model = null)
{
if (model is null)
{
model = new CordonelPressureSensorModel();
}
var where = model.Filter.Where();
var orderBy = model.Filter.OrderBy();
model.Items = this.sqlConnection
.CreateCommand($@"
SELECT [APS].[AuftragNr] AS [AuftragNr]
, [APS].[PositionNr] AS [PosNr]
, [APS].[SerienNr] AS [SerialNr]
, [APS].[KundeneigeneSerienNr] AS [CustomerSerialNr]
, [ID].[IdentNr] AS [IdentNr]
, [CPSTR].[PcbId] AS [PcbId]
, [ID].[Typ] AS [TypeI]
, [ID].[Typzusatz] AS [TypeII]
, [ID].[Nennweite] AS [Nennweite]
, [ID].[Baulaenge] AS [Baulaenge]
, [CPSTR].[AvgPressureInBar] AS [AvgPressure]
, [CPSTR].[TestPassed] AS [TestPassed]
, [CPSTR].[TestDate] AS [TestDate]
FROM [Cordonel_PressureSensor_TestResults] AS [CPSTR]
LEFT JOIN [AuftragPositionSerienNr] AS [APS]
ON [APS].[FabNr] = [CPSTR].[PcbId]
LEFT JOIN [AuftragPosition_Gesamt] AS [APG]
ON [APG].[AuftragNr] = [APS].[AuftragNr]
AND [APG].[PositionNr] = [APS].[PositionNr]
LEFT JOIN [Identnr] AS [ID]
ON [ID].[IdentNr] = [APG].[Identnr]
WHERE {where.Query}
ORDER BY {orderBy.Query}")
.SetParameters(where.Parameters)
.SetParameters(orderBy.Parameters)
.ExecuteReader(reader => new CordonelPressureSensorItem
{
AuftragNr = reader.GetValue<int?>(),
PosNr = reader.GetValue<short?>(),
SerialNr = reader.GetValue<int?>(),
CustomerSerialNr = reader.GetString(),
IdentNr = reader.GetValue<int?>(),
PcbId = reader.GetInt(),
TypeI = reader.GetString(),
TypeII = reader.GetString(),
Nennweite = reader.GetValue<int?>(),
Baulaenge = reader.GetValue<int?>(),
AVGPressure = reader.GetValue<float>(),
TestPassed = reader.GetValue<bool>(),
TestDate = reader.GetValue<DateTime>(),
});
return model;
}
public HeliumReportModel LoadHeliumPressureReport(HeliumReportModel model = null)
{
if (model is null)
{
model = new HeliumReportModel();
}
var where = model.Filter.Where();
var orderBy = model.Filter.OrderBy();
model.Items = this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT
[PT].[CordonelPressureTest_FertigungsAuftragsNr] AS [FertigungNr] -- 0
, [POS].[AuftragNr] AS [AuftragNr] -- 1
, [POS].[PositionNr] AS [PositionNr] -- 2
, [PCB2SN].[MapPcbIdToSerialNumber_SerialNumber] AS [SerialNr] -- 3
, [ID].[IdentNr] AS [IdentNr] -- 4
, [PT_HE].[CordonelPressureTestHe_Id] AS [HeId] -- 5
, [PT_HE].[CordonelPressureTestHe_TestID] AS [HeTestId] -- 6
, [PT].[CordonelPressureTest_PcbId] AS [PcbId] -- 7
, [ID].[Nennweite] AS [Nennweite] -- 8
, [ID].[Baulaenge] AS [Baulaenge] -- 9
, [ID].[Typ] AS [Typ] -- 10
, [ID].[Druck] AS [Druck] -- 11
, [ID].[Temperatur] AS [Temperatur] -- 12
, [PT_HE].[CordonelPressureTestHe_LeakRate] AS [HeLakeRate] -- 13
, [PT_HE].[CordonelPressureTestHe_TestPressure] AS [HeTestPressure] -- 14
, [PT].[CordonelPressureTest_Valid] AS [IsValid] -- 15
, [PT].[CordonelPressureTest_Date] AS [TestDate] -- 16
, [PT].[CordonelPressureTest_Text] AS [Text] -- 17
, [PT_HE].[CordonelPressureTestHe_TesterName] AS [Tester] -- 18
FROM [Cordonel_PressureTest] AS [PT]
JOIN [Cordonel_PressureTest_He] AS [PT_HE] ON [PT_HE].[CordonelPressureTestHe_TestID] = [PT].[CordonelPressureTest_Id]
LEFT JOIN [Druckpruefung] AS [DP] ON [DP].[FabNr] = [PT].[CordonelPressureTest_PcbId]
JOIN [MapPcbIdToSerialNumber] AS [PCB2SN] ON [PCB2SN].[MapPcbIdToSerialNumber_PcbId] = [PT].[CordonelPressureTest_PcbId]
JOIN [AuftragPosition_Gesamt] AS [POS] ON [POS].[FertigungsauftragNr] = [PT].[CordonelPressureTest_FertigungsAuftragsNr]
JOIN [Identnr] AS [ID] ON [ID].[IdentNr] = [POS].[Identnr]
WHERE [CordonelPressureTest_IsDeleted] = 0
AND {where.Query}
ORDER BY {orderBy.Query}")
.SetParameters(where.Parameters)
.SetParameters(orderBy.Parameters)
.ExecuteReader(reader => new HeliumReportItem
{
FertigungNr = reader.GetInt(),
AuftragNr = reader.GetInt(),
PositionNr = reader.GetValue<short>(),
SerialNr = reader.GetInt(),
IdentNr = reader.GetInt(),
HeId = reader.GetInt(),
HeTestId = reader.GetInt(),
PcbId = reader.GetInt(),
Nennweite = reader.GetValue<int?>(),
Baulaenge = reader.GetValue<int?>(),
Typ = reader.GetString(),
Druck = reader.GetValue<int?>(),
Temperatur = reader.GetValue<int?>(),
HeLakeRate = reader.GetString(),
HeTestPressure = reader.GetString(),
IsValid = reader.GetValue<bool>(),
TestDate = reader.GetValue<DateTimeOffset>(),
Text = reader.GetString(),
Tester = reader.GetString()
});
return model;
}
public byte[] LoadHeliumPressureReportAsCSV(HeliumReportModel model)
{
if (model is null)
{
model = new HeliumReportModel();
}
var where = model.Filter.Where();
var orderBy = model.Filter.OrderBy();
var csvItems = new List<object[]>
{
new object[]
{
"[FertigungNr]",
"[AuftragNr]",
"[PositionNr]",
"[SerialNr]",
"[IdentNr]",
"[HeId]",
"[HeTestId]",
"[PcbId]",
"[Nennweite]",
"[Baulaenge]",
"[Typ]",
"[Druck]",
"[Temperatur]",
"[HeLakeRate]",
"[HeTestPressure]",
"[IsValid]",
"[TestDate]",
"[Text]",
"[Tester]",
}
};
var headers = Array.Empty<string>();
var items = this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT
[PT].[CordonelPressureTest_FertigungsAuftragsNr] AS [FertigungNr] -- 0 Filter
, [POS].[AuftragNr] AS [AuftragNr] -- 1 Filter
, [POS].[PositionNr] AS [PositionNr] -- 2 Filter
, [PCB2SN].[MapPcbIdToSerialNumber_SerialNumber] AS [SerialNr] -- 3
, [ID].[IdentNr] AS [IdentNr] -- 4 Filter
, [PT_HE].[CordonelPressureTestHe_Id] AS [HeId] -- 5
, [PT_HE].[CordonelPressureTestHe_TestID] AS [HeTestId] -- 6
, [PT].[CordonelPressureTest_PcbId] AS [PcbId] -- 7 Filter
, [ID].[Nennweite] AS [Nennweite] -- 8 Filter
, [ID].[Baulaenge] AS [Baulaenge] -- 9 Filter
, [ID].[Typ] AS [Typ] -- 10 Filter
, [ID].[Druck] AS [Druck] -- 11 Filter
, [ID].[Temperatur] AS [Temperatur] -- 12 Filter
, [PT_HE].[CordonelPressureTestHe_LeakRate] AS [HeLakeRate] -- 13
, [PT_HE].[CordonelPressureTestHe_TestPressure] AS [HeTestPressure] -- 14
, [PT].[CordonelPressureTest_Valid] AS [IsValid] -- 15 Filter
, [PT].[CordonelPressureTest_Date] AS [TestDate] -- 16 Filter
, [PT].[CordonelPressureTest_Text] AS [Text] -- 17 Filter
, [PT_HE].[CordonelPressureTestHe_TesterName] AS [Tester] -- 18
FROM [Cordonel_PressureTest] AS [PT]
JOIN [Cordonel_PressureTest_He] AS [PT_HE] ON [PT_HE].[CordonelPressureTestHe_TestID] = [PT].[CordonelPressureTest_Id]
LEFT JOIN [Druckpruefung] AS [DP] ON [DP].[FabNr] = [PT].[CordonelPressureTest_PcbId]
JOIN [MapPcbIdToSerialNumber] AS [PCB2SN] ON [PCB2SN].[MapPcbIdToSerialNumber_PcbId] = [PT].[CordonelPressureTest_PcbId]
JOIN [AuftragPosition_Gesamt] AS [POS] ON [POS].[FertigungsauftragNr] = [PT].[CordonelPressureTest_FertigungsAuftragsNr]
JOIN [Identnr] AS [ID] ON [ID].[IdentNr] = [POS].[Identnr]
WHERE [CordonelPressureTest_IsDeleted] = 0
AND {where.Query}
ORDER BY {orderBy.Query}")
.SetParameters(where.Parameters)
.SetParameters(orderBy.Parameters)
.ExecuteReader(reader => new object[]
{
reader.GetInt(),
reader.GetInt(),
reader.GetSmallint(),
reader.GetInt(),
reader.GetInt(),
reader.GetInt(),
reader.GetInt(),
reader.GetInt(),
reader.GetValue<int?>(),
reader.GetValue<int?>(),
reader.GetString().Replace(',', ' '),
reader.GetValue<int?>(),
reader.GetValue<int?>(),
reader.GetString().Replace(',', '.'),
reader.GetString().Replace(',', ' '),
reader.GetValue<bool>(),
$"{reader.GetValue<DateTimeOffset>():yyyy-MM-dd}",
reader.GetString().Replace(',', ' '),
reader.GetString().Replace(',', ' ')
});
csvItems.AddRange(items);
var csvLines = csvItems.Select(x => string.Join(",", x));
var csvContent = string.Join(Environment.NewLine, csvLines);
return Encoding.UTF8.GetBytes(csvContent);
}
public IEnumerable<HeliumPressurePoint> LoadHeliumPressureResults(int testId)
=> this.sqlConnection
.CreateCommand($@"
SELECT [CordonelPressureTestTestPoints_Id]
, [CordonelPressureTest_TestPointNr]
, CAST([CordonelPressureTest_TestPointResult] AS NUMERIC(9, 8))
FROM [Cordonel_PressureTest_TestPoints]
WHERE [CordonelPressureTest_Id] = @{nameof(testId)}")
.SetParameter(nameof(testId), testId)
.ExecuteReader(reader => new HeliumPressurePoint
{
TestId = reader.GetInt(),
PointNr = reader.GetInt(),
Result = reader.GetValue<decimal>(),
});
public KottmannReportModel LoadKottmannPressureReport(KottmannReportModel model = null)
{
if (model is null)
{
model = new KottmannReportModel();
}
var where = model.Filter.Where();
var orderBy = model.Filter.OrderBy();
model.Items = this.sqlConnection
.CreateCommand($@"
SELECT [DP].[FertigungsauftragNr] AS [FertigungNr]
, [PCB2SN].[MapPcbIdToSerialNumber_SerialNumber] AS [SerienNr]
, [DP].[FabNr] AS [PcbId]
, [ID].[Typ] AS [Typ]
, [ID].[Nennweite] AS [Nennweite]
, [ID].[Baulaenge] AS [Baulaenge]
, [DP].[StartDruck] AS [StartDruck]
, [DP].[EndDruck] AS [EndDruck]
, [DP].[Pruefzeit] AS [Pruefzeit]
, [DP].[Dicht] AS [Dicht]
, [DP].[Datum] AS [Datum]
, [DP].[Bemerkung] AS [Bemerkung]
FROM [Druckpruefung] AS [DP]
JOIN [AuftragPosition_Gesamt] AS [POS]
ON [POS].[FertigungsauftragNr] = [DP].[FertigungsauftragNr]
JOIN [Identnr] AS [ID]
ON [ID].[IdentNr] = [POS].[Identnr]
JOIN [MapPcbIdToSerialNumber] AS [PCB2SN]
ON [PCB2SN].[MapPcbIdToSerialNumber_PcbId] = [DP].[FabNr]
AND [PCB2SN].[MapPcbIdToSerialNumber_Deleted] = 0
AND {where.Query}
ORDER BY {orderBy.Query}")
.SetParameters(where.Parameters)
.SetParameters(orderBy.Parameters)
.ExecuteReader(reader => new KottmannReportItem
{
FertigungsNr = reader.GetValue<int?>(),
SerialNr = reader.GetInt(),
PcbId = reader.GetInt(),
Typ = reader.GetString(),
Nennweite = reader.GetValue<int?>(),
Baulaenge = reader.GetValue<int?>(),
StartDruck = reader.GetValue<double>(),
EndDruck = reader.GetValue<double>(),
DruckZeit = reader.GetInt(),
Dicht = reader.GetValue<bool>(),
Datum = reader.GetValue<DateTime>(),
Bemerkung = reader.GetValue<string>()
});
return model;
}
public byte[] LoadKottmannPressureReportAsCSV(KottmannReportModel model)
{
if (model is null)
{
model = new KottmannReportModel();
}
var where = model.Filter.Where();
var orderBy = model.Filter.OrderBy();
var csvItems = new List<object[]>
{
new object[]
{
"[FertigungNr]",
"[SerienNr]",
"[PcbId]",
"[Typ]",
"[Nennweite]",
"[Baulaenge]",
"[StartDruck]",
"[EndDruck]",
"[Pruefzeit]",
"[Dicht]",
"[Datum]",
"[Bemerkung]"
}
};
var headers = Array.Empty<string>();
var items = this.sqlConnection
.CreateCommand($@"
SELECT [DP].[FertigungsauftragNr] AS [FertigungNr]
, [PCB2SN].[MapPcbIdToSerialNumber_SerialNumber] AS [SerienNr]
, [DP].[FabNr] AS [PcbId]
, [ID].[Typ] AS [Typ]
, [ID].[Nennweite] AS [Nennweite]
, [ID].[Baulaenge] AS [Baulaenge]
, [DP].[StartDruck] AS [StartDruck]
, [DP].[EndDruck] AS [EndDruck]
, [DP].[Pruefzeit] AS [Pruefzeit]
, [DP].[Dicht] AS [Dicht]
, [DP].[Datum] AS [Datum]
, [DP].[Bemerkung] AS [Bemerkung]
FROM [Druckpruefung] AS [DP]
JOIN [AuftragPosition_Gesamt] AS [POS]
ON [POS].[FertigungsauftragNr] = [DP].[FertigungsauftragNr]
JOIN [Identnr] AS [ID]
ON [ID].[IdentNr] = [POS].[Identnr]
JOIN [MapPcbIdToSerialNumber] AS [PCB2SN]
ON [PCB2SN].[MapPcbIdToSerialNumber_PcbId] = [DP].[FabNr]
AND [PCB2SN].[MapPcbIdToSerialNumber_Deleted] = 0
AND {where.Query}
ORDER BY {orderBy.Query}")
.SetParameters(where.Parameters)
.SetParameters(orderBy.Parameters)
.ExecuteReader(reader => new object[]
{
reader.GetValue<int?>(),
reader.GetInt(),
reader.GetInt(),
reader.GetString(),
reader.GetValue<int?>(),
reader.GetValue<int?>(),
reader.GetValue<double>(),
reader.GetValue<double>(),
reader.GetInt(),
reader.GetValue<bool>(),
$"{reader.GetValue<DateTime>():yyyy-MM-dd}",
reader.GetValue<string>().Replace(',', ' ')
});
csvItems.AddRange(items);
var csvLines = csvItems.Select(x => string.Join(",", x));
var csvContent = string.Join(Environment.NewLine, csvLines);
return Encoding.UTF8.GetBytes(csvContent);
}
}
}
@@ -0,0 +1,129 @@
namespace LaaProduction.Services
{
using LaaProductionSQL.Interfaces;
using LaaProduction.Services.Models;
using LaaProduction.Services.Interfaces;
using System.Collections.Generic;
public class SearchService : ISearchService
{
private readonly ISQLConnection sqlConnection;
public SearchService(ISQLConnection sqlConnection)
=> this.sqlConnection = sqlConnection;
public IEnumerable<WildcardResult> Find(WildcardInputModel model)
{
var requiredFields = model.GetRequiredFields(this.Options());
var ordersFound = sqlConnection
.CreateCommand($@"
DECLARE @serienNr TABLE([Nr] VARCHAR(50));
-----------------------------------------------------------------------------
-- 1. LOOK FOR SERIAL NUMBER ------------------------------------------------
-----------------------------------------------------------------------------
INSERT INTO @serienNr
SELECT [APS].[SerienNr]
FROM [AuftragPositionSerienNr] AS [APS]
WHERE [APS].[SerienNr] LIKE @{nameof(model.Token)}
OR REPLACE([APS].[KundeneigeneSerienNr], ' ', '') LIKE @{nameof(model.Token)};
-----------------------------------------------------------------------------
-- 2. LOOK FOR PCB NUMBER ---------------------------------------------------
-----------------------------------------------------------------------------
INSERT INTO @serienNr
SELECT [PCBS].[MapPcbIdToSerialNumber_SerialNumber]
FROM [MapPcbIdToSerialNumber] AS [PCBS]
WHERE [PCBS].[MapPcbIdToSerialNumber_PcbId] LIKE @{nameof(model.Token)};
-----------------------------------------------------------------------------
-- 3. LOOK FOR FUNK ADDRESS E-REGISTER --------------------------------------
-----------------------------------------------------------------------------
INSERT INTO @serienNr
SELECT [ER].[Seriennummer]
FROM [eRegister] AS [ER]
WHERE [ER].[Adresse] LIKE @{nameof(model.Token)};
-----------------------------------------------------------------------------
-- 4. LOOK FOR FUNK ADDRESS GENESIS -----------------------------------------
-----------------------------------------------------------------------------
INSERT INTO @serienNr
SELECT [GM].[Seriennummer]
FROM [Genesis_Meter] AS [GM]
WHERE [GM].[Adresse] LIKE @{nameof(model.Token)};
-----------------------------------------------------------------------------
-- 5. TAKE ORDERS INFO ------------------------------------------------------
-----------------------------------------------------------------------------
SELECT DISTINCT
[KN].[KundenNr] AS [CustomerNo]
, [KN].[Name] AS [Customer]
, [AP].[FertigungsauftragNr] AS [ProductionOrderNo]
, [APS].[AuftragNr] AS [CustomerOrderNo]
, [APS].[PositionNr] AS [PosNo]
, [APS].[SerienNr] AS [SerialNo]
, [APS].[KundeneigeneSerienNr] AS [CustomerSerialNo]
, [IDN].[KurzBez] AS [KurzBez]
, [IDN].[Typ] AS [Typ]
, [IDN].[Nennweite] AS [Nennweite]
, [IDN].[Baulaenge] AS [Baulaenge]
, [AP].[Menge] AS [Quantity]
, [APS].[FabNr] AS [FabricNo]
, [IDN].[IdentNr] AS [IdentNr]
, [PCBS].[MapPcbIdToSerialNumber_PcbId] AS [PcbId]
, [ER].[Adresse] AS [ErRadioAddress]
, [GM].[Adresse] AS [GmRadioAddress]
FROM [AuftragPositionSerienNr] AS [APS]
LEFT JOIN [AuftragPosition_Gesamt] AS [AP]
ON [AP].[AuftragNr] = [APS].[AuftragNr]
AND [AP].[PositionNr] = [APS].[PositionNr]
LEFT JOIN [Auftrag_Gesamt] AS [AG]
ON [AG].[AuftragNr] = [APS].[AuftragNr]
LEFT JOIN [Kunde] AS [KN]
ON [KN].[KundenNr] = [AG].[KundenNr]
LEFT JOIN [Identnr] AS [IDN]
ON [IDN].[IdentNr] = [AP].[Identnr]
LEFT JOIN [MapPcbIdToSerialNumber] AS [PCBS]
ON [PCBS].[MapPcbIdToSerialNumber_SerialNumber] = [APS].[SerienNr]
LEFT JOIN [eRegister] AS [ER]
ON [ER].[Seriennummer] = [APS].[SerienNr]
LEFT JOIN [Genesis_Meter] AS [GM]
ON [GM].[Seriennummer] = [APS].[SerienNr]
WHERE [APS].[SerienNr] IN (SELECT [Nr] FROM @serienNr)")
.SetParameter(nameof(model.Token), $"%{model.Token}%")
.ExecuteReader(reader => this.ToWildcardResult(reader, requiredFields));
return ordersFound;
}
public IEnumerable<string> Options()
=> new string[]
{
"CustomerNo",
"Customer",
"ProductionOrderNo",
"CustomerOrderNo",
"PosNo",
"SerialNo",
"CustomerSerialNo",
"KurzBez",
"Typ",
"Nennweite",
"Baulaenge",
"Quantity",
"FabricNo",
"IdentNr",
"PcbId",
"ErRadioAddress",
"GmRadioAddress",
};
internal WildcardResult ToWildcardResult(ISQLReader reader, IEnumerable<string> fields)
{
var wildcardResult = new WildcardResult();
foreach (var field in fields)
{
wildcardResult[field] = reader.GetValue(field);
}
return wildcardResult;
}
}
}
@@ -0,0 +1,650 @@
namespace LaaProduction.Services
{
using LaaProductionSQL.Interfaces;
using LaaProduction.Services.Interfaces;
using LaaProduction.Services.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class ShipmentsService : IShipmentsService
{
private readonly ISQLConnection sqlConnection;
public ShipmentsService(ISQLConnection sqlConnection)
=> this.sqlConnection = sqlConnection;
public OrderScanModel DeletePalletEntry(int id)
=> this.sqlConnection
.CreateCommand($@"
DELETE
FROM [PalettenScan]
OUTPUT [deleted].[AuftragNr]
, [deleted].[PositionNr]
, [deleted].[PalettenNr]
WHERE [ID] = @{nameof(id)}")
.SetParameter(nameof(id), id)
.FirstOrDefault(x => new OrderScanModel
{
OrderNr = x.GetInt(),
PositionNr = x.GetInt(),
PalletNr = x.GetSmallint()
});
public byte[] LoadBatchBuffer(OrderScanModel model)
{
var palletLoad = this.sqlConnection
.CreateCommand($@"
SELECT [PalettenNr]
, [SerienNr]
FROM [PalettenScan]
WHERE [AuftragNr] = @{nameof(model.OrderNr)}
AND [PositionNr] = @{nameof(model.PositionNr)}
AND [PalettenNr] = @{nameof(model.PalletNr)}
ORDER BY [SerienNr]")
.SetParameter(nameof(model.OrderNr), model.OrderNr)
.SetParameter(nameof(model.PositionNr), model.PositionNr)
.SetParameter(nameof(model.PalletNr), model.PalletNr)
.ExecuteReader(reader => string.Join(",", new string[]
{
reader.GetString(),
reader.GetString(),
}));
var csvContent = string.Join(Environment.NewLine, palletLoad);
return Encoding.UTF8.GetBytes($"Pallet Nr.,Serial Nr.{Environment.NewLine}{csvContent}");
}
public PalletsBatchModel LoadBatchModel(OrderScanModel model)
{
var batchModel = new PalletsBatchModel();
if (model != null && model.OrderNr != null)
{
var orderNo = model.OrderNr.Value;
var positionNo = model.PositionNr > 0 ? model.PositionNr : null;
var palletNo = model.PalletNr > 0 ? model.PalletNr : null;
batchModel = this.LoadBatchModel(orderNo, positionNo, palletNo);
if (positionNo is null)
{
if (this.PalletNrExists(orderNo, palletNo))
{
batchModel.Positions = this.LoadPalletPositions(orderNo, palletNo);
}
else
{
batchModel.Positions = this.LoadLastPalletPositions(orderNo);
}
}
else
{
if (this.SamePallet(orderNo, positionNo, palletNo))
{
batchModel.Positions = this.LoadPalletPosition(orderNo, positionNo, palletNo);
}
else
{
batchModel.Positions = this.LoadLastPalletPosition(orderNo, positionNo);
}
}
}
return batchModel;
}
public IEnumerable<MissingItem> MissingItems()
=> this.sqlConnection
.CreateCommand($@"
DECLARE @PalletOrders TABLE([OrderNo] INT NOT NULL)
INSERT INTO @PalletOrders([OrderNo])
SELECT DISTINCT [AuftragNr] FROM [PalettenScan]
SELECT [result].[Date]
, [result].[OrderNo]
, [result].[PosNo]
, [result].[SerialNo]
, [result].[CustomSerial]
, [result].[Bezeichnung]
, [result].[Type]
FROM (SELECT DISTINCT
CAST(MAX([x].[Date]) AS DATE) AS [Date]
, [x].[OrderNo]
, [x].[PosNo]
, [x].[SerialNo]
, [dbo].[NORMALIZE_SERIAL]([x].[CustomSerialNo]) AS [CustomSerial]
, ([inr].[Typ]
+ ' '
+ CASE WHEN [inr].[Typzusatz] IS NULL
THEN CAST([inr].[Nennweite] AS NVARCHAR(100))
ELSE [inr].[Typzusatz]
+ ' '
+ CAST([inr].[Nennweite] AS NVARCHAR(100))
END) AS [Type]
, [inr].[Bezeichnung]
FROM (SELECT CAST([aps].[AnlageDatum] AS DATE) AS [Date]
, [aps].[AuftragNr] AS [OrderNo]
, [aps].[PositionNr] AS [PosNo]
, [aps].[SerienNr] AS [SerialNo]
, ISNULL([aps].[KundeneigeneSerienNr], [aps].[SerienNr]) AS [CustomSerialNo]
FROM [AuftragPositionSerienNr] AS [aps]
JOIN @PalletOrders AS [po]
ON [po].[OrderNo] = [aps].[AuftragNr]
LEFT JOIN [PalettenScan] AS [ps]
ON [ps].[AuftragNr] = [aps].[AuftragNr]
AND [ps].[PositionNr] = [aps].[PositionNr]
AND [ps].[SerienNr] = [dbo].[NORMALIZE_SERIAL]([aps].[KundeneigeneSerienNr])
WHERE [ps].[SerienNr] IS NULL)
AS [x]
JOIN [AlleAuftragPositionen] AS [aap]
ON [aap].[AuftragNr] = [x].[OrderNo]
AND [aap].[PositionNr] = [x].[PosNo]
JOIN [Identnr] AS [inr]
ON [inr].[IdentNr] = [aap].[IdentNr]
GROUP BY [x].[OrderNo]
, [x].[PosNo]
, [x].[SerialNo]
, [x].[CustomSerialNo]
, [inr].[Typ]
, [inr].[Typzusatz]
, [inr].[Nennweite]
, [inr].[Bezeichnung])
AS [result]
ORDER BY [result].[OrderNo] DESC")
.ExecuteReader(x => new MissingItem
{
EntryDate = x.GetDate(),
OrderNr = x.GetInt(),
PosNr = x.GetSmallint(),
SerialNr = x.GetInt(),
CustomSerial = x.GetString(),
Term = x.GetString(),
Type = x.GetString()
});
private bool PalletNrExists(int orderNo, int? palletNo)
{
var countPalletsByNo = this.sqlConnection
.CreateCommand($@"
SELECT ISNULL(COUNT(1), 0) AS [Found]
FROM [PalettenScan] AS [PS]
WHERE [PS].[AuftragNr] = @{nameof(orderNo)}
AND [PS].[PalettenNr] = @{nameof(palletNo)}")
.SetParameter(nameof(orderNo), orderNo)
.SetParameter(nameof(palletNo), palletNo)
.FirstOrDefault(x => x.GetInt());
return countPalletsByNo > 0;
}
private IEnumerable<PalletPosition> LoadLastPalletPositions(int orderNo)
=> this.sqlConnection
.CreateCommand($@"
DECLARE @palettenNr INT;
SELECT @palettenNr = MAX([PalettenNr])
FROM [PalettenScan]
WHERE [AuftragNr] = @{nameof(orderNo)}
SELECT DISTINCT
[aap].[PositionNr] AS [Pos]
, [in].[Typ] AS [Typ]
, [in].[Typzusatz] AS [Typzusatz]
, [in].[Nennweite] AS [Nennweite]
, (SELECT COUNT(1)
FROM [PalettenScan] AS [x]
WHERE [x].[AuftragNr] = [ps].[AuftragNr]
AND [x].[PositionNr] = [ps].[PositionNr]
AND [x].[PalettenNr] = [ps].[PalettenNr])
, (SELECT TOP 1 [Menge]
FROM [AlleAuftragPositionen] AS [x]
WHERE [x].[AuftragNr] = [aap].[AuftragNr]
AND [x].[PositionNr] = [aap].[PositionNr])
, [aap].[AuftragNr]
, [aap].[PositionNr]
, [ps].[PalettenNr]
FROM [Identnr] AS [in]
JOIN [AlleAuftragPositionen] AS [aap]
ON [aap].[IdentNr] = [in].[IdentNr]
LEFT JOIN [PalettenScan] AS [ps]
ON [ps].[AuftragNr] = [aap].[AuftragNr]
AND [ps].[PositionNr] = [aap].[PositionNr]
WHERE [aap].[AuftragNr] = @{nameof(orderNo)}
AND [ps].[PalettenNr] = @palettenNr")
.SetParameter(nameof(orderNo), orderNo)
.ExecuteReader(x => new PalletPosition
{
PositionNr = x.GetSmallint(),
Description = string
.Join(" ", new[] { x.GetString(), x.GetString(), x.GetString() }
.Where(s => !string.IsNullOrWhiteSpace(s))),
ItemsCount = x.GetInt(),
TotalItemsCount = x.GetInt(),
Items = this.LoadPalletItems(x.GetInt(), x.GetSmallint(), x.GetSmallint())
});
private IEnumerable<PalletPosition> LoadPalletPositions(int orderNo, int? palletNo)
=> this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT
[aap].[PositionNr] AS [Pos]
, [in].[Typ] AS [Typ]
, [in].[Typzusatz] AS [Typzusatz]
, [in].[Nennweite] AS [Nennweite]
, (SELECT COUNT(1)
FROM [PalettenScan] AS [x]
WHERE [x].[AuftragNr] = [ps].[AuftragNr]
AND [x].[PositionNr] = [ps].[PositionNr]
AND [x].[PalettenNr] = [ps].[PalettenNr])
, (SELECT TOP 1 [Menge]
FROM [AlleAuftragPositionen] AS [x]
WHERE [x].[AuftragNr] = [aap].[AuftragNr]
AND [x].[PositionNr] = [aap].[PositionNr])
, [aap].[AuftragNr]
, [aap].[PositionNr]
, [ps].[PalettenNr]
FROM [Identnr] AS [in]
JOIN [AlleAuftragPositionen] AS [aap]
ON [aap].[IdentNr] = [in].[IdentNr]
LEFT JOIN [PalettenScan] AS [ps]
ON [ps].[AuftragNr] = [aap].[AuftragNr]
AND [ps].[PositionNr] = [aap].[PositionNr]
WHERE [aap].[AuftragNr] = @{nameof(orderNo)}
AND [ps].[PalettenNr] = @{nameof(palletNo)}")
.SetParameter(nameof(orderNo), orderNo)
.SetParameter(nameof(palletNo), palletNo)
.ExecuteReader(x => new PalletPosition
{
PositionNr = x.GetSmallint(),
Description = string
.Join(" ", new[] { x.GetString(), x.GetString(), x.GetString() }
.Where(s => !string.IsNullOrWhiteSpace(s))),
ItemsCount = x.GetInt(),
TotalItemsCount = x.GetInt(),
Items = this.LoadPalletItems(x.GetInt(), x.GetSmallint(), x.GetSmallint())
});
private bool SamePallet(int orderNo, int? positionNo, int? palletNo)
{
var countPalletsByNo = this.sqlConnection
.CreateCommand($@"
SELECT ISNULL(COUNT(1), 0) AS [Found]
FROM [PalettenScan] AS [PS]
WHERE [PS].[AuftragNr] = @{nameof(orderNo)}
AND [PS].[PositionNr] = @{nameof(positionNo)}
AND [PS].[PalettenNr] = @{nameof(palletNo)}")
.SetParameter(nameof(orderNo), orderNo)
.SetParameter(nameof(positionNo), positionNo)
.SetParameter(nameof(palletNo), palletNo)
.FirstOrDefault(x => x.GetInt());
return countPalletsByNo > 0;
}
private IEnumerable<PalletPosition> LoadLastPalletPosition(int orderNo, int? positionNo)
=> this.sqlConnection
.CreateCommand($@"
DECLARE @palettenNr INT;
SELECT @palettenNr = MAX([PalettenNr])
FROM [PalettenScan]
WHERE [AuftragNr] = @{nameof(orderNo)}
AND [PositionNr] = @{nameof(positionNo)}
SELECT DISTINCT
[aap].[PositionNr] AS [Pos]
, [in].[Typ] AS [Typ]
, [in].[Typzusatz] AS [Typzusatz]
, [in].[Nennweite] AS [Nennweite]
, (SELECT COUNT(1)
FROM [PalettenScan] AS [x]
WHERE [x].[AuftragNr] = [ps].[AuftragNr]
AND [x].[PositionNr] = [ps].[PositionNr]
AND [x].[PalettenNr] = [ps].[PalettenNr])
, (SELECT TOP 1 [Menge]
FROM [AlleAuftragPositionen] AS [x]
WHERE [x].[AuftragNr] = [aap].[AuftragNr]
AND [x].[PositionNr] = [aap].[PositionNr])
, [aap].[AuftragNr]
, [aap].[PositionNr]
, [ps].[PalettenNr]
FROM [Identnr] AS [in]
JOIN [AlleAuftragPositionen] AS [aap]
ON [aap].[IdentNr] = [in].[IdentNr]
LEFT JOIN [PalettenScan] AS [ps]
ON [ps].[AuftragNr] = [aap].[AuftragNr]
AND [ps].[PositionNr] = [aap].[PositionNr]
WHERE [aap].[AuftragNr] = @{nameof(orderNo)}
AND ([ps].[PalettenNr] = @palettenNr
OR [aap].[PositionNr] = @{nameof(positionNo)})")
.SetParameter(nameof(orderNo), orderNo)
.SetParameter(nameof(positionNo), positionNo)
.ExecuteReader(x => new PalletPosition
{
PositionNr = x.GetSmallint(),
Description = string
.Join(" ", new[] { x.GetString(), x.GetString(), x.GetString() }
.Where(s => !string.IsNullOrWhiteSpace(s))),
ItemsCount = x.GetInt(),
TotalItemsCount = x.GetInt(),
Items = this.LoadPalletItems(x.GetInt(), x.GetSmallint(), x.GetSmallint())
});
private IEnumerable<PalletPosition> LoadPalletPosition(int orderNo, int? positionNo, int? palletNo)
=> this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT
[aap].[PositionNr] AS [Pos]
, [in].[Typ] AS [Typ]
, [in].[Typzusatz] AS [Typzusatz]
, [in].[Nennweite] AS [Nennweite]
, (SELECT COUNT(1)
FROM [PalettenScan] AS [x]
WHERE [x].[AuftragNr] = [ps].[AuftragNr]
AND [x].[PositionNr] = [ps].[PositionNr]
AND [x].[PalettenNr] = [ps].[PalettenNr])
, (SELECT TOP 1 [Menge]
FROM [AlleAuftragPositionen] AS [x]
WHERE [x].[AuftragNr] = [aap].[AuftragNr]
AND [x].[PositionNr] = [aap].[PositionNr])
, [aap].[AuftragNr]
, [aap].[PositionNr]
, [ps].[PalettenNr]
FROM [Identnr] AS [in]
JOIN [AlleAuftragPositionen] AS [aap]
ON [aap].[IdentNr] = [in].[IdentNr]
LEFT JOIN [PalettenScan] AS [ps]
ON [ps].[AuftragNr] = [aap].[AuftragNr]
AND [ps].[PositionNr] = [aap].[PositionNr]
WHERE [aap].[AuftragNr] = @{nameof(orderNo)}
AND [ps].[PositionNr] = @{nameof(positionNo)}
AND [ps].[PalettenNr] = @{nameof(palletNo)}")
.SetParameter(nameof(orderNo), orderNo)
.SetParameter(nameof(positionNo), positionNo)
.SetParameter(nameof(palletNo), palletNo)
.ExecuteReader(x => new PalletPosition
{
PositionNr = x.GetSmallint(),
Description = string
.Join(" ", new[] { x.GetString(), x.GetString(), x.GetString() }
.Where(s => !string.IsNullOrWhiteSpace(s))),
ItemsCount = x.GetInt(),
TotalItemsCount = x.GetInt(),
Items = this.LoadPalletItems(x.GetInt(), x.GetSmallint(), x.GetSmallint())
});
private IEnumerable<SerialNr> LoadPalletItems(int orderNo, int posNo, int palletNr)
=> this.sqlConnection
.CreateCommand($@"
SELECT [x].[Id] AS [Id]
, [x].[PositionNr] AS [Pos]
, [x].[Serial] AS [Serial]
, [x].[CustomerSerial] AS [CustomerSerial]
, [x].[IsScanned] AS [IsScanned]
FROM (SELECT DISTINCT
[ps].[ID] AS [Id]
, [aps].[PositionNr] AS [PositionNr]
, [aps].[SerienNr] AS [Serial]
, ISNULL([dbo].[NORMALIZE_SERIAL]([aps].[KundeneigeneSerienNr]), [aps].[SerienNr]) AS [CustomerSerial]
, CAST(CASE WHEN [ps].[Datum] IS NOT NULL THEN 1 ELSE 0 END AS BIT) AS [IsScanned]
, [ps].[Datum] AS [DateAdded]
FROM [AuftragPositionSerienNr] AS [aps]
LEFT JOIN [PalettenScan] AS [ps]
ON [ps].[AuftragNr] = [aps].[AuftragNr]
AND [ps].[PositionNr] = [aps].[PositionNr]
AND [ps].[SerienNr] = [dbo].[NORMALIZE_SERIAL]([aps].[KundeneigeneSerienNr])
AND [ps].[PalettenNr] = @{nameof(palletNr)}
WHERE [aps].[AuftragNr] = @{nameof(orderNo)}
AND [aps].[PositionNr] = @{nameof(posNo)}
AND [dbo].[NORMALIZE_SERIAL]([aps].[KundeneigeneSerienNr])
NOT IN (SELECT [SerienNr]
FROM [PalettenScan]
WHERE [AuftragNr] = @{nameof(orderNo)}
AND [PositionNr] = @{nameof(posNo)}
AND [PalettenNr] != @{nameof(palletNr)}))
AS [x]
ORDER BY [x].[IsScanned] DESC
, [x].[CustomerSerial]")
.SetParameter(nameof(orderNo), orderNo)
.SetParameter(nameof(posNo), posNo)
.SetParameter(nameof(palletNr), palletNr)
.ExecuteReader(x => new SerialNr
{
Id = x.GetInt(),
PositionNr = x.GetSmallint(),
Serial = x.GetInt(),
CustomerSerial = x.GetString(),
IsScanned = x.GetBool(),
PalletNr = palletNr
});
private PalletsBatchModel LoadBatchModel(int orderNo, int? posNo, int? palletNo)
{
var batchModel = this.sqlConnection
.CreateCommand($@"
SELECT TOP 1
[AAP].[AuftragNr]
, [AAP].[FertigungsauftragNr]
, [Kunde].[Name]
, [AAP].[ZusatzText]
FROM [AlleAuftragPositionen] AS [AAP]
JOIN [Kunde] ON [Kunde].[KundenNr] = [AAP].[KundenNr]
WHERE [AAP].[AuftragNr] = @{nameof(orderNo)}
ORDER BY [AAP].[FertigungsauftragNr] DESC")
.SetParameter(nameof(orderNo), orderNo)
.SetParameter(nameof(posNo), posNo)
.FirstOrDefault(reader => new PalletsBatchModel
{
OrderNr = reader.GetInt(),
ProductionOrderNr = reader.GetInt(),
Customer = reader.GetString(),
AdditionalText = reader.GetString()
});
return batchModel ?? new PalletsBatchModel();
}
public OrderScanModel LoadPallets(OrderScanModel model)
{
if (model != null && model.OrderNr != null && model.OrderNr > 0)
{
var pallets = this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT
[PSI].[PalettenNr]
, CAST(CASE WHEN [PSII].[ID] IS NULL
THEN 0
ELSE 1
END AS BIT)
FROM [PalettenScan] AS [PSI]
LEFT JOIN [PalettenScan] AS [PSII]
ON [PSII].[ID] = [PSI].[ID]
AND [PSII].[PositionNr] = @{nameof(model.PositionNr)}
WHERE [PSI].[AuftragNr] = @{nameof(model.OrderNr)}
ORDER BY [PSI].[PalettenNr]")
.SetParameter(nameof(model.OrderNr), model.OrderNr)
.SetParameter(nameof(model.PositionNr), model.PositionNr)
.ExecuteReader(reader => new KeyValuePair<int, bool>(
key: reader.GetValue<short>(),
value: reader.GetValue<bool>()));
model.UpdatePallets(pallets);
model.Positions = this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT [x].[PositionNr]
FROM [AlleAuftragPositionen] AS [x]
WHERE [x].[AuftragNr] = @{nameof(model.OrderNr)}
ORDER BY [x].[PositionNr]")
.SetParameter(nameof(model.OrderNr), model.OrderNr)
.ExecuteReader(reader => (int)reader.GetSmallint());
}
return model;
}
public Result UpdateBatchModel(OrderScanModel model)
{
if (!string.IsNullOrWhiteSpace(model.SerialNr))
{
var orderIdentity = this.UpdateOrderIdentifiers(model.OrderNr, model.PositionNr, model.SerialNr);
if (orderIdentity is null)
{
orderIdentity = this.UpdateOrderIdentifiersGenesisMetterRadioAddresses(model.SerialNr);
}
if (orderIdentity is null)
{
orderIdentity = this.UpdateOrderIdentifiersERegisterRadioAddresses(model.SerialNr);
}
if (orderIdentity is null || orderIdentity.OrderNr != model.OrderNr)
{
return $"Wasserzähler mit Serien-Nr: {model.SerialNr} ist nicht dem Auftrag/Position: {model.OrderNr}/{model.PositionNr} zugewiesen.";
}
model.SerialNr = orderIdentity.CustomerSerialNr;
model.PositionNr = orderIdentity.PositionNr;
if (this.PalletsEntryExists(model.OrderNr, model.PositionNr, model.SerialNr))
{
return $"Wasserzähler mit Serien-Nr: {model.SerialNr} wurde bereits hinzugefügt.";
}
var rowsAffected = this.InsertPalletEntry(model);
return rowsAffected == 1;
}
return false;
}
private OrderIdentity UpdateOrderIdentifiers(int? orderNr, int? positionNr, string serialNr)
=> this.sqlConnection
.CreateCommand($@"
SELECT DISTINCT TOP 1
[APS].[PositionNr]
, [APS].[SerienNr]
, ISNULL(REPLACE(RTRIM(LTRIM([APS].[KundeneigeneSerienNr])), ' ', ''), [APS].[SerienNr])
FROM [AuftragPositionSerienNr] AS [APS]
WHERE [APS].[AuftragNr] = @{nameof(orderNr)}
AND ([APS].[PositionNr] = @{nameof(positionNr)} OR @{nameof(positionNr)} IS NULL)
AND @{nameof(serialNr)} LIKE '%' + (REPLACE(RTRIM(LTRIM([APS].[KundeneigeneSerienNr])), ' ', '')) + '%'")
.SetParameter(nameof(orderNr), orderNr)
.SetParameter(nameof(positionNr), positionNr)
.SetParameter(nameof(serialNr), serialNr)
.FirstOrDefault(reader => new OrderIdentity
{
OrderNr = orderNr ?? -1,
PositionNr = reader.GetSmallint(),
SerialNr = reader.GetInt(),
CustomerSerialNr = reader.GetString(),
});
private OrderIdentity UpdateOrderIdentifiersGenesisMetterRadioAddresses(string address)
=> this.sqlConnection
.CreateCommand($@"
DECLARE @serialNo NVARCHAR(50)
--------------------------------------------------------------------------
-- 1. FIND SERIAL-NO BY ADDRESS ------------------------------------------
--------------------------------------------------------------------------
SELECT TOP 1
@serialNo = [x].[Seriennummer]
FROM [Genesis_Meter] AS [x]
WHERE @{nameof(address)} LIKE '%' + CAST([x].[Adresse] AS NVARCHAR(50)) + '%'
ORDER BY [x].[Adresse] DESC
--------------------------------------------------------------------------
-- 2. FIND ORDER INFO ----------------------------------------------------
--------------------------------------------------------------------------
SELECT TOP 1
[APS].[AuftragNr] AS [AuftragNr]
, [APS].[PositionNr] AS [PositionNr]
, [APS].[SerienNr] AS [SerienNr]
, ISNULL(REPLACE(RTRIM(LTRIM([APS].[KundeneigeneSerienNr])), ' ', ''), [APS].[SerienNr]) AS [KundeneigeneSerienNr]
FROM [AuftragPositionSerienNr] AS [APS]
WHERE [APS].[SerienNr] = @serialNo")
.SetParameter(nameof(address), address)
.FirstOrDefault(x => new OrderIdentity
{
OrderNr = x.GetInt(),
PositionNr = x.GetSmallint(),
SerialNr = x.GetInt(),
CustomerSerialNr = x.GetString(),
});
private OrderIdentity UpdateOrderIdentifiersERegisterRadioAddresses(string address)
=> this.sqlConnection
.CreateCommand($@"
DECLARE @serialNo NVARCHAR(50)
--------------------------------------------------------------------------
-- 1. FIND SERIAL-NO BY ADDRESS ------------------------------------------
--------------------------------------------------------------------------
SELECT TOP 1
@serialNo = [x].[Seriennummer]
FROM [eRegister] AS [x]
WHERE @{nameof(address)} LIKE '%' + CAST([x].[Adresse] AS NVARCHAR(50)) + '%'
ORDER BY [x].[Adresse] DESC
--------------------------------------------------------------------------
-- 2. FIND ORDER INFO ----------------------------------------------------
--------------------------------------------------------------------------
SELECT TOP 1
[APS].[AuftragNr] AS [AuftragNr]
, [APS].[PositionNr] AS [PositionNr]
, [APS].[SerienNr] AS [SerienNr]
, ISNULL(REPLACE(RTRIM(LTRIM([APS].[KundeneigeneSerienNr])), ' ', ''), [APS].[SerienNr]) AS [KundeneigeneSerienNr]
FROM [AuftragPositionSerienNr] AS [APS]
WHERE [APS].[SerienNr] = @serialNo")
.SetParameter(nameof(address), address)
.FirstOrDefault(x => new OrderIdentity
{
OrderNr = x.GetInt(),
PositionNr = x.GetSmallint(),
SerialNr = x.GetInt(),
CustomerSerialNr = x.GetString(),
});
private int InsertPalletEntry(OrderScanModel model)
=> this.sqlConnection
.CreateCommand($@"
INSERT
INTO [PalettenScan] (
[PalettenNr]
, [AuftragNr]
, [PositionNr]
, [SerienNr]
, [Host]
, [Platz]
, [Datum])
VALUES (@{nameof(model.PalletNr)}
, @{nameof(model.OrderNr)}
, @{nameof(model.PositionNr)}
, @{nameof(model.SerialNr)}
, @{nameof(model.Host)}
, @{nameof(model.Place)}
, GETDATE())")
.SetParameter(nameof(model.PalletNr), model.PalletNr)
.SetParameter(nameof(model.OrderNr), model.OrderNr)
.SetParameter(nameof(model.PositionNr), model.PositionNr)
.SetParameter(nameof(model.SerialNr), model.SerialNr)
.SetParameter(nameof(model.Host), model.Host)
.SetParameter(nameof(model.Place), model.Place)
.ExecuteNonQuery();
private bool PalletsEntryExists(int? orderNr, int? positionNr, string serialNr)
=> this.sqlConnection
.CreateCommand($@"
SELECT CAST(CASE WHEN [PalettenScan].[ID] IS NULL THEN 0 ELSE 1 END AS BIT)
FROM [PalettenScan]
WHERE [PalettenScan].[AuftragNr] = @{nameof(orderNr)}
AND [PalettenScan].[PositionNr] = @{nameof(positionNr)}
AND [PalettenScan].[SerienNr] = @{nameof(serialNr)}")
.SetParameter(nameof(orderNr), orderNr)
.SetParameter(nameof(positionNr), positionNr)
.SetParameter(nameof(serialNr), serialNr)
.FirstOrDefault(x => x.GetBool());
}
}
@@ -0,0 +1,393 @@
namespace LaaProduction.Services
{
using LaaProductionSQL.Interfaces;
using LaaProduction.Services.Interfaces;
using LaaProduction.Services.Models.Software;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
public class SoftwareService : ISoftwareService
{
private readonly ISQLConnection sqlConnection;
public SoftwareService(ISQLConnection sqlConnection)
=> this.sqlConnection = sqlConnection;
public void AddFunction(short appId, string name)
=> this.sqlConnection
.CreateCommand($@"
INSERT INTO [SoftwareFunctions] (
[AppId]
, [Function])
VALUES (@{nameof(appId)}
, @{nameof(name)})")
.SetParameter(nameof(appId), appId)
.SetParameter(nameof(name), name)
.ExecuteNonQuery();
public int ApplicationId(string name)
=> this.sqlConnection
.CreateCommand($@"
SELECT TOP 1 [AppId]
FROM [VersionSoftwareAccess]
WHERE [SoftwareAccess_Program] = @{nameof(name)}")
.SetParameter(nameof(name), name)
.FirstOrDefault(x => x.GetSmallint());
public void DeleteFunction(int funcId)
{
this.sqlConnection
.CreateCommand($@"
DELETE FROM [SoftwareFunctions]
WHERE [Id] = @{nameof(funcId)}")
.SetParameter(nameof(funcId), funcId)
.ExecuteNonQuery();
this.sqlConnection
.CreateCommand($@"
DELETE FROM [UsersFunctions]
WHERE [SoftwareFunctionId] = @{nameof(funcId)}")
.SetParameter(nameof(funcId), funcId)
.ExecuteNonQuery();
}
public short FindAndUpdateSoftware(string windowsUser, string name, IEnumerable<string> functions)
{
var appId = this.sqlConnection
.CreateCommand($@"
SELECT TOP 1 [AppId]
, MAX([SoftwareAccess_VaildTo]) OVER (PARTITION BY [AppId])
FROM [VersionSoftwareAccess]
WHERE [SoftwareAccess_Program] = @{nameof(name)}
AND [SoftwareAccess_VaildTo] > GETDATE()")
.SetParameter(nameof(name), name)
.FirstOrDefault(x => x.GetSmallint());
if (appId > 0)
{
if (functions != null && functions.Any())
{
foreach (var function in functions)
{
if (Regex.IsMatch(function, "[a-zA-Z_]+"))
{
this.AddFunction(appId, function);
}
}
}
}
return appId;
}
public IEnumerable<SoftwareFunction> GetAllSoftwareFunctions()
=> this.sqlConnection
.CreateCommand($@"
SELECT [Id]
, [AppId]
, [Function]
FROM [SoftwareFunctions]")
.ExecuteReader(f => new SoftwareFunction
{
Id = f.GetInt(),
AppId = f.GetSmallint(),
Function = f.GetString()
});
public IEnumerable<SoftwareFunction> GetSoftwareFunctions(short appId)
=> this.sqlConnection
.CreateCommand($@"
SELECT [Id]
, [AppId]
, [Function]
FROM [SoftwareFunctions]
WHERE [AppId] = @{nameof(appId)}")
.SetParameter(nameof(appId), appId)
.ExecuteReader(f => new SoftwareFunction
{
Id = f.GetInt(),
AppId = f.GetSmallint(),
Function = f.GetString()
});
public IEnumerable<string> GetSoftwareFunctions(short appId, short userId)
=> this.sqlConnection
.CreateCommand($@"
SELECT [SF].[Function] AS [Function]
FROM [UsersFunctions] AS [UF]
JOIN [SoftwareFunctions] AS [SF]
ON [SF].[Id] = [UF].[SoftwareFunctionId]
WHERE [UF].[UserId] = @{nameof(userId)}
AND [SF].[AppId] = @{nameof(appId)}")
.SetParameter(nameof(appId), appId)
.SetParameter(nameof(userId), userId)
.ExecuteReader(x => x.GetString());
public SoftwareOverview GetSoftwareOverview(short appId)
=> this.sqlConnection
.CreateCommand($@"
SELECT [vsa].[AppID]
, [vsa].[SoftwareAccess_Program]
, COUNT([vsa].[AppID])
, (SELECT COUNT(1)
FROM [SoftwareFunctions]
WHERE [AppId] = [vsa].[AppID]) AS [CountF]
FROM [VersionSoftwareAccess] AS [vsa]
WHERE [vsa].[AppID] = @{nameof(appId)}
GROUP BY [vsa].[AppID]
, [vsa].[SoftwareAccess_Program]")
.SetParameter(nameof(appId), appId)
.FirstOrDefault(x => new SoftwareOverview
{
AppId = x.GetSmallint(),
Name = x.GetString(),
Versions = x.GetInt(),
Functions = x.GetInt()
});
public IEnumerable<Software> GetSoftwareVersions(short appId)
=> this.sqlConnection
.CreateCommand($@"
SELECT [SoftwareAccess_ID]
, [AppID]
, [SoftwareAccess_Program]
, [SoftwareAccess_MajorVersion]
, [SoftwareAccess_MinorVersion]
, [SoftwareAccess_BuildVersion]
, [SoftwareAccess_VaildTo]
, [SoftwareAccess_Desc]
FROM [VersionSoftwareAccess]
WHERE [AppId] = @{nameof(appId)}
ORDER BY [SoftwareAccess_VaildTo] DESC
, [SoftwareAccess_MajorVersion] DESC
, [SoftwareAccess_MinorVersion] DESC
, [SoftwareAccess_BuildVersion] DESC")
.SetParameter(nameof(appId), appId)
.ExecuteReader(x => new Software
{
Id = x.GetInt(),
AppId = x.GetSmallint(),
FullName = x.GetString(),
MajorV = x.GetInt(),
MinorV = x.GetInt(),
BuildV = x.GetInt(),
ValidTo = x.GetDate(),
Description = x.GetString()
});
public IEnumerable<SoftwareOverview> GetSoftwares()
=> this.sqlConnection
.CreateCommand(@"
SELECT [VSA].[AppId] AS [AppId]
, [VSA].[SoftwareAccess_Program] AS [Program]
, COUNT([VSA].[AppId]) AS [Versions]
, (SELECT COUNT(1)
FROM [SoftwareFunctions]
WHERE [AppId] = [VSA].[AppID]) AS [Functions]
FROM [VersionSoftwareAccess] AS [VSA]
GROUP BY [VSA].[AppId]
, [VSA].[SoftwareAccess_Program]")
.ExecuteReader(x => new SoftwareOverview
{
AppId = x.GetSmallint(),
Name = x.GetString(),
Versions = x.GetInt(),
Functions = x.GetInt(),
});
public IEnumerable<SoftwareUser> GetUsers(string username = null)
=> this.sqlConnection
.CreateCommand($@"
SELECT [U].[MitarbeiterNr]
, [U].[Vorname]
, [U].[Name]
, [U].[Benutzername]
, COUNT([UF].[UserId])
, CAST(CASE WHEN [U].[PasswordHash] IS NULL THEN 0 ELSE 1 END AS BIT)
FROM [Mitarbeiter] AS [U]
LEFT JOIN [UsersFunctions] AS [UF]
ON [UF].[UserId] = [U].[MitarbeiterNr]
WHERE [U].[Vorname] LIKE @{nameof(username)}
OR [U].[Name] LIKE @{nameof(username)}
OR [U].[Benutzername] LIKE @{nameof(username)}
GROUP BY [U].[MitarbeiterNr]
, [U].[Vorname]
, [U].[Name]
, [U].[Benutzername]
, [U].[PasswordHash]
ORDER BY [U].[Vorname]
, [U].[Name]
, [U].[Benutzername]")
.SetParameter(nameof(username), $"%{username}%")
.ExecuteReader(x => new SoftwareUser
{
Id = x.GetSmallint(),
FirstName = x.GetString(),
LastName = x.GetString(),
Username = x.GetString(),
FunctionsCount = x.GetInt(),
HasPassword = x.GetBool()
});
public IEnumerable<SoftwareUser> GetUsersWithFunctions(int userId = -1, string username = null)
=> this.sqlConnection
.CreateCommand($@"
SELECT [U].[MitarbeiterNr]
, [U].[Vorname]
, [U].[Name]
, [U].[Benutzername]
, COUNT([UF].[UserId])
, CAST(CASE WHEN [U].[PasswordHash] IS NULL THEN 0 ELSE 1 END AS BIT)
, (SELECT CAST([SoftwareFunctionId] * -1 AS VARCHAR(MAX))
FROM [UsersFunctions]
WHERE [UserId] = [UF].[UserId]
ORDER BY [SoftwareFunctionId]
FOR XML PATH (''))
FROM [Mitarbeiter] AS [U]
LEFT JOIN [UsersFunctions] AS [UF]
ON [UF].[UserId] = [U].[MitarbeiterNr]
WHERE [U].[Vorname] LIKE @{nameof(username)}
OR [U].[Name] LIKE @{nameof(username)}
OR [U].[Benutzername] LIKE @{nameof(username)}
OR [U].[MitarbeiterNr] = @{nameof(userId)}
GROUP BY [U].[MitarbeiterNr]
, [U].[Vorname]
, [U].[Name]
, [U].[Benutzername]
, [U].[PasswordHash]
, [UF].[UserId]
ORDER BY [U].[Vorname]
, [U].[Name]
, [U].[Benutzername]")
.SetParameter(nameof(username), $"%{username}%")
.SetParameter(nameof(userId), userId)
.ExecuteReader(x => new SoftwareUser
{
Id = x.GetSmallint(),
FirstName = x.GetString(),
LastName = x.GetString(),
Username = x.GetString(),
FunctionsCount = x.GetInt(),
HasPassword = x.GetBool(),
Functions = x.GetString()
});
public void UpdateFunction(int funcId, string name)
=> this.sqlConnection
.CreateCommand($@"
UPDATE [SoftwareFunctions]
SET [Function] = @{nameof(name)}
WHERE [Id] = @{nameof(funcId)}")
.SetParameter(nameof(funcId), funcId)
.SetParameter(nameof(name), name)
.ExecuteNonQuery();
public void UpdatePasswordHashes()
{
var pwdUsers = this.sqlConnection
.CreateCommand($@"
SELECT [MitarbeiterNr]
, [Kennwort]
FROM [Mitarbeiter]
WHERE [Kennwort] IS NOT NULL
AND [PasswordHash] IS NULL")
.ExecuteReader(x => new KeyValuePair<short, string>(
key: x.GetSmallint(),
value: x.GetString()));
var sha256 = SHA256.Create();
foreach (var kvp in pwdUsers)
{
var userId = kvp.Key;
var password = sha256.ComputeHash(kvp.Value);
this.sqlConnection
.CreateCommand($@"
UPDATE [Mitarbeiter]
SET [PasswordHash] = @{nameof(password)}
WHERE [MitarbeiterNr] = @{nameof(userId)}")
.SetParameter(nameof(userId), userId)
.SetParameter(nameof(password), password)
.ExecuteNonQuery();
}
}
public int ResetPassword(short userId)
=> this.sqlConnection
.CreateCommand($@"
UPDATE [Mitarbeiter]
SET [PasswordHash] = NULL
WHERE [MitarbeiterNr] = @{nameof(userId)}")
.SetParameter(nameof(userId), userId)
.ExecuteNonQuery();
public int ResetPassword(short userId, string password)
{
password = SHA256.Create().ComputeHash(password);
return this.sqlConnection
.CreateCommand($@"
UPDATE [Mitarbeiter]
SET [PasswordHash] = @{nameof(password)}
WHERE [MitarbeiterNr] = @{nameof(userId)}")
.SetParameter(nameof(userId), userId)
.SetParameter(nameof(password), password)
.ExecuteNonQuery();
}
public void UpdateUsersFunctions(Action<UserFunctions> mapper)
{
var model = new UserFunctions();
mapper(model);
var userId = model.UserId;
this.sqlConnection
.CreateCommand($@"DELETE FROM [UsersFunctions] WHERE [UserId] = @{nameof(userId)}")
.SetParameter(nameof(userId), userId)
.ExecuteNonQuery();
foreach (var funcId in model.Functions ?? Array.Empty<int>())
{
this.sqlConnection
.CreateCommand($@"
INSERT
INTO [UsersFunctions] ([UserId] ,[SoftwareFunctionId])
VALUES (@{nameof(userId)}, @{nameof(funcId)})")
.SetParameter(nameof(userId), userId)
.SetParameter(nameof(funcId), funcId)
.ExecuteNonQuery();
}
}
public void UpdateUsersFunctions(Action<FunctionUsers> mapper)
{
var model = new FunctionUsers();
mapper(model);
var funcId = model.FunctionId;
this.sqlConnection
.CreateCommand($@"DELETE FROM [UsersFunctions] WHERE [SoftwareFunctionId] = @{nameof(funcId)}")
.SetParameter(nameof(funcId), funcId)
.ExecuteNonQuery();
foreach (var userId in model.Users ?? Array.Empty<short>())
{
this.sqlConnection
.CreateCommand($@"
INSERT
INTO [UsersFunctions] ([UserId] ,[SoftwareFunctionId])
VALUES (@{nameof(userId)}, @{nameof(funcId)})")
.SetParameter(nameof(userId), userId)
.SetParameter(nameof(funcId), funcId)
.ExecuteNonQuery();
}
}
}
}