Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4dc8e19ed8 | ||
|
|
34556e32dc | ||
|
|
e397c9d73d |
No files matched your search
@@ -2,7 +2,7 @@ name: Test
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: ["**"]
|
branches: ["**"]
|
||||||
paths: ["Elwig/**", "Tests/**", ".gitea/workflows/test.yaml"]
|
paths: ["Elwig/**", "Tests/**", "Installer/Files/*.exe", ".gitea/workflows/test.yaml"]
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
name: Run tests
|
name: Run tests
|
||||||
|
|||||||
+364
-630
File diff suppressed because it is too large.
Load diff
+8
-1
@@ -2,11 +2,18 @@
|
|||||||
x:Class="Elwig.App"
|
x:Class="Elwig.App"
|
||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:ctrl="clr-namespace:Elwig.Controls">
|
xmlns:ctrl="clr-namespace:Elwig.Controls"
|
||||||
|
Exit="Application_Exit">
|
||||||
<Application.Resources>
|
<Application.Resources>
|
||||||
<ctrl:BoolToStringConverter x:Key="BoolToStarConverter" FalseValue="" TrueValue="*"/>
|
<ctrl:BoolToStringConverter x:Key="BoolToStarConverter" FalseValue="" TrueValue="*"/>
|
||||||
<ctrl:WidthToMarginConverter x:Key="WidthToMarginConverter"/>
|
<ctrl:WidthToMarginConverter x:Key="WidthToMarginConverter"/>
|
||||||
|
|
||||||
|
<DataTemplate x:Key="PostalDestTemplate">
|
||||||
|
<StackPanel Orientation="Horizontal">
|
||||||
|
<TextBlock Text="{Binding Dest}"/>
|
||||||
|
<TextBlock Text="{Binding Ort.Name, StringFormat='{} ({0})'}"/>
|
||||||
|
</StackPanel>
|
||||||
|
</DataTemplate>
|
||||||
<DataTemplate x:Key="KgNrTemplate">
|
<DataTemplate x:Key="KgNrTemplate">
|
||||||
<StackPanel Orientation="Horizontal">
|
<StackPanel Orientation="Horizontal">
|
||||||
<TextBlock Text="{Binding Name}"/>
|
<TextBlock Text="{Binding Name}"/>
|
||||||
|
|||||||
+56
-95
@@ -18,17 +18,16 @@ using System.Reflection;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using System.Windows;
|
using System.Windows;
|
||||||
using System.Windows.Input;
|
|
||||||
using System.Windows.Threading;
|
using System.Windows.Threading;
|
||||||
|
|
||||||
namespace Elwig {
|
namespace Elwig {
|
||||||
public partial class App : Application {
|
public partial class App : Application {
|
||||||
|
|
||||||
public static new App Current => (App)Application.Current;
|
protected static App CurrentApp;
|
||||||
public static bool ForceShutdown { get; set; } = false;
|
public static int NumWindows => CurrentApp.Windows.Count;
|
||||||
|
public static bool ForceShutdown { get; private set; } = false;
|
||||||
|
|
||||||
private readonly DispatcherTimer _autoUpdateTimer = new() { Interval = TimeSpan.FromHours(1) };
|
private readonly DispatcherTimer _autoUpdateTimer = new() { Interval = TimeSpan.FromHours(1) };
|
||||||
private readonly DispatcherTimer _autoBackupTimer = new() { Interval = TimeSpan.FromMinutes(10) };
|
|
||||||
public readonly SerialPortWatcher SerialPortWatcher = new();
|
public readonly SerialPortWatcher SerialPortWatcher = new();
|
||||||
|
|
||||||
public static readonly string DataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Elwig");
|
public static readonly string DataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Elwig");
|
||||||
@@ -41,8 +40,8 @@ namespace Elwig {
|
|||||||
public static Version Version { get; private set; } = new();
|
public static Version Version { get; private set; } = new();
|
||||||
|
|
||||||
public static int BranchNum { get; private set; }
|
public static int BranchNum { get; private set; }
|
||||||
public static string ZwstId { get; private set; } = "?";
|
public static string ZwstId { get; private set; }
|
||||||
public static string BranchName { get; private set; } = "Unbekannt";
|
public static string BranchName { get; private set; }
|
||||||
public static int? BranchPlz { get; private set; }
|
public static int? BranchPlz { get; private set; }
|
||||||
public static string? BranchLocation { get; private set; }
|
public static string? BranchLocation { get; private set; }
|
||||||
public static string? BranchAddress { get; private set; }
|
public static string? BranchAddress { get; private set; }
|
||||||
@@ -53,8 +52,9 @@ namespace Elwig {
|
|||||||
public static IList<IScale> Scales { get; private set; } = [];
|
public static IList<IScale> Scales { get; private set; } = [];
|
||||||
public static IList<ICommandScale> CommandScales => [.. Scales.Where(s => s is ICommandScale).Cast<ICommandScale>()];
|
public static IList<ICommandScale> CommandScales => [.. Scales.Where(s => s is ICommandScale).Cast<ICommandScale>()];
|
||||||
public static IList<IEventScale> EventScales => [.. Scales.Where(s => s is IEventScale).Cast<IEventScale>()];
|
public static IList<IEventScale> EventScales => [.. Scales.Where(s => s is IEventScale).Cast<IEventScale>()];
|
||||||
public static ClientParameters Client { get; set; } = new();
|
public static ClientParameters Client { get; set; }
|
||||||
|
|
||||||
|
public static Dispatcher MainDispatcher { get; private set; }
|
||||||
private DateTime LastChanged;
|
private DateTime LastChanged;
|
||||||
private static DateTime CurrentLastWrite => File.GetLastWriteTime(Config.DatabaseFile);
|
private static DateTime CurrentLastWrite => File.GetLastWriteTime(Config.DatabaseFile);
|
||||||
private readonly DispatcherTimer ContextTimer = new() { Interval = TimeSpan.FromSeconds(2) };
|
private readonly DispatcherTimer ContextTimer = new() { Interval = TimeSpan.FromSeconds(2) };
|
||||||
@@ -64,7 +64,9 @@ namespace Elwig {
|
|||||||
Directory.CreateDirectory(TempPath);
|
Directory.CreateDirectory(TempPath);
|
||||||
Directory.CreateDirectory(DataPath);
|
Directory.CreateDirectory(DataPath);
|
||||||
Directory.CreateDirectory(MailsPath);
|
Directory.CreateDirectory(MailsPath);
|
||||||
|
MainDispatcher = Dispatcher;
|
||||||
Scales = [];
|
Scales = [];
|
||||||
|
CurrentApp = this;
|
||||||
Utils.OverrideCulture();
|
Utils.OverrideCulture();
|
||||||
|
|
||||||
var args = Environment.GetCommandLineArgs();
|
var args = Environment.GetCommandLineArgs();
|
||||||
@@ -72,7 +74,7 @@ namespace Elwig {
|
|||||||
Config = new(Path.GetFullPath(args[1]));
|
Config = new(Path.GetFullPath(args[1]));
|
||||||
}
|
}
|
||||||
|
|
||||||
ContextTimer.Tick += (sender, evt) => {
|
ContextTimer.Tick += (object? sender, EventArgs evt) => {
|
||||||
var ch = CurrentLastWrite;
|
var ch = CurrentLastWrite;
|
||||||
if (ch > LastChanged) {
|
if (ch > LastChanged) {
|
||||||
LastChanged = ch;
|
LastChanged = ch;
|
||||||
@@ -82,7 +84,7 @@ namespace Elwig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static void OnContextChanged() {
|
private static void OnContextChanged() {
|
||||||
Current.Dispatcher.BeginInvoke(HintContextChange);
|
MainDispatcher.BeginInvoke(HintContextChange);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override async void OnStartup(StartupEventArgs evt) {
|
protected override async void OnStartup(StartupEventArgs evt) {
|
||||||
@@ -90,16 +92,12 @@ namespace Elwig {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await AppDbUpdater.CheckDb();
|
await AppDbUpdater.CheckDb();
|
||||||
} catch (FileNotFoundException exc) {
|
|
||||||
InteractionService.ShowException("Datenbank nicht gefunden", "Die Datenbank konnte nicht gefunden werden", exc);
|
|
||||||
} catch (Exception exc) {
|
} catch (Exception exc) {
|
||||||
if (Config.UpdateUrl != null && Utils.HasInternetConnectivity()) {
|
if (Config.UpdateUrl != null && Utils.HasInternetConnectivity()) {
|
||||||
await CheckForUpdates();
|
await CheckForUpdates();
|
||||||
}
|
}
|
||||||
InteractionService.ShowException("Fehlerhafte Datenbank", "Schwerwiegender Fehler in der Datenbank, unbedingt den Programmierern melden!", exc);
|
InteractionService.ShowException("Fehlerhafte Datenbank", "Fehlerhafte Datenbank", exc);
|
||||||
if (InteractionService.AskQuestion("Backup wiederherstellen", "Soll die Datenbank aus einem Backup wiederhergestellt werden?\n\nAchtung: Das kann zu Datenverlust führen!", false))
|
Shutdown();
|
||||||
await BackupService.RestoreDatabase();
|
|
||||||
ShutdownNow();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -108,15 +106,14 @@ namespace Elwig {
|
|||||||
|
|
||||||
Dictionary<string, (string, string, int?, string?, string?, string?, string?, string?)> branches = [];
|
Dictionary<string, (string, string, int?, string?, string?, string?, string?, string?)> branches = [];
|
||||||
using (var ctx = new AppDbContext()) {
|
using (var ctx = new AppDbContext()) {
|
||||||
branches = await ctx.FetchBranches()
|
branches = ctx.FetchBranches()
|
||||||
.ToDictionaryAsync(b => b.Name.ToLower(), b => (b.ZwstId, b.Name, b.PostalDest?.AtPlz?.Plz, b.PostalDest?.AtPlz?.Ort.Name, b.Address, b.PhoneNr, b.FaxNr, b.MobileNr));
|
.ToDictionaryAsync(b => b.Name.ToLower(), b => (b.ZwstId, b.Name, b.PostalDest?.AtPlz?.Plz, b.PostalDest?.AtPlz?.Ort.Name, b.Address, b.PhoneNr, b.FaxNr, b.MobileNr))
|
||||||
|
.GetAwaiter().GetResult();
|
||||||
try {
|
try {
|
||||||
Client = new(ctx);
|
Client = new(ctx);
|
||||||
} catch (Exception exc) {
|
} catch (Exception exc) {
|
||||||
InteractionService.ShowException("Fehler", "Fehler beim Laden der Mandantendaten, unbedingt den Programmierern melden!", exc);
|
InteractionService.ShowException("Fehler", "Fehler beim Laden der Mandantendaten", exc);
|
||||||
if (InteractionService.AskQuestion("Backup wiederherstellen", "Soll die Datenbank aus einem Backup wiederhergestellt werden?\n\nAchtung: Das kann zu Datenverlust führen!", false))
|
Shutdown();
|
||||||
await BackupService.RestoreDatabase();
|
|
||||||
ShutdownNow();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
BranchNum = branches.Count;
|
BranchNum = branches.Count;
|
||||||
@@ -127,23 +124,9 @@ namespace Elwig {
|
|||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
});
|
});
|
||||||
|
|
||||||
Utils.RunBackground("PDF Initialization", async () => Pdf.Init());
|
Utils.RunBackground("PDF Initialization", () => Pdf.Init());
|
||||||
Utils.RunBackground("JSON Schema Initialization", BillingData.Init);
|
Utils.RunBackground("JSON Schema Initialization", BillingData.Init);
|
||||||
|
|
||||||
if (Config.BackupAuto && !Config.Debug) {
|
|
||||||
Utils.RunBackground("Automatisches Backup", async () => {
|
|
||||||
Directory.CreateDirectory(Config.BackupPath);
|
|
||||||
await Task.Delay(500);
|
|
||||||
await BackupService.TryDatabaseBackup();
|
|
||||||
});
|
|
||||||
_autoBackupTimer.Tick += new EventHandler((sender, evt) => {
|
|
||||||
Utils.RunBackground("Automatisches Backup", async () => {
|
|
||||||
await BackupService.TryDatabaseBackup();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
_autoBackupTimer.Start();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Config.UpdateAuto && Config.UpdateUrl != null) {
|
if (Config.UpdateAuto && Config.UpdateUrl != null) {
|
||||||
if (Utils.HasInternetConnectivity()) {
|
if (Utils.HasInternetConnectivity()) {
|
||||||
Utils.RunBackground("Auto Updater", async () => {
|
Utils.RunBackground("Auto Updater", async () => {
|
||||||
@@ -162,13 +145,7 @@ namespace Elwig {
|
|||||||
var list = new List<IScale>();
|
var list = new List<IScale>();
|
||||||
foreach (var s in Config.Scales) {
|
foreach (var s in Config.Scales) {
|
||||||
try {
|
try {
|
||||||
var scale = Scale.FromConfig(s);
|
list.Add(Scale.FromConfig(s));
|
||||||
if (s.SyncTime && scale is ICommandScale cmd) {
|
|
||||||
try {
|
|
||||||
await cmd.SetDateAndTime(DateTime.Now);
|
|
||||||
} catch { }
|
|
||||||
}
|
|
||||||
list.Add(scale);
|
|
||||||
} catch (Exception exc) {
|
} catch (Exception exc) {
|
||||||
list.Add(new InvalidScale(s.Id));
|
list.Add(new InvalidScale(s.Id));
|
||||||
if (s.Required)
|
if (s.Required)
|
||||||
@@ -180,7 +157,7 @@ namespace Elwig {
|
|||||||
if (Config.Branch != null) {
|
if (Config.Branch != null) {
|
||||||
if (!branches.ContainsKey(Config.Branch.ToLower())) {
|
if (!branches.ContainsKey(Config.Branch.ToLower())) {
|
||||||
InteractionService.ShowError("Ungültige Zweigstelle", "Ungültige Zweigstelle in Konfigurationsdatei!");
|
InteractionService.ShowError("Ungültige Zweigstelle", "Ungültige Zweigstelle in Konfigurationsdatei!");
|
||||||
ShutdownNow();
|
Shutdown();
|
||||||
} else {
|
} else {
|
||||||
SetBranch(branches[Config.Branch.ToLower()]);
|
SetBranch(branches[Config.Branch.ToLower()]);
|
||||||
}
|
}
|
||||||
@@ -188,7 +165,7 @@ namespace Elwig {
|
|||||||
SetBranch(branches.First().Value);
|
SetBranch(branches.First().Value);
|
||||||
} else {
|
} else {
|
||||||
InteractionService.ShowError("Ungültige Zweigstelle", "Erkennen der lokalen Zweigstelle nicht möglich!");
|
InteractionService.ShowError("Ungültige Zweigstelle", "Erkennen der lokalen Zweigstelle nicht möglich!");
|
||||||
ShutdownNow();
|
Shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Config.WeighingMode == null) {
|
if (Config.WeighingMode == null) {
|
||||||
@@ -196,7 +173,7 @@ namespace Elwig {
|
|||||||
Config.WeighingMode = WeighingMode.Net;
|
Config.WeighingMode = WeighingMode.Net;
|
||||||
} else if (Client.IsHaugsdorf || Client.IsSitzendorf) {
|
} else if (Client.IsHaugsdorf || Client.IsSitzendorf) {
|
||||||
Config.WeighingMode = WeighingMode.Box;
|
Config.WeighingMode = WeighingMode.Box;
|
||||||
} else if (Client.IsBaden || Client.IsGrInzersdorf || Client.IsPamhagen) {
|
} else if (Client.IsBaden || Client.IsGrInzersdorf) {
|
||||||
Config.WeighingMode = WeighingMode.Gross;
|
Config.WeighingMode = WeighingMode.Gross;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -207,29 +184,12 @@ namespace Elwig {
|
|||||||
window.Show();
|
window.Show();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void ShutdownNow() {
|
private async void Application_Exit(object sender, ExitEventArgs evt) {
|
||||||
ForceShutdown = true;
|
|
||||||
Current.Shutdown();
|
|
||||||
}
|
|
||||||
|
|
||||||
public async void ShutdownGracefully() {
|
|
||||||
Mouse.OverrideCursor = Cursors.AppStarting;
|
|
||||||
|
|
||||||
if (Config.BackupAuto && !Config.Debug) {
|
|
||||||
try {
|
|
||||||
await BackupService.TryDatabaseBackup();
|
|
||||||
} catch (Exception exc) {
|
|
||||||
InteractionService.ShowException("Automatisches Backup", exc);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
SerialPortWatcher.Dispose();
|
SerialPortWatcher.Dispose();
|
||||||
foreach (var s in EventScales) {
|
foreach (var s in EventScales) {
|
||||||
s.Dispose();
|
s.Dispose();
|
||||||
}
|
}
|
||||||
Pdf.Cleanup();
|
await Pdf.Cleanup();
|
||||||
|
|
||||||
Shutdown();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void SetBranch(Branch b) {
|
public static void SetBranch(Branch b) {
|
||||||
@@ -255,21 +215,21 @@ namespace Elwig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void HintContextChange() {
|
public static void HintContextChange() {
|
||||||
if (Current == null) return;
|
if (CurrentApp == null) return;
|
||||||
var ch = CurrentLastWrite;
|
var ch = CurrentLastWrite;
|
||||||
if (ch > Current.LastChanged)
|
if (ch > CurrentApp.LastChanged)
|
||||||
Current.LastChanged = ch;
|
CurrentApp.LastChanged = ch;
|
||||||
Current.Dispatcher.Invoke(() => {
|
MainDispatcher.Invoke(() => {
|
||||||
foreach (Window w in Current.Windows) {
|
foreach (Window w in CurrentApp.Windows) {
|
||||||
if (w is not ContextWindow c) continue;
|
if (w is not ContextWindow c) continue;
|
||||||
Current.Dispatcher.Invoke(c.HintContextChange);
|
MainDispatcher.Invoke(c.HintContextChange);
|
||||||
Current.Dispatcher.BeginInvoke(c.TryContextReload);
|
MainDispatcher.BeginInvoke(c.TryContextReload);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnAutoUpdateTimer(object? sender, EventArgs? evt) {
|
private void OnAutoUpdateTimer(object? sender, EventArgs? evt) {
|
||||||
foreach (Window w in Current.Windows) {
|
foreach (Window w in CurrentApp.Windows) {
|
||||||
if (w is UpdateDialog) return;
|
if (w is UpdateDialog) return;
|
||||||
}
|
}
|
||||||
if (Utils.HasInternetConnectivity()) {
|
if (Utils.HasInternetConnectivity()) {
|
||||||
@@ -326,7 +286,7 @@ namespace Elwig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void UpdateScales() {
|
public static void UpdateScales() {
|
||||||
foreach (Window w in Current.Windows) {
|
foreach (Window w in CurrentApp.Windows) {
|
||||||
if (w is DeliveryAdminWindow t && t.ViewModel.IsReceipt) {
|
if (w is DeliveryAdminWindow t && t.ViewModel.IsReceipt) {
|
||||||
t.UpdateScales();
|
t.UpdateScales();
|
||||||
}
|
}
|
||||||
@@ -335,38 +295,39 @@ namespace Elwig {
|
|||||||
|
|
||||||
public static async Task CheckForUpdates(bool showAlert = false) {
|
public static async Task CheckForUpdates(bool showAlert = false) {
|
||||||
if (Config.UpdateUrl == null) return;
|
if (Config.UpdateUrl == null) return;
|
||||||
try {
|
var latest = await Utils.GetLatestInstallerUrl(Config.UpdateUrl);
|
||||||
var latest = await Utils.GetLatestInstallerUrl(Config.UpdateUrl);
|
if (latest != null && new Version(latest.Value.Version) > Version) {
|
||||||
if (new Version(latest.Version) > Version) {
|
await MainDispatcher.BeginInvoke(() => {
|
||||||
await Current.Dispatcher.BeginInvoke(() => {
|
var d = new UpdateDialog(latest.Value.Version, latest.Value.Url, latest.Value.Size);
|
||||||
var d = new UpdateDialog(latest.Version, latest.Url, latest.Size);
|
if (d.ShowDialog() == true) {
|
||||||
if (d.ShowDialog() == true) {
|
ForceShutdown = true;
|
||||||
ShutdownNow();
|
Current.Shutdown();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} else if (showAlert) {
|
} else if (showAlert) {
|
||||||
InteractionService.ShowInformation("Nach Updates suchen", $"Elwig ist auf dem aktuellsten Stand! (Version: {latest.Version})");
|
if (latest == null) {
|
||||||
|
InteractionService.ShowError("Nach Updates suchen", "Informationen konnten nicht abgerufen werden!");
|
||||||
|
} else {
|
||||||
|
InteractionService.ShowInformation("Nach Updates suchen", $"Elwig ist auf dem aktuellsten Stand! (Version: {latest.Value.Version})");
|
||||||
}
|
}
|
||||||
} catch (Exception exc) {
|
|
||||||
if (showAlert)
|
|
||||||
InteractionService.ShowException("Nach Updates suchen", $"Informationen konnten nicht abgerufen werden!", exc);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task ReplaceDatabase(string filename, IEnumerable<ReadOnlyMemory<char>>? keys = null) {
|
public static async Task ReplaceDatabase(string filename) {
|
||||||
try {
|
try {
|
||||||
await Task.Run(async () => {
|
await Task.Run(async () => {
|
||||||
await Database.Import(filename, keys);
|
await Database.Import(filename);
|
||||||
});
|
});
|
||||||
InteractionService.ShowInformation("Datenbank ersetzen", "Das Ersetzen war erfolgreich!\n\nBitte starten Sie Elwig neu!");
|
InteractionService.ShowInformation("Datenbank ersetzen", "Das Ersetzen war erfolgreich!\n\nBitte starten Sie Elwig neu!");
|
||||||
ShutdownNow();
|
ForceShutdown = true;
|
||||||
|
Current.Shutdown();
|
||||||
} catch (Exception exc) {
|
} catch (Exception exc) {
|
||||||
InteractionService.ShowException("Datenbank ersetzen", "Fehler beim Ersetzen", exc);
|
InteractionService.ShowException("Datenbank ersetzen", "Fehler beim Ersetzen", exc);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static T FocusWindow<T>(Func<T> constructor, Predicate<T>? selector = null) where T : Window {
|
private static T FocusWindow<T>(Func<T> constructor, Predicate<T>? selector = null) where T : Window {
|
||||||
foreach (Window w in Current.Windows) {
|
foreach (Window w in CurrentApp.Windows) {
|
||||||
if (w is T t && (selector == null || selector(t))) {
|
if (w is T t && (selector == null || selector(t))) {
|
||||||
if (t.WindowState == WindowState.Minimized)
|
if (t.WindowState == WindowState.Minimized)
|
||||||
t.WindowState = WindowState.Normal;
|
t.WindowState = WindowState.Normal;
|
||||||
@@ -391,15 +352,15 @@ namespace Elwig {
|
|||||||
return FocusWindow<DeliveryAdminWindow>(() => new(mgnr), w => w.ViewModel.FilterMember?.MgNr == mgnr);
|
return FocusWindow<DeliveryAdminWindow>(() => new(mgnr), w => w.ViewModel.FilterMember?.MgNr == mgnr);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static AreaCmtAdminWindow FocusMemberAreaCmts(int mgnr) {
|
public static AreaComAdminWindow FocusMemberAreaComs(int mgnr) {
|
||||||
return FocusWindow<AreaCmtAdminWindow>(() => new(mgnr), w => w.ViewModel.FilterMember.MgNr == mgnr);
|
return FocusWindow<AreaComAdminWindow>(() => new(mgnr), w => w.ViewModel.FilterMember.MgNr == mgnr);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static BaseDataWindow FocusBaseData() {
|
public static BaseDataWindow FocusBaseData() {
|
||||||
return FocusWindow<BaseDataWindow>(() => new());
|
return FocusWindow<BaseDataWindow>(() => new());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static BaseDataWindow FocusBaseDataAreaCmtType() {
|
public static BaseDataWindow FocusBaseDataAreaComType() {
|
||||||
var w = FocusBaseData();
|
var w = FocusBaseData();
|
||||||
w.AreaCommitmentTypes.Focus();
|
w.AreaCommitmentTypes.Focus();
|
||||||
return w;
|
return w;
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ using System.Globalization;
|
|||||||
|
|
||||||
namespace Elwig.Controls {
|
namespace Elwig.Controls {
|
||||||
public class BoolToValueConverter<T> : IValueConverter {
|
public class BoolToValueConverter<T> : IValueConverter {
|
||||||
public required T FalseValue { get; set; }
|
public T FalseValue { get; set; }
|
||||||
public required T TrueValue { get; set; }
|
public T TrueValue { get; set; }
|
||||||
|
|
||||||
public object? Convert(object value, Type targetType, object parameter, CultureInfo culture) {
|
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||||
return (bool)value ? TrueValue : FalseValue;
|
return (bool)value ? TrueValue : FalseValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ namespace Elwig.Controls {
|
|||||||
|
|
||||||
private bool _viewHandled;
|
private bool _viewHandled;
|
||||||
private bool _modelHandled;
|
private bool _modelHandled;
|
||||||
private TextBlock? _textBox;
|
private TextBlock _textBox;
|
||||||
|
|
||||||
public CheckComboBox() {
|
public CheckComboBox() {
|
||||||
SelectionMode = SelectionMode.Multiple;
|
SelectionMode = SelectionMode.Multiple;
|
||||||
@@ -131,11 +131,11 @@ namespace Elwig.Controls {
|
|||||||
AllItemsSelected = null;
|
AllItemsSelected = null;
|
||||||
}
|
}
|
||||||
if (SelectedItems.Count > 1 && SelectedItems.Count == ItemsSource.Cast<object>().Count() && AllItemsSelectedContent != null) {
|
if (SelectedItems.Count > 1 && SelectedItems.Count == ItemsSource.Cast<object>().Count() && AllItemsSelectedContent != null) {
|
||||||
_textBox?.Text = AllItemsSelectedContent;
|
_textBox.Text = AllItemsSelectedContent;
|
||||||
} else if (SelectedItems.Count == 0) {
|
} else if (SelectedItems.Count == 0) {
|
||||||
_textBox?.Text = "";
|
_textBox.Text = "";
|
||||||
} else {
|
} else {
|
||||||
_textBox?.Text = string.Join(Delimiter,
|
_textBox.Text = string.Join(Delimiter,
|
||||||
dmp == null ? SelectedItems.Cast<object>() :
|
dmp == null ? SelectedItems.Cast<object>() :
|
||||||
SelectedItems.Cast<object>()
|
SelectedItems.Cast<object>()
|
||||||
.Select(i => i.GetType().GetProperty(dmp)?.GetValue(i))
|
.Select(i => i.GetType().GetProperty(dmp)?.GetValue(i))
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
<Window x:Class="Elwig.Dialogs.AreaCmtModifyDialog"
|
<Window x:Class="Elwig.Dialogs.AreaComModifyDialog"
|
||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
+2
-2
@@ -4,7 +4,7 @@ using System.Windows;
|
|||||||
using System.Windows.Controls;
|
using System.Windows.Controls;
|
||||||
|
|
||||||
namespace Elwig.Dialogs {
|
namespace Elwig.Dialogs {
|
||||||
public partial class AreaCmtModifyDialog : Window {
|
public partial class AreaComModifyDialog : Window {
|
||||||
|
|
||||||
public int? YearTo { get; set; }
|
public int? YearTo { get; set; }
|
||||||
public bool ModifyRetroactively { get; set; }
|
public bool ModifyRetroactively { get; set; }
|
||||||
@@ -13,7 +13,7 @@ namespace Elwig.Dialogs {
|
|||||||
public string OrigYearTo { get; set; }
|
public string OrigYearTo { get; set; }
|
||||||
public string Area { get; set; }
|
public string Area { get; set; }
|
||||||
|
|
||||||
public AreaCmtModifyDialog(int? yearFrom, int? yearTo, int area, bool delete, bool forceRetroactive = false) {
|
public AreaComModifyDialog(int? yearFrom, int? yearTo, int area, bool delete, bool forceRetroactive = false) {
|
||||||
Area = $"{area:N0}";
|
Area = $"{area:N0}";
|
||||||
OrigYearFrom = $"{yearFrom}";
|
OrigYearFrom = $"{yearFrom}";
|
||||||
OrigYearTo = $"{yearTo}";
|
OrigYearTo = $"{yearTo}";
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<Window x:Class="Elwig.Dialogs.AreaCmtTransferDialog"
|
<Window x:Class="Elwig.Dialogs.AreaComTransferDialog"
|
||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
@@ -35,11 +35,11 @@
|
|||||||
<TextBlock x:Name="QuestionBlock1" TextAlignment="Center" Margin="0,10,0,0"
|
<TextBlock x:Name="QuestionBlock1" TextAlignment="Center" Margin="0,10,0,0"
|
||||||
HorizontalAlignment="Center" VerticalAlignment="Top">
|
HorizontalAlignment="Center" VerticalAlignment="Top">
|
||||||
Sollen die aktiven Flächenbindungen des angegebenen Vorgängers<LineBreak/>
|
Sollen die aktiven Flächenbindungen des angegebenen Vorgängers<LineBreak/>
|
||||||
übernommen werden? (<Run Text="{Binding AreaCmtNum}"/> FB, <Run Text="{Binding Area}"/> m²)
|
übernommen werden? (<Run Text="{Binding AreaComNum}"/> FB, <Run Text="{Binding Area}"/> m²)
|
||||||
</TextBlock>
|
</TextBlock>
|
||||||
<TextBlock x:Name="QuestionBlock2" TextAlignment="Center" Margin="0,10,0,0" Visibility="Hidden"
|
<TextBlock x:Name="QuestionBlock2" TextAlignment="Center" Margin="0,10,0,0" Visibility="Hidden"
|
||||||
HorizontalAlignment="Center" VerticalAlignment="Top">
|
HorizontalAlignment="Center" VerticalAlignment="Top">
|
||||||
Sollen die aktiven Flächenbindungen gekündigt werden? (<Run Text="{Binding AreaCmtNum}"/> FB, <Run Text="{Binding Area}"/> m²)
|
Sollen die aktiven Flächenbindungen gekündigt werden? (<Run Text="{Binding AreaComNum}"/> FB, <Run Text="{Binding Area}"/> m²)
|
||||||
</TextBlock>
|
</TextBlock>
|
||||||
|
|
||||||
<Label x:Name="SeasonLabel" Content="Saison:" Margin="0,50,100,0"
|
<Label x:Name="SeasonLabel" Content="Saison:" Margin="0,50,100,0"
|
||||||
+6
-6
@@ -3,17 +3,17 @@ using System.Windows;
|
|||||||
using System.Windows.Controls;
|
using System.Windows.Controls;
|
||||||
|
|
||||||
namespace Elwig.Dialogs {
|
namespace Elwig.Dialogs {
|
||||||
public partial class AreaCmtTransferDialog : Window {
|
public partial class AreaComTransferDialog : Window {
|
||||||
|
|
||||||
public int CancelSeason => SuccessorSeason - 1;
|
public int CancelSeason => SuccessorSeason - 1;
|
||||||
public int SuccessorSeason { get; set; }
|
public int SuccessorSeason { get; set; }
|
||||||
|
|
||||||
public string AreaCmtNum { get; set; }
|
public string AreaComNum { get; set; }
|
||||||
public string Area { get; set; }
|
public string Area { get; set; }
|
||||||
|
|
||||||
public AreaCmtTransferDialog(string name, int areaCmtNum, int area) {
|
public AreaComTransferDialog(string name, int areaComNum, int area) {
|
||||||
SuccessorSeason = Utils.FollowingSeason;
|
SuccessorSeason = Utils.FollowingSeason;
|
||||||
AreaCmtNum = $"{areaCmtNum:N0}";
|
AreaComNum = $"{areaComNum:N0}";
|
||||||
Area = $"{area:N0}";
|
Area = $"{area:N0}";
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
SeasonInput.Text = $"{SuccessorSeason}";
|
SeasonInput.Text = $"{SuccessorSeason}";
|
||||||
@@ -28,9 +28,9 @@ namespace Elwig.Dialogs {
|
|||||||
SeasonLabel.Margin = new(0, 40, 100, 0);
|
SeasonLabel.Margin = new(0, 40, 100, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
public AreaCmtTransferDialog(string name, string successorName, int areaCmtNum, int area) {
|
public AreaComTransferDialog(string name, string successorName, int areaComNum, int area) {
|
||||||
SuccessorSeason = Utils.FollowingSeason;
|
SuccessorSeason = Utils.FollowingSeason;
|
||||||
AreaCmtNum = $"{areaCmtNum:N0}";
|
AreaComNum = $"{areaComNum:N0}";
|
||||||
Area = $"{area:N0}";
|
Area = $"{area:N0}";
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
SeasonInput.Text = $"{SuccessorSeason}";
|
SeasonInput.Text = $"{SuccessorSeason}";
|
||||||
@@ -47,9 +47,9 @@
|
|||||||
TextChanged="NameInput_TextChanged"/>
|
TextChanged="NameInput_TextChanged"/>
|
||||||
|
|
||||||
<Label Content="Beim Löschen müssen folgende Daten auch gelöscht werden:" Margin="10,120,10,10"/>
|
<Label Content="Beim Löschen müssen folgende Daten auch gelöscht werden:" Margin="10,120,10,10"/>
|
||||||
<CheckBox x:Name="AreaCmtInput" Content="Flächenbindungen" Margin="40,145,0,0"
|
<CheckBox x:Name="AreaComInput" Content="Flächenbindungen" Margin="40,145,0,0"
|
||||||
Checked="CheckBox_Changed" Unchecked="CheckBox_Changed"
|
Checked="CheckBox_Changed" Unchecked="CheckBox_Changed"
|
||||||
IsChecked="{Binding DeleteAreaCmts}"/>
|
IsChecked="{Binding DeleteAreaComs}"/>
|
||||||
<CheckBox x:Name="DeliveryInput" Content="Lieferungen" Margin="40,165,0,0"
|
<CheckBox x:Name="DeliveryInput" Content="Lieferungen" Margin="40,165,0,0"
|
||||||
Checked="CheckBox_Changed" Unchecked="CheckBox_Changed"
|
Checked="CheckBox_Changed" Unchecked="CheckBox_Changed"
|
||||||
IsChecked="{Binding DeleteDeliveries}"/>
|
IsChecked="{Binding DeleteDeliveries}"/>
|
||||||
|
|||||||
@@ -8,16 +8,16 @@ namespace Elwig.Dialogs {
|
|||||||
|
|
||||||
protected string[] NameParts;
|
protected string[] NameParts;
|
||||||
|
|
||||||
public bool DeleteAreaCmts { get; set; }
|
public bool DeleteAreaComs { get; set; }
|
||||||
public bool DeleteDeliveries { get; set; }
|
public bool DeleteDeliveries { get; set; }
|
||||||
public bool DeletePaymentData { get; set; }
|
public bool DeletePaymentData { get; set; }
|
||||||
|
|
||||||
public DeleteMemberDialog(int mgnr, string name, int numAreaCmts, int numDeliveries, int numCredits) {
|
public DeleteMemberDialog(int mgnr, string name, int numAreaComs, int numDeliveries, int numCredits) {
|
||||||
NameParts = [.. name.ToLower().Split(' ', System.StringSplitOptions.RemoveEmptyEntries), $"{mgnr}"];
|
NameParts = name.ToLower().Split(' ').Where(p => p.Length > 0).Append($"{mgnr}").ToArray();
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
Title += " - " + name;
|
Title += " - " + name;
|
||||||
AreaCmtInput.IsEnabled = numAreaCmts != 0;
|
AreaComInput.IsEnabled = numAreaComs != 0;
|
||||||
AreaCmtInput.Content += $" ({numAreaCmts:N0})";
|
AreaComInput.Content += $" ({numAreaComs:N0})";
|
||||||
DeliveryInput.IsEnabled = numDeliveries != 0;
|
DeliveryInput.IsEnabled = numDeliveries != 0;
|
||||||
DeliveryInput.Content += $" ({numDeliveries:N0})";
|
DeliveryInput.Content += $" ({numDeliveries:N0})";
|
||||||
PaymentInput.IsEnabled = numCredits != 0;
|
PaymentInput.IsEnabled = numCredits != 0;
|
||||||
@@ -43,7 +43,7 @@ namespace Elwig.Dialogs {
|
|||||||
private void Update() {
|
private void Update() {
|
||||||
var t = NameInput.Text.ToLower().Split(' ');
|
var t = NameInput.Text.ToLower().Split(' ');
|
||||||
var nameValid = NameParts.All(t.Contains);
|
var nameValid = NameParts.All(t.Contains);
|
||||||
UpdateCheckBox(AreaCmtInput);
|
UpdateCheckBox(AreaComInput);
|
||||||
UpdateCheckBox(DeliveryInput);
|
UpdateCheckBox(DeliveryInput);
|
||||||
UpdateCheckBox(PaymentInput);
|
UpdateCheckBox(PaymentInput);
|
||||||
if (!nameValid) {
|
if (!nameValid) {
|
||||||
@@ -52,7 +52,7 @@ namespace Elwig.Dialogs {
|
|||||||
ControlUtils.ClearInputState(NameInput);
|
ControlUtils.ClearInputState(NameInput);
|
||||||
}
|
}
|
||||||
ConfirmButton.IsEnabled =
|
ConfirmButton.IsEnabled =
|
||||||
(!AreaCmtInput.IsEnabled || DeleteAreaCmts) &&
|
(!AreaComInput.IsEnabled || DeleteAreaComs) &&
|
||||||
(!DeliveryInput.IsEnabled || DeleteDeliveries) &&
|
(!DeliveryInput.IsEnabled || DeleteDeliveries) &&
|
||||||
(!PaymentInput.IsEnabled || DeletePaymentData) &&
|
(!PaymentInput.IsEnabled || DeletePaymentData) &&
|
||||||
nameValid;
|
nameValid;
|
||||||
|
|||||||
@@ -74,7 +74,7 @@
|
|||||||
<StackPanel Orientation="Horizontal">
|
<StackPanel Orientation="Horizontal">
|
||||||
<TextBlock Text="{Binding Part.DPNr}" Width="20" TextAlignment="Right"
|
<TextBlock Text="{Binding Part.DPNr}" Width="20" TextAlignment="Right"
|
||||||
VerticalAlignment="Center" Margin="0,0,5,0" FontSize="14"/>
|
VerticalAlignment="Center" Margin="0,0,5,0" FontSize="14"/>
|
||||||
<TextBlock Text="{Binding Part.SortId}" Foreground="{Binding Part.Variety.Color}" Width="40" TextAlignment="Center"
|
<TextBlock Text="{Binding Part.SortId}" Width="40" TextAlignment="Center"
|
||||||
VerticalAlignment="Center" Margin="0,0,0,0" FontSize="14"/>
|
VerticalAlignment="Center" Margin="0,0,0,0" FontSize="14"/>
|
||||||
<TextBlock Text="{Binding Part.Kmw, StringFormat='{}{0:N1}°'}" Width="40" TextAlignment="Right" Padding="0,0,10,0"
|
<TextBlock Text="{Binding Part.Kmw, StringFormat='{}{0:N1}°'}" Width="40" TextAlignment="Right" Padding="0,0,10,0"
|
||||||
VerticalAlignment="Center"/>
|
VerticalAlignment="Center"/>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using Elwig.Helpers;
|
|||||||
using Elwig.Models.Entities;
|
using Elwig.Models.Entities;
|
||||||
using Elwig.Windows;
|
using Elwig.Windows;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using System;
|
||||||
using System.Collections.ObjectModel;
|
using System.Collections.ObjectModel;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -13,7 +14,7 @@ namespace Elwig.Dialogs {
|
|||||||
public partial class DeliverySplittingDialog : ContextWindow {
|
public partial class DeliverySplittingDialog : ContextWindow {
|
||||||
|
|
||||||
public class Row {
|
public class Row {
|
||||||
public required DeliveryPart Part { get; set; }
|
public DeliveryPart Part { get; set; }
|
||||||
public bool SplitCompletely { get; set; }
|
public bool SplitCompletely { get; set; }
|
||||||
public string? SplitWeightString { get; set; }
|
public string? SplitWeightString { get; set; }
|
||||||
public int? SplitWeight {
|
public int? SplitWeight {
|
||||||
@@ -27,18 +28,18 @@ namespace Elwig.Dialogs {
|
|||||||
|
|
||||||
public int? MgNr { get; set; }
|
public int? MgNr { get; set; }
|
||||||
public string? LsNr { get; set; }
|
public string? LsNr { get; set; }
|
||||||
public int[]? Weights => [.. DeliveryParts.Select(r => r.SplitCompletely ? r.Part.Weight : r.SplitWeight ?? 0)];
|
public int[]? Weights => DeliveryParts.Select(r => r.SplitCompletely ? r.Part.Weight : r.SplitWeight ?? 0).ToArray();
|
||||||
|
|
||||||
public ObservableCollection<Row> DeliveryParts { get; set; }
|
public ObservableCollection<Row> DeliveryParts { get; set; }
|
||||||
|
|
||||||
public DeliverySplittingDialog(Delivery d) {
|
public DeliverySplittingDialog(Delivery d) {
|
||||||
_delivery = d;
|
_delivery = d;
|
||||||
DeliveryParts = [with([.. d.Parts.Select(p => new Row {
|
DeliveryParts = new(d.Parts.Select(p => new Row {
|
||||||
Part = p,
|
Part = p,
|
||||||
SplitCompletely = false,
|
SplitCompletely = false,
|
||||||
SplitWeight = null,
|
SplitWeight = null,
|
||||||
SplitWeightEnabled = true,
|
SplitWeightEnabled = true,
|
||||||
})])];
|
}).ToList());
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
<Window x:Class="Elwig.Dialogs.ManualWeighingDialog"
|
<Window x:Class="Elwig.Dialogs.ManualWeighingDialog"
|
||||||
AutomationProperties.AutomationId="ManualWeighingDialog"
|
|
||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
xmlns:local="clr-namespace:Elwig.Dialogs"
|
xmlns:local="clr-namespace:Elwig.Dialogs"
|
||||||
xmlns:ctrl="clr-namespace:Elwig.Controls"
|
|
||||||
ResizeMode="NoResize" ShowInTaskbar="False" Topmost="True"
|
ResizeMode="NoResize" ShowInTaskbar="False" Topmost="True"
|
||||||
WindowStartupLocation="CenterOwner"
|
WindowStartupLocation="CenterOwner"
|
||||||
FocusManager.FocusedElement="{Binding ElementName=WeightInput}"
|
FocusManager.FocusedElement="{Binding ElementName=WeightInput}"
|
||||||
@@ -39,9 +37,11 @@
|
|||||||
</Grid.ColumnDefinitions>
|
</Grid.ColumnDefinitions>
|
||||||
|
|
||||||
<Label Content="Gewicht:" Margin="10,20,10,10"/>
|
<Label Content="Gewicht:" Margin="10,20,10,10"/>
|
||||||
<ctrl:UnitTextBox x:Name="WeightInput" Grid.Column="1" Width="62" Height="25" Unit="kg"
|
<Grid Grid.Column="1" Width="70" Height="25" Margin="0,20,10,10" HorizontalAlignment="Left" VerticalAlignment="Top">
|
||||||
Margin="0,20,10,10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="14" Padding="2"
|
<TextBox x:Name="WeightInput" TextAlignment="Right" Padding="2,2,17,2"
|
||||||
TextChanged="WeightInput_TextChanged"/>
|
TextChanged="WeightInput_TextChanged"/>
|
||||||
|
<Label Content="kg" Margin="0,4,3,0" HorizontalAlignment="Right" FontSize="10" Padding="2,4,2,4"/>
|
||||||
|
</Grid>
|
||||||
|
|
||||||
<Label Content="Grund:" Margin="10,50,10,10"/>
|
<Label Content="Grund:" Margin="10,50,10,10"/>
|
||||||
<TextBox x:Name="ReasonInput" Grid.Column="1" Margin="0,50,10,10"
|
<TextBox x:Name="ReasonInput" Grid.Column="1" Margin="0,50,10,10"
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ using System.Windows.Controls;
|
|||||||
namespace Elwig.Dialogs {
|
namespace Elwig.Dialogs {
|
||||||
public partial class ManualWeighingDialog : Window {
|
public partial class ManualWeighingDialog : Window {
|
||||||
|
|
||||||
public int Weight { get; private set; }
|
public int Weight = 0;
|
||||||
public string? Reason { get; private set; }
|
public string? Reason = null;
|
||||||
|
|
||||||
public ManualWeighingDialog(string? reason = null) {
|
public ManualWeighingDialog(string? reason = null) {
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
<Window x:Class="Elwig.Dialogs.TareCorrectionDialog"
|
|
||||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
|
||||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
|
||||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
|
||||||
xmlns:local="clr-namespace:Elwig.Dialogs"
|
|
||||||
xmlns:ctrl="clr-namespace:Elwig.Controls"
|
|
||||||
ResizeMode="NoResize" ShowInTaskbar="False" Topmost="True"
|
|
||||||
WindowStartupLocation="CenterOwner"
|
|
||||||
FocusManager.FocusedElement="{Binding ElementName=TargetTareInput}"
|
|
||||||
Title="Tara korrigieren" Height="170" Width="300">
|
|
||||||
<Window.Resources>
|
|
||||||
<Style TargetType="Label">
|
|
||||||
<Setter Property="HorizontalAlignment" Value="Left"/>
|
|
||||||
<Setter Property="VerticalAlignment" Value="Top"/>
|
|
||||||
<Setter Property="Padding" Value="2,4,2,4"/>
|
|
||||||
<Setter Property="Height" Value="25"/>
|
|
||||||
</Style>
|
|
||||||
<Style TargetType="TextBox">
|
|
||||||
<Setter Property="HorizontalAlignment" Value="Stretch"/>
|
|
||||||
<Setter Property="VerticalAlignment" Value="Top"/>
|
|
||||||
<Setter Property="FontSize" Value="14"/>
|
|
||||||
<Setter Property="Padding" Value="2"/>
|
|
||||||
<Setter Property="Height" Value="25"/>
|
|
||||||
<Setter Property="TextWrapping" Value="NoWrap"/>
|
|
||||||
</Style>
|
|
||||||
<Style TargetType="Button">
|
|
||||||
<Setter Property="HorizontalAlignment" Value="Right"/>
|
|
||||||
<Setter Property="VerticalAlignment" Value="Bottom"/>
|
|
||||||
<Setter Property="Width" Value="100"/>
|
|
||||||
<Setter Property="Height" Value="25"/>
|
|
||||||
</Style>
|
|
||||||
</Window.Resources>
|
|
||||||
<Grid>
|
|
||||||
<Grid.ColumnDefinitions>
|
|
||||||
<ColumnDefinition Width="*"/>
|
|
||||||
<ColumnDefinition Width="70"/>
|
|
||||||
<ColumnDefinition Width="3*"/>
|
|
||||||
</Grid.ColumnDefinitions>
|
|
||||||
|
|
||||||
<Label Content="Ist-Tara:" Margin="10,20,0,10" Grid.Column="1"/>
|
|
||||||
<ctrl:UnitTextBox x:Name="ActualTareInput" Grid.Column="2" Width="56" Height="25" Unit="kg" IsReadOnly="True"
|
|
||||||
Margin="0,20,10,10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="14" Padding="2"
|
|
||||||
TextChanged="TareInput_TextChanged"/>
|
|
||||||
|
|
||||||
<Label Content="Soll-Tara:" Margin="10,50,0,10" Grid.Column="1"/>
|
|
||||||
<ctrl:UnitTextBox x:Name="TargetTareInput" Grid.Column="2" Width="56" Height="25" Unit="kg"
|
|
||||||
Margin="0,50,10,10" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="14" Padding="2"
|
|
||||||
TextChanged="TareInput_TextChanged"/>
|
|
||||||
|
|
||||||
<Button x:Name="ConfirmButton" Content="Bestätigen" Margin="10,10,115,10" Grid.ColumnSpan="3" IsEnabled="False" IsDefault="True"
|
|
||||||
Click="ConfirmButton_Click"/>
|
|
||||||
<Button x:Name="CancelButton" Content="Abbrechen" Margin="10,10,10,10" Grid.ColumnSpan="3" IsCancel="True"/>
|
|
||||||
</Grid>
|
|
||||||
</Window>
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
using Elwig.Helpers;
|
|
||||||
using System.Windows;
|
|
||||||
using System.Windows.Controls;
|
|
||||||
|
|
||||||
namespace Elwig.Dialogs {
|
|
||||||
public partial class TareCorrectionDialog : Window {
|
|
||||||
|
|
||||||
public int ActualTare { get; private set; }
|
|
||||||
public int TargetTare { get; private set; }
|
|
||||||
|
|
||||||
public TareCorrectionDialog(int? actualTare, int? targetTare = null) {
|
|
||||||
InitializeComponent();
|
|
||||||
ActualTare = actualTare ?? 0;
|
|
||||||
TargetTare = targetTare ?? actualTare ?? 0;
|
|
||||||
ActualTareInput.IsReadOnly = actualTare != null;
|
|
||||||
ActualTareInput.Text = ActualTare.ToString();
|
|
||||||
TargetTareInput.Text = TargetTare.ToString();
|
|
||||||
TargetTareInput.SelectAll();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ConfirmButton_Click(object sender, RoutedEventArgs evt) {
|
|
||||||
DialogResult = true;
|
|
||||||
ActualTare = int.Parse(ActualTareInput.Text);
|
|
||||||
TargetTare = int.Parse(TargetTareInput.Text);
|
|
||||||
Close();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void UpdateButtons() {
|
|
||||||
ConfirmButton.IsEnabled = ActualTareInput.Text.Length > 0 && TargetTareInput.Text.Length > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void TareInput_TextChanged(object sender, TextChangedEventArgs evt) {
|
|
||||||
if (sender is not TextBox b) return;
|
|
||||||
Validator.CheckInteger(b, true, 4);
|
|
||||||
UpdateButtons();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -30,27 +30,23 @@ namespace Elwig.Documents {
|
|||||||
get {
|
get {
|
||||||
IAddress addr = (Member.BillingAddress != null && UseBillingAddress) ? Member.BillingAddress : Member;
|
IAddress addr = (Member.BillingAddress != null && UseBillingAddress) ? Member.BillingAddress : Member;
|
||||||
var plz = addr.PostalDest.AtPlz;
|
var plz = addr.PostalDest.AtPlz;
|
||||||
return string.Join("\n", ((string?[])[addr is BillingAddr ? addr.FullName : null, Member.AdministrativeName, Member.ForTheAttentionOf, addr.Address, $"{plz?.Plz} {plz?.Ort.Name.Split(",")[0]}", addr.PostalDest.Country.Name]).Where(s => !string.IsNullOrWhiteSpace(s)));
|
return string.Join("\n", ((string?[])[Member.BillingAddress?.FullName, Member.AdministrativeName, Member.ForTheAttentionOf, addr.Address, $"{plz?.Plz} {plz?.Ort.Name.Split(",")[0]}", addr.PostalDest.Country.Name]).Where(s => !string.IsNullOrWhiteSpace(s)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Cell NewAsideCell(Paragraph text, int colspan = 1, bool isName = false, bool right = false, bool center = false) {
|
protected Cell NewAsideCell(Paragraph text, int colspan = 1, bool isName = false) {
|
||||||
var cell = NewCell(text, colspan: colspan).SetPaddingsMM(0.25f, center ? 0 : right ? 1 : 0.5f, 0.25f, isName ? 1 : 0);
|
var cell = NewCell(text, colspan: colspan).SetPaddingsMM(0.25f, 0.5f, 0.25f, isName ? 1 : 0);
|
||||||
if (colspan == 26) {
|
if (colspan > 1) {
|
||||||
cell.SetTextAlignment(TextAlignment.CENTER).SetFont(BF)
|
cell.SetTextAlignment(TextAlignment.CENTER).SetFont(BF)
|
||||||
.SetBackgroundColor(new DeviceRgb(0xe0, 0xe0, 0xe0))
|
.SetBackgroundColor(new DeviceRgb(0xe0, 0xe0, 0xe0))
|
||||||
.SetBorderTop(new SolidBorder(new DeviceRgb(0x80, 0x80, 0x80), BorderThickness))
|
.SetBorderTop(new SolidBorder(new DeviceRgb(0x80, 0x80, 0x80), BorderThickness))
|
||||||
.SetPaddingsMM(0.5f, 1, 0.5f, 1);
|
.SetPaddingsMM(0.5f, 1, 0.5f, 1);
|
||||||
} else if (isName) {
|
|
||||||
cell.SetBorderLeft(new SolidBorder(new DeviceRgb(0x80, 0x80, 0x80), BorderThickness));
|
|
||||||
}
|
}
|
||||||
if (right) cell.SetTextAlignment(TextAlignment.RIGHT);
|
|
||||||
if (center) cell.SetTextAlignment(TextAlignment.CENTER);
|
|
||||||
return cell;
|
return cell;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Cell NewAsideCell(string text, int colspan = 1, bool isName = false, bool right = false, bool center = false) {
|
protected Cell NewAsideCell(string text, int colspan = 1, bool isName = false) {
|
||||||
return NewAsideCell(new KernedParagraph(text, 10), colspan, isName, right, center);
|
return NewAsideCell(new KernedParagraph(text, 10), colspan, isName);
|
||||||
}
|
}
|
||||||
|
|
||||||
public BusinessDocument(string title, Member m, DateOnly? dateFrom, bool includeSender = false) :
|
public BusinessDocument(string title, Member m, DateOnly? dateFrom, bool includeSender = false) :
|
||||||
@@ -64,27 +60,16 @@ namespace Elwig.Documents {
|
|||||||
|
|
||||||
protected override void BeforeRenderBody(iText.Layout.Document doc, PdfDocument pdf) {
|
protected override void BeforeRenderBody(iText.Layout.Document doc, PdfDocument pdf) {
|
||||||
base.BeforeRenderBody(doc, pdf);
|
base.BeforeRenderBody(doc, pdf);
|
||||||
Aside = new Table(ColsMM(2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5))
|
var uid = new KernedParagraph(Member.UstIdNr ?? "-", 10);
|
||||||
.SetWidth(UnitValue.CreatePointValue(65 * PtInMM)).SetFixedLayout()
|
if (!Member.IsBuchführend) uid.Add(Normal(" ")).Add(Italic("(pauschaliert)"));
|
||||||
.SetBorderCollapse(BorderCollapsePropertyValue.COLLAPSE)
|
Aside = new Table(ColsMM(22.5, 42.5))
|
||||||
.SetFont(NF).SetFontSize(10)
|
.SetFont(NF).SetFontSize(10)
|
||||||
|
.SetBorderCollapse(BorderCollapsePropertyValue.COLLAPSE)
|
||||||
.SetBorder(new SolidBorder(new DeviceRgb(0x80, 0x80, 0x80), BorderThickness))
|
.SetBorder(new SolidBorder(new DeviceRgb(0x80, 0x80, 0x80), BorderThickness))
|
||||||
.AddCell(NewAsideCell("Mitglied", 26));
|
.AddCell(NewAsideCell("Mitglied", 2))
|
||||||
if (Member.IsOrganic) {
|
.AddCell(NewAsideCell("Mitglieds-Nr.:", isName: true)).AddCell(NewAsideCell($"{Member.MgNr}"))
|
||||||
Aside
|
.AddCell(NewAsideCell("Betriebs-Nr.:", isName: true)).AddCell(NewAsideCell(Member.LfbisNr ?? ""))
|
||||||
.AddCell(NewAsideCell("Mitgl.-Nr.:", 8, isName: true)).AddCell(NewAsideCell($"{Member.MgNr}", 4, right: true))
|
.AddCell(NewAsideCell("UID:", isName: true)).AddCell(NewAsideCell(uid));
|
||||||
.AddCell(NewAsideCell("Bio-KSt.:", 6, isName: true)).AddCell(NewAsideCell(Member.OrganicAuthorityCode ?? "-", 8, right: true, center: Member.OrganicAuthorityCode == null))
|
|
||||||
.AddCell(NewAsideCell("Betr.-Nr.:", 6, isName: true)).AddCell(NewAsideCell(Member.LfbisNr ?? "-", 6, right: true, center: Member.LfbisNr == null))
|
|
||||||
.AddCell(NewAsideCell("OOC-ID:", 6, isName: true)).AddCell(NewAsideCell(Member.OrganicOperatorId ?? "-", 8, right: true, center: Member.OrganicOperatorId == null))
|
|
||||||
.AddCell(NewAsideCell("UID:", 6, isName: true)).AddCell(NewAsideCell(Member.UstIdNr ?? "-", 10, right: true, center: Member.UstIdNr == null))
|
|
||||||
.AddCell(NewAsideCell(new KernedParagraph("", 10).Add(Italic(Member.IsAccounting ? "(buchführend)" : "(pauschaliert)")), 10, center: true));
|
|
||||||
} else {
|
|
||||||
Aside
|
|
||||||
.AddCell(NewAsideCell("Mitglieds-Nr.:", 12, isName: true)).AddCell(NewAsideCell($"{Member.MgNr}", 4, right: true)).AddCell(NewAsideCell("", 10))
|
|
||||||
.AddCell(NewAsideCell("Betriebs-Nr.:", 10, isName: true)).AddCell(NewAsideCell(Member.LfbisNr ?? "-", 6, right: true, center: Member.LfbisNr == null)).AddCell(NewAsideCell("", 10))
|
|
||||||
.AddCell(NewAsideCell("UID:", 6, isName: true)).AddCell(NewAsideCell(Member.UstIdNr ?? "-", 10, right: true, center: Member.UstIdNr == null))
|
|
||||||
.AddCell(NewAsideCell(new KernedParagraph("", 10).Add(Italic(Member.IsAccounting ? "(buchführend)" : "(pauschaliert)")), 10, center: true));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void RenderAddress(Canvas canvas, Rectangle pageSize) {
|
protected void RenderAddress(Canvas canvas, Rectangle pageSize) {
|
||||||
@@ -137,15 +122,11 @@ namespace Elwig.Documents {
|
|||||||
return new KernedParagraph(10)
|
return new KernedParagraph(10)
|
||||||
.AddAll(Utils.GenerateFooter("\n", " \u00b7 ")
|
.AddAll(Utils.GenerateFooter("\n", " \u00b7 ")
|
||||||
.Item(c.NameFull).NextLine()
|
.Item(c.NameFull).NextLine()
|
||||||
.Item(c.Address).Item($"{c.Plz} {c.Ort}").Item("Österreich").NextGroup()
|
.Item(c.Address).Item($"{c.Plz} {c.Ort}").Item("Österreich").Item("Tel.", c.PhoneNr).Item("Fax", c.FaxNr).NextLine()
|
||||||
.Item("Tel.", c.PhoneNr).Item("Fax", c.FaxNr).NextGroup()
|
.Item(c.EmailAddress != null ? link1 : null)
|
||||||
.Item(c.EmailAddress != null ? link1 : null).NextLine()
|
.Item(c.Website != null ? link2 : null)
|
||||||
.Item(c.Website != null ? link2 : null).NextGroup()
|
.Item("Betriebs-Nr.", c.LfbisNr).Item("Bio-KSt.", c.OrganicAuthority).NextLine()
|
||||||
.Item("Betriebs-Nr.", c.LfbisNr).NextGroup()
|
|
||||||
.Item("Bio-KSt.", c.OrganicAuthorityCode).NextGroup()
|
|
||||||
.Item("OOC-ID", c.OrganicOperatorId).NextLine()
|
|
||||||
.Item("UID", c.UstIdNr).Item("BIC", c.Bic).Item("IBAN", c.Iban)
|
.Item("UID", c.UstIdNr).Item("BIC", c.Bic).Item("IBAN", c.Iban)
|
||||||
.RebalanceLines()
|
|
||||||
.ToLeafElements());
|
.ToLeafElements());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -125,10 +125,10 @@ namespace Elwig.Documents {
|
|||||||
|
|
||||||
protected override void BeforeRenderBody(iText.Layout.Document doc, PdfDocument pdf) {
|
protected override void BeforeRenderBody(iText.Layout.Document doc, PdfDocument pdf) {
|
||||||
base.BeforeRenderBody(doc, pdf);
|
base.BeforeRenderBody(doc, pdf);
|
||||||
Aside?.AddCell(NewAsideCell("Gutschrift", 26))
|
Aside?.AddCell(NewAsideCell("Gutschrift", 2))
|
||||||
.AddCell(NewAsideCell("Tr.-Gutschr.-Nr.:", 12, isName: true)).AddCell(NewAsideCell(Payment?.Credit != null ? $"{Payment.Credit.Year}/{Payment.Credit.TgNr:000}" : "-", 14))
|
.AddCell(NewAsideCell("TG-Nr.:", isName: true)).AddCell(NewAsideCell(Payment?.Credit != null ? $"{Payment.Credit.Year}/{Payment.Credit.TgNr:000}" : "-"))
|
||||||
.AddCell(NewAsideCell("Datum:", 12, isName: true)).AddCell(NewAsideCell($"{Payment?.Variant.Date:dd.MM.yyyy}", 14))
|
.AddCell(NewAsideCell("Datum:", isName: true)).AddCell(NewAsideCell($"{Payment?.Variant.Date:dd.MM.yyyy}"))
|
||||||
.AddCell(NewAsideCell("Überwiesen am:", 12, isName: true)).AddCell(NewAsideCell($"{Payment?.Variant.TransferDate:dd.MM.yyyy}", 14));
|
.AddCell(NewAsideCell("Überw. am:", isName: true)).AddCell(NewAsideCell($"{Payment?.Variant.TransferDate:dd.MM.yyyy}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void RenderBody(iText.Layout.Document doc, PdfDocument pdf) {
|
protected override void RenderBody(iText.Layout.Document doc, PdfDocument pdf) {
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ namespace Elwig.Documents {
|
|||||||
_year = year;
|
_year = year;
|
||||||
ShowDateAndLocation = true;
|
ShowDateAndLocation = true;
|
||||||
UseBillingAddress = true;
|
UseBillingAddress = true;
|
||||||
DocumentId = $"Anlfrg.-Bstng. {_year}/{m.MgNr}";
|
DocumentId = $"Anl.-Best. {_year}/{m.MgNr}";
|
||||||
Data = data;
|
Data = data;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,10 +55,10 @@ namespace Elwig.Documents {
|
|||||||
base.BeforeRenderBody(doc, pdf);
|
base.BeforeRenderBody(doc, pdf);
|
||||||
var firstDay = Data.Rows.MinBy(r => r.Date)?.Date;
|
var firstDay = Data.Rows.MinBy(r => r.Date)?.Date;
|
||||||
var lastDay = Data.Rows.MaxBy(r => r.Date)?.Date;
|
var lastDay = Data.Rows.MaxBy(r => r.Date)?.Date;
|
||||||
Aside?.AddCell(NewAsideCell("Saison", 26))
|
Aside?.AddCell(NewAsideCell("Saison", 2))
|
||||||
.AddCell(NewAsideCell("Lieferungen:", 12, isName: true)).AddCell(NewAsideCell($"{Data.Rows.DistinctBy(r => r.LsNr).Count():N0} (Teil-Lfrg.: {Data.RowNum:N0})", 14))
|
.AddCell(NewAsideCell("Lieferungen:", isName: true)).AddCell(NewAsideCell($"{Data.Rows.DistinctBy(r => r.LsNr).Count():N0} (Teil-Lfrg.: {Data.RowNum:N0})"))
|
||||||
.AddCell(NewAsideCell("Zeitraum:", 8, isName: true)).AddCell(NewAsideCell(firstDay == null || lastDay == null ? "-" : firstDay == lastDay ? $"{firstDay:dd.MM.} (1 Tag)" : $"{firstDay:dd.MM.}\u2013{lastDay:dd.MM.} ({lastDay?.DayNumber - firstDay?.DayNumber + 1:N0} Tage)", 18, center: true))
|
.AddCell(NewAsideCell("Zeitraum:", isName: true)).AddCell(NewAsideCell(firstDay == null || lastDay == null ? "-" : firstDay == lastDay ? $"{firstDay:dd.MM.} (1 Tag)" : $"{firstDay:dd.MM.}\u2013{lastDay:dd.MM.} ({lastDay?.DayNumber - firstDay?.DayNumber + 1:N0} Tage)"))
|
||||||
.AddCell(NewAsideCell("Menge:", 12, isName: true)).AddCell(NewAsideCell($"{MemberStats.Sum(s => s.Weight):N0} kg", 14));
|
.AddCell(NewAsideCell("Menge:", isName: true)).AddCell(NewAsideCell($"{MemberStats.Sum(s => s.Weight):N0} kg"));
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void RenderBody(iText.Layout.Document doc, PdfDocument pdf) {
|
protected override void RenderBody(iText.Layout.Document doc, PdfDocument pdf) {
|
||||||
|
|||||||
@@ -72,10 +72,10 @@ namespace Elwig.Documents {
|
|||||||
|
|
||||||
protected override void BeforeRenderBody(iText.Layout.Document doc, PdfDocument pdf) {
|
protected override void BeforeRenderBody(iText.Layout.Document doc, PdfDocument pdf) {
|
||||||
base.BeforeRenderBody(doc, pdf);
|
base.BeforeRenderBody(doc, pdf);
|
||||||
Aside?.AddCell(NewAsideCell("Lieferung", 26))
|
Aside?.AddCell(NewAsideCell("Lieferung", 2))
|
||||||
.AddCell(NewAsideCell("Lieferschein-Nr.:", 12, isName: true)).AddCell(NewAsideCell(Delivery.LsNr, 14))
|
.AddCell(NewAsideCell("LS-Nr.:", isName: true)).AddCell(NewAsideCell(Delivery.LsNr))
|
||||||
.AddCell(NewAsideCell("Datum/Zeit:", 12, isName: true)).AddCell(NewAsideCell($"{Delivery.Date:dd.MM.yyyy} / {Delivery.Time:HH:mm}", 14))
|
.AddCell(NewAsideCell("Datum/Zeit:", isName: true)).AddCell(NewAsideCell($"{Delivery.Date:dd.MM.yyyy} / {Delivery.Time:HH:mm}"))
|
||||||
.AddCell(NewAsideCell("Zweigstelle:", 12, isName: true)).AddCell(NewAsideCell(Delivery.Branch.Name, 14));
|
.AddCell(NewAsideCell("Zweigstelle:", isName: true)).AddCell(NewAsideCell(Delivery.Branch.Name));
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void RenderBody(iText.Layout.Document doc, PdfDocument pdf) {
|
protected override void RenderBody(iText.Layout.Document doc, PdfDocument pdf) {
|
||||||
@@ -121,7 +121,7 @@ namespace Elwig.Documents {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected Table NewDeliveryTable() {
|
protected Table NewDeliveryTable() {
|
||||||
var tbl = new Table(ColsMM(10, 21, 25, 20, 20, 30, 12.5, 12.5, 14), true)
|
var tbl = new Table(ColsMM(10, 21, 25, 19.5, 19.5, 30, 12.5, 12.5, 15), true)
|
||||||
.SetWidth(UnitValue.CreatePercentValue(100)).SetFixedLayout()
|
.SetWidth(UnitValue.CreatePercentValue(100)).SetFixedLayout()
|
||||||
.SetBorder(Border.NO_BORDER).SetBorderCollapse(BorderCollapsePropertyValue.COLLAPSE);
|
.SetBorder(Border.NO_BORDER).SetBorderCollapse(BorderCollapsePropertyValue.COLLAPSE);
|
||||||
|
|
||||||
@@ -130,16 +130,15 @@ namespace Elwig.Documents {
|
|||||||
.AddHeaderCell(NewTh("Attribut", colspan: 2, rowspan: 2, left: true))
|
.AddHeaderCell(NewTh("Attribut", colspan: 2, rowspan: 2, left: true))
|
||||||
.AddHeaderCell(NewTh("Qualitätsstufe", rowspan: 2, left: true))
|
.AddHeaderCell(NewTh("Qualitätsstufe", rowspan: 2, left: true))
|
||||||
.AddHeaderCell(NewTh("Gradation", colspan: 2))
|
.AddHeaderCell(NewTh("Gradation", colspan: 2))
|
||||||
.AddHeaderCell(NewTh("Menge").SetPaddingRight(0))
|
.AddHeaderCell(NewTh("Menge"))
|
||||||
.AddHeaderCell(NewTh("[°Oe]", 8))
|
.AddHeaderCell(NewTh("[°Oe]", 8))
|
||||||
.AddHeaderCell(NewTh("[°KMW]", 8))
|
.AddHeaderCell(NewTh("[°KMW]", 8))
|
||||||
.AddHeaderCell(NewTh("[kg]", 8).SetPaddingRight(0));
|
.AddHeaderCell(NewTh("[kg]", 8));
|
||||||
|
|
||||||
foreach (var part in Delivery.Parts.OrderBy(p => p.DPNr)) {
|
foreach (var part in Delivery.Parts.OrderBy(p => p.DPNr)) {
|
||||||
var sub = new Table(ColsMM(10, 21, 25, 20, 20, 30, 12.5, 12.5, 14), true)
|
var sub = new Table(ColsMM(10, 21, 25, 19.5, 19.5, 30, 12.5, 12.5, 15), true)
|
||||||
.SetWidth(UnitValue.CreatePercentValue(100)).SetFixedLayout()
|
.SetWidth(UnitValue.CreatePercentValue(100)).SetFixedLayout()
|
||||||
.SetBorderCollapse(BorderCollapsePropertyValue.COLLAPSE)
|
.SetBorderCollapse(BorderCollapsePropertyValue.COLLAPSE);
|
||||||
.SetKeepTogether(true);
|
|
||||||
|
|
||||||
int rowspan = 1 + (part.Cultivation != null ? 1 : 0) + 1 + part.Modifiers.Count() + 1 + (part.Comment != null ? 1 : 0) + (part.Temperature != null || part.Acid != null ? 1 : 0);
|
int rowspan = 1 + (part.Cultivation != null ? 1 : 0) + 1 + part.Modifiers.Count() + 1 + (part.Comment != null ? 1 : 0) + (part.Temperature != null || part.Acid != null ? 1 : 0);
|
||||||
sub.AddCell(NewDeliveryMainTd($"{part.DPNr:N0}", center: true))
|
sub.AddCell(NewDeliveryMainTd($"{part.DPNr:N0}", center: true))
|
||||||
@@ -148,14 +147,11 @@ namespace Elwig.Documents {
|
|||||||
.AddCell(NewDeliveryMainTd(part.Quality.Name))
|
.AddCell(NewDeliveryMainTd(part.Quality.Name))
|
||||||
.AddCell(NewDeliveryMainTd($"{part.Oe:N0}", center: true))
|
.AddCell(NewDeliveryMainTd($"{part.Oe:N0}", center: true))
|
||||||
.AddCell(NewDeliveryMainTd($"{part.Kmw:N1}", center: true))
|
.AddCell(NewDeliveryMainTd($"{part.Kmw:N1}", center: true))
|
||||||
.AddCell(NewDeliveryMainTd($"{part.Weight:N0}", right: true).SetPaddingRight(0));
|
.AddCell(NewDeliveryMainTd($"{part.Weight:N0}", center: true));
|
||||||
|
|
||||||
if (part.Cultivation != null) {
|
if (part.Cultivation != null) {
|
||||||
var cult = new KernedParagraph(8);
|
var cult = new KernedParagraph(8);
|
||||||
cult.Add(Italic("Bewirtschaftung:")).Add(Normal(" " + part.Cultivation.Name + (part.Cultivation.Description != null ? $" ({part.Cultivation.Description})" : "")));
|
cult.Add(Italic("Bewirtschaftung:")).Add(Normal(" " + part.Cultivation.Name + (part.Cultivation.Description != null ? $" ({part.Cultivation.Description})" : "")));
|
||||||
if (part.Cultivation.IsOrganic) {
|
|
||||||
cult.Add(" \u2013 ").Add(Italic("Kontrollstelle:")).Add(Normal($" {Member.OrganicAuthorityCode ?? "?"}"));
|
|
||||||
}
|
|
||||||
sub.AddCell(NewTd())
|
sub.AddCell(NewTd())
|
||||||
.AddCell(NewTd(cult, colspan: 5))
|
.AddCell(NewTd(cult, colspan: 5))
|
||||||
.AddCell(NewTd(colspan: 3));
|
.AddCell(NewTd(colspan: 3));
|
||||||
@@ -185,8 +181,8 @@ namespace Elwig.Documents {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
var info = part.WeighingInfo;
|
var info = part.WeighingInfo;
|
||||||
weighing.Add(Italic("Waage/Terminal:"))
|
weighing.Add(Italic("Waage:"))
|
||||||
.Add(Normal(" " + (info.ScaleId ?? "?") + "/" + (part.ScaleTerminalId ?? "?") + ", "))
|
.Add(Normal(" " + (part.ScaleId ?? "?") + ", "))
|
||||||
.Add(Italic("ID:"))
|
.Add(Italic("ID:"))
|
||||||
.Add(Normal(" " + (info.Id ?? "?")));
|
.Add(Normal(" " + (info.Id ?? "?")));
|
||||||
if (info.Date != null || info.Time != null)
|
if (info.Date != null || info.Time != null)
|
||||||
@@ -200,17 +196,9 @@ namespace Elwig.Documents {
|
|||||||
.Add(Italic("Brutto:"))
|
.Add(Italic("Brutto:"))
|
||||||
.Add(Normal($" {info.Gross:N0} kg \u2013 "))
|
.Add(Normal($" {info.Gross:N0} kg \u2013 "))
|
||||||
.Add(Italic("Tara:"))
|
.Add(Italic("Tara:"))
|
||||||
.Add(Normal($" {info.Tare:N0} kg "));
|
.Add(Normal($" {info.Tare:N0} kg \u2013 "))
|
||||||
if (info.TareCorrection != null && info.TareCorrection != 0)
|
|
||||||
weighing.Add(Bold($"(Korr.: {Utils.GetSign(info.TareCorrection.Value)}{Math.Abs(info.TareCorrection.Value)} kg)")).Add(" ");
|
|
||||||
weighing
|
|
||||||
.Add(Normal("\u2013 "))
|
|
||||||
.Add(Italic("Netto:"))
|
.Add(Italic("Netto:"))
|
||||||
.Add(Normal($" {info.Net:N0} kg "));
|
.Add(Normal($" {info.Net:N0} kg \u2013 "))
|
||||||
if (info.TareCorrection != null && info.TareCorrection != 0)
|
|
||||||
weighing.Add(Normal($"({Utils.GetSign(-info.TareCorrection.Value)}{Math.Abs(info.TareCorrection.Value)} kg) "));
|
|
||||||
weighing
|
|
||||||
.Add(Normal("\u2013 "))
|
|
||||||
.Add(Italic(part.IsNetWeight ? "gerebelt gewogen" : "nicht gerebelt gewogen"));
|
.Add(Italic(part.IsNetWeight ? "gerebelt gewogen" : "nicht gerebelt gewogen"));
|
||||||
} else {
|
} else {
|
||||||
weighing.Add(" ")
|
weighing.Add(" ")
|
||||||
@@ -222,7 +210,7 @@ namespace Elwig.Documents {
|
|||||||
.AddCell(NewCell(colspan: 3));
|
.AddCell(NewCell(colspan: 3));
|
||||||
if (part.Comment != null) {
|
if (part.Comment != null) {
|
||||||
sub.AddCell(NewCell())
|
sub.AddCell(NewCell())
|
||||||
.AddCell(NewCell(new KernedParagraph(8).Add(Italic("Anmerkung:")).Add(Normal(" " + part.Comment)), colspan: 5))
|
.AddCell(NewCell(new KernedParagraph(8).Add(Italic("Anmerkung")).Add(Normal(" " + part.Comment)), colspan: 5))
|
||||||
.AddCell(NewCell(colspan: 3));
|
.AddCell(NewCell(colspan: 3));
|
||||||
}
|
}
|
||||||
if (part.Temperature != null || part.Acid != null) {
|
if (part.Temperature != null || part.Acid != null) {
|
||||||
@@ -232,7 +220,7 @@ namespace Elwig.Documents {
|
|||||||
if (part.Temperature != null && part.Acid != null)
|
if (part.Temperature != null && part.Acid != null)
|
||||||
p.Add(Normal(", "));
|
p.Add(Normal(", "));
|
||||||
if (part.Acid != null)
|
if (part.Acid != null)
|
||||||
p.Add(Italic("Säure:")).Add(Normal($" {part.Acid:N1} g/l"));
|
p.Add(Italic("Säure")).Add(Normal($" {part.Acid:N1} g/l"));
|
||||||
sub.AddCell(NewCell())
|
sub.AddCell(NewCell())
|
||||||
.AddCell(NewCell(p, colspan: 5))
|
.AddCell(NewCell(p, colspan: 5))
|
||||||
.AddCell(NewCell(colspan: 3));
|
.AddCell(NewCell(colspan: 3));
|
||||||
@@ -241,10 +229,10 @@ namespace Elwig.Documents {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (Delivery.Parts.Count > 1) {
|
if (Delivery.Parts.Count > 1) {
|
||||||
tbl.AddCell(NewTd("Gesamt:", 12, bold: true, borderTop: true, colspan: 6).SetPaddingsMM(1, 1, 1, 0))
|
tbl.AddCell(NewTd("Gesamt:", 12, bold: true, borderTop: true, colspan: 6).SetPaddingsMM(1, 1, 1, 1))
|
||||||
.AddCell(NewTd($"{Delivery.Oe:N0}", 12, bold: true, center: true, borderTop: true).SetPaddingsMM(1, 1, 1, 1))
|
.AddCell(NewTd($"{Delivery.Oe:N0}", 12, bold: true, center: true, borderTop: true).SetPaddingsMM(1, 1, 1, 1))
|
||||||
.AddCell(NewTd($"{Delivery.Kmw:N1}", 12, bold: true, center: true, borderTop: true).SetPaddingsMM(1, 1, 1, 1))
|
.AddCell(NewTd($"{Delivery.Kmw:N1}", 12, bold: true, center: true, borderTop: true).SetPaddingsMM(1, 1, 1, 1))
|
||||||
.AddCell(NewTd($"{Delivery.Weight:N0}", 12, bold: true, right: true, borderTop: true).SetPaddingsMM(1, 0, 1, 1));
|
.AddCell(NewTd($"{Delivery.Weight:N0}", 12, bold: true, right: true, borderTop: true).SetPaddingsMM(1, 1, 1, 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
return tbl;
|
return tbl;
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ namespace Elwig.Documents {
|
|||||||
public Document(string title) {
|
public Document(string title) {
|
||||||
Title = title;
|
Title = title;
|
||||||
Author = App.Client.NameFull;
|
Author = App.Client.NameFull;
|
||||||
Date = DateOnly.FromDateTime(DateTime.Today);
|
Date = DateOnly.FromDateTime(Utils.Today);
|
||||||
}
|
}
|
||||||
|
|
||||||
~Document() {
|
~Document() {
|
||||||
@@ -252,7 +252,7 @@ namespace Elwig.Documents {
|
|||||||
|
|
||||||
public async Task Print(int copies = 1) {
|
public async Task Print(int copies = 1) {
|
||||||
if (PdfPath == null) throw new InvalidOperationException("Pdf file has not been generated yet");
|
if (PdfPath == null) throw new InvalidOperationException("Pdf file has not been generated yet");
|
||||||
Pdf.Print(PdfPath, copies, IsDoublePaged);
|
await Pdf.Print(PdfPath, copies, IsDoublePaged);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Show() {
|
public void Show() {
|
||||||
@@ -343,17 +343,22 @@ namespace Elwig.Documents {
|
|||||||
return t;
|
return t;
|
||||||
}
|
}
|
||||||
|
|
||||||
private class EventHandler(Document doc) : AbstractPdfDocumentEventHandler {
|
private class EventHandler : AbstractPdfDocumentEventHandler {
|
||||||
|
|
||||||
private const float _fontSize = 10;
|
private const float _fontSize = 10;
|
||||||
private const float _placeholderWidth = 50 * PtInMM;
|
private const float _placeholderWidth = 50 * PtInMM;
|
||||||
|
|
||||||
private readonly Document _doc = doc;
|
private readonly Document _doc;
|
||||||
private readonly List<PdfFormXObject> _pageNumPlaceholders = [];
|
private readonly List<PdfFormXObject> _pageNumPlaceholders;
|
||||||
|
|
||||||
|
|
||||||
public int NumberOfPages { get; private set; }
|
public int NumberOfPages { get; private set; }
|
||||||
|
|
||||||
|
public EventHandler(Document doc) {
|
||||||
|
_doc = doc;
|
||||||
|
_pageNumPlaceholders = [];
|
||||||
|
}
|
||||||
|
|
||||||
protected override void OnAcceptedEvent(AbstractPdfDocumentEvent evt) {
|
protected override void OnAcceptedEvent(AbstractPdfDocumentEvent evt) {
|
||||||
if (evt.GetType() == PdfDocumentEvent.START_PAGE) {
|
if (evt.GetType() == PdfDocumentEvent.START_PAGE) {
|
||||||
OnPageStart((PdfDocumentEvent)evt);
|
OnPageStart((PdfDocumentEvent)evt);
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ namespace Elwig.Documents {
|
|||||||
public int MemberDeliveredWeightWhite;
|
public int MemberDeliveredWeightWhite;
|
||||||
public List<MemberHistory> MemberHistory = [];
|
public List<MemberHistory> MemberHistory = [];
|
||||||
public Dictionary<string, MemberBucket> MemberBuckets = [];
|
public Dictionary<string, MemberBucket> MemberBuckets = [];
|
||||||
public List<AreaCmt> ActiveAreaCommitments = [];
|
public List<AreaCom> ActiveAreaCommitments = [];
|
||||||
|
|
||||||
public MemberDataSheet(Member m) :
|
public MemberDataSheet(Member m) :
|
||||||
base($"{Name} {m.AdministrativeName}", m, DateOnly.FromDateTime(m.ModifiedAt)) {
|
base($"{Name} {m.AdministrativeName}", m, DateOnly.FromDateTime(m.ModifiedAt)) {
|
||||||
@@ -68,9 +68,9 @@ namespace Elwig.Documents {
|
|||||||
firstOnPage = true;
|
firstOnPage = true;
|
||||||
}
|
}
|
||||||
doc.Add(new KernedParagraph(12).Add(Bold($"Flächenbindungen per {Date:dd.MM.yyyy}")).SetMargins(firstOnPage ? 0 : 24, 0, 6, 0));
|
doc.Add(new KernedParagraph(12).Add(Bold($"Flächenbindungen per {Date:dd.MM.yyyy}")).SetMargins(firstOnPage ? 0 : 24, 0, 6, 0));
|
||||||
doc.Add(NewAreaCmtTable(ActiveAreaCommitments));
|
doc.Add(NewAreaComTable(ActiveAreaCommitments));
|
||||||
}
|
}
|
||||||
if (App.Client.EnableMemberHistory && App.Client.ModeMemberDataSheetShares > 0) {
|
if (App.Client.EnableMemberHistory) {
|
||||||
bool firstOnPage = false;
|
bool firstOnPage = false;
|
||||||
if (pdf.GetNumberOfPages() == 1) {
|
if (pdf.GetNumberOfPages() == 1) {
|
||||||
doc.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
|
doc.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
|
||||||
@@ -158,29 +158,28 @@ namespace Elwig.Documents {
|
|||||||
.AddCell(NewDataTh("Betriebs-Nr.:")).AddCell(NewTd(Member.LfbisNr))
|
.AddCell(NewDataTh("Betriebs-Nr.:")).AddCell(NewTd(Member.LfbisNr))
|
||||||
.AddCell(NewDataTh("UID:", colspan: 2)).AddCell(NewTd(Member.UstIdNr, colspan: 2))
|
.AddCell(NewDataTh("UID:", colspan: 2)).AddCell(NewTd(Member.UstIdNr, colspan: 2))
|
||||||
.AddCell(NewDataTh("Stammgemeinde:")).AddCell(NewTd(Member.DefaultKg?.Name))
|
.AddCell(NewDataTh("Stammgemeinde:")).AddCell(NewTd(Member.DefaultKg?.Name))
|
||||||
.AddCell(NewDataTh("Buchführend:", colspan: 2)).AddCell(NewTd(new KernedParagraph(Member.IsAccounting ? "Ja " : "Nein ", 10)
|
.AddCell(NewDataTh("Buchführend:", colspan: 2)).AddCell(NewTd(new KernedParagraph(Member.IsBuchführend ? "Ja " : "Nein ", 10)
|
||||||
.Add(Normal($"({(Member.IsAccounting ? season.VatNormal : season.VatFlatrate) * 100:N0}% USt.)", 8)), colspan: 2))
|
.Add(Normal($"({(Member.IsBuchführend ? season.VatNormal : season.VatFlatrate) * 100:N0}% USt.)", 8)), colspan: 2))
|
||||||
.AddCell(NewDataTh("(Katastralgemeinde mit dem größten Anteil an Weinbauflächen)", 8, colspan: 2))
|
.AddCell(NewDataTh("(Katastralgemeinde mit dem größten Anteil an Weinbauflächen)", 8, colspan: 2))
|
||||||
.AddCell(NewDataTh("Bio:", colspan: 2)).AddCell(NewTd(new KernedParagraph(Member.IsOrganic ? "Ja" : "Nein", 10)
|
.AddCell(NewDataTh("Bio:", colspan: 2)).AddCell(NewTd(Member.IsOrganic ? "Ja" : "Nein", colspan: 2))
|
||||||
.Add(Normal(Member.OrganicAuthorityCode != null || Member.OrganicOperatorId != null ? $" ({Member.OrganicAuthorityCode}{(Member.OrganicAuthorityCode != null && Member.OrganicOperatorId != null ? ", " : "")}{Member.OrganicOperatorId})" : "", 8)), colspan: 2))
|
|
||||||
.AddCell(NewDataHdr("Genossenschaft", colspan: 6))
|
.AddCell(NewDataHdr("Genossenschaft", colspan: 6))
|
||||||
.AddCell(NewDataTh("Status:")).AddCell(NewTd(new KernedParagraph(Member.IsActive ? "Aktiv " : "Nicht aktiv ", 10)
|
.AddCell(NewDataTh("Status:")).AddCell(NewTd(new KernedParagraph(Member.IsActive ? "Aktiv " : "Nicht aktiv ", 10)
|
||||||
.Add(Normal("(" + (Member.ExitDate != null ? $"{Member.EntryDate:dd.MM.yyyy}\u2013{Member.ExitDate:dd.MM.yyyy}" : $"seit {Member.EntryDate:dd.MM.yyyy}") + ")", 8))))
|
.Add(Normal("(" + (Member.ExitDate != null ? $"{Member.EntryDate:dd.MM.yyyy}\u2013{Member.ExitDate:dd.MM.yyyy}" : $"seit {Member.EntryDate:dd.MM.yyyy}") + ")", 8))))
|
||||||
.AddCell(NewDataTh("Geschäftsanteile:", colspan: 2)).AddCell(NewTd(shares, colspan: 2))
|
.AddCell(NewDataTh("Geschäftsanteile:", colspan: 2)).AddCell(NewTd(shares, colspan: 2))
|
||||||
.AddCell(NewDataTh("Stamm-Zweigstelle:")).AddCell(NewTd(Member.Branch?.Name))
|
.AddCell(NewDataTh("Stamm-Zweigstelle:")).AddCell(NewTd(Member.Branch?.Name))
|
||||||
.AddCell(NewDataTh("Vollablieferer:", colspan: 2)).AddCell(NewTd(Member.IsFullDelivery ? "Ja" : "Nein", colspan: 2))
|
.AddCell(NewDataTh("Volllieferant:", colspan: 2)).AddCell(NewTd(Member.IsVollLieferant ? "Ja" : "Nein", colspan: 2))
|
||||||
.AddCell(NewDataTh("Zusendungen per\u2026")).AddCell(NewTd(new KernedParagraph(10)
|
.AddCell(NewDataTh("Zusendungen per\u2026")).AddCell(NewTd(new KernedParagraph(10)
|
||||||
.Add(Italic("Post:")).Add(Normal(Member.ContactViaPost ? " Ja \u2013 " : " Nein \u2013 "))
|
.Add(Italic("Post:")).Add(Normal(Member.ContactViaPost ? " Ja \u2013 " : " Nein \u2013 "))
|
||||||
.Add(Italic("E-Mail:")).Add(Normal(Member.ContactViaEmail ? " Ja" : " Nein"))))
|
.Add(Italic("E-Mail:")).Add(Normal(Member.ContactViaEmail ? " Ja" : " Nein"))))
|
||||||
.AddCell(NewDataTh("Funktionär:", colspan: 2)).AddCell(NewTd(Member.IsOfficer ? "Ja" : "Nein", colspan: 2));
|
.AddCell(NewDataTh("Funktionär:", colspan: 2)).AddCell(NewTd(Member.IsFunktionär ? "Ja" : "Nein", colspan: 2));
|
||||||
|
|
||||||
return tbl;
|
return tbl;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Table NewAreaCmtTable(IEnumerable<AreaCmt> activeAreaCmts) {
|
protected Table NewAreaComTable(IEnumerable<AreaCom> activeAreaComs) {
|
||||||
var areaCmts = activeAreaCmts.GroupBy(a => a.AreaCmtType).Select(group => new {
|
var areaComs = activeAreaComs.GroupBy(a => a.AreaComType).Select(group => new {
|
||||||
Type = group.Key,
|
Type = group.Key,
|
||||||
AreaCmts = group.OrderBy(c => c.Contract.Kg.AtKg.Name).ToList(),
|
AreaComs = group.OrderBy(c => c.Contract.Kg.AtKg.Name).ToList(),
|
||||||
Size = group.Sum(c => c.Area)
|
Size = group.Sum(c => c.Area)
|
||||||
}).OrderByDescending(a => a.Size).ToList();
|
}).OrderByDescending(a => a.Size).ToList();
|
||||||
|
|
||||||
@@ -199,7 +198,7 @@ namespace Elwig.Documents {
|
|||||||
.AddHeaderCell(NewTh("[m²]"));
|
.AddHeaderCell(NewTh("[m²]"));
|
||||||
|
|
||||||
var lastContract = "";
|
var lastContract = "";
|
||||||
foreach (var contractType in areaCmts) {
|
foreach (var contractType in areaComs) {
|
||||||
tbl.AddCell(NewCell(new KernedParagraph(10).Add(BoldItalic($"{contractType.Type.WineVar.Name} {(contractType.Type.WineAttr != null ? "(" + contractType.Type.WineAttr + ")" : "")}")), colspan: 3)
|
tbl.AddCell(NewCell(new KernedParagraph(10).Add(BoldItalic($"{contractType.Type.WineVar.Name} {(contractType.Type.WineAttr != null ? "(" + contractType.Type.WineAttr + ")" : "")}")), colspan: 3)
|
||||||
.SetBorderTop(contractType.Type.DisplayName != lastContract && lastContract != "" ? new SolidBorder(BorderThickness) : Border.NO_BORDER))
|
.SetBorderTop(contractType.Type.DisplayName != lastContract && lastContract != "" ? new SolidBorder(BorderThickness) : Border.NO_BORDER))
|
||||||
.AddCell(NewCell(new KernedParagraph(10).Add(Bold($"{contractType.Size:N0}")).SetTextAlignment(TextAlignment.RIGHT))
|
.AddCell(NewCell(new KernedParagraph(10).Add(Bold($"{contractType.Size:N0}")).SetTextAlignment(TextAlignment.RIGHT))
|
||||||
@@ -207,20 +206,20 @@ namespace Elwig.Documents {
|
|||||||
.AddCell(NewCell(colspan: 2)
|
.AddCell(NewCell(colspan: 2)
|
||||||
.SetBorderTop(contractType.Type.DisplayName != lastContract && lastContract != "" ? new SolidBorder(BorderThickness) : Border.NO_BORDER));
|
.SetBorderTop(contractType.Type.DisplayName != lastContract && lastContract != "" ? new SolidBorder(BorderThickness) : Border.NO_BORDER));
|
||||||
|
|
||||||
foreach (var areaCmt in contractType.AreaCmts) {
|
foreach (var areaCom in contractType.AreaComs) {
|
||||||
var c = areaCmt.Contract;
|
var c = areaCom.Contract;
|
||||||
tbl.AddCell(NewTd(new KernedParagraph(10).Add(Normal($"{c.Kg.AtKg.Name} ")).Add(Normal($"({c.Kg.AtKg.KgNr:00000})", 8))))
|
tbl.AddCell(NewTd(new KernedParagraph(10).Add(Normal($"{c.Kg.AtKg.Name} ")).Add(Normal($"({c.Kg.AtKg.KgNr:00000})", 8))))
|
||||||
.AddCell(NewTd(c.Rd?.Name))
|
.AddCell(NewTd(c.Rd?.Name))
|
||||||
.AddCell(NewTd(Regex.Replace(areaCmt.GstNr.Replace(",", ", ").Replace("-", "\u2013"), @"\s+", " "), 10))
|
.AddCell(NewTd(Regex.Replace(areaCom.GstNr.Replace(",", ", ").Replace("-", "\u2013"), @"\s+", " "), 10))
|
||||||
.AddCell(NewTd($"{areaCmt.Area:N0}", right: true))
|
.AddCell(NewTd($"{areaCom.Area:N0}", right: true))
|
||||||
.AddCell(NewTd(areaCmt.WineCult?.Name, center: true))
|
.AddCell(NewTd(areaCom.WineCult?.Name, center: true))
|
||||||
.AddCell(NewTd(c.YearTo == null ? (c.YearFrom == null ? "unbefristet" : $"ab {c.YearFrom}") : (c.YearFrom == null ? $"bis {c.YearTo}" : $"{c.YearFrom}–{c.YearTo}"), center: true));
|
.AddCell(NewTd(c.YearTo == null ? (c.YearFrom == null ? "unbefristet" : $"ab {c.YearFrom}") : (c.YearFrom == null ? $"bis {c.YearTo}" : $"{c.YearFrom}–{c.YearTo}"), center: true));
|
||||||
lastContract = contractType.Type.DisplayName;
|
lastContract = contractType.Type.DisplayName;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tbl.AddCell(NewTd("Gesamt:", 12, colspan: 2, bold: true, borderTop: true).SetPaddingsMM(1, 1, 1, 1));
|
tbl.AddCell(NewTd("Gesamt:", 12, colspan: 2, bold: true, borderTop: true).SetPaddingsMM(1, 1, 1, 1));
|
||||||
tbl.AddCell(NewTd($"{activeAreaCmts.Sum(a => a.Area):N0}", 12, colspan: 2, right: true, bold: true, borderTop: true).SetPaddingsMM(1, 1, 1, 1));
|
tbl.AddCell(NewTd($"{activeAreaComs.Sum(a => a.Area):N0}", 12, colspan: 2, right: true, bold: true, borderTop: true).SetPaddingsMM(1, 1, 1, 1));
|
||||||
tbl.AddCell(NewTd(colspan: 2, borderTop: true).SetPaddingsMM(1, 1, 1, 1));
|
tbl.AddCell(NewTd(colspan: 2, borderTop: true).SetPaddingsMM(1, 1, 1, 1));
|
||||||
|
|
||||||
return tbl;
|
return tbl;
|
||||||
@@ -274,11 +273,11 @@ namespace Elwig.Documents {
|
|||||||
.AddCells(NewBusinessSharesCells(new()));
|
.AddCells(NewBusinessSharesCells(new()));
|
||||||
}
|
}
|
||||||
|
|
||||||
var recorded = history.Aggregate(new MemberHistoryPoint(), (s, h) => new(
|
var recorded = history.Aggregate(new MemberHistoryPoint(), (s, h) => new(
|
||||||
s.Shares + (h.ToMgNr == Member.MgNr && h.ToType == BusinessShareType.Normal ? h.Shares : 0) - (h.ToMgNr == h.FromMgNr && h.ToType == BusinessShareType.Normal && h.FromType == BusinessShareType.Normal ? 0 : h.FromMgNr == Member.MgNr && h.FromType == BusinessShareType.Normal ? h.Shares : 0),
|
s.Shares + (h.ToMgNr == Member.MgNr && h.ToType == BusinessShareType.Normal ? h.Shares : 0) - (h.FromMgNr == Member.MgNr && h.FromType == BusinessShareType.Normal ? h.Shares : 0),
|
||||||
s.SharesRed + (h.ToMgNr == Member.MgNr && h.ToType == BusinessShareType.Red ? h.Shares : 0) - (h.ToMgNr == h.FromMgNr && h.ToType == BusinessShareType.Red && h.FromType == BusinessShareType.Red ? 0 : h.FromMgNr == Member.MgNr && h.FromType == BusinessShareType.Red ? h.Shares : 0),
|
s.SharesRed + (h.ToMgNr == Member.MgNr && h.ToType == BusinessShareType.Red ? h.Shares : 0) - (h.FromMgNr == Member.MgNr && h.FromType == BusinessShareType.Red ? h.Shares : 0),
|
||||||
s.SharesWhite + (h.ToMgNr == Member.MgNr && h.ToType == BusinessShareType.White ? h.Shares : 0) - (h.ToMgNr == h.FromMgNr && h.ToType == BusinessShareType.White && h.FromType == BusinessShareType.White ? 0 : h.FromMgNr == Member.MgNr && h.FromType == BusinessShareType.White ? h.Shares : 0),
|
s.SharesWhite + (h.ToMgNr == Member.MgNr && h.ToType == BusinessShareType.White ? h.Shares : 0) - (h.FromMgNr == Member.MgNr && h.FromType == BusinessShareType.White ? h.Shares : 0),
|
||||||
s.SharesDormant + (h.ToMgNr == Member.MgNr && h.ToType == BusinessShareType.Dormant ? h.Shares : 0) - (h.ToMgNr == h.FromMgNr && h.ToType == BusinessShareType.Dormant && h.FromType == BusinessShareType.Dormant ? 0 : h.FromMgNr == Member.MgNr && h.FromType == BusinessShareType.Dormant ? h.Shares : 0)));
|
s.SharesDormant + (h.ToMgNr == Member.MgNr && h.ToType == BusinessShareType.Dormant ? h.Shares : 0) - (h.FromMgNr == Member.MgNr && h.FromType == BusinessShareType.Dormant ? h.Shares : 0)));
|
||||||
var cur = new MemberHistoryPoint(Member.Shares - recorded.Shares, Member.SharesRed - recorded.SharesRed, Member.SharesWhite - recorded.SharesWhite, Member.SharesDormant - recorded.SharesDormant);
|
var cur = new MemberHistoryPoint(Member.Shares - recorded.Shares, Member.SharesRed - recorded.SharesRed, Member.SharesWhite - recorded.SharesWhite, Member.SharesDormant - recorded.SharesDormant);
|
||||||
|
|
||||||
if (cur.Shares != 0 || cur.SharesRed != 0 || cur.SharesWhite != 0 || cur.SharesDormant != 0) {
|
if (cur.Shares != 0 || cur.SharesRed != 0 || cur.SharesWhite != 0 || cur.SharesDormant != 0) {
|
||||||
@@ -297,7 +296,7 @@ namespace Elwig.Documents {
|
|||||||
DateOnly? lastDate = null;
|
DateOnly? lastDate = null;
|
||||||
foreach (var row in history) {
|
foreach (var row in history) {
|
||||||
int s = 0, r = 0, w = 0, d = 0;
|
int s = 0, r = 0, w = 0, d = 0;
|
||||||
if (row.FromMgNr == Member.MgNr && !(row.FromMgNr == row.ToMgNr && row.FromType == row.ToType)) {
|
if (row.FromMgNr == Member.MgNr) {
|
||||||
switch (row.FromType) {
|
switch (row.FromType) {
|
||||||
case BusinessShareType.Normal: s -= row.Shares; break;
|
case BusinessShareType.Normal: s -= row.Shares; break;
|
||||||
case BusinessShareType.Red: r -= row.Shares; break;
|
case BusinessShareType.Red: r -= row.Shares; break;
|
||||||
|
|||||||
@@ -16,14 +16,14 @@ namespace Elwig.Documents {
|
|||||||
public string Filter;
|
public string Filter;
|
||||||
public List<MemberListRow> Members;
|
public List<MemberListRow> Members;
|
||||||
|
|
||||||
public string[] AreaCmtFilters;
|
public string[] AreaComFilters;
|
||||||
public bool FilterAreaCmts => AreaCmtFilters.Length > 0;
|
public bool FilterAreaComs => AreaComFilters.Length > 0;
|
||||||
|
|
||||||
public MemberList(string filter, IEnumerable<MemberListRow> members) :
|
public MemberList(string filter, IEnumerable<MemberListRow> members) :
|
||||||
base(Name) {
|
base(Name) {
|
||||||
Filter = filter;
|
Filter = filter;
|
||||||
Members = [.. members];
|
Members = [.. members];
|
||||||
AreaCmtFilters = [..members
|
AreaComFilters = [..members
|
||||||
.SelectMany(m => m.AreaCommitmentsFiltered)
|
.SelectMany(m => m.AreaCommitmentsFiltered)
|
||||||
.Select(c => c.VtrgId)
|
.Select(c => c.VtrgId)
|
||||||
.Distinct()
|
.Distinct()
|
||||||
@@ -46,11 +46,11 @@ namespace Elwig.Documents {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected Table NewMemberTable(List<MemberListRow> members) {
|
protected Table NewMemberTable(List<MemberListRow> members) {
|
||||||
var tbl = new Table(AreaCmtFilters.Length > 1 ? ColsMM(8, 38, 36, 8, 18, 12, 5, 16, 12, 12) : ColsMM(8, 42, 40, 8, 20, 12, 5, 18, 12), true)
|
var tbl = new Table(AreaComFilters.Length > 1 ? ColsMM(8, 38, 36, 8, 18, 12, 5, 16, 12, 12) : ColsMM(8, 42, 40, 8, 20, 12, 5, 18, 12), true)
|
||||||
.SetWidth(UnitValue.CreatePercentValue(100)).SetFixedLayout()
|
.SetWidth(UnitValue.CreatePercentValue(100)).SetFixedLayout()
|
||||||
.SetBorderCollapse(BorderCollapsePropertyValue.COLLAPSE);
|
.SetBorderCollapse(BorderCollapsePropertyValue.COLLAPSE);
|
||||||
|
|
||||||
var headerSpan = FilterAreaCmts ? 3 : 2;
|
var headerSpan = FilterAreaComs ? 3 : 2;
|
||||||
tbl.AddHeaderCell(NewTh("Nr.", rowspan: headerSpan))
|
tbl.AddHeaderCell(NewTh("Nr.", rowspan: headerSpan))
|
||||||
.AddHeaderCell(NewTh("Name", rowspan: headerSpan, left: true))
|
.AddHeaderCell(NewTh("Name", rowspan: headerSpan, left: true))
|
||||||
.AddHeaderCell(NewTh("Adresse", rowspan: headerSpan, left: true))
|
.AddHeaderCell(NewTh("Adresse", rowspan: headerSpan, left: true))
|
||||||
@@ -59,21 +59,21 @@ namespace Elwig.Documents {
|
|||||||
.AddHeaderCell(NewTh("Betr.-Nr.", rowspan: headerSpan))
|
.AddHeaderCell(NewTh("Betr.-Nr.", rowspan: headerSpan))
|
||||||
.AddHeaderCell(NewTh("GA", rowspan: headerSpan).SetPaddingLeft(0).SetPaddingRight(0))
|
.AddHeaderCell(NewTh("GA", rowspan: headerSpan).SetPaddingLeft(0).SetPaddingRight(0))
|
||||||
.AddHeaderCell(NewTh("Stamm-KG", rowspan: headerSpan, left: true))
|
.AddHeaderCell(NewTh("Stamm-KG", rowspan: headerSpan, left: true))
|
||||||
.AddHeaderCell(NewTh("Geb. Fl.", colspan: FilterAreaCmts ? AreaCmtFilters.Length : 1));
|
.AddHeaderCell(NewTh("Geb. Fl.", colspan: FilterAreaComs ? AreaComFilters.Length : 1));
|
||||||
if (FilterAreaCmts) {
|
if (FilterAreaComs) {
|
||||||
foreach (var vtrgId in AreaCmtFilters) {
|
foreach (var vtrgId in AreaComFilters) {
|
||||||
tbl.AddHeaderCell(NewTh(vtrgId));
|
tbl.AddHeaderCell(NewTh(vtrgId));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (int i = 0; i < (FilterAreaCmts ? AreaCmtFilters.Length : 1); i++) {
|
for (int i = 0; i < (FilterAreaComs ? AreaComFilters.Length : 1); i++) {
|
||||||
tbl.AddHeaderCell(NewTh("[m²]"));
|
tbl.AddHeaderCell(NewTh("[m²]"));
|
||||||
}
|
}
|
||||||
|
|
||||||
string? lastBranch = members.Select(m => m.Branch).Distinct().Count() == 1 ? null : "";
|
string? lastBranch = members.Select(m => m.Branch).Distinct().Count() == 1 ? null : "";
|
||||||
foreach (var m in members) {
|
foreach (var m in members) {
|
||||||
if (lastBranch != null && m.Branch != lastBranch) {
|
if (lastBranch != null && m.Branch != lastBranch) {
|
||||||
tbl.AddCell(NewCell(colspan: 8 + Math.Max(AreaCmtFilters.Length, 1)).SetHeightMM(5).SetKeepWithNext(true));
|
tbl.AddCell(NewCell(colspan: 8 + Math.Max(AreaComFilters.Length, 1)).SetHeightMM(5).SetKeepWithNext(true));
|
||||||
tbl.AddCell(NewCell(new KernedParagraph(m.Branch ?? "", 16).SetFont(BF), colspan: 8 + Math.Max(AreaCmtFilters.Length, 1))
|
tbl.AddCell(NewCell(new KernedParagraph(m.Branch ?? "", 16).SetFont(BF), colspan: 8 + Math.Max(AreaComFilters.Length, 1))
|
||||||
.SetPaddingsMM(1, 2, 1, 2)
|
.SetPaddingsMM(1, 2, 1, 2)
|
||||||
.SetBorder(new SolidBorder(BorderThickness))
|
.SetBorder(new SolidBorder(BorderThickness))
|
||||||
.SetBackgroundColor(new DeviceRgb(0xe0, 0xe0, 0xe0)));
|
.SetBackgroundColor(new DeviceRgb(0xe0, 0xe0, 0xe0)));
|
||||||
@@ -88,8 +88,8 @@ namespace Elwig.Documents {
|
|||||||
.AddCell(NewTd(m.LfbisNr ?? "", 8))
|
.AddCell(NewTd(m.LfbisNr ?? "", 8))
|
||||||
.AddCell(NewTd($"{m.SharesActive:N0}", 8, right: true).SetPaddingLeft(0).SetPaddingRight(0))
|
.AddCell(NewTd($"{m.SharesActive:N0}", 8, right: true).SetPaddingLeft(0).SetPaddingRight(0))
|
||||||
.AddCell(NewTd(m.DefaultKg ?? "", 6));
|
.AddCell(NewTd(m.DefaultKg ?? "", 6));
|
||||||
if (AreaCmtFilters.Length > 0) {
|
if (AreaComFilters.Length > 0) {
|
||||||
foreach (var v in AreaCmtFilters) {
|
foreach (var v in AreaComFilters) {
|
||||||
tbl.AddCell(NewTd($"{m.AreaCommitmentsFiltered.FirstOrDefault(c => c.VtrgId == v).Area:N0}", 8, right: true));
|
tbl.AddCell(NewTd($"{m.AreaCommitmentsFiltered.FirstOrDefault(c => c.VtrgId == v).Area:N0}", 8, right: true));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -101,7 +101,7 @@ namespace Elwig.Documents {
|
|||||||
.AddCell(NewTd(m.BillingAddress ?? "", 8))
|
.AddCell(NewTd(m.BillingAddress ?? "", 8))
|
||||||
.AddCell(NewTd($"{m.BillingPlz}", 8))
|
.AddCell(NewTd($"{m.BillingPlz}", 8))
|
||||||
.AddCell(NewTd(m.BillingLocality ?? "", 6))
|
.AddCell(NewTd(m.BillingLocality ?? "", 6))
|
||||||
.AddCell(NewTd(colspan: 3 + Math.Max(AreaCmtFilters.Length, 1)));
|
.AddCell(NewTd(colspan: 3 + Math.Max(AreaComFilters.Length, 1)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -108,16 +108,16 @@ namespace Elwig.Documents {
|
|||||||
var totalSum = _credits.Sum(p => p.Amount);
|
var totalSum = _credits.Sum(p => p.Amount);
|
||||||
|
|
||||||
var weiRows = data.Rows.Where(r => r.QualityLevel == "Wein");
|
var weiRows = data.Rows.Where(r => r.QualityLevel == "Wein");
|
||||||
var minWei = weiRows.Min(r => r.UnCtrd.MinPrice);
|
var minWei = weiRows.Min(r => r.Ungeb.MinPrice);
|
||||||
var maxWei = weiRows.Max(r => r.UnCtrd.MaxPrice);
|
var maxWei = weiRows.Max(r => r.Ungeb.MaxPrice);
|
||||||
var quwRows = data.Rows.Where(r => r.QualityLevel != "Wein");
|
var quwRows = data.Rows.Where(r => r.QualityLevel != "Wein");
|
||||||
var minPrice = quwRows.Min(r => r.UnCtrd.MinPrice);
|
var minPrice = quwRows.Min(r => r.Ungeb.MinPrice);
|
||||||
var maxPrice = quwRows.Max(r => r.UnCtrd.MaxPrice);
|
var maxPrice = quwRows.Max(r => r.Ungeb.MaxPrice);
|
||||||
var ctrdRows = data.Rows
|
var gebRows = data.Rows
|
||||||
.Where(r => r.Ctrd.MaxPrice != null && r.UnCtrd.MinPrice != null)
|
.Where(r => r.Geb.MaxPrice != null && r.Ungeb.MinPrice != null)
|
||||||
.Select(r => r.Ctrd.MaxPrice - r.UnCtrd.MinPrice);
|
.Select(r => r.Geb.MaxPrice - r.Ungeb.MinPrice);
|
||||||
var minCtrd = ctrdRows.Min();
|
var minGeb = gebRows.Min();
|
||||||
var maxCtrd = ctrdRows.Max();
|
var maxGeb = gebRows.Max();
|
||||||
|
|
||||||
tbl.AddCell(NewSectionHdr("Allgemein", colspan: 5))
|
tbl.AddCell(NewSectionHdr("Allgemein", colspan: 5))
|
||||||
.AddCell(NewSectionHdr("Berücksichtigt", colspan: 3, borderLeft: true))
|
.AddCell(NewSectionHdr("Berücksichtigt", colspan: 3, borderLeft: true))
|
||||||
@@ -197,7 +197,7 @@ namespace Elwig.Documents {
|
|||||||
.AddCell(NewTd(CurrencySymbol))
|
.AddCell(NewTd(CurrencySymbol))
|
||||||
.AddCell(NewTd($"{Math.Abs(vat):N2}", right: true))
|
.AddCell(NewTd($"{Math.Abs(vat):N2}", right: true))
|
||||||
.AddCell(NewSectionTh("Gebunden-Zuschlag:", borderLeft: true))
|
.AddCell(NewSectionTh("Gebunden-Zuschlag:", borderLeft: true))
|
||||||
.AddCell(NewTd(minCtrd == null && maxCtrd == null ? "-" : minCtrd != maxCtrd ? $"{minCtrd:N4}\u2013{maxCtrd:N4} {CurrencySymbol}/kg" : minCtrd == 0 ? "-" : $"{minCtrd:N4} {CurrencySymbol}/kg", colspan: 2, center: true))
|
.AddCell(NewTd(minGeb == null && maxGeb == null ? "-" : minGeb != maxGeb ? $"{minGeb:N4}\u2013{maxGeb:N4} {CurrencySymbol}/kg" : minGeb == 0 ? "-" : $"{minGeb:N4} {CurrencySymbol}/kg", colspan: 2, center: true))
|
||||||
|
|
||||||
.AddCell(NewSectionTh("Bruttosumme:", colspan: 2))
|
.AddCell(NewSectionTh("Bruttosumme:", colspan: 2))
|
||||||
.AddCell(NewTd(borderTop: true))
|
.AddCell(NewTd(borderTop: true))
|
||||||
@@ -211,21 +211,21 @@ namespace Elwig.Documents {
|
|||||||
.AddCell(NewTd(CurrencySymbol))
|
.AddCell(NewTd(CurrencySymbol))
|
||||||
.AddCell(NewTd($"{Math.Abs(totalMods):N2}", right: true))
|
.AddCell(NewTd($"{Math.Abs(totalMods):N2}", right: true))
|
||||||
.AddCell(NewSectionTh("Menge (ungebunden):", borderLeft: true, borderTop: true))
|
.AddCell(NewSectionTh("Menge (ungebunden):", borderLeft: true, borderTop: true))
|
||||||
.AddCell(NewTd($"{data.Rows.Sum(r => r.UnCtrd.Weight):N0} kg", colspan: 2, right: true, borderTop: true))
|
.AddCell(NewTd($"{data.Rows.Sum(r => r.Ungeb.Weight):N0} kg", colspan: 2, right: true, borderTop: true))
|
||||||
|
|
||||||
.AddCell(NewSectionTh("Bereits berücksichtigte Abzüge:", colspan: 2))
|
.AddCell(NewSectionTh("Bereits berücksichtigte Abzüge:", colspan: 2))
|
||||||
.AddCell(NewTd(Utils.GetSign(considered)))
|
.AddCell(NewTd(Utils.GetSign(considered)))
|
||||||
.AddCell(NewTd(CurrencySymbol))
|
.AddCell(NewTd(CurrencySymbol))
|
||||||
.AddCell(NewTd($"{Math.Abs(considered):N2}", right: true))
|
.AddCell(NewTd($"{Math.Abs(considered):N2}", right: true))
|
||||||
.AddCell(NewSectionTh("Menge (gebunden):", borderLeft: true))
|
.AddCell(NewSectionTh("Menge (gebunden):", borderLeft: true))
|
||||||
.AddCell(NewTd($"{data.Rows.Sum(r => r.Ctrd.Weight + r.LowCtrd.Weight):N0} kg", colspan: 2, right: true))
|
.AddCell(NewTd($"{data.Rows.Sum(r => r.Geb.Weight + r.LowGeb.Weight):N0} kg", colspan: 2, right: true))
|
||||||
|
|
||||||
.AddCell(NewSectionTh("Auszahlungsbetrag:", colspan: 2))
|
.AddCell(NewSectionTh("Auszahlungsbetrag:", colspan: 2))
|
||||||
.AddCell(NewTd(borderTop: true))
|
.AddCell(NewTd(borderTop: true))
|
||||||
.AddCell(NewTd(CurrencySymbol, borderTop: true))
|
.AddCell(NewTd(CurrencySymbol, borderTop: true))
|
||||||
.AddCell(NewTd($"{totalSum:N2}", right: true, borderTop: true))
|
.AddCell(NewTd($"{totalSum:N2}", right: true, borderTop: true))
|
||||||
.AddCell(NewSectionTh("Gesamtmenge:", borderLeft: true))
|
.AddCell(NewSectionTh("Gesamtmenge:", borderLeft: true))
|
||||||
.AddCell(NewTd($"{data.Rows.Sum(r => r.UnCtrd.Weight + r.LowCtrd.Weight + r.Ctrd.Weight):N0} kg", colspan: 2, right: true, borderTop: true));
|
.AddCell(NewTd($"{data.Rows.Sum(r => r.Ungeb.Weight + r.LowGeb.Weight + r.Geb.Weight):N0} kg", colspan: 2, right: true, borderTop: true));
|
||||||
|
|
||||||
return tbl;
|
return tbl;
|
||||||
}
|
}
|
||||||
@@ -290,22 +290,22 @@ namespace Elwig.Documents {
|
|||||||
.ToList();
|
.ToList();
|
||||||
var border = lastHdr != null;
|
var border = lastHdr != null;
|
||||||
tbl.AddCell(NewTd(hdr, colspan: 2, bold: true, italic: true, borderTop: border))
|
tbl.AddCell(NewTd(hdr, colspan: 2, bold: true, italic: true, borderTop: border))
|
||||||
.AddCell(NewTd($"{rows.Sum(r => r.UnCtrd.Weight):N0}", right: true, bold: true, borderTop: border))
|
.AddCell(NewTd($"{rows.Sum(r => r.Ungeb.Weight):N0}", right: true, bold: true, borderTop: border))
|
||||||
.AddCell(NewTd(borderTop: border))
|
.AddCell(NewTd(borderTop: border))
|
||||||
.AddCell(NewTd($"{rows.Sum(r => r.LowCtrd.Weight):N0}", right: true, bold: true, borderTop: border))
|
.AddCell(NewTd($"{rows.Sum(r => r.LowGeb.Weight):N0}", right: true, bold: true, borderTop: border))
|
||||||
.AddCell(NewTd(borderTop: border))
|
.AddCell(NewTd(borderTop: border))
|
||||||
.AddCell(NewTd($"{rows.Sum(r => r.Ctrd.Weight):N0}", right: true, bold: true, borderTop: border))
|
.AddCell(NewTd($"{rows.Sum(r => r.Geb.Weight):N0}", right: true, bold: true, borderTop: border))
|
||||||
.AddCell(NewTd(borderTop: border))
|
.AddCell(NewTd(borderTop: border))
|
||||||
.AddCell(NewTd($"{rows.Sum(r => r.Amount):N2}", right: true, bold: true, borderTop: border));
|
.AddCell(NewTd($"{rows.Sum(r => r.Amount):N2}", right: true, bold: true, borderTop: border));
|
||||||
}
|
}
|
||||||
tbl.AddCell(NewTd(row.QualityLevel))
|
tbl.AddCell(NewTd(row.QualityLevel))
|
||||||
.AddCell(NewTd($"{row.Oe:N0}", center: true))
|
.AddCell(NewTd($"{row.Oe:N0}", center: true))
|
||||||
.AddCell(NewTd(row.UnCtrd.Weight != 0 ? $"{row.UnCtrd.Weight:N0}" : "-", right: true))
|
.AddCell(NewTd(row.Ungeb.Weight != 0 ? $"{row.Ungeb.Weight:N0}" : "-", right: true))
|
||||||
.AddCell(NewTd(row.UnCtrd.MaxPrice != null ? $"{row.UnCtrd.MaxPrice:N4}" : "-", right: true))
|
.AddCell(NewTd(row.Ungeb.MaxPrice != null ? $"{row.Ungeb.MaxPrice:N4}" : "-", right: true))
|
||||||
.AddCell(NewTd(row.LowCtrd.Weight != 0 ? $"{row.LowCtrd.Weight:N0}" : "-", right: true))
|
.AddCell(NewTd(row.LowGeb.Weight != 0 ? $"{row.LowGeb.Weight:N0}" : "-", right: true))
|
||||||
.AddCell(NewTd(row.LowCtrd.MaxPrice != null ? $"{row.LowCtrd.MaxPrice:N4}" : "-", right: true))
|
.AddCell(NewTd(row.LowGeb.MaxPrice != null ? $"{row.LowGeb.MaxPrice:N4}" : "-", right: true))
|
||||||
.AddCell(NewTd(row.Ctrd.Weight != 0 ? $"{row.Ctrd.Weight:N0}" : "-", right: true))
|
.AddCell(NewTd(row.Geb.Weight != 0 ? $"{row.Geb.Weight:N0}" : "-", right: true))
|
||||||
.AddCell(NewTd(row.Ctrd.MaxPrice != null ? $"{row.Ctrd.MaxPrice:N4}" : "-", right: true))
|
.AddCell(NewTd(row.Geb.MaxPrice != null ? $"{row.Geb.MaxPrice:N4}" : "-", right: true))
|
||||||
.AddCell(NewTd($"{row.Amount:N2}", right: true));
|
.AddCell(NewTd($"{row.Amount:N2}", right: true));
|
||||||
lastHdr = hdr;
|
lastHdr = hdr;
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-16
@@ -2,17 +2,17 @@
|
|||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>WinExe</OutputType>
|
<OutputType>WinExe</OutputType>
|
||||||
<TargetFramework>net11.0-windows</TargetFramework>
|
<TargetFramework>net10.0-windows</TargetFramework>
|
||||||
<PlatformTarget>x64</PlatformTarget>
|
<PlatformTarget>x64</PlatformTarget>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<UseWPF>true</UseWPF>
|
<UseWPF>true</UseWPF>
|
||||||
<UseWindowsForms>true</UseWindowsForms>
|
<UseWindowsForms>true</UseWindowsForms>
|
||||||
<PreserveCompilationContext>true</PreserveCompilationContext>
|
<PreserveCompilationContext>true</PreserveCompilationContext>
|
||||||
<ApplicationIcon>Resources\Images\Elwig.ico</ApplicationIcon>
|
<ApplicationIcon>Resources\Images\Elwig.ico</ApplicationIcon>
|
||||||
<Version>1.2.1.0</Version>
|
<Version>1.0.5.6</Version>
|
||||||
<SatelliteResourceLanguages>de-AT</SatelliteResourceLanguages>
|
<SatelliteResourceLanguages>de-AT</SatelliteResourceLanguages>
|
||||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
<ApplicationManifest>App.manifest</ApplicationManifest>
|
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@@ -23,21 +23,21 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="bblanchon.PDFium.Win32" Version="160.0.8179" />
|
<PackageReference Include="bblanchon.PDFium.Win32" Version="152.0.7934" />
|
||||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />
|
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />
|
||||||
<PackageReference Include="itext" Version="9.8.1.1" />
|
<PackageReference Include="itext" Version="9.7.0" />
|
||||||
<PackageReference Include="itext.bouncy-castle-adapter" Version="9.8.1.1" />
|
<PackageReference Include="itext.bouncy-castle-adapter" Version="9.7.0" />
|
||||||
<PackageReference Include="LinqKit" Version="1.4.2" />
|
<PackageReference Include="LinqKit" Version="1.3.11" />
|
||||||
<PackageReference Include="MailKit" Version="5.0.0" />
|
<PackageReference Include="MailKit" Version="4.17.0" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="11.0.0" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.9" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Configuration.Ini" Version="11.0.0" />
|
<PackageReference Include="Microsoft.Extensions.Configuration.Ini" Version="10.0.9" />
|
||||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4370.26" />
|
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4078.44" />
|
||||||
<PackageReference Include="NJsonSchema" Version="11.6.2" />
|
<PackageReference Include="NJsonSchema" Version="11.6.1" />
|
||||||
<PackageReference Include="ScottPlot.WPF" Version="5.1.59" />
|
<PackageReference Include="ScottPlot.WPF" Version="5.1.59" />
|
||||||
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" />
|
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.3" />
|
||||||
<PackageReference Include="System.IO.Hashing" Version="11.0.0" />
|
<PackageReference Include="System.IO.Hashing" Version="10.0.9" />
|
||||||
<PackageReference Include="System.IO.Ports" Version="11.0.0" />
|
<PackageReference Include="System.IO.Ports" Version="10.0.9" />
|
||||||
<PackageReference Include="System.Management" Version="11.0.0" />
|
<PackageReference Include="System.Management" Version="10.0.9" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -2,10 +2,14 @@ using System;
|
|||||||
using System.Windows.Input;
|
using System.Windows.Input;
|
||||||
|
|
||||||
namespace Elwig.Helpers {
|
namespace Elwig.Helpers {
|
||||||
public class ActionCommand(Action action) : ICommand {
|
public class ActionCommand : ICommand {
|
||||||
|
|
||||||
public event EventHandler? CanExecuteChanged;
|
public event EventHandler? CanExecuteChanged;
|
||||||
private readonly Action Action = action;
|
private readonly Action Action;
|
||||||
|
|
||||||
|
public ActionCommand(Action action) {
|
||||||
|
Action = action;
|
||||||
|
}
|
||||||
|
|
||||||
public void Execute(object? parameter) {
|
public void Execute(object? parameter) {
|
||||||
Action();
|
Action();
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
using Elwig.Models;
|
|
||||||
using Elwig.Models.Dtos;
|
using Elwig.Models.Dtos;
|
||||||
using Elwig.Models.Entities;
|
using Elwig.Models.Entities;
|
||||||
using Elwig.Services;
|
using Elwig.Services;
|
||||||
@@ -16,7 +15,7 @@ using System.Threading.Tasks;
|
|||||||
namespace Elwig.Helpers {
|
namespace Elwig.Helpers {
|
||||||
|
|
||||||
public record struct MemberHistoryPoint(int Shares, int SharesRed, int SharesWhite, int SharesDormant);
|
public record struct MemberHistoryPoint(int Shares, int SharesRed, int SharesWhite, int SharesDormant);
|
||||||
public record struct AreaCmtBucket(int Area, int Obligation, int Right);
|
public record struct AreaComBucket(int Area, int Obligation, int Right);
|
||||||
public record struct UnderDelivery(int Weight, int Diff);
|
public record struct UnderDelivery(int Weight, int Diff);
|
||||||
public record struct MemberBucket(string Name, int Area, int Obligation, int Right, int Delivery, int DeliveryStrict, int DeliveryTotal, int Payment);
|
public record struct MemberBucket(string Name, int Area, int Obligation, int Right, int Delivery, int DeliveryStrict, int DeliveryTotal, int Payment);
|
||||||
public record struct MemberStat(string Variety, string Discr, int Weight);
|
public record struct MemberStat(string Variety, string Discr, int Weight);
|
||||||
@@ -44,14 +43,14 @@ namespace Elwig.Helpers {
|
|||||||
public DbSet<WineAttr> WineAttributes { get; private set; }
|
public DbSet<WineAttr> WineAttributes { get; private set; }
|
||||||
public DbSet<WineCult> WineCultivations { get; private set; }
|
public DbSet<WineCult> WineCultivations { get; private set; }
|
||||||
public DbSet<Branch> Branches { get; private set; }
|
public DbSet<Branch> Branches { get; private set; }
|
||||||
public DbSet<AreaCmtType> AreaCommitmentTypes { get; private set; }
|
public DbSet<AreaComType> AreaCommitmentTypes { get; private set; }
|
||||||
public DbSet<Member> Members { get; private set; }
|
public DbSet<Member> Members { get; private set; }
|
||||||
public DbSet<BillingAddr> BillingAddresses { get; private set; }
|
public DbSet<BillingAddr> BillingAddresses { get; private set; }
|
||||||
public DbSet<MemberTelNr> MemberTelephoneNrs { get; private set; }
|
public DbSet<MemberTelNr> MemberTelephoneNrs { get; private set; }
|
||||||
public DbSet<MemberEmailAddr> MemberEmailAddrs { get; private set; }
|
public DbSet<MemberEmailAddr> MemberEmailAddrs { get; private set; }
|
||||||
public DbSet<MemberHistory> MemberHistory { get; private set; }
|
public DbSet<MemberHistory> MemberHistory { get; private set; }
|
||||||
public DbSet<AreaCmtContract> AreaCommitmentContracts { get; private set; }
|
public DbSet<AreaComContract> AreaCommitmentContracts { get; private set; }
|
||||||
public DbSet<AreaCmt> AreaCommitments { get; private set; }
|
public DbSet<AreaCom> AreaCommitments { get; private set; }
|
||||||
public DbSet<Season> Seasons { get; private set; }
|
public DbSet<Season> Seasons { get; private set; }
|
||||||
public DbSet<DeliverySchedule> DeliverySchedules { get; private set; }
|
public DbSet<DeliverySchedule> DeliverySchedules { get; private set; }
|
||||||
public DbSet<DeliveryScheduleWineVar> DeliveryScheduleWineVarieties { get; private set; }
|
public DbSet<DeliveryScheduleWineVar> DeliveryScheduleWineVarieties { get; private set; }
|
||||||
@@ -68,10 +67,9 @@ namespace Elwig.Helpers {
|
|||||||
public DbSet<DeliveryPartBucket> DeliveryPartBuckets { get; private set; }
|
public DbSet<DeliveryPartBucket> DeliveryPartBuckets { get; private set; }
|
||||||
|
|
||||||
public DbSet<OverUnderDeliveryRow> OverUnderDeliveryRows { get; private set; }
|
public DbSet<OverUnderDeliveryRow> OverUnderDeliveryRows { get; private set; }
|
||||||
public DbSet<AreaCmtUnderDeliveryRowSingle> AreaCmtUnderDeliveryRows { get; private set; }
|
public DbSet<AreaComUnderDeliveryRowSingle> AreaComUnderDeliveryRows { get; private set; }
|
||||||
public DbSet<MemberDeliveryPerVarietyRowSingle> MemberDeliveryPerVariantRows { get; private set; }
|
public DbSet<MemberDeliveryPerVarietyRowSingle> MemberDeliveryPerVariantRows { get; private set; }
|
||||||
public DbSet<MemberAreaCmtTotalsRowSingle> MemberAreaCmtTotalsRows { get; private set; }
|
public DbSet<MemberAreaComsRowSingle> MemberAreaComsRows { get; private set; }
|
||||||
public DbSet<MemberAreaCmtsRow> MemberAreaCmtsRows { get; private set; }
|
|
||||||
public DbSet<CreditNoteDeliveryRowSingle> CreditNoteDeliveryRows { get; private set; }
|
public DbSet<CreditNoteDeliveryRowSingle> CreditNoteDeliveryRows { get; private set; }
|
||||||
public DbSet<CreditNoteRowSingle> CreditNoteRows { get; private set; }
|
public DbSet<CreditNoteRowSingle> CreditNoteRows { get; private set; }
|
||||||
public DbSet<WeightBreakdownRow> WeightBreakDownRows { get; private set; }
|
public DbSet<WeightBreakdownRow> WeightBreakDownRows { get; private set; }
|
||||||
@@ -111,7 +109,7 @@ namespace Elwig.Helpers {
|
|||||||
private static readonly Func<AppDbContext, bool, IAsyncEnumerable<WineQualLevel>> _compiledQueryWineQualityLevels =
|
private static readonly Func<AppDbContext, bool, IAsyncEnumerable<WineQualLevel>> _compiledQueryWineQualityLevels =
|
||||||
EF.CompileAsyncQuery<AppDbContext, bool, WineQualLevel>((ctx, includePredicate) => ctx.WineQualityLevels
|
EF.CompileAsyncQuery<AppDbContext, bool, WineQualLevel>((ctx, includePredicate) => ctx.WineQualityLevels
|
||||||
.Where(l => includePredicate || !l.IsPredicate)
|
.Where(l => includePredicate || !l.IsPredicate)
|
||||||
.OrderBy(l => l.IsPredicate).ThenBy(l => l.MinKmw));
|
.OrderBy(l => l.MinKmw));
|
||||||
|
|
||||||
private static readonly Func<AppDbContext, int?, bool, IAsyncEnumerable<Modifier>> _compiledQueryModifiers =
|
private static readonly Func<AppDbContext, int?, bool, IAsyncEnumerable<Modifier>> _compiledQueryModifiers =
|
||||||
EF.CompileAsyncQuery<AppDbContext, int?, bool, Modifier>((ctx, year, incudeNotActive) => ctx.Modifiers
|
EF.CompileAsyncQuery<AppDbContext, int?, bool, Modifier>((ctx, year, incudeNotActive) => ctx.Modifiers
|
||||||
@@ -133,8 +131,8 @@ namespace Elwig.Helpers {
|
|||||||
.OrderBy(m => m.Name).ThenBy(m => m.GivenName).ThenBy(m => m.MgNr)
|
.OrderBy(m => m.Name).ThenBy(m => m.GivenName).ThenBy(m => m.MgNr)
|
||||||
.AsSplitQuery());
|
.AsSplitQuery());
|
||||||
|
|
||||||
private static readonly Func<AppDbContext, int?, IAsyncEnumerable<AreaCmt>> _compiledQueryAreaCommitments =
|
private static readonly Func<AppDbContext, int?, IAsyncEnumerable<AreaCom>> _compiledQueryAreaCommitments =
|
||||||
EF.CompileAsyncQuery<AppDbContext, int?, AreaCmt>((ctx, fbnr) => ctx.AreaCommitments
|
EF.CompileAsyncQuery<AppDbContext, int?, AreaCom>((ctx, fbnr) => ctx.AreaCommitments
|
||||||
.Where(c => fbnr == null || c.FbNr == fbnr)
|
.Where(c => fbnr == null || c.FbNr == fbnr)
|
||||||
.OrderBy(c => c.FbNr).ThenBy(c => c.RevNr));
|
.OrderBy(c => c.FbNr).ThenBy(c => c.RevNr));
|
||||||
|
|
||||||
@@ -150,7 +148,7 @@ namespace Elwig.Helpers {
|
|||||||
.OrderByDescending(s => s.Year));
|
.OrderByDescending(s => s.Year));
|
||||||
|
|
||||||
private readonly Dictionary<int, Dictionary<int, MemberHistoryPoint>> _memberHistory = [];
|
private readonly Dictionary<int, Dictionary<int, MemberHistoryPoint>> _memberHistory = [];
|
||||||
private readonly Dictionary<int, Dictionary<int, Dictionary<string, AreaCmtBucket>>> _memberAreaCommitmentBuckets = [];
|
private readonly Dictionary<int, Dictionary<int, Dictionary<string, AreaComBucket>>> _memberAreaCommitmentBuckets = [];
|
||||||
private readonly Dictionary<int, Dictionary<int, Dictionary<string, int>>> _memberDeliveryBuckets = [];
|
private readonly Dictionary<int, Dictionary<int, Dictionary<string, int>>> _memberDeliveryBuckets = [];
|
||||||
private readonly Dictionary<int, Dictionary<int, Dictionary<string, int>>> _memberDeliveryBucketsStrict = [];
|
private readonly Dictionary<int, Dictionary<int, Dictionary<string, int>>> _memberDeliveryBucketsStrict = [];
|
||||||
private readonly Dictionary<int, Dictionary<int, Dictionary<string, int>>> _memberPaymentBuckets = [];
|
private readonly Dictionary<int, Dictionary<int, Dictionary<string, int>>> _memberPaymentBuckets = [];
|
||||||
@@ -171,25 +169,16 @@ namespace Elwig.Helpers {
|
|||||||
SavedChanges += OnSavedChanges;
|
SavedChanges += OnSavedChanges;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void CreateFunctions(SqliteConnection cnx) {
|
|
||||||
cnx.CreateFunction<string, string?, bool?>("REGEXP", (pattern, value) => {
|
|
||||||
return value == null ? null : Regex.IsMatch(value, pattern);
|
|
||||||
}, true);
|
|
||||||
cnx.CreateFunction<string?, string?, string?>("NORMALIZE_ADDRESS", (address, locality) => {
|
|
||||||
return string.IsNullOrWhiteSpace(address) ? null : Normalizer.NormalizeAddress(address, locality);
|
|
||||||
}, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static SqliteConnection Connect(string? connectionString = null) {
|
public static SqliteConnection Connect(string? connectionString = null) {
|
||||||
var cnx = new SqliteConnection(connectionString ?? ConnectionString);
|
var cnx = new SqliteConnection(connectionString ?? ConnectionString);
|
||||||
CreateFunctions(cnx);
|
cnx.CreateFunction<string, string?, bool?>("REGEXP", (pattern, value) => value == null ? null : Regex.Match(value, pattern).Success, true);
|
||||||
cnx.Open();
|
cnx.Open();
|
||||||
return cnx;
|
return cnx;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<SqliteConnection> ConnectAsync(string? connectionString = null) {
|
public static async Task<SqliteConnection> ConnectAsync(string? connectionString = null) {
|
||||||
var cnx = new SqliteConnection(connectionString ?? ConnectionString);
|
var cnx = new SqliteConnection(connectionString ?? ConnectionString);
|
||||||
CreateFunctions(cnx);
|
cnx.CreateFunction<string, string?, bool?>("REGEXP", (pattern, value) => value == null ? null : Regex.Match(value, pattern).Success, true);
|
||||||
await cnx.OpenAsync();
|
await cnx.OpenAsync();
|
||||||
return cnx;
|
return cnx;
|
||||||
}
|
}
|
||||||
@@ -217,8 +206,6 @@ namespace Elwig.Helpers {
|
|||||||
modelBuilder.Entity<BillingAddr>().Navigation(a => a.PostalDest).AutoInclude();
|
modelBuilder.Entity<BillingAddr>().Navigation(a => a.PostalDest).AutoInclude();
|
||||||
modelBuilder.Entity<Modifier>().Navigation(m => m.Season).AutoInclude();
|
modelBuilder.Entity<Modifier>().Navigation(m => m.Season).AutoInclude();
|
||||||
modelBuilder.Entity<Season>().Navigation(s => s.Currency).AutoInclude();
|
modelBuilder.Entity<Season>().Navigation(s => s.Currency).AutoInclude();
|
||||||
modelBuilder.Entity<WineAttr>().Navigation(s => s.MinQualityLevel).AutoInclude();
|
|
||||||
modelBuilder.Entity<WineAttr>().Navigation(s => s.MaxQualityLevel).AutoInclude();
|
|
||||||
modelBuilder.Entity<PaymentVar>().Navigation(v => v.Season).AutoInclude();
|
modelBuilder.Entity<PaymentVar>().Navigation(v => v.Season).AutoInclude();
|
||||||
modelBuilder.Entity<PaymentDeliveryPart>().Navigation(p => p.Variant).AutoInclude();
|
modelBuilder.Entity<PaymentDeliveryPart>().Navigation(p => p.Variant).AutoInclude();
|
||||||
modelBuilder.Entity<Credit>().Navigation(c => c.Payment).AutoInclude();
|
modelBuilder.Entity<Credit>().Navigation(c => c.Payment).AutoInclude();
|
||||||
@@ -232,13 +219,13 @@ namespace Elwig.Helpers {
|
|||||||
modelBuilder.Entity<DeliveryPart>().Navigation(p => p.Kg).AutoInclude();
|
modelBuilder.Entity<DeliveryPart>().Navigation(p => p.Kg).AutoInclude();
|
||||||
modelBuilder.Entity<DeliveryPart>().Navigation(p => p.Rd).AutoInclude();
|
modelBuilder.Entity<DeliveryPart>().Navigation(p => p.Rd).AutoInclude();
|
||||||
modelBuilder.Entity<DeliveryPartModifier>().Navigation(m => m.Modifier).AutoInclude();
|
modelBuilder.Entity<DeliveryPartModifier>().Navigation(m => m.Modifier).AutoInclude();
|
||||||
modelBuilder.Entity<AreaCmtContract>().Navigation(c => c.Kg).AutoInclude();
|
modelBuilder.Entity<AreaComContract>().Navigation(c => c.Kg).AutoInclude();
|
||||||
modelBuilder.Entity<AreaCmtContract>().Navigation(c => c.Rd).AutoInclude();
|
modelBuilder.Entity<AreaComContract>().Navigation(c => c.Rd).AutoInclude();
|
||||||
modelBuilder.Entity<AreaCmt>().Navigation(c => c.Contract).AutoInclude();
|
modelBuilder.Entity<AreaCom>().Navigation(c => c.Contract).AutoInclude();
|
||||||
modelBuilder.Entity<AreaCmt>().Navigation(c => c.WineCult).AutoInclude();
|
modelBuilder.Entity<AreaCom>().Navigation(c => c.WineCult).AutoInclude();
|
||||||
modelBuilder.Entity<AreaCmt>().Navigation(c => c.AreaCmtType).AutoInclude();
|
modelBuilder.Entity<AreaCom>().Navigation(c => c.AreaComType).AutoInclude();
|
||||||
modelBuilder.Entity<AreaCmtType>().Navigation(c => c.WineVar).AutoInclude();
|
modelBuilder.Entity<AreaComType>().Navigation(c => c.WineVar).AutoInclude();
|
||||||
modelBuilder.Entity<AreaCmtType>().Navigation(c => c.WineAttr).AutoInclude();
|
modelBuilder.Entity<AreaComType>().Navigation(c => c.WineAttr).AutoInclude();
|
||||||
modelBuilder.Entity<PaymentMember>().Navigation(c => c.Credit).AutoInclude();
|
modelBuilder.Entity<PaymentMember>().Navigation(c => c.Credit).AutoInclude();
|
||||||
modelBuilder.Entity<PaymentMember>().Navigation(c => c.Member).AutoInclude();
|
modelBuilder.Entity<PaymentMember>().Navigation(c => c.Member).AutoInclude();
|
||||||
modelBuilder.Entity<PaymentMember>().Navigation(c => c.Variant).AutoInclude();
|
modelBuilder.Entity<PaymentMember>().Navigation(c => c.Variant).AutoInclude();
|
||||||
@@ -246,8 +233,6 @@ namespace Elwig.Helpers {
|
|||||||
modelBuilder.Entity<DeliveryAncmt>().Navigation(a => a.Schedule).AutoInclude();
|
modelBuilder.Entity<DeliveryAncmt>().Navigation(a => a.Schedule).AutoInclude();
|
||||||
modelBuilder.Entity<DeliveryAncmt>().Navigation(a => a.Variety).AutoInclude();
|
modelBuilder.Entity<DeliveryAncmt>().Navigation(a => a.Variety).AutoInclude();
|
||||||
modelBuilder.Entity<DeliverySchedule>().Navigation(s => s.Branch).AutoInclude();
|
modelBuilder.Entity<DeliverySchedule>().Navigation(s => s.Branch).AutoInclude();
|
||||||
modelBuilder.Entity<DeliverySchedule>().Navigation(s => s.Attribute).AutoInclude();
|
|
||||||
modelBuilder.Entity<DeliverySchedule>().Navigation(s => s.Cultivation).AutoInclude();
|
|
||||||
modelBuilder.Entity<MemberHistory>().Navigation(s => s.FromMember).AutoInclude();
|
modelBuilder.Entity<MemberHistory>().Navigation(s => s.FromMember).AutoInclude();
|
||||||
modelBuilder.Entity<MemberHistory>().Navigation(s => s.ToMember).AutoInclude();
|
modelBuilder.Entity<MemberHistory>().Navigation(s => s.ToMember).AutoInclude();
|
||||||
modelBuilder.Entity<MemberHistory>().Navigation(s => s.Currency).AutoInclude();
|
modelBuilder.Entity<MemberHistory>().Navigation(s => s.Currency).AutoInclude();
|
||||||
@@ -441,7 +426,7 @@ namespace Elwig.Helpers {
|
|||||||
private async Task FetchMemberAreaCommitmentBuckets(int year, SqliteConnection? cnx = null) {
|
private async Task FetchMemberAreaCommitmentBuckets(int year, SqliteConnection? cnx = null) {
|
||||||
var ownCnx = cnx == null;
|
var ownCnx = cnx == null;
|
||||||
cnx ??= await ConnectAsync();
|
cnx ??= await ConnectAsync();
|
||||||
var buckets = new Dictionary<int, Dictionary<string, AreaCmtBucket>>();
|
var buckets = new Dictionary<int, Dictionary<string, AreaComBucket>>();
|
||||||
using (var cmd = cnx.CreateCommand()) {
|
using (var cmd = cnx.CreateCommand()) {
|
||||||
cmd.CommandText = $"SELECT mgnr, bucket, area, min_kg, max_kg FROM v_area_commitment_bucket WHERE year = {year}";
|
cmd.CommandText = $"SELECT mgnr, bucket, area, min_kg, max_kg FROM v_area_commitment_bucket WHERE year = {year}";
|
||||||
using var reader = await cmd.ExecuteReaderAsync();
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
@@ -534,45 +519,7 @@ namespace Elwig.Helpers {
|
|||||||
return _memberHistory[year].GetValueOrDefault(mgnr, new());
|
return _memberHistory[year].GetValueOrDefault(mgnr, new());
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Dictionary<int, SortedDictionary<DateOnly, MemberHistoryPoint>>> GetMemberHistory() {
|
public async Task<Dictionary<string, AreaComBucket>> GetMemberAreaCommitmentBuckets(int year, int mgnr, SqliteConnection? cnx = null) {
|
||||||
var today = DateOnly.FromDateTime(DateTime.Today).AddDays(1);
|
|
||||||
var history = new Dictionary<int, SortedDictionary<DateOnly, MemberHistoryPoint>>();
|
|
||||||
|
|
||||||
var members = await Members.ToListAsync();
|
|
||||||
foreach (var m in members) {
|
|
||||||
history[m.MgNr] = new() {
|
|
||||||
[today] = new(m.Shares, m.SharesRed, m.SharesWhite, m.SharesDormant),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
var hist = await MemberHistory.OrderByDescending(h => h.DateNoticeString).ToListAsync();
|
|
||||||
foreach (var h in hist) {
|
|
||||||
if (h.FromMgNr is int from) {
|
|
||||||
var latest = history[from].Last().Value;
|
|
||||||
switch (h.FromType) {
|
|
||||||
case BusinessShareType.Normal: latest.Shares += h.Shares; break;
|
|
||||||
case BusinessShareType.Red: latest.SharesRed += h.Shares; break;
|
|
||||||
case BusinessShareType.White: latest.SharesWhite += h.Shares; break;
|
|
||||||
case BusinessShareType.Dormant: latest.SharesDormant += h.Shares; break;
|
|
||||||
}
|
|
||||||
history[from][h.DateNotice] = latest;
|
|
||||||
}
|
|
||||||
if (h.ToMgNr is int to) {
|
|
||||||
var latest = history[to].Last().Value;
|
|
||||||
switch (h.ToType) {
|
|
||||||
case BusinessShareType.Normal: latest.Shares -= h.Shares; break;
|
|
||||||
case BusinessShareType.Red: latest.SharesRed -= h.Shares; break;
|
|
||||||
case BusinessShareType.White: latest.SharesWhite -= h.Shares; break;
|
|
||||||
case BusinessShareType.Dormant: latest.SharesDormant -= h.Shares; break;
|
|
||||||
}
|
|
||||||
history[to][h.DateNotice] = latest;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return history;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<Dictionary<string, AreaCmtBucket>> GetMemberAreaCommitmentBuckets(int year, int mgnr, SqliteConnection? cnx = null) {
|
|
||||||
if (!_memberAreaCommitmentBuckets.ContainsKey(year))
|
if (!_memberAreaCommitmentBuckets.ContainsKey(year))
|
||||||
await FetchMemberAreaCommitmentBuckets(year, cnx);
|
await FetchMemberAreaCommitmentBuckets(year, cnx);
|
||||||
return _memberAreaCommitmentBuckets[year].GetValueOrDefault(mgnr, []);
|
return _memberAreaCommitmentBuckets[year].GetValueOrDefault(mgnr, []);
|
||||||
|
|||||||
@@ -1,33 +1,23 @@
|
|||||||
using Elwig.Services;
|
|
||||||
using Microsoft.Data.Sqlite;
|
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using System.Windows.Input;
|
|
||||||
|
|
||||||
namespace Elwig.Helpers {
|
namespace Elwig.Helpers {
|
||||||
public static class AppDbUpdater {
|
public static class AppDbUpdater {
|
||||||
|
|
||||||
// Don't forget to update value in Tests/fetch-resources.bat!
|
// Don't forget to update value in Tests/fetch-resources.bat!
|
||||||
public static readonly int RequiredSchemaVersion = 43;
|
public static readonly int RequiredSchemaVersion = 40;
|
||||||
|
|
||||||
private static int VersionOffset = 0;
|
private static int VersionOffset = 0;
|
||||||
|
|
||||||
public static async Task<Version> CheckDb() {
|
public static async Task<Version> CheckDb() {
|
||||||
if (!File.Exists(App.Config.DatabaseFile))
|
|
||||||
throw new FileNotFoundException($"Die Datei \"{App.Config.DatabaseFile}\" exisitiert nicht");
|
|
||||||
|
|
||||||
long? applId, schemaVers;
|
long? applId, schemaVers;
|
||||||
using (var cnx = await AppDbContext.ConnectAsync()) {
|
using (var cnx = await AppDbContext.ConnectAsync()) {
|
||||||
|
|
||||||
await cnx.QuickCheck();
|
|
||||||
|
|
||||||
applId = (long?)await cnx.ExecuteScalar("PRAGMA application_id") ?? 0;
|
applId = (long?)await cnx.ExecuteScalar("PRAGMA application_id") ?? 0;
|
||||||
if (applId != 0x454C5747)
|
if (applId != 0x454C5747) throw new Exception($"Invalid application_id in database (0x{applId:X08})");
|
||||||
throw new FileFormatException($"Invalid application_id in database (0x{applId:X08})");
|
|
||||||
|
|
||||||
schemaVers = (long?)await cnx.ExecuteScalar("PRAGMA schema_version") ?? 0;
|
schemaVers = (long?)await cnx.ExecuteScalar("PRAGMA schema_version") ?? 0;
|
||||||
VersionOffset = (int)(schemaVers % 100);
|
VersionOffset = (int)(schemaVers % 100);
|
||||||
@@ -71,11 +61,11 @@ namespace Elwig.Helpers {
|
|||||||
})
|
})
|
||||||
.OrderBy(s => s.Item1).ThenBy(s => s.Item2)];
|
.OrderBy(s => s.Item1).ThenBy(s => s.Item2)];
|
||||||
|
|
||||||
List<(int ToVersion, string File)> toExecute = [];
|
List<string> toExecute = [];
|
||||||
var vers = fromVersion;
|
var vers = fromVersion;
|
||||||
while (vers < toVersion) {
|
while (vers < toVersion) {
|
||||||
var (_, to, name) = scripts.Last(s => s.From == vers);
|
var (_, to, name) = scripts.Last(s => s.From == vers);
|
||||||
toExecute.Add((to, name));
|
toExecute.Add(name);
|
||||||
vers = to;
|
vers = to;
|
||||||
}
|
}
|
||||||
if (toExecute.Count == 0)
|
if (toExecute.Count == 0)
|
||||||
@@ -86,19 +76,16 @@ namespace Elwig.Helpers {
|
|||||||
try {
|
try {
|
||||||
using var cnx = await AppDbContext.ConnectAsync();
|
using var cnx = await AppDbContext.ConnectAsync();
|
||||||
await cnx.ExecuteBatch("PRAGMA locking_mode = EXCLUSIVE");
|
await cnx.ExecuteBatch("PRAGMA locking_mode = EXCLUSIVE");
|
||||||
|
foreach (var script in toExecute) {
|
||||||
await cnx.IntegrityCheck();
|
|
||||||
await cnx.ForeignKeyCheck();
|
|
||||||
|
|
||||||
foreach (var (to, script) in toExecute) {
|
|
||||||
await cnx.ExecuteEmbeddedScript(asm, script);
|
await cnx.ExecuteEmbeddedScript(asm, script);
|
||||||
if (to == 42) {
|
|
||||||
await UpdateDbSchema_41_To_42(cnx);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await cnx.IntegrityCheck();
|
var violations = await cnx.ForeignKeyCheck();
|
||||||
await cnx.ForeignKeyCheck();
|
if (violations.Length > 0) {
|
||||||
|
throw new Exception($"Foreign key violations ({violations.Length}):\n" + string.Join("\n", violations
|
||||||
|
.Take(50)
|
||||||
|
.Select(v => $"{v.Table} - {v.RowId} - {v.Parent} - {v.FkId}")));
|
||||||
|
}
|
||||||
|
|
||||||
await cnx.ExecuteBatch("VACUUM");
|
await cnx.ExecuteBatch("VACUUM");
|
||||||
await cnx.ExecuteBatch($"PRAGMA schema_version = {toVersion * 100 + VersionOffset}");
|
await cnx.ExecuteBatch($"PRAGMA schema_version = {toVersion * 100 + VersionOffset}");
|
||||||
@@ -109,57 +96,5 @@ namespace Elwig.Helpers {
|
|||||||
File.Delete(backup);
|
File.Delete(backup);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task UpdateDbSchema_41_To_42(SqliteConnection cnx) {
|
|
||||||
List<(int MgNr, string LfbisNr, string Name, string Address, int Plz)> members = [];
|
|
||||||
using (var cmd = cnx.CreateCommand()) {
|
|
||||||
cmd.CommandText = """
|
|
||||||
SELECT m.mgnr, m.lfbis_nr,
|
|
||||||
COALESCE(a.name, (COALESCE(m.prefix || ' ', '') || COALESCE(m.given_name || ' ', '') || m.name || COALESCE(' ' || m.middle_names, '') || COALESCE(' ' || m.suffix, ''))),
|
|
||||||
COALESCE(a.address, m.address),
|
|
||||||
COALESCE(aplz.plz, mplz.plz)
|
|
||||||
FROM member m
|
|
||||||
JOIN postal_dest mp ON (mp.country, mp.id) = (m.country, m.postal_dest)
|
|
||||||
JOIN AT_plz_dest ma ON (ma.country, ma.id) = (mp.country, mp.id)
|
|
||||||
JOIN AT_plz mplz ON mplz.plz = ma.plz
|
|
||||||
LEFT JOIN member_billing_address a ON a.mgnr = m.mgnr
|
|
||||||
LEFT JOIN postal_dest ap ON (ap.country, ap.id) = (a.country, a.postal_dest)
|
|
||||||
LEFT JOIN AT_plz_dest aa ON (aa.country, aa.id) = (ap.country, mp.id)
|
|
||||||
LEFT JOIN AT_plz aplz ON aplz.plz = aa.plz
|
|
||||||
WHERE organic
|
|
||||||
""";
|
|
||||||
using var reader = await cmd.ExecuteReaderAsync();
|
|
||||||
var header = await reader.GetColumnSchemaAsync();
|
|
||||||
while (await reader.ReadAsync()) {
|
|
||||||
members.Add((reader.GetInt32(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetInt32(4)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (members.Count > 0)
|
|
||||||
InteractionService.ShowInformation("Datenbank-Update", "Es wird versucht, die Bio-Kontrollstellen-Informationen der Mitglieder automatisch abzurufen. Dies könnte einen kurzen Moment dauern.");
|
|
||||||
|
|
||||||
try {
|
|
||||||
Mouse.OverrideCursor = Cursors.Wait;
|
|
||||||
foreach (var m in members) {
|
|
||||||
string? oocId = null;
|
|
||||||
string? authCode = null;
|
|
||||||
|
|
||||||
var certs = await OrganicService.FetchTracesCertificates(lfbisNr: m.LfbisNr, address: (m.Name, m.Address, m.Plz.ToString()));
|
|
||||||
|
|
||||||
if (certs.Length > 0) {
|
|
||||||
oocId = certs[0].OperatorId;
|
|
||||||
authCode = certs[0].AuthorityCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (oocId != null || authCode != null) {
|
|
||||||
oocId = oocId == null ? "NULL" : $"'{oocId}'";
|
|
||||||
authCode = authCode == null ? "NULL" : $"'{authCode}'";
|
|
||||||
await cnx.ExecuteBatch($"UPDATE member SET ooc_id = {oocId}, org_auth_code = {authCode} WHERE mgnr = {m.MgNr}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
Mouse.OverrideCursor = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -13,32 +13,32 @@ namespace Elwig.Helpers.Billing {
|
|||||||
protected readonly Season Season;
|
protected readonly Season Season;
|
||||||
protected readonly Dictionary<string, string> Attributes;
|
protected readonly Dictionary<string, string> Attributes;
|
||||||
protected readonly Dictionary<string, (decimal?, decimal?)> Modifiers;
|
protected readonly Dictionary<string, (decimal?, decimal?)> Modifiers;
|
||||||
protected readonly Dictionary<string, (string, string?, string?, int?, decimal?)> AreaCmtTypes;
|
protected readonly Dictionary<string, (string, string?, string?, int?, decimal?)> AreaComTypes;
|
||||||
|
|
||||||
protected Billing(int year, Season season,
|
protected Billing(int year, Season season,
|
||||||
Dictionary<string, string> attributes,
|
Dictionary<string, string> attributes,
|
||||||
Dictionary<string, (decimal?, decimal?)> modifiers,
|
Dictionary<string, (decimal?, decimal?)> modifiers,
|
||||||
Dictionary<string, (string, string?, string?, int?, decimal?)> areaCmtTypes
|
Dictionary<string, (string, string?, string?, int?, decimal?)> areaComTypes
|
||||||
) {
|
) {
|
||||||
Year = year;
|
Year = year;
|
||||||
Season = season;
|
Season = season;
|
||||||
Attributes = attributes;
|
Attributes = attributes;
|
||||||
Modifiers = modifiers;
|
Modifiers = modifiers;
|
||||||
AreaCmtTypes = areaCmtTypes;
|
AreaComTypes = areaComTypes;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected static async Task<(Season, Dictionary<string, string>, Dictionary<string, (decimal?, decimal?)>, Dictionary<string, (string, string?, string?, int?, decimal?)>)> LoadData(AppDbContext ctx, int year) {
|
protected static async Task<(Season, Dictionary<string, string>, Dictionary<string, (decimal?, decimal?)>, Dictionary<string, (string, string?, string?, int?, decimal?)>)> LoadData(AppDbContext ctx, int year) {
|
||||||
var season = await ctx.FetchSeasons(year).SingleOrDefaultAsync() ?? throw new ArgumentException("Invalid season");
|
var season = await ctx.FetchSeasons(year).SingleOrDefaultAsync() ?? throw new ArgumentException("Invalid season");
|
||||||
var attributes = await ctx.FetchWineAttributes().ToDictionaryAsync(a => a.AttrId, a => a.Name);
|
var attributes = await ctx.FetchWineAttributes().ToDictionaryAsync(a => a.AttrId, a => a.Name);
|
||||||
var modifiers = await ctx.FetchModifiers(year).ToDictionaryAsync(m => m.ModId, m => (m.Abs, m.Rel));
|
var modifiers = await ctx.FetchModifiers(year).ToDictionaryAsync(m => m.ModId, m => (m.Abs, m.Rel));
|
||||||
var areaCmtTypes = ctx.AreaCommitmentTypes.ToDictionary(v => v.VtrgId, v => (v.SortId, v.AttrId, v.Discriminator, v.MinKgPerHa, v.PenaltyAmount));
|
var areaComTypes = ctx.AreaCommitmentTypes.ToDictionary(v => v.VtrgId, v => (v.SortId, v.AttrId, v.Discriminator, v.MinKgPerHa, v.PenaltyAmount));
|
||||||
return (season, attributes, modifiers, areaCmtTypes);
|
return (season, attributes, modifiers, areaComTypes);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<Billing> Create(int year) {
|
public static async Task<Billing> Create(int year) {
|
||||||
using var ctx = new AppDbContext();
|
using var ctx = new AppDbContext();
|
||||||
var (season, attributes, modifiers, areaCmtTypes) = await LoadData(ctx, year);
|
var (season, attributes, modifiers, areaComTypes) = await LoadData(ctx, year);
|
||||||
return new Billing(year, season, attributes, modifiers, areaCmtTypes);
|
return new Billing(year, season, attributes, modifiers, areaComTypes);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task FinishSeason() {
|
public async Task FinishSeason() {
|
||||||
@@ -77,13 +77,13 @@ namespace Elwig.Helpers.Billing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async Task CalculateBuckets(
|
public async Task CalculateBuckets(
|
||||||
bool? honorContractedField = null,
|
bool? honorGebundenField = null,
|
||||||
bool? allowAttributesIntoLower = null,
|
bool? allowAttributesIntoLower = null,
|
||||||
bool? avoidUnderDeliveries = null,
|
bool? avoidUnderDeliveries = null,
|
||||||
SqliteConnection? cnx = null
|
SqliteConnection? cnx = null
|
||||||
) {
|
) {
|
||||||
using var ctx = new AppDbContext();
|
using var ctx = new AppDbContext();
|
||||||
var honorContracted = honorContractedField ?? Season.Billing_HonorContracted;
|
var honorGebunden = honorGebundenField ?? Season.Billing_HonorGebunden;
|
||||||
var allowAttrsIntoLower = allowAttributesIntoLower ?? Season.Billing_AllowAttrsIntoLower;
|
var allowAttrsIntoLower = allowAttributesIntoLower ?? Season.Billing_AllowAttrsIntoLower;
|
||||||
var avoidUnderDlvrs = avoidUnderDeliveries ?? Season.Billing_AvoidUnderDeliveries;
|
var avoidUnderDlvrs = avoidUnderDeliveries ?? Season.Billing_AvoidUnderDeliveries;
|
||||||
var attrVals = ctx.WineAttributes.ToDictionary(a => a.AttrId, a => (a.IsStrict, a.FillLower));
|
var attrVals = ctx.WineAttributes.ToDictionary(a => a.AttrId, a => (a.IsStrict, a.FillLower));
|
||||||
@@ -96,10 +96,10 @@ namespace Elwig.Helpers.Billing {
|
|||||||
var deliveries = new List<(int, int, int, string, int, double, string, string?, string[], bool?)>();
|
var deliveries = new List<(int, int, int, string, int, double, string, string?, string[], bool?)>();
|
||||||
using (var cmd = cnx.CreateCommand()) {
|
using (var cmd = cnx.CreateCommand()) {
|
||||||
cmd.CommandText = $"""
|
cmd.CommandText = $"""
|
||||||
SELECT mgnr, did, dpnr, sortid, weight, kmw, qualid, attrid, modifiers, contracted
|
SELECT mgnr, did, dpnr, sortid, weight, kmw, qualid, attrid, modifiers, gebunden
|
||||||
FROM v_delivery
|
FROM v_delivery
|
||||||
WHERE year = {Year}
|
WHERE year = {Year}
|
||||||
ORDER BY mgnr, sortid, abgewertet ASC, {(honorContracted ? "contracted IS NOT NULL DESC, contracted DESC," : "")}
|
ORDER BY mgnr, sortid, abgewertet ASC, {(honorGebunden ? "gebunden IS NOT NULL DESC, gebunden DESC," : "")}
|
||||||
attribute_prio DESC, COALESCE(attrid, '~'), kmw DESC, lsnr, dpnr
|
attribute_prio DESC, COALESCE(attrid, '~'), kmw DESC, lsnr, dpnr
|
||||||
""";
|
""";
|
||||||
using var reader = await cmd.ExecuteReaderAsync();
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
@@ -115,14 +115,14 @@ namespace Elwig.Helpers.Billing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int lastMgNr = 0;
|
int lastMgNr = 0;
|
||||||
Dictionary<string, AreaCmtBucket>? rightsAndObligations = null;
|
Dictionary<string, AreaComBucket>? rightsAndObligations = null;
|
||||||
Dictionary<string, int> used = [];
|
Dictionary<string, int> used = [];
|
||||||
foreach (var (mgnr, did, dpnr, sortid, weight, kmw, qualid, attrid, modifiers, contracted) in deliveries) {
|
foreach (var (mgnr, did, dpnr, sortid, weight, kmw, qualid, attrid, modifiers, gebunden) in deliveries) {
|
||||||
if (lastMgNr != mgnr) {
|
if (lastMgNr != mgnr) {
|
||||||
rightsAndObligations = await ctx.GetMemberAreaCommitmentBuckets(Year, mgnr);
|
rightsAndObligations = await ctx.GetMemberAreaCommitmentBuckets(Year, mgnr);
|
||||||
used = [];
|
used = [];
|
||||||
}
|
}
|
||||||
if ((honorContracted && contracted == false) ||
|
if ((honorGebunden && gebunden == false) ||
|
||||||
rightsAndObligations == null || rightsAndObligations.Count == 0 ||
|
rightsAndObligations == null || rightsAndObligations.Count == 0 ||
|
||||||
qualid == "WEI" || qualid == "RSW" || qualid == "LDW")
|
qualid == "WEI" || qualid == "RSW" || qualid == "LDW")
|
||||||
{
|
{
|
||||||
@@ -140,7 +140,7 @@ namespace Elwig.Helpers.Billing {
|
|||||||
foreach (var p in Utils.Permutate(attributes, attributes.Intersect(attrForced))) {
|
foreach (var p in Utils.Permutate(attributes, attributes.Intersect(attrForced))) {
|
||||||
var c = p.Count();
|
var c = p.Count();
|
||||||
var key = sortid + string.Join("", p);
|
var key = sortid + string.Join("", p);
|
||||||
if (rightsAndObligations.TryGetValue(key, out AreaCmtBucket value)) {
|
if (rightsAndObligations.TryGetValue(key, out AreaComBucket value)) {
|
||||||
int i = (c == 0) ? 1 : 2;
|
int i = (c == 0) ? 1 : 2;
|
||||||
var u = used.GetValueOrDefault(key, 0);
|
var u = used.GetValueOrDefault(key, 0);
|
||||||
var vr = Math.Max(0, Math.Min(value.Right - u, w));
|
var vr = Math.Max(0, Math.Min(value.Right - u, w));
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ namespace Elwig.Helpers.Billing {
|
|||||||
|
|
||||||
public enum CalculationMode { Elwig, WgMaster }
|
public enum CalculationMode { Elwig, WgMaster }
|
||||||
public enum CurveMode { Oe, Kmw }
|
public enum CurveMode { Oe, Kmw }
|
||||||
public record struct Curve(CurveMode Mode, Dictionary<double, decimal> Normal, Dictionary<double, decimal>? Contracted);
|
public record struct Curve(CurveMode Mode, Dictionary<double, decimal> Normal, Dictionary<double, decimal>? Gebunden);
|
||||||
|
|
||||||
public static JsonSchema? Schema { get; private set; }
|
public static JsonSchema? Schema { get; private set; }
|
||||||
|
|
||||||
@@ -179,10 +179,10 @@ namespace Elwig.Helpers.Billing {
|
|||||||
} else {
|
} else {
|
||||||
throw new InvalidOperationException();
|
throw new InvalidOperationException();
|
||||||
}
|
}
|
||||||
var ctrd = obj["ctrd"] ?? obj["geb"];
|
var geb = obj["geb"];
|
||||||
if (ctrd is JsonObject) {
|
if (geb is JsonObject) {
|
||||||
c2 = GetCurveData(ctrd.AsObject(), cMode);
|
c2 = GetCurveData(geb.AsObject(), cMode);
|
||||||
} else if (ctrd?.AsValue().TryGetValue(out decimal v) == true) {
|
} else if (geb?.AsValue().TryGetValue(out decimal v) == true) {
|
||||||
var splitVal = GetCurveValueAt(c1, quw);
|
var splitVal = GetCurveValueAt(c1, quw);
|
||||||
c2 = c1.ToDictionary(e => e.Key, e => e.Value + (e.Key >= quw ? v : 0));
|
c2 = c1.ToDictionary(e => e.Key, e => e.Value + (e.Key >= quw ? v : 0));
|
||||||
c2[quw] = splitVal + v;
|
c2[quw] = splitVal + v;
|
||||||
@@ -251,31 +251,31 @@ namespace Elwig.Helpers.Billing {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
return new JsonObject() {
|
return new JsonObject() {
|
||||||
["15kmw"] = Math.Round((decimal)y.Distinct().Single(), prec)
|
["15kmw"] = Math.Round(y.Distinct().Single(), prec)
|
||||||
};
|
};
|
||||||
} catch { }
|
} catch { }
|
||||||
|
|
||||||
var data = new JsonObject();
|
var data = new JsonObject();
|
||||||
if (y[0] != y[1]) {
|
if (y[0] != y[1]) {
|
||||||
data[$"{x[0]}{mode}"] = Math.Round((decimal)y[0], prec);
|
data[$"{x[0]}{mode}"] = Math.Round(y[0], prec);
|
||||||
}
|
}
|
||||||
for (int i = 1; i < x.Length - 1; i++) {
|
for (int i = 1; i < x.Length - 1; i++) {
|
||||||
var d1 = Math.Round((decimal)(y[i] - y[i - 1]), prec);
|
var d1 = Math.Round(y[i] - y[i - 1], prec);
|
||||||
var d2 = Math.Round((decimal)(y[i + 1] - y[i]), prec);
|
var d2 = Math.Round(y[i + 1] - y[i], prec);
|
||||||
if (d1 != d2) {
|
if (d1 != d2) {
|
||||||
data[$"{x[i]}{mode}"] = Math.Round((decimal)y[i], prec);
|
data[$"{x[i]}{mode}"] = Math.Round(y[i], prec);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (y[^1] != y[^2]) {
|
if (y[^1] != y[^2]) {
|
||||||
data[$"{x[^1]}{mode}"] = Math.Round((decimal)y[^1], prec);
|
data[$"{x[^1]}{mode}"] = Math.Round(y[^1], prec);
|
||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected static JsonNode GraphEntryToJson(GraphEntry entry) {
|
protected static JsonNode GraphEntryToJson(GraphEntry entry) {
|
||||||
try {
|
try {
|
||||||
if (entry.ContractedFlatBonus == null) {
|
if (entry.GebundenFlatBonus == null) {
|
||||||
return JsonValue.Create(Math.Round((decimal)entry.DataGraph.DataY.Distinct().Single(), entry.DataGraph.Precision));
|
return JsonValue.Create((decimal)entry.DataGraph.DataY.Distinct().Single());
|
||||||
}
|
}
|
||||||
} catch { }
|
} catch { }
|
||||||
|
|
||||||
@@ -286,10 +286,10 @@ namespace Elwig.Helpers.Billing {
|
|||||||
|
|
||||||
curve["data"] = GraphToJson(entry.DataGraph, entry.Mode.ToString().ToLower());
|
curve["data"] = GraphToJson(entry.DataGraph, entry.Mode.ToString().ToLower());
|
||||||
|
|
||||||
if (entry.ContractedFlatBonus != null) {
|
if (entry.GebundenFlatBonus != null) {
|
||||||
curve["ctrd"] = Math.Round((decimal)entry.ContractedFlatBonus, entry.ContractedGraph?.Precision ?? entry.DataGraph.Precision);
|
curve["geb"] = (decimal)entry.GebundenFlatBonus;
|
||||||
} else if (entry.ContractedGraph != null) {
|
} else if (entry.GebundenGraph != null) {
|
||||||
curve["ctrd"] = GraphToJson(entry.ContractedGraph, entry.Mode.ToString().ToLower());
|
curve["geb"] = GraphToJson(entry.GebundenGraph, entry.Mode.ToString().ToLower());
|
||||||
}
|
}
|
||||||
|
|
||||||
return curve;
|
return curve;
|
||||||
|
|||||||
@@ -16,9 +16,9 @@ namespace Elwig.Helpers.Billing {
|
|||||||
protected BillingVariant(int year, int avnr, Season season,
|
protected BillingVariant(int year, int avnr, Season season,
|
||||||
Dictionary<string, string> attributes,
|
Dictionary<string, string> attributes,
|
||||||
Dictionary<string, (decimal?, decimal?)> modifiers,
|
Dictionary<string, (decimal?, decimal?)> modifiers,
|
||||||
Dictionary<string, (string, string?, string?, int?, decimal?)> areaCmtTypes,
|
Dictionary<string, (string, string?, string?, int?, decimal?)> areaComTypes,
|
||||||
PaymentVar paymentVar, PaymentBillingData data) :
|
PaymentVar paymentVar, PaymentBillingData data) :
|
||||||
base(year, season, attributes, modifiers, areaCmtTypes) {
|
base(year, season, attributes, modifiers, areaComTypes) {
|
||||||
AvNr = avnr;
|
AvNr = avnr;
|
||||||
PaymentVariant = paymentVar;
|
PaymentVariant = paymentVar;
|
||||||
Data = data;
|
Data = data;
|
||||||
@@ -32,16 +32,16 @@ namespace Elwig.Helpers.Billing {
|
|||||||
|
|
||||||
public static async Task<BillingVariant> Create(int year, int avnr) {
|
public static async Task<BillingVariant> Create(int year, int avnr) {
|
||||||
using var ctx = new AppDbContext();
|
using var ctx = new AppDbContext();
|
||||||
var (season, attributes, modifiers, areaCmtTypes) = await LoadData(ctx, year);
|
var (season, attributes, modifiers, areaComTypes) = await LoadData(ctx, year);
|
||||||
var (paymentVar, data) = await LoadData(ctx, year, avnr);
|
var (paymentVar, data) = await LoadData(ctx, year, avnr);
|
||||||
return new BillingVariant(year, avnr, season, attributes, modifiers, areaCmtTypes, paymentVar, data);
|
return new BillingVariant(year, avnr, season, attributes, modifiers, areaComTypes, paymentVar, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task Calculate(bool strictPrices = true, bool? honorContracted = null, bool? allowAttrsIntoLower = null, bool? avoidUnderDeliveries = null) {
|
public async Task Calculate(bool strictPrices = true, bool? honorGebunden = null, bool? allowAttrsIntoLower = null, bool? avoidUnderDeliveries = null) {
|
||||||
if (PaymentVariant == null || Data == null) throw new Exception("Call Load before Calculate");
|
if (PaymentVariant == null || Data == null) throw new Exception("Call Load before Calculate");
|
||||||
using var cnx = await AppDbContext.ConnectAsync();
|
using var cnx = await AppDbContext.ConnectAsync();
|
||||||
using var tx = await cnx.BeginTransactionAsync();
|
using var tx = await cnx.BeginTransactionAsync();
|
||||||
await CalculateBuckets(honorContracted, allowAttrsIntoLower, avoidUnderDeliveries, cnx);
|
await CalculateBuckets(honorGebunden, allowAttrsIntoLower, avoidUnderDeliveries, cnx);
|
||||||
await DeleteInDb(cnx);
|
await DeleteInDb(cnx);
|
||||||
await SetCalcTime(cnx);
|
await SetCalcTime(cnx);
|
||||||
KeyNotFoundException? exception = null;
|
KeyNotFoundException? exception = null;
|
||||||
@@ -73,7 +73,7 @@ namespace Elwig.Helpers.Billing {
|
|||||||
v.avnr,
|
v.avnr,
|
||||||
ROUND(p.amount / POW(10, s.precision - 2)) AS net_amount,
|
ROUND(p.amount / POW(10, s.precision - 2)) AS net_amount,
|
||||||
IIF(lc.amount < 0, 0, ROUND(lp.amount / POW(10, s.precision - 2))) AS prev_net_amount,
|
IIF(lc.amount < 0, 0, ROUND(lp.amount / POW(10, s.precision - 2))) AS prev_net_amount,
|
||||||
IIF(m.accounting, s.vat_normal, s.vat_flatrate) AS vat,
|
IIF(m.buchführend, s.vat_normal, s.vat_flatrate) AS vat,
|
||||||
ROUND(IIF({Data.ConsiderTotalPenalty}, COALESCE(b.total_penalty, 0), 0) / POW(10, s.precision - 2)) +
|
ROUND(IIF({Data.ConsiderTotalPenalty}, COALESCE(b.total_penalty, 0), 0) / POW(10, s.precision - 2)) +
|
||||||
ROUND(IIF({Data.ConsiderContractPenalties}, COALESCE(u.total_penalty, 0), 0) / POW(10, 4 - 2)) +
|
ROUND(IIF({Data.ConsiderContractPenalties}, COALESCE(u.total_penalty, 0), 0) / POW(10, 4 - 2)) +
|
||||||
ROUND(IIF({Data.ConsiderAutoBusinessShares}, -COALESCE(a.total_amount, 0), 0)) +
|
ROUND(IIF({Data.ConsiderAutoBusinessShares}, -COALESCE(a.total_amount, 0), 0)) +
|
||||||
@@ -170,7 +170,7 @@ namespace Elwig.Helpers.Billing {
|
|||||||
|
|
||||||
protected async Task CalculatePrices(SqliteConnection cnx, bool strict = true) {
|
protected async Task CalculatePrices(SqliteConnection cnx, bool strict = true) {
|
||||||
var invalid = new HashSet<string>();
|
var invalid = new HashSet<string>();
|
||||||
var parts = new List<(int Year, int DId, int DPNr, int BktNr, string SortId, string? AttrId, string? CultId, string Discr, int Value, double Oe, double Kmw, string QualId, bool AttrAreaCmt)>();
|
var parts = new List<(int Year, int DId, int DPNr, int BktNr, string SortId, string? AttrId, string? CultId, string Discr, int Value, double Oe, double Kmw, string QualId, bool AttrAreaCom)>();
|
||||||
using (var cmd = cnx.CreateCommand()) {
|
using (var cmd = cnx.CreateCommand()) {
|
||||||
cmd.CommandText = $"""
|
cmd.CommandText = $"""
|
||||||
SELECT d.year, d.did, d.dpnr, b.bktnr, d.sortid, d.attrid, d.cultid, b.discr, b.value, d.oe, d.kmw, d.qualid, COALESCE(a.area_com, TRUE)
|
SELECT d.year, d.did, d.dpnr, b.bktnr, d.sortid, d.attrid, d.cultid, b.discr, b.value, d.oe, d.kmw, d.qualid, COALESCE(a.area_com, TRUE)
|
||||||
@@ -195,13 +195,13 @@ namespace Elwig.Helpers.Billing {
|
|||||||
foreach (var part in parts) {
|
foreach (var part in parts) {
|
||||||
if (part.Value == 0)
|
if (part.Value == 0)
|
||||||
continue;
|
continue;
|
||||||
var unctrd = part.Discr == "_";
|
var ungeb = part.Discr == "_";
|
||||||
var payAttrId = (part.Discr is "" or "_") ? null : part.Discr;
|
var payAttrId = (part.Discr is "" or "_") ? null : part.Discr;
|
||||||
var attrId = part.AttrAreaCmt ? payAttrId : part.AttrId;
|
var attrId = part.AttrAreaCom ? payAttrId : part.AttrId;
|
||||||
var ctrd = !unctrd && (payAttrId == attrId || !part.AttrAreaCmt);
|
var geb = !ungeb && (payAttrId == attrId || !part.AttrAreaCom);
|
||||||
decimal price = 0;
|
decimal price = 0;
|
||||||
try {
|
try {
|
||||||
price = Data.CalculatePrice(part.SortId, attrId, part.CultId, part.QualId, ctrd, part.Oe, part.Kmw);
|
price = Data.CalculatePrice(part.SortId, attrId, part.CultId, part.QualId, geb, part.Oe, part.Kmw);
|
||||||
} catch (KeyNotFoundException e) {
|
} catch (KeyNotFoundException e) {
|
||||||
invalid.Add(e.Message.Split('\'')[1]);
|
invalid.Add(e.Message.Split('\'')[1]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ namespace Elwig.Helpers.Billing {
|
|||||||
public class GraphEntry {
|
public class GraphEntry {
|
||||||
|
|
||||||
public const int MinX = 50;
|
public const int MinX = 50;
|
||||||
public const int MinXCtrd = 73;
|
public const int MinXGeb = 73;
|
||||||
public const int MaxX = 120;
|
public const int MaxX = 120;
|
||||||
|
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
@@ -15,11 +15,11 @@ namespace Elwig.Helpers.Billing {
|
|||||||
public bool Abgewertet { get; set; }
|
public bool Abgewertet { get; set; }
|
||||||
|
|
||||||
public Graph DataGraph { get; set; }
|
public Graph DataGraph { get; set; }
|
||||||
public Graph? ContractedGraph { get; set; }
|
public Graph? GebundenGraph { get; set; }
|
||||||
public double? ContractedFlatBonus {
|
public double? GebundenFlatBonus {
|
||||||
get {
|
get {
|
||||||
try {
|
try {
|
||||||
var val = ContractedGraph?.DataX.Zip(ContractedGraph.DataY)
|
var val = GebundenGraph?.DataX.Zip(GebundenGraph.DataY)
|
||||||
.Select(e => Math.Round(e.Second - DataGraph.GetPriceAtOe(e.First), Precision))
|
.Select(e => Math.Round(e.Second - DataGraph.GetPriceAtOe(e.First), Precision))
|
||||||
.Distinct()
|
.Distinct()
|
||||||
.Single();
|
.Single();
|
||||||
@@ -30,10 +30,10 @@ namespace Elwig.Helpers.Billing {
|
|||||||
}
|
}
|
||||||
set {
|
set {
|
||||||
if (value is not double v) return;
|
if (value is not double v) return;
|
||||||
var values = Enumerable.Range(MinXCtrd, MaxX - MinXCtrd + 1)
|
var values = Enumerable.Range(MinXGeb, MaxX - MinXGeb + 1)
|
||||||
.Select(i => Math.Round(DataGraph.GetPriceAtOe(i) + v, Precision))
|
.Select(i => Math.Round(DataGraph.GetPriceAtOe(i) + v, Precision))
|
||||||
.ToArray();
|
.ToArray();
|
||||||
ContractedGraph = new Graph(values, Precision, MinXCtrd, MaxX);
|
GebundenGraph = new Graph(values, Precision, MinXGeb, MaxX);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,39 +52,39 @@ namespace Elwig.Helpers.Billing {
|
|||||||
Vaributes = [];
|
Vaributes = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
public GraphEntry(int id, int precision, BillingData.CurveMode mode, Dictionary<double, decimal> data, Dictionary<double, decimal>? contracted) :
|
public GraphEntry(int id, int precision, BillingData.CurveMode mode, Dictionary<double, decimal> data, Dictionary<double, decimal>? gebunden) :
|
||||||
this(id, precision, mode) {
|
this(id, precision, mode) {
|
||||||
DataGraph = new Graph(data, precision, MinX, MaxX);
|
DataGraph = new Graph(data, precision, MinX, MaxX);
|
||||||
if (contracted != null) ContractedGraph = new Graph(contracted, precision, MinXCtrd, MaxX);
|
if (gebunden != null) GebundenGraph = new Graph(gebunden, precision, MinXGeb, MaxX);
|
||||||
}
|
}
|
||||||
|
|
||||||
public GraphEntry(int id, int precision, BillingData.Curve curve, List<Varibute> vaributes) :
|
public GraphEntry(int id, int precision, BillingData.Curve curve, List<Varibute> vaributes) :
|
||||||
this(id, precision, curve.Mode) {
|
this(id, precision, curve.Mode) {
|
||||||
DataGraph = new Graph(curve.Normal, precision, MinX, MaxX);
|
DataGraph = new Graph(curve.Normal, precision, MinX, MaxX);
|
||||||
if (curve.Contracted != null)
|
if (curve.Gebunden != null)
|
||||||
ContractedGraph = new Graph(curve.Contracted, precision, MinXCtrd, MaxX);
|
GebundenGraph = new Graph(curve.Gebunden, precision, MinXGeb, MaxX);
|
||||||
Vaributes = vaributes;
|
Vaributes = vaributes;
|
||||||
}
|
}
|
||||||
|
|
||||||
private GraphEntry(int id, int precision, BillingData.CurveMode mode, Graph dataGraph, Graph? contractedGraph, List<Varibute> vaributes) {
|
private GraphEntry(int id, int precision, BillingData.CurveMode mode, Graph dataGraph, Graph? gebundenGraph, List<Varibute> vaributes) {
|
||||||
Id = id;
|
Id = id;
|
||||||
Precision = precision;
|
Precision = precision;
|
||||||
Mode = mode;
|
Mode = mode;
|
||||||
DataGraph = dataGraph;
|
DataGraph = dataGraph;
|
||||||
ContractedGraph = contractedGraph;
|
GebundenGraph = gebundenGraph;
|
||||||
Vaributes = vaributes;
|
Vaributes = vaributes;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void AddContractedGraph() {
|
public void AddGebundenGraph() {
|
||||||
ContractedGraph ??= new Graph(Precision, MinXCtrd, MaxX);
|
GebundenGraph ??= new Graph(Precision, MinXGeb, MaxX);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void RemoveContractedGraph() {
|
public void RemoveGebundenGraph() {
|
||||||
ContractedGraph = null;
|
GebundenGraph = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public GraphEntry Copy(int id) {
|
public GraphEntry Copy(int id) {
|
||||||
return new GraphEntry(id, Precision, Mode, (Graph)DataGraph.Clone(), (Graph?)ContractedGraph?.Clone(), []);
|
return new GraphEntry(id, Precision, Mode, (Graph)DataGraph.Clone(), (Graph?)GebundenGraph?.Clone(), []);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -45,9 +45,9 @@ namespace Elwig.Helpers.Billing {
|
|||||||
return dict;
|
return dict;
|
||||||
}
|
}
|
||||||
|
|
||||||
public decimal CalculatePrice(string sortid, string? attrid, string? cultid, string qualid, bool contracted, double oe, double kmw) {
|
public decimal CalculatePrice(string sortid, string? attrid, string? cultid, string qualid, bool gebunden, double oe, double kmw) {
|
||||||
var curve = GetQualityCurve(qualid, sortid, attrid, cultid) ?? GetCurve(sortid, attrid, cultid);
|
var curve = GetQualityCurve(qualid, sortid, attrid, cultid) ?? GetCurve(sortid, attrid, cultid);
|
||||||
return GetCurveValueAt((contracted ? curve.Contracted : null) ?? curve.Normal, curve.Mode == CurveMode.Oe ? oe : kmw);
|
return GetCurveValueAt((gebunden ? curve.Gebunden : null) ?? curve.Normal, curve.Mode == CurveMode.Oe ? oe : kmw);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Curve LookupCurve(JsonValue val) {
|
private Curve LookupCurve(JsonValue val) {
|
||||||
|
|||||||
@@ -63,9 +63,9 @@ namespace Elwig.Helpers.Billing {
|
|||||||
((Variety != null || Attribute != null) && Cultivation != null ? " " : "") + $"{Cultivation?.Name}";
|
((Variety != null || Attribute != null) && Cultivation != null ? " " : "") + $"{Cultivation?.Name}";
|
||||||
|
|
||||||
public Varibute(RawVaribute raw) :
|
public Varibute(RawVaribute raw) :
|
||||||
this(raw.SortId != null ? new WineVar { SortId = raw.SortId, Name = raw.SortId, MaxQualId = "QUW", Type = "?" } : null,
|
this(raw.SortId != null ? new WineVar(raw.SortId, raw.SortId) : null,
|
||||||
raw.AttrId != null ? new WineAttr { AttrId = raw.AttrId, Name = raw.AttrId } : null,
|
raw.AttrId != null ? new WineAttr() { AttrId = raw.AttrId, Name = raw.AttrId } : null,
|
||||||
raw.CultId != null ? new WineCult { CultId = raw.CultId, Name = raw.CultId } : null) {
|
raw.CultId != null ? new WineCult() { CultId = raw.CultId, Name = raw.CultId } : null) {
|
||||||
}
|
}
|
||||||
|
|
||||||
public Varibute(RawVaribute raw, Dictionary<string, WineVar> vars, Dictionary<string, WineAttr> attrs, Dictionary<string, WineCult> cults) :
|
public Varibute(RawVaribute raw, Dictionary<string, WineVar> vars, Dictionary<string, WineAttr> attrs, Dictionary<string, WineCult> cults) :
|
||||||
|
|||||||
@@ -49,8 +49,7 @@ namespace Elwig.Helpers {
|
|||||||
public string? Bic;
|
public string? Bic;
|
||||||
public string? UstIdNr;
|
public string? UstIdNr;
|
||||||
public string? LfbisNr;
|
public string? LfbisNr;
|
||||||
public string? OrganicOperatorId;
|
public string? OrganicAuthority;
|
||||||
public string? OrganicAuthorityCode;
|
|
||||||
|
|
||||||
public string? PhoneNr;
|
public string? PhoneNr;
|
||||||
public string? FaxNr;
|
public string? FaxNr;
|
||||||
@@ -61,7 +60,6 @@ namespace Elwig.Helpers {
|
|||||||
public int ModeBusinessShares;
|
public int ModeBusinessShares;
|
||||||
public bool HasRedWhite => ModeBusinessShares == 1;
|
public bool HasRedWhite => ModeBusinessShares == 1;
|
||||||
|
|
||||||
public int ModeMemberDataSheetShares;
|
|
||||||
public int ModeDeliveryNoteStats;
|
public int ModeDeliveryNoteStats;
|
||||||
public int ModeWineQualityStatistics;
|
public int ModeWineQualityStatistics;
|
||||||
public int OrderingMemberList;
|
public int OrderingMemberList;
|
||||||
@@ -81,27 +79,9 @@ namespace Elwig.Helpers {
|
|||||||
public int ExportEbicsVersion;
|
public int ExportEbicsVersion;
|
||||||
public int ExportEbicsAddress;
|
public int ExportEbicsAddress;
|
||||||
|
|
||||||
public string? ReceiptMaxQualId;
|
|
||||||
|
|
||||||
public (int? AllowanceKg, double? AllowanceShares, int? AllowanceKgPerShare, double? AllowancePercent, int? MinShares) AutoAdjustShares;
|
public (int? AllowanceKg, double? AllowanceShares, int? AllowanceKgPerShare, double? AllowancePercent, int? MinShares) AutoAdjustShares;
|
||||||
|
|
||||||
public static readonly Dictionary<string, string?> DefaultParameters = new() {
|
public ClientParameters(AppDbContext ctx) : this(ctx.ClientParameters.ToDictionary(e => e.Param, e => e.Value)) { }
|
||||||
{ "CLIENT_NAME_TOKEN", "XXX" },
|
|
||||||
{ "CLIENT_NAME_SHORT", "Unbekannt" },
|
|
||||||
{ "CLIENT_NAME", "Unbekannt" },
|
|
||||||
{ "CLIENT_NAME_TYPE", "Unbekannt" },
|
|
||||||
{ "CLIENT_PLZ", "9999" },
|
|
||||||
{ "CLIENT_ORT", "Unbekannt" },
|
|
||||||
{ "CLIENT_ADDRESS", "Unbekannt" },
|
|
||||||
};
|
|
||||||
|
|
||||||
public ClientParameters() :
|
|
||||||
this(DefaultParameters) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public ClientParameters(AppDbContext ctx) :
|
|
||||||
this(ctx.ClientParameters.ToDictionary(e => e.Param, e => e.Value)) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public ClientParameters(Dictionary<string, string?> parameters) {
|
public ClientParameters(Dictionary<string, string?> parameters) {
|
||||||
try {
|
try {
|
||||||
@@ -134,8 +114,7 @@ namespace Elwig.Helpers {
|
|||||||
UstIdNr = parameters.GetValueOrDefault("CLIENT_USTIDNR");
|
UstIdNr = parameters.GetValueOrDefault("CLIENT_USTIDNR");
|
||||||
Bic = parameters.GetValueOrDefault("CLIENT_BIC");
|
Bic = parameters.GetValueOrDefault("CLIENT_BIC");
|
||||||
Iban = parameters.GetValueOrDefault("CLIENT_IBAN");
|
Iban = parameters.GetValueOrDefault("CLIENT_IBAN");
|
||||||
OrganicOperatorId = parameters.GetValueOrDefault("CLIENT_ORGANIC_OPERATORID");
|
OrganicAuthority = parameters.GetValueOrDefault("CLIENT_ORGANIC_AUTHORITY");
|
||||||
OrganicAuthorityCode = parameters.GetValueOrDefault("CLIENT_ORGANIC_AUTHORITYCODE");
|
|
||||||
|
|
||||||
EnableMemberHistory = (parameters.GetValueOrDefault("ENABLE_MEMBERHISTORY")?.ToUpper()) switch {
|
EnableMemberHistory = (parameters.GetValueOrDefault("ENABLE_MEMBERHISTORY")?.ToUpper()) switch {
|
||||||
"1" or "TRUE" or "YES" or "JA" => true,
|
"1" or "TRUE" or "YES" or "JA" => true,
|
||||||
@@ -146,10 +125,6 @@ namespace Elwig.Helpers {
|
|||||||
case "SIMPLE": ModeBusinessShares = 0; break;
|
case "SIMPLE": ModeBusinessShares = 0; break;
|
||||||
case "RED_WHITE": ModeBusinessShares = 1; break;
|
case "RED_WHITE": ModeBusinessShares = 1; break;
|
||||||
}
|
}
|
||||||
switch (parameters.GetValueOrDefault("MODE_MEMBERDATASHEET_SHARES", "FULL")?.ToUpper()) {
|
|
||||||
case "NONE": ModeMemberDataSheetShares = 0; break;
|
|
||||||
case "FULL": ModeMemberDataSheetShares = 1; break;
|
|
||||||
}
|
|
||||||
switch (parameters.GetValueOrDefault("MODE_DELIVERYNOTE_STATS", "SHORT")?.ToUpper()) {
|
switch (parameters.GetValueOrDefault("MODE_DELIVERYNOTE_STATS", "SHORT")?.ToUpper()) {
|
||||||
case "NONE": ModeDeliveryNoteStats = 0; break;
|
case "NONE": ModeDeliveryNoteStats = 0; break;
|
||||||
case "GA_ONLY": ModeDeliveryNoteStats = 1; break;
|
case "GA_ONLY": ModeDeliveryNoteStats = 1; break;
|
||||||
@@ -213,11 +188,6 @@ namespace Elwig.Helpers {
|
|||||||
case "FULL": ExportEbicsAddress = 2; break;
|
case "FULL": ExportEbicsAddress = 2; break;
|
||||||
}
|
}
|
||||||
|
|
||||||
ReceiptMaxQualId = parameters.GetValueOrDefault("RECEIPT_MAX_QUALID", "QUW")?.ToUpper();
|
|
||||||
if (ReceiptMaxQualId?.Length != 3 || !ReceiptMaxQualId.All(char.IsAsciiLetter)) {
|
|
||||||
ReceiptMaxQualId = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var autoAdjust = (parameters.GetValueOrDefault("AUTOADJUST_BUSINESSSHARES") ?? "").Split(';');
|
var autoAdjust = (parameters.GetValueOrDefault("AUTOADJUST_BUSINESSSHARES") ?? "").Split(';');
|
||||||
AutoAdjustShares = autoAdjust.Length == 5 ? (
|
AutoAdjustShares = autoAdjust.Length == 5 ? (
|
||||||
int.TryParse(autoAdjust[0], out var v1) ? v1 : null,
|
int.TryParse(autoAdjust[0], out var v1) ? v1 : null,
|
||||||
@@ -237,11 +207,6 @@ namespace Elwig.Helpers {
|
|||||||
case 0: businessShares = "SIMPLE"; break;
|
case 0: businessShares = "SIMPLE"; break;
|
||||||
case 1: businessShares = "RED_WHITE"; break;
|
case 1: businessShares = "RED_WHITE"; break;
|
||||||
}
|
}
|
||||||
string memberDataSheetShares = "FULL";
|
|
||||||
switch (ModeMemberDataSheetShares) {
|
|
||||||
case 0: memberDataSheetShares = "NONE"; break;
|
|
||||||
case 1: memberDataSheetShares = "FULL"; break;
|
|
||||||
}
|
|
||||||
string deliveryNoteStats = "SHORT";
|
string deliveryNoteStats = "SHORT";
|
||||||
switch (ModeDeliveryNoteStats) {
|
switch (ModeDeliveryNoteStats) {
|
||||||
case 0: deliveryNoteStats = "NONE"; break;
|
case 0: deliveryNoteStats = "NONE"; break;
|
||||||
@@ -308,11 +273,9 @@ namespace Elwig.Helpers {
|
|||||||
("CLIENT_USTIDNR", UstIdNr),
|
("CLIENT_USTIDNR", UstIdNr),
|
||||||
("CLIENT_BIC", Bic),
|
("CLIENT_BIC", Bic),
|
||||||
("CLIENT_IBAN", Iban),
|
("CLIENT_IBAN", Iban),
|
||||||
("CLIENT_ORGANIC_OPERATORID", OrganicOperatorId),
|
("CLIENT_ORGANIC_AUTHORITY", OrganicAuthority),
|
||||||
("CLIENT_ORGANIC_AUTHORITYCODE", OrganicAuthorityCode),
|
|
||||||
("ENABLE_MEMBERHISTORY", EnableMemberHistory ? "YES" : "NO"),
|
("ENABLE_MEMBERHISTORY", EnableMemberHistory ? "YES" : "NO"),
|
||||||
("MODE_BUSINESSSHARES", businessShares),
|
("MODE_BUSINESSSHARES", businessShares),
|
||||||
("MODE_MEMBERDATASHEET_SHARES", memberDataSheetShares),
|
|
||||||
("MODE_DELIVERYNOTE_STATS", deliveryNoteStats),
|
("MODE_DELIVERYNOTE_STATS", deliveryNoteStats),
|
||||||
("MODE_WINEQUALITYSTATISTICS", modeWineQualityStatistics),
|
("MODE_WINEQUALITYSTATISTICS", modeWineQualityStatistics),
|
||||||
("ORDERING_MEMBERLIST", orderingMemberList),
|
("ORDERING_MEMBERLIST", orderingMemberList),
|
||||||
@@ -329,7 +292,6 @@ namespace Elwig.Helpers {
|
|||||||
("MAIL_ORDERING", mailOrdering),
|
("MAIL_ORDERING", mailOrdering),
|
||||||
("EXPORT_EBICS_VERSION", ExportEbicsVersion.ToString()),
|
("EXPORT_EBICS_VERSION", ExportEbicsVersion.ToString()),
|
||||||
("EXPORT_EBICS_ADDRESS", exportEbicsAddress),
|
("EXPORT_EBICS_ADDRESS", exportEbicsAddress),
|
||||||
("RECEIPT_MAX_QUALID", ReceiptMaxQualId),
|
|
||||||
("AUTOADJUST_BUSINESSSHARES", autoAdjust),
|
("AUTOADJUST_BUSINESSSHARES", autoAdjust),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-46
@@ -2,7 +2,6 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Windows;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
|
|
||||||
namespace Elwig.Helpers {
|
namespace Elwig.Helpers {
|
||||||
@@ -18,11 +17,10 @@ namespace Elwig.Helpers {
|
|||||||
public string? Filling;
|
public string? Filling;
|
||||||
public string? Limit;
|
public string? Limit;
|
||||||
public bool Required;
|
public bool Required;
|
||||||
public bool SyncTime;
|
|
||||||
public string? Log;
|
public string? Log;
|
||||||
public string? _Log;
|
public string? _Log;
|
||||||
|
|
||||||
public ScaleConfig(string id, string? type, string? model, string? cnx, string? empty, string? filling, string? limit, bool? required, bool? syncTime, string? log) {
|
public ScaleConfig(string id, string? type, string? model, string? cnx, string? empty, string? filling, string? limit, bool? required, string? log) {
|
||||||
Id = id;
|
Id = id;
|
||||||
Type = type;
|
Type = type;
|
||||||
Model = model;
|
Model = model;
|
||||||
@@ -31,7 +29,6 @@ namespace Elwig.Helpers {
|
|||||||
Filling = filling;
|
Filling = filling;
|
||||||
Limit = limit;
|
Limit = limit;
|
||||||
Required = required ?? true;
|
Required = required ?? true;
|
||||||
SyncTime = syncTime ?? true;
|
|
||||||
_Log = log;
|
_Log = log;
|
||||||
Log = log != null ? Path.Combine(App.DataPath, log) : null;
|
Log = log != null ? Path.Combine(App.DataPath, log) : null;
|
||||||
}
|
}
|
||||||
@@ -40,49 +37,29 @@ namespace Elwig.Helpers {
|
|||||||
public class Config {
|
public class Config {
|
||||||
|
|
||||||
private static readonly string[] TrueValues = ["1", "true", "yes", "on"];
|
private static readonly string[] TrueValues = ["1", "true", "yes", "on"];
|
||||||
private static readonly string[] FalseValues = ["0", "false", "no", "off"];
|
|
||||||
|
|
||||||
private readonly string FileName;
|
private readonly string FileName;
|
||||||
|
|
||||||
public bool Debug;
|
public bool Debug;
|
||||||
public string DatabaseFile = Path.Combine(App.DataPath, "database.sqlite3");
|
public string DatabaseFile = App.DataPath + "database.sqlite3";
|
||||||
public string? DatabaseLog = null;
|
public string? DatabaseLog = null;
|
||||||
public string? Branch = null;
|
public string? Branch = null;
|
||||||
public WeighingMode? WeighingMode;
|
public WeighingMode? WeighingMode;
|
||||||
|
|
||||||
public bool BackupAuto = true;
|
|
||||||
public string BackupPath = Path.Combine(App.DataPath, "backups");
|
|
||||||
public int BackupRetainHours = 36;
|
|
||||||
public int BackupRetainDays = 8;
|
|
||||||
public int BackupRetainWeeks = 6;
|
|
||||||
public int BackupRetainMonths = 18;
|
|
||||||
private string[] _backupKeys = [];
|
|
||||||
public ReadOnlyMemory<char>[] BackupDecryptionKeys => [.. _backupKeys.Select(k => k.AsMemory())];
|
|
||||||
public ReadOnlyMemory<char> BackupEncryptionKey => _backupKeys.Length == 0 ? null : _backupKeys[0].AsMemory();
|
|
||||||
|
|
||||||
public string? UpdateUrl = null;
|
public string? UpdateUrl = null;
|
||||||
public bool UpdateAuto = false;
|
public bool UpdateAuto = false;
|
||||||
|
|
||||||
public string? SyncUrl = null;
|
public string? SyncUrl = null;
|
||||||
public string SyncUsername = "";
|
public string SyncUsername = "";
|
||||||
private string _syncPassword = "";
|
public string SyncPassword = "";
|
||||||
public ReadOnlyMemory<char> SyncPassword => _syncPassword.AsMemory();
|
|
||||||
public bool SyncMain = false;
|
|
||||||
private string[] _syncKeys = [];
|
|
||||||
public ReadOnlyMemory<char>[] SyncDecryptionKeys => [.. _syncKeys.Select(k => k.AsMemory())];
|
|
||||||
public ReadOnlyMemory<char> SyncEncryptionKey => _syncKeys.Length == 0 ? null : _syncKeys[0].AsMemory();
|
|
||||||
|
|
||||||
public string? SmtpHost = null;
|
public string? SmtpHost = null;
|
||||||
public int? SmtpPort = null;
|
public int? SmtpPort = null;
|
||||||
public string? SmtpMode = null;
|
public string? SmtpMode = null;
|
||||||
public string? SmtpUsername = null;
|
public string? SmtpUsername = null;
|
||||||
private string? _smtpPassword = null;
|
public string? SmtpPassword = null;
|
||||||
public ReadOnlyMemory<char> SmtpPassword => _smtpPassword.AsMemory();
|
|
||||||
public string? SmtpFrom = null;
|
public string? SmtpFrom = null;
|
||||||
public double SmtpWait = 0;
|
public (string Host, int Port, string Mode, string Username, string Password, string From)? Smtp =>
|
||||||
public (string Host, int Port, string Mode, string Username, ReadOnlyMemory<char> Password, string From, double Wait)? Smtp =>
|
SmtpHost == null || SmtpPort == null || SmtpMode == null || SmtpUsername == null || SmtpPassword == null || SmtpFrom == null ?
|
||||||
SmtpHost == null || SmtpPort == null || SmtpMode == null || SmtpUsername == null || !SmtpPassword.IsEmpty || SmtpFrom == null ?
|
null : (SmtpHost, (int)SmtpPort, SmtpMode, SmtpUsername, SmtpPassword, SmtpFrom);
|
||||||
null : (SmtpHost, (int)SmtpPort, SmtpMode, SmtpUsername, SmtpPassword, SmtpFrom, SmtpWait);
|
|
||||||
|
|
||||||
public IList<ScaleConfig> Scales;
|
public IList<ScaleConfig> Scales;
|
||||||
private readonly List<ScaleConfig> ScaleList = [];
|
private readonly List<ScaleConfig> ScaleList = [];
|
||||||
@@ -103,31 +80,18 @@ namespace Elwig.Helpers {
|
|||||||
Debug = TrueValues.Contains(config["general:debug"]?.ToLower());
|
Debug = TrueValues.Contains(config["general:debug"]?.ToLower());
|
||||||
var weighing = config["general:weighing"];
|
var weighing = config["general:weighing"];
|
||||||
WeighingMode = weighing != null && Enum.TryParse<WeighingMode>(weighing, true, out var w) ? w : null;
|
WeighingMode = weighing != null && Enum.TryParse<WeighingMode>(weighing, true, out var w) ? w : null;
|
||||||
|
|
||||||
BackupAuto = !FalseValues.Contains(config["backup:auto"]?.ToLower());
|
|
||||||
BackupPath = Path.Combine(Path.GetDirectoryName(DatabaseFile) ?? App.DataPath, config["backup:path"] ?? "backups");
|
|
||||||
BackupRetainHours = int.TryParse(config["backup:retain_hours"], out var hours) ? hours : 36;
|
|
||||||
BackupRetainDays = int.TryParse(config["backup:retain_days"], out var days) ? days : 8;
|
|
||||||
BackupRetainWeeks = int.TryParse(config["backup:retain_weeks"], out var weeks) ? weeks : 6;
|
|
||||||
BackupRetainMonths = int.TryParse(config["backup:retain_months"], out var months) ? months : 18;
|
|
||||||
_backupKeys = config["backup:key"]?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? [];
|
|
||||||
|
|
||||||
UpdateUrl = config["update:url"];
|
UpdateUrl = config["update:url"];
|
||||||
UpdateAuto = TrueValues.Contains(config["update:auto"]?.ToLower());
|
UpdateAuto = TrueValues.Contains(config["update:auto"]?.ToLower());
|
||||||
|
|
||||||
SyncUrl = config["sync:url"];
|
SyncUrl = config["sync:url"];
|
||||||
SyncUsername = config["sync:username"] ?? "";
|
SyncUsername = config["sync:username"] ?? "";
|
||||||
_syncPassword = config["sync:password"] ?? "";
|
SyncPassword = config["sync:password"] ?? "";
|
||||||
SyncMain = TrueValues.Contains(config["sync:main"]?.ToLower());
|
|
||||||
_syncKeys = config["sync:key"]?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? [];
|
|
||||||
|
|
||||||
SmtpHost = config["smtp:host"];
|
SmtpHost = config["smtp:host"];
|
||||||
SmtpPort = config["smtp:port"]?.All(char.IsAsciiDigit) == true && config["smtp:port"]?.Length > 0 ? int.Parse(config["smtp:port"]!) : null;
|
SmtpPort = config["smtp:port"]?.All(char.IsAsciiDigit) == true && config["smtp:port"]?.Length > 0 ? int.Parse(config["smtp:port"]!) : null;
|
||||||
SmtpMode = config["smtp:mode"];
|
SmtpMode = config["smtp:mode"];
|
||||||
SmtpUsername = config["smtp:username"];
|
SmtpUsername = config["smtp:username"];
|
||||||
_smtpPassword = config["smtp:password"];
|
SmtpPassword = config["smtp:password"];
|
||||||
SmtpFrom = config["smtp:from"];
|
SmtpFrom = config["smtp:from"];
|
||||||
SmtpWait = double.TryParse(config["smtp:wait"], out var res) ? res : 0;
|
|
||||||
|
|
||||||
var scales = config.AsEnumerable().Where(i => i.Key.StartsWith("scale.")).GroupBy(i => i.Key.Split(':')[0][6..]).Select(i => i.Key).Order();
|
var scales = config.AsEnumerable().Where(i => i.Key.StartsWith("scale.")).GroupBy(i => i.Key.Split(':')[0][6..]).Select(i => i.Key).Order();
|
||||||
ScaleList.Clear();
|
ScaleList.Clear();
|
||||||
@@ -137,7 +101,6 @@ namespace Elwig.Helpers {
|
|||||||
s, config[$"scale.{s}:type"], config[$"scale.{s}:model"], config[$"scale.{s}:connection"],
|
s, config[$"scale.{s}:type"], config[$"scale.{s}:model"], config[$"scale.{s}:connection"],
|
||||||
config[$"scale.{s}:empty"], config[$"scale.{s}:filling"], config[$"scale.{s}:limit"],
|
config[$"scale.{s}:empty"], config[$"scale.{s}:filling"], config[$"scale.{s}:limit"],
|
||||||
config[$"scale.{s}:required"] != null ? TrueValues.Contains(config[$"scale.{s}:required"]?.ToLower()) : null,
|
config[$"scale.{s}:required"] != null ? TrueValues.Contains(config[$"scale.{s}:required"]?.ToLower()) : null,
|
||||||
config[$"scale.{s}:synctime"] != null ? !FalseValues.Contains(config[$"scale.{s}:synctime"]?.ToLower()) : null,
|
|
||||||
config[$"scale.{s}:log"]
|
config[$"scale.{s}:log"]
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,9 +6,9 @@ using System;
|
|||||||
|
|
||||||
namespace Elwig.Helpers.Export {
|
namespace Elwig.Helpers.Export {
|
||||||
|
|
||||||
using Row = Tuple<(string?, string?, string?, string?, string, int, string, bool, int), (string, int, string, string, string, int, string, double, double)>;
|
using Row = Tuple<(string?, string?, string?, string?, string, int, string, int), (string, int, string, string, string, int, string, double, double)>;
|
||||||
|
|
||||||
public class Bki : CsvFile<Row> {
|
public class Bki : Csv<Row> {
|
||||||
|
|
||||||
private readonly string _clientData;
|
private readonly string _clientData;
|
||||||
|
|
||||||
@@ -29,7 +29,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
using var cnx = await AppDbContext.ConnectAsync();
|
using var cnx = await AppDbContext.ConnectAsync();
|
||||||
using var cmd = cnx.CreateCommand();
|
using var cmd = cnx.CreateCommand();
|
||||||
cmd.CommandText = $"""
|
cmd.CommandText = $"""
|
||||||
SELECT lfbis_nr, name, other_names, billing_name, address, plz, ort, vollablieferer, area,
|
SELECT lfbis_nr, name, other_names, billing_name, address, plz, ort, area,
|
||||||
date, weight, type, sortid, qualid, year, hkid, kmw, oe
|
date, weight, type, sortid, qualid, year, hkid, kmw, oe
|
||||||
FROM v_bki_delivery
|
FROM v_bki_delivery
|
||||||
WHERE year = {year}
|
WHERE year = {year}
|
||||||
@@ -38,24 +38,28 @@ namespace Elwig.Helpers.Export {
|
|||||||
List<Row> rows = [];
|
List<Row> rows = [];
|
||||||
while (await r.ReadAsync()) {
|
while (await r.ReadAsync()) {
|
||||||
rows.Add(new(
|
rows.Add(new(
|
||||||
(r.IsDBNull(0) ? null : r.GetString(0), r.IsDBNull(1) ? null : r.GetString(1), r.IsDBNull(2) ? null : r.GetString(2), r.IsDBNull(3) ? null : r.GetString(3), r.GetString(4), r.GetInt32(5), r.GetString(6), r.GetBoolean(7), r.GetInt32(8)),
|
(r.IsDBNull(0) ? null : r.GetString(0), r.IsDBNull(1) ? null : r.GetString(1), r.IsDBNull(2) ? null : r.GetString(2), r.IsDBNull(3) ? null : r.GetString(3), r.GetString(4), r.GetInt32(5), r.GetString(6), r.GetInt32(7)),
|
||||||
(r.GetString(9), r.GetInt32(10), r.GetString(11), r.GetString(12), r.GetString(13), r.GetInt32(14), r.GetString(15), r.GetDouble(16), r.GetDouble(17))
|
(r.GetString(8), r.GetInt32(9), r.GetString(10), r.GetString(11), r.GetString(12), r.GetInt32(13), r.GetString(14), r.GetDouble(15), r.GetDouble(16))
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
await ExportAsync(rows);
|
await ExportAsync(rows);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void Export(int year) {
|
||||||
|
ExportAsync(year).GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
|
||||||
public override string FormatRow(Row row) {
|
public override string FormatRow(Row row) {
|
||||||
var (member, delivery) = row;
|
var (member, delivery) = row;
|
||||||
var (lfBisNr, familyName, name, billingName, address, plz, ort, vollablieferer, area) = member;
|
var (lfBisNr, familyName, name, billingName, address, plz, ort, area) = member;
|
||||||
var (date, weight, type, sortid, qualid, year, hkid, kmw, oe) = delivery;
|
var (date, weight, type, sortid, qualid, year, hkid, kmw, oe) = delivery;
|
||||||
|
|
||||||
var (n1, n2) = billingName == null ? (familyName, name) : Utils.SplitName(billingName, familyName);
|
var (n1, n2) = billingName == null ? (familyName, name) : Utils.SplitName(billingName, familyName);
|
||||||
var (a1, a2) = Utils.SplitAddress(address);
|
var (a1, a2) = Utils.SplitAddress(address);
|
||||||
var memberData = $"{lfBisNr};{n1};{n2};{a1};\t{a2};{plz};{ort}";
|
var memberData = $"{lfBisNr};{n1};{n2};{a1};\t{a2};{plz};{ort}";
|
||||||
var deliveryData = $"{string.Join(".", date.Split("-").Reverse())};{weight};TB;{(type == "W" ? "J" : "")};{(type == "R" ? "J" : "")};{sortid};;;{qualid};{year};{hkid};{kmw:0.0};{oe:0}";
|
var deliveryData = $"{string.Join(".", date.Split("-").Reverse())};{weight};TB;{(type == "W" ? "J" : "")};{(type == "R" ? "J" : "")};{sortid};;;{qualid};{year};{hkid};{kmw:0.0};{oe:0}";
|
||||||
var vollData = $"{(vollablieferer ? "J" : "N")};{(vollablieferer ? area / 10_000.0 : null):N4};{(vollablieferer ? area / 10_000.0 : null):N4};{area / 10_000.0:N4}";
|
var vollData = $"N;;;{area / 10_000.0}";
|
||||||
|
|
||||||
return $"{_clientData};{memberData};{deliveryData};{vollData}";
|
return $"{_clientData};{memberData};{deliveryData};{vollData}";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ using System.Text;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace Elwig.Helpers.Export {
|
namespace Elwig.Helpers.Export {
|
||||||
public abstract class CsvFile<T> : IExporter<T> {
|
public abstract class Csv<T> : IExporter<T> {
|
||||||
|
|
||||||
public static string FileExtension => "csv";
|
public static string FileExtension => "csv";
|
||||||
|
|
||||||
@@ -15,11 +15,11 @@ namespace Elwig.Helpers.Export {
|
|||||||
protected readonly char Separator;
|
protected readonly char Separator;
|
||||||
protected string? Header;
|
protected string? Header;
|
||||||
|
|
||||||
public CsvFile(string filename, char separator = ';') :
|
public Csv(string filename, char separator = ';') :
|
||||||
this(filename, separator, Utils.UTF8) {
|
this(filename, separator, Utils.UTF8) {
|
||||||
}
|
}
|
||||||
|
|
||||||
public CsvFile(string filename, char separator, Encoding encoding) {
|
public Csv(string filename, char separator, Encoding encoding) {
|
||||||
_writer = new StreamWriter(filename, false, encoding);
|
_writer = new StreamWriter(filename, false, encoding);
|
||||||
Separator = separator;
|
Separator = separator;
|
||||||
}
|
}
|
||||||
@@ -29,6 +29,11 @@ namespace Elwig.Helpers.Export {
|
|||||||
_writer.Dispose();
|
_writer.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ValueTask DisposeAsync() {
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
return _writer.DisposeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
public async Task ExportAsync(IEnumerable<T> data, IProgress<double>? progress = null) {
|
public async Task ExportAsync(IEnumerable<T> data, IProgress<double>? progress = null) {
|
||||||
progress?.Report(0.0);
|
progress?.Report(0.0);
|
||||||
int count = data.Count() + 2, i = 0;
|
int count = data.Count() + 2, i = 0;
|
||||||
@@ -45,6 +50,10 @@ namespace Elwig.Helpers.Export {
|
|||||||
progress?.Report(100.0);
|
progress?.Report(100.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void Export(IEnumerable<T> data, IProgress<double>? progress = null) {
|
||||||
|
ExportAsync(data, progress).GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
|
||||||
public string FormatRow(IEnumerable row) {
|
public string FormatRow(IEnumerable row) {
|
||||||
return string.Join(Separator, row);
|
return string.Join(Separator, row);
|
||||||
}
|
}
|
||||||
@@ -52,7 +61,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
public abstract string FormatRow(T row);
|
public abstract string FormatRow(T row);
|
||||||
}
|
}
|
||||||
|
|
||||||
public class CsvSimple : CsvFile<IEnumerable<object?>> {
|
public class CsvSimple : Csv<IEnumerable<object?>> {
|
||||||
|
|
||||||
public CsvSimple(string filename, char separator, Encoding encoding) :
|
public CsvSimple(string filename, char separator, Encoding encoding) :
|
||||||
base(filename, separator, encoding) {
|
base(filename, separator, encoding) {
|
||||||
@@ -17,90 +17,74 @@ namespace Elwig.Helpers.Export {
|
|||||||
return (applId, userVers != null ? $"{userVers >> 24}.{(userVers >> 16) & 0xFF}.{(userVers >> 8) & 0xFF}.{userVers & 0xFF}" : null, schemaVers, size);
|
return (applId, userVers != null ? $"{userVers >> 24}.{(userVers >> 16) & 0xFF}.{(userVers >> 8) & 0xFF}.{userVers & 0xFF}" : null, schemaVers, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task ExportSqlite(string filename, bool zipFile, ReadOnlyMemory<char> password = default) {
|
public static async Task ExportSqlite(string filename, bool zipFile) {
|
||||||
var tmp = filename + ".tmp";
|
if (zipFile) {
|
||||||
try {
|
File.Delete(filename);
|
||||||
File.Delete(tmp);
|
using var zip = ZipFile.Open(filename, ZipArchiveMode.Create);
|
||||||
if (zipFile) {
|
|
||||||
using var zip = await ZipFile.OpenAsync(tmp, ZipArchiveMode.Create);
|
|
||||||
|
|
||||||
var version = zip.CreateEntry("version", CompressionLevel.NoCompression);
|
var version = zip.CreateEntry("version", CompressionLevel.NoCompression);
|
||||||
using (var writer = new StreamWriter(await version.OpenAsync(), Utils.UTF8)) {
|
using (var writer = new StreamWriter(version.Open(), Utils.UTF8)) {
|
||||||
await writer.WriteAsync("elwig:1");
|
await writer.WriteAsync("elwig:1");
|
||||||
}
|
|
||||||
|
|
||||||
var (applId, userVers, schemaVers, size) = await GetMeta();
|
|
||||||
var meta = zip.CreateEntry("meta.json", CompressionLevel.NoCompression);
|
|
||||||
using (var writer = new StreamWriter(await meta.OpenAsync(), Utils.UTF8)) {
|
|
||||||
var obj = new JsonObject {
|
|
||||||
["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}",
|
|
||||||
["zwstid"] = App.ZwstId,
|
|
||||||
["device"] = Environment.MachineName,
|
|
||||||
["database"] = new JsonObject {
|
|
||||||
["application_id"] = applId,
|
|
||||||
["user_version"] = userVers,
|
|
||||||
["schema_version"] = schemaVers,
|
|
||||||
["file_size"] = size,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
|
|
||||||
}
|
|
||||||
|
|
||||||
var db = password.IsEmpty ?
|
|
||||||
zip.CreateEntryFromFile(App.Config.DatabaseFile, "database.sqlite3", CompressionLevel.SmallestSize) :
|
|
||||||
zip.CreateEntryFromFile(App.Config.DatabaseFile, "database.sqlite3", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
|
||||||
} else {
|
|
||||||
File.Copy(App.Config.DatabaseFile, tmp);
|
|
||||||
}
|
}
|
||||||
File.Move(tmp, filename, true);
|
|
||||||
} finally {
|
var (applId, userVers, schemaVers, size) = await GetMeta();
|
||||||
File.Delete(tmp);
|
var meta = zip.CreateEntry("meta.json", CompressionLevel.NoCompression);
|
||||||
|
using (var writer = new StreamWriter(meta.Open(), Utils.UTF8)) {
|
||||||
|
var obj = new JsonObject {
|
||||||
|
["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}",
|
||||||
|
["zwstid"] = App.ZwstId,
|
||||||
|
["device"] = Environment.MachineName,
|
||||||
|
["database"] = new JsonObject {
|
||||||
|
["application_id"] = applId,
|
||||||
|
["user_version"] = userVers,
|
||||||
|
["schema_version"] = schemaVers,
|
||||||
|
["file_size"] = size,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
|
||||||
|
}
|
||||||
|
|
||||||
|
var db = zip.CreateEntryFromFile(App.Config.DatabaseFile, "database.sqlite3", CompressionLevel.SmallestSize);
|
||||||
|
} else {
|
||||||
|
File.Copy(App.Config.DatabaseFile, filename, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task ExportSql(string filename, bool zipFile, ReadOnlyMemory<char> password = default) {
|
public static async Task ExportSql(string filename, bool zipFile) {
|
||||||
var tmp = filename + ".tmp";
|
if (zipFile) {
|
||||||
try {
|
File.Delete(filename);
|
||||||
File.Delete(tmp);
|
using var zip = ZipFile.Open(filename, ZipArchiveMode.Create);
|
||||||
if (zipFile) {
|
|
||||||
using var zip = await ZipFile.OpenAsync(tmp, ZipArchiveMode.Create);
|
|
||||||
|
|
||||||
var version = zip.CreateEntry("version", CompressionLevel.NoCompression);
|
var version = zip.CreateEntry("version", CompressionLevel.NoCompression);
|
||||||
using (var writer = new StreamWriter(await version.OpenAsync(), Utils.UTF8)) {
|
using (var writer = new StreamWriter(version.Open(), Utils.UTF8)) {
|
||||||
await writer.WriteAsync("elwig:1");
|
await writer.WriteAsync("elwig:1");
|
||||||
}
|
}
|
||||||
|
|
||||||
var (applId, userVers, schemaVers, size) = await GetMeta();
|
var (applId, userVers, schemaVers, size) = await GetMeta();
|
||||||
var meta = zip.CreateEntry("meta.json", CompressionLevel.NoCompression);
|
var meta = zip.CreateEntry("meta.json", CompressionLevel.NoCompression);
|
||||||
using (var writer = new StreamWriter(await meta.OpenAsync(), Utils.UTF8)) {
|
using (var writer = new StreamWriter(meta.Open(), Utils.UTF8)) {
|
||||||
var obj = new JsonObject {
|
var obj = new JsonObject {
|
||||||
["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}",
|
["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}",
|
||||||
["zwstid"] = App.ZwstId,
|
["zwstid"] = App.ZwstId,
|
||||||
["device"] = Environment.MachineName,
|
["device"] = Environment.MachineName,
|
||||||
["database"] = new JsonObject {
|
["database"] = new JsonObject {
|
||||||
["application_id"] = applId,
|
["application_id"] = applId,
|
||||||
["user_version"] = userVers,
|
["user_version"] = userVers,
|
||||||
["schema_version"] = schemaVers,
|
["schema_version"] = schemaVers,
|
||||||
["file_size"] = size,
|
["file_size"] = size,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
|
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
|
||||||
}
|
}
|
||||||
|
|
||||||
var sql = password.IsEmpty ?
|
var sql = zip.CreateEntry("database.sql", CompressionLevel.SmallestSize);
|
||||||
zip.CreateEntry("database.sql", CompressionLevel.SmallestSize) :
|
using (var writer = new StreamWriter(sql.Open(), Utils.UTF8)) {
|
||||||
zip.CreateEntry("database.sql", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
|
||||||
using (var writer = new StreamWriter(await sql.OpenAsync(), Utils.UTF8)) {
|
|
||||||
await ExportSql(writer);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
using var stream = File.OpenWrite(tmp);
|
|
||||||
using var writer = new StreamWriter(stream, Utils.UTF8);
|
|
||||||
await ExportSql(writer);
|
await ExportSql(writer);
|
||||||
}
|
}
|
||||||
File.Move(tmp, filename, true);
|
} else {
|
||||||
} finally {
|
using var stream = File.OpenWrite(filename);
|
||||||
File.Delete(tmp);
|
using var writer = new StreamWriter(stream, Utils.UTF8);
|
||||||
|
await ExportSql(writer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,27 +166,27 @@ namespace Elwig.Helpers.Export {
|
|||||||
await writer.WriteLineAsync("VACUUM;");
|
await writer.WriteLineAsync("VACUUM;");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task Import(string filename, IEnumerable<ReadOnlyMemory<char>>? passwords = null) {
|
public static async Task Import(string filename) {
|
||||||
if (filename.EndsWith(".sql")) {
|
if (filename.EndsWith(".sql")) {
|
||||||
await ImportSql(filename, false);
|
await ImportSql(filename, false);
|
||||||
} else if (filename.EndsWith(".sql.zip")) {
|
} else if (filename.EndsWith(".sql.zip")) {
|
||||||
await ImportSql(filename, true, passwords);
|
await ImportSql(filename, true);
|
||||||
} else if (filename.EndsWith(".sqlite3")) {
|
} else if (filename.EndsWith(".sqlite3")) {
|
||||||
await ImportSqlite(filename, false);
|
await ImportSqlite(filename, false);
|
||||||
} else if (filename.EndsWith(".sqlite3.zip")) {
|
} else if (filename.EndsWith(".sqlite3.zip")) {
|
||||||
await ImportSqlite(filename, true, passwords);
|
await ImportSqlite(filename, true);
|
||||||
} else {
|
} else {
|
||||||
throw new ArgumentException($"Unknown file extension for importing: '{filename}'");
|
throw new ArgumentException($"Unknown file extension for importing: '{filename}'");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task ImportSql(string filename, bool zipFile = false, IEnumerable<ReadOnlyMemory<char>>? passwords = null) {
|
public static async Task ImportSql(string filename, bool zipFile = false) {
|
||||||
if (zipFile) {
|
if (zipFile) {
|
||||||
using var zip = await ZipFile.OpenAsync(filename, ZipArchiveMode.Read);
|
using var zip = ZipFile.Open(filename, ZipArchiveMode.Read);
|
||||||
var password = await zip.CheckIntegrity(passwords ?? []);
|
await zip.CheckIntegrity();
|
||||||
foreach (var entry in zip.Entries) {
|
foreach (var entry in zip.Entries) {
|
||||||
if (entry.Name.EndsWith(".sql")) {
|
if (entry.Name.EndsWith(".sql")) {
|
||||||
using var stream = await entry.OpenAsync(password.Span);
|
using var stream = entry.Open();
|
||||||
using var reader = new StreamReader(stream, Utils.UTF8);
|
using var reader = new StreamReader(stream, Utils.UTF8);
|
||||||
await ImportSql(reader);
|
await ImportSql(reader);
|
||||||
return;
|
return;
|
||||||
@@ -216,16 +200,16 @@ namespace Elwig.Helpers.Export {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task ImportSqlite(string filename, bool zipFile = false, IEnumerable<ReadOnlyMemory<char>>? passwords = null, bool keepSource = true) {
|
public static async Task ImportSqlite(string filename, bool zipFile = false) {
|
||||||
if (zipFile) {
|
if (zipFile) {
|
||||||
var newName = Path.ChangeExtension(App.Config.DatabaseFile, ".new.sqlite3");
|
var newName = Path.ChangeExtension(App.Config.DatabaseFile, ".new.sqlite3");
|
||||||
try {
|
try {
|
||||||
using var zip = await ZipFile.OpenAsync(filename, ZipArchiveMode.Read);
|
using var zip = ZipFile.Open(filename, ZipArchiveMode.Read);
|
||||||
var password = await zip.CheckIntegrity(passwords ?? []);
|
await zip.CheckIntegrity();
|
||||||
foreach (var entry in zip.Entries) {
|
foreach (var entry in zip.Entries) {
|
||||||
if (entry.Name.EndsWith(".sqlite3")) {
|
if (entry.Name.EndsWith(".sqlite3")) {
|
||||||
entry.ExtractToFile(newName, new ZipExtractionOptions { Password = password });
|
entry.ExtractToFile(newName);
|
||||||
await ImportSqlite(newName, keepSource: false);
|
await ImportSqlite(newName);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -237,11 +221,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
|
|
||||||
var oldName = Path.ChangeExtension(App.Config.DatabaseFile, ".old.sqlite3");
|
var oldName = Path.ChangeExtension(App.Config.DatabaseFile, ".old.sqlite3");
|
||||||
File.Move(App.Config.DatabaseFile, oldName, true);
|
File.Move(App.Config.DatabaseFile, oldName, true);
|
||||||
if (keepSource) {
|
File.Move(filename, App.Config.DatabaseFile, false);
|
||||||
File.Copy(filename, App.Config.DatabaseFile, false);
|
|
||||||
} else {
|
|
||||||
File.Move(filename, App.Config.DatabaseFile, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
using var cnx = await AppDbContext.ConnectAsync();
|
using var cnx = await AppDbContext.ConnectAsync();
|
||||||
await cnx.ExecuteBatch("VACUUM");
|
await cnx.ExecuteBatch("VACUUM");
|
||||||
@@ -254,7 +234,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
using (var cnx = await AppDbContext.ConnectAsync($"Data Source=\"{newName}\"; Mode=ReadWriteCreate; Foreign Keys=False; Cache=Default; Pooling=False")) {
|
using (var cnx = await AppDbContext.ConnectAsync($"Data Source=\"{newName}\"; Mode=ReadWriteCreate; Foreign Keys=False; Cache=Default; Pooling=False")) {
|
||||||
await cnx.ExecuteBatch(await reader.ReadToEndAsync());
|
await cnx.ExecuteBatch(await reader.ReadToEndAsync());
|
||||||
}
|
}
|
||||||
await ImportSqlite(newName, keepSource: false);
|
await ImportSqlite(newName);
|
||||||
} finally {
|
} finally {
|
||||||
if (File.Exists(newName)) File.Delete(newName);
|
if (File.Exists(newName)) File.Delete(newName);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ using System.Security;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace Elwig.Helpers.Export {
|
namespace Elwig.Helpers.Export {
|
||||||
public class Ebics(PaymentVar variant, string filename, int version, Ebics.AddressMode mode = Ebics.AddressMode.Full) : IExporter<Transaction> {
|
public class Ebics(PaymentVar variant, string filename, int version, Ebics.AddressMode mode = Ebics.AddressMode.Full) : IBankingExporter {
|
||||||
|
|
||||||
public enum AddressMode { Omit = 0, Lines = 1, Full = 2 }
|
public enum AddressMode { Omit = 0, Lines = 1, Full = 2 }
|
||||||
|
|
||||||
@@ -28,6 +28,15 @@ namespace Elwig.Helpers.Export {
|
|||||||
Writer.Dispose();
|
Writer.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ValueTask DisposeAsync() {
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
return Writer.DisposeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Export(IEnumerable<Transaction> transactions, IProgress<double>? progress = null) {
|
||||||
|
ExportAsync(transactions, progress).GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
|
||||||
public async Task ExportAsync(IEnumerable<Transaction> transactions, IProgress<double>? progress = null) {
|
public async Task ExportAsync(IEnumerable<Transaction> transactions, IProgress<double>? progress = null) {
|
||||||
if (transactions.Any(tx => tx.Amount < 0)) {
|
if (transactions.Any(tx => tx.Amount < 0)) {
|
||||||
throw new ArgumentException("Tranaction amount may not be negative");
|
throw new ArgumentException("Tranaction amount may not be negative");
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
using Elwig.Models.Dtos;
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace Elwig.Helpers.Export {
|
||||||
|
public class Elba : Csv<Transaction>, IBankingExporter {
|
||||||
|
|
||||||
|
public static new string FileExtension => "elba";
|
||||||
|
|
||||||
|
public Elba(string filename) : base(filename) { }
|
||||||
|
|
||||||
|
public override string FormatRow(Transaction row) {
|
||||||
|
throw new NotImplementedException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ using System.IO.Compression;
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.Json.Nodes;
|
using System.Text.Json.Nodes;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using System.Windows;
|
||||||
|
|
||||||
namespace Elwig.Helpers.Export {
|
namespace Elwig.Helpers.Export {
|
||||||
public static class ElwigData {
|
public static class ElwigData {
|
||||||
@@ -30,21 +31,19 @@ namespace Elwig.Helpers.Export {
|
|||||||
await File.AppendAllLinesAsync(ImportedTxt, filenames, Utils.UTF8);
|
await File.AppendAllLinesAsync(ImportedTxt, filenames, Utils.UTF8);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Task Import(string filename, ImportMode mode, IEnumerable<ReadOnlyMemory<char>>? passwords = null) => Import([filename], mode, passwords);
|
public static Task Import(string filename, ImportMode mode) => Import([filename], mode);
|
||||||
|
|
||||||
public static async Task Import(IEnumerable<string> filenames, ImportMode mode, IEnumerable<ReadOnlyMemory<char>>? passwords = null) {
|
public static async Task Import(IEnumerable<string> filenames, ImportMode mode) {
|
||||||
try {
|
try {
|
||||||
Dictionary<string, Branch> branches;
|
Dictionary<string, Branch> branches;
|
||||||
Dictionary<int, AT_Kg> kgs;
|
|
||||||
Dictionary<int, int> currentDids;
|
Dictionary<int, int> currentDids;
|
||||||
Dictionary<string, int> currentLsNrs;
|
Dictionary<string, int> currentLsNrs;
|
||||||
Dictionary<int, List<WbRd>> currentWbRde;
|
Dictionary<int, List<WbRd>> currentWbRde;
|
||||||
Dictionary<int, WbKg> currentWbKgs;
|
Dictionary<int, AT_Kg> kgs;
|
||||||
List<WbGl> currentWbGls;
|
List<WbGl> currentWbGls;
|
||||||
|
|
||||||
using (var ctx = new AppDbContext()) {
|
using (var ctx = new AppDbContext()) {
|
||||||
branches = await ctx.FetchBranches().ToDictionaryAsync(b => b.ZwstId);
|
branches = await ctx.FetchBranches().ToDictionaryAsync(b => b.ZwstId);
|
||||||
kgs = await ctx.Katastralgemeinden.ToDictionaryAsync(k => k.KgNr);
|
|
||||||
currentDids = await ctx.Deliveries
|
currentDids = await ctx.Deliveries
|
||||||
.GroupBy(d => d.Year)
|
.GroupBy(d => d.Year)
|
||||||
.ToDictionaryAsync(g => g.Key, g => g.Max(d => d.DId));
|
.ToDictionaryAsync(g => g.Key, g => g.Max(d => d.DId));
|
||||||
@@ -53,8 +52,8 @@ namespace Elwig.Helpers.Export {
|
|||||||
currentWbRde = await ctx.WbRde
|
currentWbRde = await ctx.WbRde
|
||||||
.GroupBy(r => r.KgNr)
|
.GroupBy(r => r.KgNr)
|
||||||
.ToDictionaryAsync(g => g.Key, g => g.ToList());
|
.ToDictionaryAsync(g => g.Key, g => g.ToList());
|
||||||
currentWbKgs = await ctx.WbKgs.ToDictionaryAsync(k => k.KgNr);
|
|
||||||
currentWbGls = await ctx.WbGls.ToListAsync();
|
currentWbGls = await ctx.WbGls.ToListAsync();
|
||||||
|
kgs = await ctx.Katastralgemeinden.Include(k => k.WbKg).ToDictionaryAsync(k => k.KgNr);
|
||||||
}
|
}
|
||||||
|
|
||||||
var data = new List<(
|
var data = new List<(
|
||||||
@@ -63,8 +62,8 @@ namespace Elwig.Helpers.Export {
|
|||||||
List<MemberTelNr> TelephoneNumbers,
|
List<MemberTelNr> TelephoneNumbers,
|
||||||
List<MemberEmailAddr> EmailAddresses,
|
List<MemberEmailAddr> EmailAddresses,
|
||||||
List<MemberHistory> MemberHistory,
|
List<MemberHistory> MemberHistory,
|
||||||
List<AreaCmt> AreaCommitments,
|
List<AreaCom> AreaCommitments,
|
||||||
List<AreaCmtContract> Contracts,
|
List<AreaComContract> Contracts,
|
||||||
List<WbRd> Riede,
|
List<WbRd> Riede,
|
||||||
List<WbKg> WbKgs,
|
List<WbKg> WbKgs,
|
||||||
List<WbGl> WbGls,
|
List<WbGl> WbGls,
|
||||||
@@ -75,7 +74,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
|
|
||||||
var metaData = new List<(string FileName, string ZwstId, string Device,
|
var metaData = new List<(string FileName, string ZwstId, string Device,
|
||||||
int? MemberNum, string? MemberFilters,
|
int? MemberNum, string? MemberFilters,
|
||||||
int? AreaCmtNum, string? AreaCmtFilters,
|
int? AreaComNum, string? AreaComFilters,
|
||||||
int? DeliveryNum, string? DeliveryFilters)>();
|
int? DeliveryNum, string? DeliveryFilters)>();
|
||||||
|
|
||||||
foreach (var filename in filenames) {
|
foreach (var filename in filenames) {
|
||||||
@@ -89,42 +88,42 @@ namespace Elwig.Helpers.Export {
|
|||||||
})));
|
})));
|
||||||
var r = data[^1];
|
var r = data[^1];
|
||||||
|
|
||||||
using var zip = await ZipFile.OpenReadAsync(filename);
|
// TODO read encrypted files
|
||||||
var password = await zip.CheckIntegrity(passwords ?? []);
|
using var zip = ZipFile.Open(filename, ZipArchiveMode.Read);
|
||||||
|
await zip.CheckIntegrity();
|
||||||
|
|
||||||
string[] acceptableVersions = ["1", "2"];
|
string[] acceptableVersions = ["1", "2"];
|
||||||
var version = zip.GetEntry("version");
|
var version = zip.GetEntry("version");
|
||||||
using (var reader = new StreamReader(await version!.OpenAsync(), Utils.UTF8)) {
|
using (var reader = new StreamReader(version!.Open(), Utils.UTF8)) {
|
||||||
var v = await reader.ReadToEndAsync();
|
var v = await reader.ReadToEndAsync();
|
||||||
if (!v.StartsWith("elwig:") || !acceptableVersions.Contains(v[6..]))
|
if (!v.StartsWith("elwig:") || !acceptableVersions.Contains(v[6..]))
|
||||||
throw new FileFormatException($"Ungültige Elwig-Export-Datei ({filename})");
|
throw new FileFormatException($"Ungültige Elwig-Export-Datei ({filename})");
|
||||||
}
|
}
|
||||||
|
|
||||||
var metaJson = zip.GetEntry("meta.json");
|
var metaJson = zip.GetEntry("meta.json");
|
||||||
var meta = await JsonNode.ParseAsync(await metaJson!.OpenAsync());
|
var meta = await JsonNode.ParseAsync(metaJson!.Open());
|
||||||
var memberCount = meta!["members"]?["count"]?.AsValue().GetValue<int>();
|
var memberCount = meta!["members"]?["count"]?.AsValue().GetValue<int>();
|
||||||
var memberFilters = meta!["members"]?["filters"]?.AsArray().Select(f => f!.AsValue().GetValue<string>()).ToArray();
|
var memberFilters = meta!["members"]?["filters"]?.AsArray().Select(f => f!.AsValue().GetValue<string>()).ToArray();
|
||||||
var areaCmtCount = meta!["area_commitment_contracts"]?["count"]?.AsValue().GetValue<int>();
|
var areaComCount = meta!["area_commitment_contracts"]?["count"]?.AsValue().GetValue<int>();
|
||||||
var areaCmtFilters = meta!["area_commitment_contracts"]?["filters"]?.AsArray().Select(f => f!.AsValue().GetValue<string>()).ToArray();
|
var areaComFilters = meta!["area_commitment_contracts"]?["filters"]?.AsArray().Select(f => f!.AsValue().GetValue<string>()).ToArray();
|
||||||
var deliveryCount = meta!["deliveries"]?["count"]?.AsValue().GetValue<int>();
|
var deliveryCount = meta!["deliveries"]?["count"]?.AsValue().GetValue<int>();
|
||||||
var deliveryFilters = meta!["deliveries"]?["filters"]?.AsArray().Select(f => f!.AsValue().GetValue<string>()).ToArray();
|
var deliveryFilters = meta!["deliveries"]?["filters"]?.AsArray().Select(f => f!.AsValue().GetValue<string>()).ToArray();
|
||||||
metaData.Add((Path.GetFileName(filename),
|
metaData.Add((Path.GetFileName(filename),
|
||||||
meta["zwstid"]!.AsValue().GetValue<string>(), meta["device"]!.AsValue().GetValue<string>(),
|
meta["zwstid"]!.AsValue().GetValue<string>(), meta["device"]!.AsValue().GetValue<string>(),
|
||||||
memberCount, memberFilters != null ? string.Join(" / ", memberFilters) : null,
|
memberCount, memberFilters != null ? string.Join(" / ", memberFilters) : null,
|
||||||
areaCmtCount, areaCmtFilters != null ? string.Join(" / ", areaCmtFilters) : null,
|
areaComCount, areaComFilters != null ? string.Join(" / ", areaComFilters) : null,
|
||||||
deliveryCount, deliveryFilters != null ? string.Join(" / ", deliveryFilters) : null));
|
deliveryCount, deliveryFilters != null ? string.Join(" / ", deliveryFilters) : null));
|
||||||
|
|
||||||
var wbKgsJson = zip.GetEntry("wb_kgs.json");
|
var wbKgsJson = zip.GetEntry("wb_kgs.json");
|
||||||
if (wbKgsJson != null) {
|
if (wbKgsJson != null) {
|
||||||
using var reader = new StreamReader(await wbKgsJson.OpenAsync(password.Span), Utils.UTF8);
|
using var reader = new StreamReader(wbKgsJson.Open(), Utils.UTF8);
|
||||||
string? line;
|
string? line;
|
||||||
while ((line = await reader.ReadLineAsync()) != null) {
|
while ((line = await reader.ReadLineAsync()) != null) {
|
||||||
var obj = JsonNode.Parse(line)!.AsObject();
|
var obj = JsonNode.Parse(line)!.AsObject();
|
||||||
var (k, g) = obj.ToWbKg(currentWbGls);
|
var (k, g) = obj.ToWbKg(currentWbGls);
|
||||||
r.WbKgs.Add(k);
|
r.WbKgs.Add(k);
|
||||||
currentWbKgs[k.KgNr] = k;
|
|
||||||
if (g != null) {
|
if (g != null) {
|
||||||
currentWbGls.Add(g);
|
currentWbGls[g.GlNr] = g;
|
||||||
r.WbGls.Add(g);
|
r.WbGls.Add(g);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -132,11 +131,11 @@ namespace Elwig.Helpers.Export {
|
|||||||
|
|
||||||
var membersJson = zip.GetEntry("members.json");
|
var membersJson = zip.GetEntry("members.json");
|
||||||
if (membersJson != null) {
|
if (membersJson != null) {
|
||||||
using var reader = new StreamReader(await membersJson.OpenAsync(password.Span), Utils.UTF8);
|
using var reader = new StreamReader(membersJson.Open(), Utils.UTF8);
|
||||||
string? line;
|
string? line;
|
||||||
while ((line = await reader.ReadLineAsync()) != null) {
|
while ((line = await reader.ReadLineAsync()) != null) {
|
||||||
var obj = JsonNode.Parse(line)!.AsObject();
|
var obj = JsonNode.Parse(line)!.AsObject();
|
||||||
var (m, b, telNrs, emailAddrs, timestamps) = obj.ToMember(kgs, currentWbKgs);
|
var (m, b, telNrs, emailAddrs, timestamps) = obj.ToMember(kgs);
|
||||||
r.Members.Add(m);
|
r.Members.Add(m);
|
||||||
if (b != null) r.BillingAddresses.Add(b);
|
if (b != null) r.BillingAddresses.Add(b);
|
||||||
r.TelephoneNumbers.AddRange(telNrs);
|
r.TelephoneNumbers.AddRange(telNrs);
|
||||||
@@ -148,7 +147,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
|
|
||||||
var historyJson = zip.GetEntry("member_history.json");
|
var historyJson = zip.GetEntry("member_history.json");
|
||||||
if (historyJson != null) {
|
if (historyJson != null) {
|
||||||
using var reader = new StreamReader(await historyJson.OpenAsync(password.Span), Utils.UTF8);
|
using var reader = new StreamReader(historyJson.Open(), Utils.UTF8);
|
||||||
string? line;
|
string? line;
|
||||||
while ((line = await reader.ReadLineAsync()) != null) {
|
while ((line = await reader.ReadLineAsync()) != null) {
|
||||||
var obj = JsonNode.Parse(line)!.AsObject();
|
var obj = JsonNode.Parse(line)!.AsObject();
|
||||||
@@ -158,53 +157,53 @@ namespace Elwig.Helpers.Export {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// legacy area commitments
|
// legacy area commitments
|
||||||
var areaCmtsJson = zip.GetEntry("area_commitments.json");
|
var areaComsJson = zip.GetEntry("area_commitments.json");
|
||||||
if (areaCmtsJson != null) {
|
if (areaComsJson != null) {
|
||||||
using var reader = new StreamReader(await areaCmtsJson.OpenAsync(password.Span), Utils.UTF8);
|
using var reader = new StreamReader(areaComsJson.Open(), Utils.UTF8);
|
||||||
string? line;
|
string? line;
|
||||||
while ((line = await reader.ReadLineAsync()) != null) {
|
while ((line = await reader.ReadLineAsync()) != null) {
|
||||||
var obj = JsonNode.Parse(line)!.AsObject();
|
var obj = JsonNode.Parse(line)!.AsObject();
|
||||||
var (contract, areaCmt, wbrd, timestamps) = obj.ToAreaCmt(kgs, currentWbKgs, currentWbRde);
|
var (contract, areaCom, wbrd, timestamps) = obj.ToAreaCom(currentWbRde);
|
||||||
r.Contracts.Add(contract);
|
r.Contracts.Add(contract);
|
||||||
r.AreaCommitments.Add(areaCmt);
|
r.AreaCommitments.Add(areaCom);
|
||||||
if (wbrd != null) {
|
if (wbrd != null) {
|
||||||
r.Riede.Add(wbrd);
|
r.Riede.Add(wbrd);
|
||||||
}
|
}
|
||||||
if (timestamps.HasValue) {
|
if (timestamps.HasValue) {
|
||||||
r.Timestamps["area_commitment_contract"].Add((contract.FbNr, 0, 0, timestamps.Value.CreatedAt, timestamps.Value.ModifiedAt));
|
r.Timestamps["area_commitment_contract"].Add((contract.FbNr, 0, 0, timestamps.Value.CreatedAt, timestamps.Value.ModifiedAt));
|
||||||
r.Timestamps["area_commitment"].Add((areaCmt.FbNr, areaCmt.RevNr, 0, timestamps.Value.CreatedAt, timestamps.Value.ModifiedAt));
|
r.Timestamps["area_commitment"].Add((areaCom.FbNr, areaCom.RevNr, 0, timestamps.Value.CreatedAt, timestamps.Value.ModifiedAt));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var contractsJson = zip.GetEntry("area_commitment_contracts.json");
|
var contractsJson = zip.GetEntry("area_commitment_contracts.json");
|
||||||
if (contractsJson != null) {
|
if (contractsJson != null) {
|
||||||
using var reader = new StreamReader(await contractsJson.OpenAsync(password.Span), Utils.UTF8);
|
using var reader = new StreamReader(contractsJson.Open(), Utils.UTF8);
|
||||||
string? line;
|
string? line;
|
||||||
while ((line = await reader.ReadLineAsync()) != null) {
|
while ((line = await reader.ReadLineAsync()) != null) {
|
||||||
var obj = JsonNode.Parse(line)!.AsObject();
|
var obj = JsonNode.Parse(line)!.AsObject();
|
||||||
var (contract, areaCmts, wbrd, timestamps) = obj.ToAreaCmtContract(kgs, currentWbKgs, currentWbRde);
|
var (contract, areaComs, wbrd, timestamps) = obj.ToAreaComContract(currentWbRde);
|
||||||
r.Contracts.Add(contract);
|
r.Contracts.Add(contract);
|
||||||
r.AreaCommitments.AddRange(areaCmts.Select(v => v.Item1));
|
r.AreaCommitments.AddRange(areaComs.Select(v => v.Item1));
|
||||||
if (wbrd != null) {
|
if (wbrd != null) {
|
||||||
r.Riede.Add(wbrd);
|
r.Riede.Add(wbrd);
|
||||||
}
|
}
|
||||||
if (timestamps.HasValue)
|
if (timestamps.HasValue)
|
||||||
r.Timestamps["area_commitment_contract"].Add((contract.FbNr, 0, 0, timestamps.Value.CreatedAt, timestamps.Value.ModifiedAt));
|
r.Timestamps["area_commitment_contract"].Add((contract.FbNr, 0, 0, timestamps.Value.CreatedAt, timestamps.Value.ModifiedAt));
|
||||||
foreach (var (areaCmt, ts) in areaCmts) {
|
foreach (var (areaCom, ts) in areaComs) {
|
||||||
if (!ts.HasValue) continue;
|
if (!ts.HasValue) continue;
|
||||||
r.Timestamps["area_commitment"].Add((areaCmt.FbNr, areaCmt.RevNr, 0, ts.Value.CreatedAt, ts.Value.ModifiedAt));
|
r.Timestamps["area_commitment"].Add((areaCom.FbNr, areaCom.RevNr, 0, ts.Value.CreatedAt, ts.Value.ModifiedAt));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var deliveriesJson = zip.GetEntry("deliveries.json");
|
var deliveriesJson = zip.GetEntry("deliveries.json");
|
||||||
if (deliveriesJson != null) {
|
if (deliveriesJson != null) {
|
||||||
using var reader = new StreamReader(await deliveriesJson.OpenAsync(password.Span), Utils.UTF8);
|
using var reader = new StreamReader(deliveriesJson.Open(), Utils.UTF8);
|
||||||
string? line;
|
string? line;
|
||||||
while ((line = await reader.ReadLineAsync()) != null) {
|
while ((line = await reader.ReadLineAsync()) != null) {
|
||||||
var obj = JsonNode.Parse(line)!.AsObject();
|
var obj = JsonNode.Parse(line)!.AsObject();
|
||||||
var (d, parts, mods, rde, timestamps) = obj.ToDelivery(currentLsNrs, currentDids, kgs, currentWbKgs, currentWbRde);
|
var (d, parts, mods, rde, timestamps) = obj.ToDelivery(currentLsNrs, currentDids, kgs, currentWbRde);
|
||||||
r.Deliveries.Add(d);
|
r.Deliveries.Add(d);
|
||||||
r.DeliveryParts.AddRange(parts.Select(p => p.Item1));
|
r.DeliveryParts.AddRange(parts.Select(p => p.Item1));
|
||||||
r.Modifiers.AddRange(mods);
|
r.Modifiers.AddRange(mods);
|
||||||
@@ -234,7 +233,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var importedMembers = new List<(string FileName, string ZwstId, string Device, int New, int Overwritten, int NotImported, string? Filters)>();
|
var importedMembers = new List<(string FileName, string ZwstId, string Device, int New, int Overwritten, int NotImported, string? Filters)>();
|
||||||
var importedAreaCmts = new List<(string FileName, string ZwstId, string Device, int New, int Overwritten, int NotImported, string? Filters)>();
|
var importedAreaComs = new List<(string FileName, string ZwstId, string Device, int New, int Overwritten, int NotImported, string? Filters)>();
|
||||||
var importedDeliveries = new List<(string FileName, string ZwstId, string Device, int New, int Overwritten, int NotImported, string? Filters)>();
|
var importedDeliveries = new List<(string FileName, string ZwstId, string Device, int New, int Overwritten, int NotImported, string? Filters)>();
|
||||||
|
|
||||||
foreach (var ((members, billingAddresses, telephoneNumbers, emailAddresses, history, areaCommitments, contracts, riede, wbKgs, wbGls, deliveries, deliveryParts, modifiers, timestamps), meta) in data.Zip(metaData)) {
|
foreach (var ((members, billingAddresses, telephoneNumbers, emailAddresses, history, areaCommitments, contracts, riede, wbKgs, wbGls, deliveries, deliveryParts, modifiers, timestamps), meta) in data.Zip(metaData)) {
|
||||||
@@ -364,7 +363,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
ctx.AddRange(riede);
|
ctx.AddRange(riede);
|
||||||
var n = importNewContracts ? contracts.Count - duplicateFbNrs.Count : 0;
|
var n = importNewContracts ? contracts.Count - duplicateFbNrs.Count : 0;
|
||||||
var o = importDuplicateContracts ? duplicateFbNrs.Count : 0;
|
var o = importDuplicateContracts ? duplicateFbNrs.Count : 0;
|
||||||
importedAreaCmts.Add((meta.FileName, meta.ZwstId, meta.Device, n, o, contracts.Count - n - o, meta.AreaCmtFilters));
|
importedAreaComs.Add((meta.FileName, meta.ZwstId, meta.Device, n, o, contracts.Count - n - o, meta.AreaComFilters));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (allowedDuplicateLsNrs.Count > 0) {
|
if (allowedDuplicateLsNrs.Count > 0) {
|
||||||
@@ -446,17 +445,17 @@ namespace Elwig.Helpers.Export {
|
|||||||
$" ({d.New} neu, {d.Overwritten} überschrieben, {d.NotImported} nicht importiert)\n" +
|
$" ({d.New} neu, {d.Overwritten} überschrieben, {d.NotImported} nicht importiert)\n" +
|
||||||
$" Zweigstelle: {branches[d.ZwstId].Name} (Gerät {d.Device})\n" +
|
$" Zweigstelle: {branches[d.ZwstId].Name} (Gerät {d.Device})\n" +
|
||||||
$" Filter: {d.Filters}"),
|
$" Filter: {d.Filters}"),
|
||||||
$"Flächenbindungen: {importedAreaCmts.Sum(d => d.New + d.Overwritten)}",
|
$"Flächenbindungen: {importedAreaComs.Sum(d => d.New + d.Overwritten)}",
|
||||||
..importedAreaCmts.Select(d =>
|
..importedAreaComs.Select(d =>
|
||||||
$" {d.FileName} ({d.New + d.Overwritten})\n" +
|
$" {d.FileName} ({d.New + d.Overwritten})\n" +
|
||||||
$" ({d.New} neu, {d.Overwritten} überschrieben, {d.NotImported} nicht importiert)\n" +
|
$" ({d.New} importiert, {d.Overwritten} überschreiben, {d.NotImported} nicht importiert)\n" +
|
||||||
$" Zweigstelle: {branches[d.ZwstId].Name} (Gerät {d.Device})\n" +
|
$" Zweigstelle: {branches[d.ZwstId].Name} (Gerät {d.Device})\n" +
|
||||||
$" Filter: {d.Filters}"),
|
$" Filter: {d.Filters}"),
|
||||||
$"Lieferungen: {importedDeliveries.Sum(d => d.New + d.Overwritten)}",
|
$"Lieferungen: {importedDeliveries.Sum(d => d.New + d.Overwritten)}",
|
||||||
..importedDeliveries.Select(d =>
|
..importedDeliveries.Select(d =>
|
||||||
$" {d.FileName} ({d.New + d.Overwritten})\n" +
|
$" {d.FileName} ({d.New + d.Overwritten})\n" +
|
||||||
$" ({d.New} neu, {d.Overwritten} überschrieben, {d.NotImported} nicht importiert)\n" +
|
$" ({d.New} neu, {d.Overwritten} überschr., {d.NotImported} nicht importiert)\n" +
|
||||||
$" Zweigstelle: {branches[d.ZwstId].Name} (Gerät {d.Device})\n" +
|
$" Zwst.: {branches[d.ZwstId].Name} (Gerät {d.Device})\n" +
|
||||||
$" Filter: {d.Filters}")
|
$" Filter: {d.Filters}")
|
||||||
]));
|
]));
|
||||||
} catch (Exception exc) {
|
} catch (Exception exc) {
|
||||||
@@ -472,48 +471,48 @@ namespace Elwig.Helpers.Export {
|
|||||||
$"{branch} (Gerät {device}) {(duplicate ? "überschrieben" : "importiert")} werden?", true);
|
$"{branch} (Gerät {device}) {(duplicate ? "überschrieben" : "importiert")} werden?", true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Task Export(string filename, IEnumerable<Member> members, IEnumerable<MemberHistory> history, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters, ReadOnlyMemory<char> password = default) {
|
public static Task Export(string filename, IEnumerable<Member> members, IEnumerable<MemberHistory> history, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters) {
|
||||||
return new ElwigExport {
|
return new ElwigExport {
|
||||||
Members = (members, filters),
|
Members = (members, filters),
|
||||||
History = (history, ["von exportierten Mitgliedern"]),
|
History = (history, ["von exportierten Mitgliedern"]),
|
||||||
WbKgs = (wbKgs, ["von exportierten Mitgliedern"]),
|
WbKgs = (wbKgs, ["von exportierten Mitgliedern"]),
|
||||||
}.Export(filename, password);
|
}.Export(filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Task Export(string filename, IEnumerable<Member> members, IEnumerable<MemberHistory> history, IEnumerable<AreaCmtContract> areaCmts, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters, ReadOnlyMemory<char> password = default) {
|
public static Task Export(string filename, IEnumerable<Member> members, IEnumerable<MemberHistory> history, IEnumerable<AreaComContract> areaComs, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters) {
|
||||||
return new ElwigExport {
|
return new ElwigExport {
|
||||||
Members = (members, filters),
|
Members = (members, filters),
|
||||||
History = (history, ["von exportierten Mitgliedern"]),
|
History = (history, ["von exportierten Mitgliedern"]),
|
||||||
AreaCmts = (areaCmts, ["von exportierten Mitgliedern"]),
|
AreaComs = (areaComs, ["von exportierten Mitgliedern"]),
|
||||||
WbKgs = (wbKgs, ["von exportierten Mitgliedern und Flächenbindungen"]),
|
WbKgs = (wbKgs, ["von exportierten Mitgliedern und Flächenbindungen"]),
|
||||||
}.Export(filename, password);
|
}.Export(filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Task Export(string filename, IEnumerable<Delivery> deliveries, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters, ReadOnlyMemory<char> password = default) {
|
public static Task Export(string filename, IEnumerable<Delivery> deliveries, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters) {
|
||||||
return new ElwigExport {
|
return new ElwigExport {
|
||||||
Deliveries = (deliveries, filters),
|
Deliveries = (deliveries, filters),
|
||||||
WbKgs = (wbKgs, ["von exportierten Lieferungen"]),
|
WbKgs = (wbKgs, ["von exportierten Lieferungen"]),
|
||||||
}.Export(filename, password);
|
}.Export(filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
public class ElwigExport {
|
public class ElwigExport {
|
||||||
public (IEnumerable<WbKg> WbKgs, IEnumerable<string> Filters)? WbKgs { get; set; }
|
public (IEnumerable<WbKg> WbKgs, IEnumerable<string> Filters)? WbKgs { get; set; }
|
||||||
public (IEnumerable<Member> Members, IEnumerable<string> Filters)? Members { get; set; }
|
public (IEnumerable<Member> Members, IEnumerable<string> Filters)? Members { get; set; }
|
||||||
public (IEnumerable<MemberHistory> History, IEnumerable<string> Filters)? History { get; set; }
|
public (IEnumerable<MemberHistory> History, IEnumerable<string> Filters)? History { get; set; }
|
||||||
public (IEnumerable<AreaCmtContract> AreaCmts, IEnumerable<string> Filters)? AreaCmts { get; set; }
|
public (IEnumerable<AreaComContract> AreaComs, IEnumerable<string> Filters)? AreaComs { get; set; }
|
||||||
public (IEnumerable<Delivery> Deliveries, IEnumerable<string> Filters)? Deliveries { get; set; }
|
public (IEnumerable<Delivery> Deliveries, IEnumerable<string> Filters)? Deliveries { get; set; }
|
||||||
|
|
||||||
public async Task Export(string filename, ReadOnlyMemory<char> password = default) {
|
public async Task Export(string filename) {
|
||||||
File.Delete(filename);
|
File.Delete(filename);
|
||||||
using var zip = await ZipFile.OpenAsync(filename, ZipArchiveMode.Create);
|
using var zip = ZipFile.Open(filename, ZipArchiveMode.Create);
|
||||||
|
|
||||||
var version = zip.CreateEntry("version", CompressionLevel.NoCompression);
|
var version = zip.CreateEntry("version", CompressionLevel.NoCompression);
|
||||||
using (var writer = new StreamWriter(await version.OpenAsync(), Utils.UTF8)) {
|
using (var writer = new StreamWriter(version.Open(), Utils.UTF8)) {
|
||||||
await writer.WriteAsync("elwig:2");
|
await writer.WriteAsync("elwig:2");
|
||||||
}
|
}
|
||||||
|
|
||||||
var meta = zip.CreateEntry("meta.json", CompressionLevel.NoCompression);
|
var meta = zip.CreateEntry("meta.json", CompressionLevel.NoCompression);
|
||||||
using (var writer = new StreamWriter(await meta.OpenAsync(), Utils.UTF8)) {
|
using (var writer = new StreamWriter(meta.Open(), Utils.UTF8)) {
|
||||||
var obj = new JsonObject {
|
var obj = new JsonObject {
|
||||||
["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}",
|
["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}",
|
||||||
["zwstid"] = App.ZwstId,
|
["zwstid"] = App.ZwstId,
|
||||||
@@ -534,11 +533,11 @@ namespace Elwig.Helpers.Export {
|
|||||||
["count"] = History.Value.History.Count(),
|
["count"] = History.Value.History.Count(),
|
||||||
["filters"] = new JsonArray(History.Value.Filters.Select(f => (JsonNode)f).ToArray()),
|
["filters"] = new JsonArray(History.Value.Filters.Select(f => (JsonNode)f).ToArray()),
|
||||||
};
|
};
|
||||||
if (AreaCmts != null)
|
if (AreaComs != null)
|
||||||
obj["area_commitment_contracts"] = new JsonObject {
|
obj["area_commitment_contracts"] = new JsonObject {
|
||||||
["count"] = AreaCmts.Value.AreaCmts.Count(),
|
["count"] = AreaComs.Value.AreaComs.Count(),
|
||||||
["revisions"] = AreaCmts.Value.AreaCmts.Sum(c => c.Revisions.Count),
|
["revisions"] = AreaComs.Value.AreaComs.Sum(c => c.Revisions.Count),
|
||||||
["filters"] = new JsonArray(AreaCmts.Value.Filters.Select(f => (JsonNode)f).ToArray()),
|
["filters"] = new JsonArray(AreaComs.Value.Filters.Select(f => (JsonNode)f).ToArray()),
|
||||||
};
|
};
|
||||||
if (Deliveries != null)
|
if (Deliveries != null)
|
||||||
obj["deliveries"] = new JsonObject {
|
obj["deliveries"] = new JsonObject {
|
||||||
@@ -549,47 +548,38 @@ namespace Elwig.Helpers.Export {
|
|||||||
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
|
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO encrypt files
|
||||||
if (WbKgs != null) {
|
if (WbKgs != null) {
|
||||||
var json = password.IsEmpty ?
|
var json = zip.CreateEntry("wb_kgs.json", CompressionLevel.SmallestSize);
|
||||||
zip.CreateEntry("wb_kgs.json", CompressionLevel.SmallestSize) :
|
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
|
||||||
zip.CreateEntry("wb_kgs.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
|
||||||
using var writer = new StreamWriter(await json.OpenAsync(), Utils.UTF8);
|
|
||||||
foreach (var k in WbKgs.Value.WbKgs) {
|
foreach (var k in WbKgs.Value.WbKgs) {
|
||||||
await writer.WriteLineAsync(k.ToJson().ToJsonString(Utils.JsonOpts));
|
await writer.WriteLineAsync(k.ToJson().ToJsonString(Utils.JsonOpts));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Members != null) {
|
if (Members != null) {
|
||||||
var json = password.IsEmpty ?
|
var json = zip.CreateEntry("members.json", CompressionLevel.SmallestSize);
|
||||||
zip.CreateEntry("members.json", CompressionLevel.SmallestSize) :
|
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
|
||||||
zip.CreateEntry("members.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
|
||||||
using var writer = new StreamWriter(await json.OpenAsync(), Utils.UTF8);
|
|
||||||
foreach (var m in Members.Value.Members) {
|
foreach (var m in Members.Value.Members) {
|
||||||
await writer.WriteLineAsync(m.ToJson().ToJsonString(Utils.JsonOpts));
|
await writer.WriteLineAsync(m.ToJson().ToJsonString(Utils.JsonOpts));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (History != null) {
|
if (History != null) {
|
||||||
var json = password.IsEmpty ?
|
var json = zip.CreateEntry("member_history.json", CompressionLevel.SmallestSize);
|
||||||
zip.CreateEntry("member_history.json", CompressionLevel.SmallestSize) :
|
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
|
||||||
zip.CreateEntry("member_history.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
|
||||||
using var writer = new StreamWriter(await json.OpenAsync(), Utils.UTF8);
|
|
||||||
foreach (var h in History.Value.History) {
|
foreach (var h in History.Value.History) {
|
||||||
await writer.WriteLineAsync(h.ToJson().ToJsonString(Utils.JsonOpts));
|
await writer.WriteLineAsync(h.ToJson().ToJsonString(Utils.JsonOpts));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (AreaCmts != null) {
|
if (AreaComs != null) {
|
||||||
var json = password.IsEmpty ?
|
var json = zip.CreateEntry("area_commitment_contracts.json", CompressionLevel.SmallestSize);
|
||||||
zip.CreateEntry("area_commitment_contracts.json", CompressionLevel.SmallestSize) :
|
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
|
||||||
zip.CreateEntry("area_commitment_contracts.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
foreach (var c in AreaComs.Value.AreaComs) {
|
||||||
using var writer = new StreamWriter(await json.OpenAsync(), Utils.UTF8);
|
|
||||||
foreach (var c in AreaCmts.Value.AreaCmts) {
|
|
||||||
await writer.WriteLineAsync(c.ToJson().ToJsonString(Utils.JsonOpts));
|
await writer.WriteLineAsync(c.ToJson().ToJsonString(Utils.JsonOpts));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Deliveries != null) {
|
if (Deliveries != null) {
|
||||||
var json = password.IsEmpty ?
|
var json = zip.CreateEntry("deliveries.json", CompressionLevel.SmallestSize);
|
||||||
zip.CreateEntry("deliveries.json", CompressionLevel.SmallestSize) :
|
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
|
||||||
zip.CreateEntry("deliveries.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
|
|
||||||
using var writer = new StreamWriter(await json.OpenAsync(), Utils.UTF8);
|
|
||||||
foreach (var d in Deliveries.Value.Deliveries) {
|
foreach (var d in Deliveries.Value.Deliveries) {
|
||||||
await writer.WriteLineAsync(d.ToJson().ToJsonString(Utils.JsonOpts));
|
await writer.WriteLineAsync(d.ToJson().ToJsonString(Utils.JsonOpts));
|
||||||
}
|
}
|
||||||
@@ -616,7 +606,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
GlNr = (gls.Count == 0 ? 1 : gls.Max(g => g.GlNr)) + 1,
|
GlNr = (gls.Count == 0 ? 1 : gls.Max(g => g.GlNr)) + 1,
|
||||||
Name = grosslage,
|
Name = grosslage,
|
||||||
};
|
};
|
||||||
gls.Add(gl);
|
gls[gl.GlNr] = gl;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return (new WbKg {
|
return (new WbKg {
|
||||||
@@ -646,13 +636,11 @@ namespace Elwig.Helpers.Export {
|
|||||||
["zwstid"] = m.ZwstId,
|
["zwstid"] = m.ZwstId,
|
||||||
["lfbis_nr"] = m.LfbisNr,
|
["lfbis_nr"] = m.LfbisNr,
|
||||||
["ustid_nr"] = m.UstIdNr,
|
["ustid_nr"] = m.UstIdNr,
|
||||||
["ooc_id"] = m.OrganicOperatorId,
|
|
||||||
["org_auth_code"] = m.OrganicAuthorityCode,
|
|
||||||
["juridical_pers"] = m.IsJuridicalPerson,
|
["juridical_pers"] = m.IsJuridicalPerson,
|
||||||
["full_delivery"] = m.IsFullDelivery,
|
["volllieferant"] = m.IsVollLieferant,
|
||||||
["accounting"] = m.IsAccounting,
|
["buchführend"] = m.IsBuchführend,
|
||||||
["organic"] = m.IsOrganic,
|
["organic"] = m.IsOrganic,
|
||||||
["officer"] = m.IsOfficer,
|
["funktionär"] = m.IsFunktionär,
|
||||||
["active"] = m.IsActive,
|
["active"] = m.IsActive,
|
||||||
["deceased"] = m.IsDeceased,
|
["deceased"] = m.IsDeceased,
|
||||||
["iban"] = m.Iban,
|
["iban"] = m.Iban,
|
||||||
@@ -692,11 +680,11 @@ namespace Elwig.Helpers.Export {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public static (Member, BillingAddr?, List<MemberTelNr>, List<MemberEmailAddr>, (DateTime CreatedAt, DateTime ModifiedAt)?) ToMember(this JsonNode json, Dictionary<int, AT_Kg> kgs, Dictionary<int, WbKg> currentWbKgs) {
|
public static (Member, BillingAddr?, List<MemberTelNr>, List<MemberEmailAddr>, (DateTime CreatedAt, DateTime ModifiedAt)?) ToMember(this JsonNode json, Dictionary<int, AT_Kg> kgs) {
|
||||||
var mgnr = json["mgnr"]!.AsValue().GetValue<int>();
|
var mgnr = json["mgnr"]!.AsValue().GetValue<int>();
|
||||||
var kgnr = json["default_kgnr"]?.AsValue().GetValue<int>();
|
var kgnr = json["default_kgnr"]?.AsValue().GetValue<int>();
|
||||||
if (kgnr != null && !currentWbKgs.Values.Any(k => k.KgNr == kgnr)) {
|
if (kgnr != null && !kgs.Values.Any(k => k.WbKg?.KgNr == kgnr)) {
|
||||||
throw new KeyNotFoundException($"Für KG {(kgs.TryGetValue(kgnr.Value, out var k) ? k.Name : "?")} ({kgnr:00000}) ist noch keine Großlage festgelegt!\n(Stammdaten \u2192 Herkunftshierarchie)");
|
throw new ArgumentException($"Für KG {(kgs.TryGetValue(kgnr.Value, out var k) ? k.Name : "?")} ({kgnr:00000}) ist noch keine Großlage festgelegt!\n(Stammdaten → Herkunftshierarchie)");
|
||||||
}
|
}
|
||||||
var createdAt = json["created_at"]?.AsValue().GetValue<string>();
|
var createdAt = json["created_at"]?.AsValue().GetValue<string>();
|
||||||
var modifiedAt = json["modified_at"]?.AsValue().GetValue<string>();
|
var modifiedAt = json["modified_at"]?.AsValue().GetValue<string>();
|
||||||
@@ -720,13 +708,11 @@ namespace Elwig.Helpers.Export {
|
|||||||
ZwstId = json["zwstid"]?.AsValue().GetValue<string>(),
|
ZwstId = json["zwstid"]?.AsValue().GetValue<string>(),
|
||||||
LfbisNr = json["lfbis_nr"]?.AsValue().GetValue<string>(),
|
LfbisNr = json["lfbis_nr"]?.AsValue().GetValue<string>(),
|
||||||
UstIdNr = json["ustid_nr"]?.AsValue().GetValue<string>(),
|
UstIdNr = json["ustid_nr"]?.AsValue().GetValue<string>(),
|
||||||
OrganicOperatorId = json["ooc_id"]?.AsValue().GetValue<string>(),
|
|
||||||
OrganicAuthorityCode = json["org_auth_code"]?.AsValue().GetValue<string>(),
|
|
||||||
IsJuridicalPerson = json["juridical_pers"]?.AsValue().GetValue<bool>() ?? false,
|
IsJuridicalPerson = json["juridical_pers"]?.AsValue().GetValue<bool>() ?? false,
|
||||||
IsFullDelivery = json["full_delivery"]?.AsValue().GetValue<bool>() ?? json["volllieferant"]?.AsValue().GetValue<bool>() ?? false,
|
IsVollLieferant = json["volllieferant"]?.AsValue().GetValue<bool>() ?? false,
|
||||||
IsAccounting = json["accounting"]?.AsValue().GetValue<bool>() ?? json["buchführend"]?.AsValue().GetValue<bool>() ?? false,
|
IsBuchführend = json["buchführend"]?.AsValue().GetValue<bool>() ?? false,
|
||||||
IsOrganic = json["organic"]?.AsValue().GetValue<bool>() ?? false,
|
IsOrganic = json["organic"]?.AsValue().GetValue<bool>() ?? false,
|
||||||
IsOfficer = json["officer"]?.AsValue().GetValue<bool>() ?? json["funktionär"]?.AsValue().GetValue<bool>() ?? false,
|
IsFunktionär = json["funktionär"]?.AsValue().GetValue<bool>() ?? false,
|
||||||
IsActive = json["active"]?.AsValue().GetValue<bool>() ?? false,
|
IsActive = json["active"]?.AsValue().GetValue<bool>() ?? false,
|
||||||
IsDeceased = json["deceased"]?.AsValue().GetValue<bool>() ?? false,
|
IsDeceased = json["deceased"]?.AsValue().GetValue<bool>() ?? false,
|
||||||
Iban = json["iban"]?.AsValue().GetValue<string>(),
|
Iban = json["iban"]?.AsValue().GetValue<string>(),
|
||||||
@@ -774,8 +760,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
["reason"] = h.Reason,
|
["reason"] = h.Reason,
|
||||||
["source"] = h.Source,
|
["source"] = h.Source,
|
||||||
["shares"] = h.Shares,
|
["shares"] = h.Shares,
|
||||||
["signed_company"] = h.CompanyHasSigned,
|
["signed"] = h.MemberHasSigned,
|
||||||
["signed_member"] = h.MemberHasSigned,
|
|
||||||
["value_per_share"] = h.ValuePerShare,
|
["value_per_share"] = h.ValuePerShare,
|
||||||
["currency"] = h.CurrencyCode,
|
["currency"] = h.CurrencyCode,
|
||||||
["deduct_year"] = h.DeductYear,
|
["deduct_year"] = h.DeductYear,
|
||||||
@@ -795,8 +780,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
Reason = json["reason"]!.AsValue().GetValue<string>(),
|
Reason = json["reason"]!.AsValue().GetValue<string>(),
|
||||||
Source = json["source"]!.AsValue().GetValue<string>(),
|
Source = json["source"]!.AsValue().GetValue<string>(),
|
||||||
Shares = json["shares"]!.AsValue().GetValue<int>(),
|
Shares = json["shares"]!.AsValue().GetValue<int>(),
|
||||||
CompanyHasSigned = json["signed_company"]?.AsValue().GetValue<bool>() ?? false,
|
MemberHasSigned = json["signed"]?.AsValue().GetValue<bool>() ?? false,
|
||||||
MemberHasSigned = json["signed_member"]?.AsValue().GetValue<bool>() ?? false,
|
|
||||||
ValuePerShare = json["value_per_share"]?.AsValue().GetValue<decimal>(),
|
ValuePerShare = json["value_per_share"]?.AsValue().GetValue<decimal>(),
|
||||||
CurrencyCode = json["currency"]?.AsValue().GetValue<string>(),
|
CurrencyCode = json["currency"]?.AsValue().GetValue<string>(),
|
||||||
DeductYear = json["deduct_year"]?.AsValue().GetValue<int>(),
|
DeductYear = json["deduct_year"]?.AsValue().GetValue<int>(),
|
||||||
@@ -804,7 +788,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public static JsonObject ToJson(this AreaCmtContract c) {
|
public static JsonObject ToJson(this AreaComContract c) {
|
||||||
return new JsonObject {
|
return new JsonObject {
|
||||||
["fbnr"] = c.FbNr,
|
["fbnr"] = c.FbNr,
|
||||||
["kgnr"] = c.KgNr,
|
["kgnr"] = c.KgNr,
|
||||||
@@ -816,7 +800,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static JsonObject ToJson(this AreaCmt c) {
|
private static JsonObject ToJson(this AreaCom c) {
|
||||||
return new JsonObject {
|
return new JsonObject {
|
||||||
["revnr"] = c.RevNr,
|
["revnr"] = c.RevNr,
|
||||||
["mgnr"] = c.MgNr,
|
["mgnr"] = c.MgNr,
|
||||||
@@ -831,13 +815,10 @@ namespace Elwig.Helpers.Export {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public static (AreaCmtContract, List<(AreaCmt, (DateTime CreatedAt, DateTime ModifiedAt)?)>, WbRd?, (DateTime CreatedAt, DateTime ModifiedAt)?) ToAreaCmtContract(this JsonNode json, Dictionary<int, AT_Kg> kgs, Dictionary<int, WbKg> currentWbKgs, Dictionary<int, List<WbRd>> riede) {
|
public static (AreaComContract, List<(AreaCom, (DateTime CreatedAt, DateTime ModifiedAt)?)>, WbRd?, (DateTime CreatedAt, DateTime ModifiedAt)?) ToAreaComContract(this JsonNode json, Dictionary<int, List<WbRd>> riede) {
|
||||||
var kgnr = json["kgnr"]!.AsValue().GetValue<int>();
|
var kgnr = json["kgnr"]!.AsValue().GetValue<int>();
|
||||||
var ried = json["ried"]?.AsValue().GetValue<string>();
|
var ried = json["ried"]?.AsValue().GetValue<string>();
|
||||||
var fbnr = json["fbnr"]!.AsValue()!.GetValue<int>();
|
var fbnr = json["fbnr"]!.AsValue()!.GetValue<int>();
|
||||||
if (!currentWbKgs.Values.Any(k => k.KgNr == kgnr)) {
|
|
||||||
throw new KeyNotFoundException($"Für KG {(kgs.TryGetValue(kgnr, out var k) ? k.Name : "?")} ({kgnr:00000}) ist noch keine Großlage festgelegt!\n(Stammdaten \u2192 Herkunftshierarchie)");
|
|
||||||
}
|
|
||||||
WbRd? rd = null;
|
WbRd? rd = null;
|
||||||
bool newRd = false;
|
bool newRd = false;
|
||||||
if (ried != null) {
|
if (ried != null) {
|
||||||
@@ -856,16 +837,16 @@ namespace Elwig.Helpers.Export {
|
|||||||
}
|
}
|
||||||
var createdAt = json["created_at"]?.AsValue().GetValue<string>();
|
var createdAt = json["created_at"]?.AsValue().GetValue<string>();
|
||||||
var modifiedAt = json["modified_at"]?.AsValue().GetValue<string>();
|
var modifiedAt = json["modified_at"]?.AsValue().GetValue<string>();
|
||||||
return (new AreaCmtContract {
|
return (new AreaComContract {
|
||||||
FbNr = fbnr,
|
FbNr = fbnr,
|
||||||
KgNr = kgnr,
|
KgNr = kgnr,
|
||||||
RdNr = rd?.RdNr ?? json["rdnr"]?.AsValue().GetValue<int>(),
|
RdNr = rd?.RdNr ?? json["rdnr"]?.AsValue().GetValue<int>(),
|
||||||
Comment = json["comment"]?.AsValue().GetValue<string>(),
|
Comment = json["comment"]?.AsValue().GetValue<string>(),
|
||||||
ImportedAt = DateTime.Now,
|
ImportedAt = DateTime.Now,
|
||||||
}, [.. json["revisions"]!.AsArray().Select(r => r!.AsObject()).Select<JsonObject, (AreaCmt, (DateTime, DateTime)?)>(r => {
|
}, [.. json["revisions"]!.AsArray().Select(r => r!.AsObject()).Select<JsonObject, (AreaCom, (DateTime, DateTime)?)>(r => {
|
||||||
var createdAt = json["created_at"]?.AsValue().GetValue<string>();
|
var createdAt = json["created_at"]?.AsValue().GetValue<string>();
|
||||||
var modifiedAt = json["modified_at"]?.AsValue().GetValue<string>();
|
var modifiedAt = json["modified_at"]?.AsValue().GetValue<string>();
|
||||||
return (new AreaCmt {
|
return (new AreaCom {
|
||||||
FbNr = fbnr,
|
FbNr = fbnr,
|
||||||
RevNr = r["revnr"]!.AsValue().GetValue<int>(),
|
RevNr = r["revnr"]!.AsValue().GetValue<int>(),
|
||||||
MgNr = r["mgnr"]!.AsValue().GetValue<int>(),
|
MgNr = r["mgnr"]!.AsValue().GetValue<int>(),
|
||||||
@@ -885,12 +866,9 @@ namespace Elwig.Helpers.Export {
|
|||||||
DateTime.ParseExact(modifiedAt, "yyyy-MM-ddTHH:mm:ssK", CultureInfo.InvariantCulture, DateTimeStyles.None)));
|
DateTime.ParseExact(modifiedAt, "yyyy-MM-ddTHH:mm:ssK", CultureInfo.InvariantCulture, DateTimeStyles.None)));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static (AreaCmtContract, AreaCmt, WbRd?, (DateTime CreatedAt, DateTime ModifiedAt)?) ToAreaCmt(this JsonNode json, Dictionary<int, AT_Kg> kgs, Dictionary<int, WbKg> currentWbKgs, Dictionary<int, List<WbRd>> riede) {
|
public static (AreaComContract, AreaCom, WbRd?, (DateTime CreatedAt, DateTime ModifiedAt)?) ToAreaCom(this JsonNode json, Dictionary<int, List<WbRd>> riede) {
|
||||||
var kgnr = json["kgnr"]!.AsValue().GetValue<int>();
|
var kgnr = json["kgnr"]!.AsValue().GetValue<int>();
|
||||||
var ried = json["ried"]?.AsValue().GetValue<string>();
|
var ried = json["ried"]?.AsValue().GetValue<string>();
|
||||||
if (!currentWbKgs.Values.Any(k => k.KgNr == kgnr)) {
|
|
||||||
throw new KeyNotFoundException($"Für KG {(kgs.TryGetValue(kgnr, out var k) ? k.Name : "?")} ({kgnr:00000}) ist noch keine Großlage festgelegt!\n(Stammdaten \u2192 Herkunftshierarchie)");
|
|
||||||
}
|
|
||||||
WbRd? rd = null;
|
WbRd? rd = null;
|
||||||
bool newRd = false;
|
bool newRd = false;
|
||||||
if (ried != null) {
|
if (ried != null) {
|
||||||
@@ -909,13 +887,13 @@ namespace Elwig.Helpers.Export {
|
|||||||
}
|
}
|
||||||
var createdAt = json["created_at"]?.AsValue().GetValue<string>();
|
var createdAt = json["created_at"]?.AsValue().GetValue<string>();
|
||||||
var modifiedAt = json["modified_at"]?.AsValue().GetValue<string>();
|
var modifiedAt = json["modified_at"]?.AsValue().GetValue<string>();
|
||||||
return (new AreaCmtContract {
|
return (new AreaComContract {
|
||||||
FbNr = json["fbnr"]!.AsValue().GetValue<int>(),
|
FbNr = json["fbnr"]!.AsValue().GetValue<int>(),
|
||||||
KgNr = kgnr,
|
KgNr = kgnr,
|
||||||
RdNr = rd?.RdNr ?? json["rdnr"]?.AsValue().GetValue<int>(),
|
RdNr = rd?.RdNr ?? json["rdnr"]?.AsValue().GetValue<int>(),
|
||||||
Comment = json["comment"]?.AsValue().GetValue<string>(),
|
Comment = json["comment"]?.AsValue().GetValue<string>(),
|
||||||
ImportedAt = DateTime.Now,
|
ImportedAt = DateTime.Now,
|
||||||
}, new AreaCmt {
|
}, new AreaCom {
|
||||||
FbNr = json["fbnr"]!.AsValue().GetValue<int>(),
|
FbNr = json["fbnr"]!.AsValue().GetValue<int>(),
|
||||||
RevNr = 1,
|
RevNr = 1,
|
||||||
MgNr = json["mgnr"]!.AsValue().GetValue<int>(),
|
MgNr = json["mgnr"]!.AsValue().GetValue<int>(),
|
||||||
@@ -969,17 +947,17 @@ namespace Elwig.Helpers.Export {
|
|||||||
};
|
};
|
||||||
if (p.IsSplCheck) obj["spl_check"] = p.IsSplCheck;
|
if (p.IsSplCheck) obj["spl_check"] = p.IsSplCheck;
|
||||||
if (p.IsHandPicked != null) obj["hand_picked"] = p.IsHandPicked;
|
if (p.IsHandPicked != null) obj["hand_picked"] = p.IsHandPicked;
|
||||||
if (p.IsContracted != null) obj["contracted"] = p.IsContracted;
|
if (p.IsGebunden != null) obj["gebunden"] = p.IsGebunden;
|
||||||
if (p.Unloading != null) obj["unloading"] = p.Unloading;
|
if (p.Unloading != null) obj["unloading"] = p.Unloading;
|
||||||
if (p.Temperature != null) obj["temperature"] = p.Temperature;
|
if (p.Temperature != null) obj["temperature"] = p.Temperature;
|
||||||
if (p.Acid != null) obj["acid"] = p.Acid;
|
if (p.Acid != null) obj["acid"] = p.Acid;
|
||||||
if (p.ScaleTerminalId != null) obj["scale_terminal"] = p.ScaleTerminalId;
|
if (p.ScaleId != null) obj["scale_id"] = p.ScaleId;
|
||||||
if (p.WeighingData != null) obj["weighing_data"] = JsonNode.Parse(p.WeighingData);
|
if (p.WeighingData != null) obj["weighing_data"] = JsonNode.Parse(p.WeighingData);
|
||||||
if (p.WeighingReason != null) obj["weighing_reason"] = p.WeighingReason;
|
if (p.WeighingReason != null) obj["weighing_reason"] = p.WeighingReason;
|
||||||
return obj;
|
return obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static (Delivery, List<(DeliveryPart, (DateTime CreatedAt, DateTime ModifiedAt)?)>, List<DeliveryPartModifier>, List<WbRd>, (DateTime CreatedAt, DateTime ModifiedAt)?) ToDelivery(this JsonNode json, Dictionary<string, int> currentLsNrs, Dictionary<int, int> currentDids, Dictionary<int, AT_Kg> kgs, Dictionary<int, WbKg> currentWbKgs, Dictionary<int, List<WbRd>> riede) {
|
public static (Delivery, List<(DeliveryPart, (DateTime CreatedAt, DateTime ModifiedAt)?)>, List<DeliveryPartModifier>, List<WbRd>, (DateTime CreatedAt, DateTime ModifiedAt)?) ToDelivery(this JsonNode json, Dictionary<string, int> currentLsNrs, Dictionary<int, int> currentDids, Dictionary<int, AT_Kg> kgs, Dictionary<int, List<WbRd>> riede) {
|
||||||
var year = json["year"]!.AsValue().GetValue<int>();
|
var year = json["year"]!.AsValue().GetValue<int>();
|
||||||
var lsnr = json["lsnr"]!.AsValue().GetValue<string>();
|
var lsnr = json["lsnr"]!.AsValue().GetValue<string>();
|
||||||
var did = currentLsNrs.GetValueOrDefault(lsnr, -1);
|
var did = currentLsNrs.GetValueOrDefault(lsnr, -1);
|
||||||
@@ -1005,9 +983,6 @@ namespace Elwig.Helpers.Export {
|
|||||||
}, [.. json["parts"]!.AsArray().Select(p => p!.AsObject()).Select<JsonObject, (DeliveryPart, (DateTime, DateTime)?)>(p => {
|
}, [.. json["parts"]!.AsArray().Select(p => p!.AsObject()).Select<JsonObject, (DeliveryPart, (DateTime, DateTime)?)>(p => {
|
||||||
var kgnr = p["kgnr"]?.AsValue().GetValue<int>();
|
var kgnr = p["kgnr"]?.AsValue().GetValue<int>();
|
||||||
var ried = p["ried"]?.AsValue().GetValue<string>();
|
var ried = p["ried"]?.AsValue().GetValue<string>();
|
||||||
if (kgnr != null && !currentWbKgs.Values.Any(k => k.KgNr == kgnr)) {
|
|
||||||
throw new KeyNotFoundException($"Für KG {(kgs.TryGetValue(kgnr.Value, out var k) ? k.Name : "?")} ({kgnr:00000}) ist noch keine Großlage festgelegt!\n(Stammdaten \u2192 Herkunftshierarchie)");
|
|
||||||
}
|
|
||||||
WbRd? rd = null;
|
WbRd? rd = null;
|
||||||
if (ried != null && kgnr != null) {
|
if (ried != null && kgnr != null) {
|
||||||
var rde = riede.GetValueOrDefault(kgnr.Value, []);
|
var rde = riede.GetValueOrDefault(kgnr.Value, []);
|
||||||
@@ -1043,11 +1018,11 @@ namespace Elwig.Helpers.Export {
|
|||||||
Comment = p["comment"]?.AsValue().GetValue<string>(),
|
Comment = p["comment"]?.AsValue().GetValue<string>(),
|
||||||
IsSplCheck = p["spl_check"]?.AsValue().GetValue<bool>() ?? false,
|
IsSplCheck = p["spl_check"]?.AsValue().GetValue<bool>() ?? false,
|
||||||
IsHandPicked = p["hand_picked"]?.AsValue().GetValue<bool>(),
|
IsHandPicked = p["hand_picked"]?.AsValue().GetValue<bool>(),
|
||||||
IsContracted = p["contracted"]?.AsValue().GetValue<bool>() ?? p["gebunden"]?.AsValue().GetValue<bool>(),
|
IsGebunden = p["gebunden"]?.AsValue().GetValue<bool>(),
|
||||||
Unloading = p["unloading"]?.AsValue().GetValue<string>() ?? ((p["lesewagen"]?.AsValue().GetValue<bool>() ?? false) ? DeliveryPart.Pumped : null),
|
Unloading = p["unloading"]?.AsValue().GetValue<string>() ?? ((p["lesewagen"]?.AsValue().GetValue<bool>() ?? false) ? DeliveryPart.Pumped : null),
|
||||||
Temperature = p["temperature"]?.AsValue().GetValue<double>(),
|
Temperature = p["temperature"]?.AsValue().GetValue<double>(),
|
||||||
Acid = p["acid"]?.AsValue().GetValue<double>(),
|
Acid = p["acid"]?.AsValue().GetValue<double>(),
|
||||||
ScaleTerminalId = p["scale_terminal"]?.AsValue().GetValue<string>() ?? p["scale_id"]?.AsValue().GetValue<string>(),
|
ScaleId = p["scale_id"]?.AsValue().GetValue<string>(),
|
||||||
WeighingData = p["weighing_data"]?.AsObject().ToJsonString(Utils.JsonOpts),
|
WeighingData = p["weighing_data"]?.AsObject().ToJsonString(Utils.JsonOpts),
|
||||||
WeighingReason = p["weighing_reason"]?.AsValue().GetValue<string>(),
|
WeighingReason = p["weighing_reason"]?.AsValue().GetValue<string>(),
|
||||||
}, createdAt == null || modifiedAt == null ? null :
|
}, createdAt == null || modifiedAt == null ? null :
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using Elwig.Models.Dtos;
|
||||||
|
|
||||||
|
namespace Elwig.Helpers.Export {
|
||||||
|
/// <summary>
|
||||||
|
/// Interface for exporting banking data
|
||||||
|
/// </summary>
|
||||||
|
public interface IBankingExporter : IExporter<Transaction> { }
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ using System.Collections.Generic;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace Elwig.Helpers.Export {
|
namespace Elwig.Helpers.Export {
|
||||||
public interface IExporter<T> : IDisposable {
|
public interface IExporter<T> : IDisposable, IAsyncDisposable {
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The default file extension of the exported files to be used (whithout a preceding ".")
|
/// The default file extension of the exported files to be used (whithout a preceding ".")
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -14,9 +14,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="data">The data to be exported</param>
|
/// <param name="data">The data to be exported</param>
|
||||||
/// <param name="progress">The progress object to report to</param>
|
/// <param name="progress">The progress object to report to</param>
|
||||||
void Export(IEnumerable<T> data, IProgress<double>? progress = null) {
|
void Export(IEnumerable<T> data, IProgress<double>? progress = null);
|
||||||
ExportAsync(data, progress).GetAwaiter().GetResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Asynchronosly export the given data to the given file.
|
/// Asynchronosly export the given data to the given file.
|
||||||
|
|||||||
@@ -32,12 +32,12 @@ namespace Elwig.Helpers.Export {
|
|||||||
|
|
||||||
private async Task AddHeader() {
|
private async Task AddHeader() {
|
||||||
var mimetype = ZipArchive.CreateEntry("mimetype", CompressionLevel.NoCompression);
|
var mimetype = ZipArchive.CreateEntry("mimetype", CompressionLevel.NoCompression);
|
||||||
using (var writer = new StreamWriter(await mimetype.OpenAsync(), Utils.UTF8)) {
|
using (var writer = new StreamWriter(mimetype.Open(), Utils.UTF8)) {
|
||||||
await writer.WriteAsync("application/vnd.oasis.opendocument.spreadsheet");
|
await writer.WriteAsync("application/vnd.oasis.opendocument.spreadsheet");
|
||||||
}
|
}
|
||||||
|
|
||||||
var manifest = ZipArchive.CreateEntry("META-INF/manifest.xml");
|
var manifest = ZipArchive.CreateEntry("META-INF/manifest.xml");
|
||||||
using (var writer = new StreamWriter(await manifest.OpenAsync(), Utils.UTF8)) {
|
using (var writer = new StreamWriter(manifest.Open(), Utils.UTF8)) {
|
||||||
await writer.WriteAsync("""
|
await writer.WriteAsync("""
|
||||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||||
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.3">
|
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.3">
|
||||||
@@ -52,7 +52,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var styles = ZipArchive.CreateEntry("styles.xml");
|
var styles = ZipArchive.CreateEntry("styles.xml");
|
||||||
using (var writer = new StreamWriter(await styles.OpenAsync(), Utils.UTF8)) {
|
using (var writer = new StreamWriter(styles.Open(), Utils.UTF8)) {
|
||||||
await writer.WriteAsync("""
|
await writer.WriteAsync("""
|
||||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||||
<office:document-styles xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" office:version="1.3">
|
<office:document-styles xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" office:version="1.3">
|
||||||
@@ -62,7 +62,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var meta = ZipArchive.CreateEntry("meta.xml");
|
var meta = ZipArchive.CreateEntry("meta.xml");
|
||||||
using (var writer = new StreamWriter(await meta.OpenAsync(), Utils.UTF8)) {
|
using (var writer = new StreamWriter(meta.Open(), Utils.UTF8)) {
|
||||||
var now = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
|
var now = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
|
||||||
await writer.WriteAsync($"""
|
await writer.WriteAsync($"""
|
||||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||||
@@ -80,7 +80,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var content = ZipArchive.CreateEntry("content.xml");
|
var content = ZipArchive.CreateEntry("content.xml");
|
||||||
Content = new StreamWriter(await content.OpenAsync(), Utils.UTF8);
|
Content = new StreamWriter(content.Open(), Utils.UTF8);
|
||||||
await Content.WriteAsync("""
|
await Content.WriteAsync("""
|
||||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||||
<office:document-content xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" office:version="1.3">
|
<office:document-content xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" office:version="1.3">
|
||||||
@@ -109,13 +109,8 @@ namespace Elwig.Helpers.Export {
|
|||||||
<style:paragraph-properties fo:text-align="center"/>
|
<style:paragraph-properties fo:text-align="center"/>
|
||||||
<style:text-properties fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold"/>
|
<style:text-properties fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold"/>
|
||||||
</style:style>
|
</style:style>
|
||||||
<style:style style:name="sectionheader" style:family="table-cell" style:parent-style-name="default">
|
|
||||||
<style:table-cell-properties style:text-align-source="fix" style:repeat-content="false"/>
|
|
||||||
<style:paragraph-properties fo:text-align="left"/>
|
|
||||||
<style:text-properties fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold" fo:font-size="14pt"/>
|
|
||||||
</style:style>
|
|
||||||
<style:style style:name="th" style:family="table-cell" style:parent-style-name="default">
|
<style:style style:name="th" style:family="table-cell" style:parent-style-name="default">
|
||||||
<style:table-cell-properties style:text-align-source="fix" style:repeat-content="false" style:vertical-align="middle" fo:wrap-option="wrap"/>
|
<style:table-cell-properties style:text-align-source="fix" style:repeat-content="false" style:vertical-align="middle"/>
|
||||||
<style:paragraph-properties fo:text-align="center"/>
|
<style:paragraph-properties fo:text-align="center"/>
|
||||||
<style:text-properties fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold"/>
|
<style:text-properties fo:font-weight="bold" style:font-weight-asian="bold" style:font-weight-complex="bold"/>
|
||||||
</style:style>
|
</style:style>
|
||||||
@@ -168,7 +163,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
Content = null;
|
Content = null;
|
||||||
|
|
||||||
var settings = ZipArchive.CreateEntry("settings.xml");
|
var settings = ZipArchive.CreateEntry("settings.xml");
|
||||||
using (var writer = new StreamWriter(await settings.OpenAsync(), Utils.UTF8)) {
|
using (var writer = new StreamWriter(settings.Open(), Utils.UTF8)) {
|
||||||
await writer.WriteAsync("""
|
await writer.WriteAsync("""
|
||||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||||
<office:document-settings xmlns:config="urn:oasis:names:tc:opendocument:xmlns:config:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ooo="http://openoffice.org/2004/office" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" office:version="1.3">
|
<office:document-settings xmlns:config="urn:oasis:names:tc:opendocument:xmlns:config:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ooo="http://openoffice.org/2004/office" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" office:version="1.3">
|
||||||
@@ -216,59 +211,35 @@ namespace Elwig.Helpers.Export {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await Content.WriteAsync($"""
|
await Content.WriteAsync(
|
||||||
<table:table-row>
|
$" <table:table-row>\r\n" +
|
||||||
{FormatCell(table.FullName, colSpan: totalSpan, style: "header")}
|
FormatCell(table.FullName, colSpan: totalSpan, style: "header") +
|
||||||
</table:table-row>
|
$" </table:table-row>\r\n" +
|
||||||
<table:table-row>
|
$" <table:table-row>\r\n" +
|
||||||
{FormatCell(table.Subtitle, colSpan: totalSpan, style: "subheader")}
|
FormatCell(table.Subtitle, colSpan: totalSpan, style: "subheader") +
|
||||||
</table:table-row>
|
$" </table:table-row>\r\n" +
|
||||||
<table:table-row>
|
$" <table:table-row>\r\n" +
|
||||||
<table:table-cell table:number-columns-repeated="{totalSpan}"/>
|
$" <table:table-cell table:number-columns-repeated=\"{totalSpan}\"/>\r\n" +
|
||||||
</table:table-row>
|
$" </table:table-row>\r\n" +
|
||||||
""");
|
$" <table:table-row>\r\n");
|
||||||
|
foreach (var (name, span, units) in table.ColumnNames.Zip(table.ColumnSpans, table.ColumnUnits)) {
|
||||||
|
var hasUnits = units.Length > 0;
|
||||||
|
await Content.WriteAsync(FormatCell(name, colSpan: span, rowSpan: hasUnits ? 1 : 2, style: "th"));
|
||||||
|
}
|
||||||
|
await Content.WriteAsync(" </table:table-row>\r\n <table:table-row>\r\n");
|
||||||
|
foreach (var (span, units) in table.ColumnSpans.Zip(table.ColumnUnits)) {
|
||||||
|
if (units.Length == 0) {
|
||||||
|
await Content.WriteAsync($" <table:covered-table-cell table:number-columns-repeated=\"{span}\"/>\r\n");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
foreach (var u in units) {
|
||||||
|
await Content.WriteAsync(FormatCell(u == null ? null : $"[{u}]", style: "th"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await Content.WriteAsync(" </table:table-row>\r\n");
|
||||||
|
|
||||||
var firstSection = true;
|
foreach (var row in table.GetData()) {
|
||||||
foreach (var sec in table.GetData()) {
|
await FormatRow(row, table.ColumnUnits, mergeSubRowCells);
|
||||||
if (!firstSection) {
|
|
||||||
await Content.WriteAsync($"""
|
|
||||||
<table:table-row>
|
|
||||||
<table:table-cell table:number-columns-repeated="{totalSpan}"/>
|
|
||||||
</table:table-row>
|
|
||||||
<table:table-row>
|
|
||||||
<table:table-cell table:number-columns-repeated="{totalSpan}"/>
|
|
||||||
</table:table-row>
|
|
||||||
""");
|
|
||||||
}
|
|
||||||
if (sec.Name != null) {
|
|
||||||
await Content.WriteAsync($"""
|
|
||||||
<table:table-row>
|
|
||||||
{FormatCell(sec.Name, colSpan: totalSpan, style: "sectionheader")}
|
|
||||||
</table:table-row>
|
|
||||||
""");
|
|
||||||
}
|
|
||||||
|
|
||||||
await Content.WriteAsync(" <table:table-row>\r\n");
|
|
||||||
foreach (var (name, span, units) in table.ColumnNames.Zip(table.ColumnSpans, table.ColumnUnits)) {
|
|
||||||
var hasUnits = units.Length > 0;
|
|
||||||
await Content.WriteAsync(FormatCell(name, colSpan: span, rowSpan: hasUnits ? 1 : 2, style: "th"));
|
|
||||||
}
|
|
||||||
await Content.WriteAsync(" </table:table-row>\r\n <table:table-row>\r\n");
|
|
||||||
foreach (var (span, units) in table.ColumnSpans.Zip(table.ColumnUnits)) {
|
|
||||||
if (units.Length == 0) {
|
|
||||||
await Content.WriteAsync($" <table:covered-table-cell table:number-columns-repeated=\"{span}\"/>\r\n");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
foreach (var u in units) {
|
|
||||||
await Content.WriteAsync(FormatCell(u == null ? null : $"[{u}]", style: "th"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await Content.WriteAsync(" </table:table-row>\r\n");
|
|
||||||
|
|
||||||
foreach (var row in sec.Rows) {
|
|
||||||
await FormatRow(row, table.ColumnUnits, mergeSubRowCells);
|
|
||||||
}
|
|
||||||
firstSection = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await Content.WriteAsync(" </table:table>\r\n");
|
await Content.WriteAsync(" </table:table>\r\n");
|
||||||
@@ -343,8 +314,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
}
|
}
|
||||||
c = $"<{ct} office:value-type=\"float\" calcext:value-type=\"float\" office:value=\"{v.ToString(CultureInfo.InvariantCulture)}\"{add}><text:p>{data}</text:p></{ct}>";
|
c = $"<{ct} office:value-type=\"float\" calcext:value-type=\"float\" office:value=\"{v.ToString(CultureInfo.InvariantCulture)}\"{add}><text:p>{data}</text:p></{ct}>";
|
||||||
} else {
|
} else {
|
||||||
var lines = string.Join("", data.ToString()?.Split('\n').Select(l => $"<text:p>{SecurityElement.Escape(l)}</text:p>") ?? []);
|
c = $"<{ct} office:value-type=\"string\" calcext:value-type=\"string\"{add}><text:p>{SecurityElement.Escape(data.ToString())}</text:p></{ct}>";
|
||||||
c = $"<{ct} office:value-type=\"string\" calcext:value-type=\"string\"{add}>{lines}</{ct}>";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return $" {c}\r\n" + (colSpan > 1 ? $" <table:covered-table-cell table:number-columns-repeated=\"{colSpan - 1}\"/>\r\n" : "");
|
return $" {c}\r\n" + (colSpan > 1 ? $" <table:covered-table-cell table:number-columns-repeated=\"{colSpan - 1}\"/>\r\n" : "");
|
||||||
@@ -13,9 +13,7 @@ namespace Elwig.Helpers.Export {
|
|||||||
|
|
||||||
private readonly StreamWriter _writer;
|
private readonly StreamWriter _writer;
|
||||||
|
|
||||||
public VCard(string filename) :
|
public VCard(string filename) : this(filename, Utils.UTF8) { }
|
||||||
this(filename, Utils.UTF8) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public VCard(string filename, Encoding encoding) {
|
public VCard(string filename, Encoding encoding) {
|
||||||
_writer = new StreamWriter(filename, false, encoding);
|
_writer = new StreamWriter(filename, false, encoding);
|
||||||
@@ -26,6 +24,11 @@ namespace Elwig.Helpers.Export {
|
|||||||
_writer.Dispose();
|
_writer.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ValueTask DisposeAsync() {
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
return _writer.DisposeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
public async Task ExportAsync(IEnumerable<Member> data, IProgress<double>? progress = null) {
|
public async Task ExportAsync(IEnumerable<Member> data, IProgress<double>? progress = null) {
|
||||||
progress?.Report(0.0);
|
progress?.Report(0.0);
|
||||||
int count = data.Count() + 1, i = 0;
|
int count = data.Count() + 1, i = 0;
|
||||||
@@ -55,6 +58,10 @@ namespace Elwig.Helpers.Export {
|
|||||||
progress?.Report(100.0);
|
progress?.Report(100.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void Export(IEnumerable<Member> data, IProgress<double>? progress = null) {
|
||||||
|
ExportAsync(data, progress).GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
|
||||||
private static string? Escape(string? text) {
|
private static string? Escape(string? text) {
|
||||||
return text?.Replace("\\", "\\\\").Replace(",", "\\,").Replace(";", "\\;").Replace("\n", "\\n").Replace("\r", "");
|
return text?.Replace("\\", "\\\\").Replace(",", "\\,").Replace(";", "\\;").Replace("\n", "\\n").Replace("\r", "");
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-70
@@ -1,7 +1,6 @@
|
|||||||
using Microsoft.Data.Sqlite;
|
using Microsoft.Data.Sqlite;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Globalization;
|
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.IO.Compression;
|
using System.IO.Compression;
|
||||||
using System.IO.Hashing;
|
using System.IO.Hashing;
|
||||||
@@ -13,7 +12,6 @@ using System.Threading;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using System.Windows;
|
using System.Windows;
|
||||||
using System.Windows.Controls;
|
using System.Windows.Controls;
|
||||||
using System.Windows.Media;
|
|
||||||
|
|
||||||
namespace Elwig.Helpers {
|
namespace Elwig.Helpers {
|
||||||
public static partial class Extensions {
|
public static partial class Extensions {
|
||||||
@@ -62,7 +60,7 @@ namespace Elwig.Helpers {
|
|||||||
var buf = new char[512];
|
var buf = new char[512];
|
||||||
int bufSize = 0;
|
int bufSize = 0;
|
||||||
var tmpBuf = new char[1];
|
var tmpBuf = new char[1];
|
||||||
while (bufSize < buf.Length - 1) {
|
while (!reader.EndOfStream && bufSize < buf.Length - 1) {
|
||||||
if ((await reader.ReadAsync(tmpBuf, 0, 1)) != 1)
|
if ((await reader.ReadAsync(tmpBuf, 0, 1)) != 1)
|
||||||
return null;
|
return null;
|
||||||
buf[bufSize++] = tmpBuf[0];
|
buf[bufSize++] = tmpBuf[0];
|
||||||
@@ -106,30 +104,14 @@ namespace Elwig.Helpers {
|
|||||||
progress.Report(100.0);
|
progress.Report(100.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<ReadOnlyMemory<char>> FindPassword(this ZipArchive zip, IEnumerable<ReadOnlyMemory<char>> passwords) {
|
public static async Task CheckIntegrity(this ZipArchive zip) {
|
||||||
foreach (var pwd in passwords) {
|
var crc = new Crc32();
|
||||||
try {
|
|
||||||
await zip.CheckIntegrity(pwd);
|
|
||||||
return pwd;
|
|
||||||
} catch { }
|
|
||||||
}
|
|
||||||
throw new InvalidDataException("No matching password found");
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task<ReadOnlyMemory<char>> CheckIntegrity(this ZipArchive zip, IEnumerable<ReadOnlyMemory<char>> passwords) {
|
|
||||||
if (zip.Entries.Any(e => e.IsEncrypted)) {
|
|
||||||
return await zip.FindPassword(passwords);
|
|
||||||
} else {
|
|
||||||
await zip.CheckIntegrity();
|
|
||||||
return default;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task CheckIntegrity(this ZipArchive zip, ReadOnlyMemory<char> password = default) {
|
|
||||||
byte[] buffer = new byte[8192];
|
|
||||||
foreach (var entry in zip.Entries) {
|
foreach (var entry in zip.Entries) {
|
||||||
using var stream = await entry.OpenAsync(password.Span);
|
crc.Reset();
|
||||||
while (await stream.ReadAsync(buffer) > 0);
|
using var stream = entry.Open();
|
||||||
|
await crc.AppendAsync(stream);
|
||||||
|
if (crc.GetCurrentHashAsUInt32() != entry.Crc32)
|
||||||
|
throw new InvalidDataException($"CRC-32 mismatch in '{entry.FullName}'");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,39 +134,11 @@ namespace Elwig.Helpers {
|
|||||||
return await cmd.ExecuteScalarAsync();
|
return await cmd.ExecuteScalarAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task QuickCheck(this SqliteConnection cnx) {
|
public static async Task<(string Table, long RowId, string Parent, long FkId)[]> ForeignKeyCheck(this SqliteConnection cnx) {
|
||||||
using var cmd = cnx.CreateCommand();
|
|
||||||
cmd.CommandText = "PRAGMA quick_check";
|
|
||||||
using var reader = await cmd.ExecuteReaderAsync();
|
|
||||||
var list = new List<string>();
|
|
||||||
while (await reader.ReadAsync()) {
|
|
||||||
list.Add(reader.GetString(0));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (list.Count != 1 || list[0] != "ok") {
|
|
||||||
throw new FileFormatException($"Integrity problems ({list.Count}):\n" + string.Join("\n", list.Take(50)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task IntegrityCheck(this SqliteConnection cnx) {
|
|
||||||
using var cmd = cnx.CreateCommand();
|
|
||||||
cmd.CommandText = "PRAGMA integrity_check";
|
|
||||||
using var reader = await cmd.ExecuteReaderAsync();
|
|
||||||
var list = new List<string>();
|
|
||||||
while (await reader.ReadAsync()) {
|
|
||||||
list.Add(reader.GetString(0));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (list.Count != 1 || list[0] != "ok") {
|
|
||||||
throw new FileFormatException($"Integrity problems ({list.Count}):\n" + string.Join("\n", list.Take(50)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task ForeignKeyCheck(this SqliteConnection cnx) {
|
|
||||||
using var cmd = cnx.CreateCommand();
|
using var cmd = cnx.CreateCommand();
|
||||||
cmd.CommandText = "PRAGMA foreign_key_check";
|
cmd.CommandText = "PRAGMA foreign_key_check";
|
||||||
using var reader = await cmd.ExecuteReaderAsync();
|
using var reader = await cmd.ExecuteReaderAsync();
|
||||||
var list = new List<(string Table, long RowId, string Parent, long FkId)>();
|
var list = new List<(string, long, string, long)>();
|
||||||
while (await reader.ReadAsync()) {
|
while (await reader.ReadAsync()) {
|
||||||
var table = reader.GetString(0);
|
var table = reader.GetString(0);
|
||||||
var rowid = reader.GetInt64(1);
|
var rowid = reader.GetInt64(1);
|
||||||
@@ -192,11 +146,7 @@ namespace Elwig.Helpers {
|
|||||||
var fkid = reader.GetInt64(3);
|
var fkid = reader.GetInt64(3);
|
||||||
list.Add((table, rowid, parent, fkid));
|
list.Add((table, rowid, parent, fkid));
|
||||||
}
|
}
|
||||||
|
return [.. list];
|
||||||
if (list.Count > 0) {
|
|
||||||
throw new InvalidDataException($"Foreign key violations ({list.Count}):\n" + string.Join("\n", list.Take(50)
|
|
||||||
.Select(v => $"{v.Table} - {v.RowId} - {v.Parent} - {v.FkId}")));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IEnumerable<T> Join<T>(this IEnumerable<T> src, Func<T> separatorFactory) {
|
public static IEnumerable<T> Join<T>(this IEnumerable<T> src, Func<T> separatorFactory) {
|
||||||
@@ -209,25 +159,17 @@ namespace Elwig.Helpers {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void AddToolTipCell(this Grid grid, string text, int row, int col, int colSpan = 1, bool bold = false, bool alignRight = false, bool alignCenter = false, Brush? color = null) {
|
public static void AddToolTipCell(this Grid grid, string text, int row, int col, int colSpan = 1, bool bold = false, bool alignRight = false, bool alignCenter = false) {
|
||||||
var tb = new TextBlock() {
|
var tb = new TextBlock() {
|
||||||
Text = text,
|
Text = text,
|
||||||
TextAlignment = alignRight ? TextAlignment.Right : alignCenter ? TextAlignment.Center : TextAlignment.Left,
|
TextAlignment = alignRight ? TextAlignment.Right : alignCenter ? TextAlignment.Center : TextAlignment.Left,
|
||||||
Margin = new(0, 12 * row, 0, 0),
|
Margin = new(0, 12 * row, 0, 0),
|
||||||
FontWeight = bold ? FontWeights.Bold : FontWeights.Normal,
|
FontWeight = bold ? FontWeights.Bold : FontWeights.Normal,
|
||||||
};
|
};
|
||||||
if (color != null) tb.Foreground = color;
|
|
||||||
tb.SetValue(Grid.ColumnProperty, col);
|
tb.SetValue(Grid.ColumnProperty, col);
|
||||||
tb.SetValue(Grid.ColumnSpanProperty, colSpan);
|
tb.SetValue(Grid.ColumnSpanProperty, colSpan);
|
||||||
grid.Children.Add(tb);
|
grid.Children.Add(tb);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static (int Year, int Week) GetYearAndWeek(this DateTime date) {
|
|
||||||
return (ISOWeek.GetYear(date), ISOWeek.GetWeekOfYear(date));
|
|
||||||
}
|
|
||||||
|
|
||||||
public static (int Year, int Tertial) GetYearAndTertial(this DateTime date) {
|
|
||||||
return (date.Month <= 7 ? date.Year - 1 : date.Year, date.Month == 12 || date.Month <= 3 ? 2 : date.Month <= 7 ? 3 : 1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,303 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text.RegularExpressions;
|
|
||||||
|
|
||||||
namespace Elwig.Helpers {
|
|
||||||
public static partial class Normalizer {
|
|
||||||
|
|
||||||
[GeneratedRegex(@"(?=(?:(?:bundes)?straße|gasse|weg|platz|allee|ring|zeile?|steig|hof|markt|kai|ufer|brücke|tor|stiege|promenade|gang|siedlung)\b)|[\s-]+", RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase)]
|
|
||||||
private static partial Regex GeneratedStreetNameWordsRegex();
|
|
||||||
private static readonly Regex StreetNameWordsRegex = GeneratedStreetNameWordsRegex();
|
|
||||||
|
|
||||||
private static readonly HashSet<string> StreetTypes = [
|
|
||||||
"Straße", "Gasse", "Weg", "Platz", "Allee", "Ring", "Zeile", "Zeil", "Steig", "Hof",
|
|
||||||
"Markt", "Kai", "Ufer", "Brücke", "Tor", "Stiege", "Promenade", "Gang", "Siedlung"];
|
|
||||||
|
|
||||||
private static readonly HashSet<string> StreetArticles = ["der", "die", "das", "des", "dem", "den"];
|
|
||||||
|
|
||||||
private static readonly HashSet<string> StreetPrepositions = [
|
|
||||||
"an", "am", "auf", "aus", "bei", "beim", "hinter", "hinterm", "in", "im", "ins", "nach",
|
|
||||||
"neben", "über", "unter", "von", "vom", "van", "vor", "zu", "zum", "zur", "zwischen",
|
|
||||||
"durch", "mit"];
|
|
||||||
|
|
||||||
private static readonly HashSet<string> StreetNumbers = [ "Zwei", "Drei", "Vier", "Fünf", "Sechs", "Sieben" ];
|
|
||||||
|
|
||||||
private static readonly HashSet<string> StreetAdjectives = [
|
|
||||||
"alter", "alte", "alten", "altem", "altes",
|
|
||||||
"äußere", "äußere", "äußeren", "äußerem", "äußeres",
|
|
||||||
// "breiter", "breite", "breiten", "breitem", "breites",
|
|
||||||
"dritter", "dritte", "dritten", "drittem", "drittes",
|
|
||||||
"erster", "erste", "ersten", "erstem", "erstes",
|
|
||||||
"großer", "große", "großen", "großem", "großes",
|
|
||||||
"hoher", "hohe", "hohen", "hohem", "hohes",
|
|
||||||
"innerer", "innere", "inneren", "innerem", "inneres",
|
|
||||||
"kleiner", "kleine", "kleinen", "kleinem", "kleines",
|
|
||||||
"kurzer", "kurze", "kurzen", "kurzem", "kurzes",
|
|
||||||
"langer", "lange", "langen", "langem", "langes",
|
|
||||||
"linker", "linke", "linken", "linkem", "linkes",
|
|
||||||
"mittlerer", "mittlere", "mittleren", "mittlerem", "mittleres",
|
|
||||||
"neuer", "neue", "neuen", "neuem", "neues",
|
|
||||||
"oberer", "obere", "oberen", "oberem", "oberes",
|
|
||||||
"rechter", "rechte", "rechten", "rechtem", "rechtes",
|
|
||||||
"schmaler", "schmale", "schmalen", "schmalem", "schmales",
|
|
||||||
"schöner", "schöne", "schönen", "schönem", "schönes",
|
|
||||||
"unterer", "untere", "unteren", "unterem", "unteres",
|
|
||||||
"hinterer", "hintere", "hinteren", "hinterem", "hinteres",
|
|
||||||
"vorderer", "vordere", "vorderen", "vorderem", "vorderes",
|
|
||||||
"runder", "runde", "runden", "rundem", "rundes",
|
|
||||||
"kalter", "kalte", "kalten", "kaltem", "kaltes"];
|
|
||||||
|
|
||||||
private static readonly HashSet<string> StreetLastNames = [
|
|
||||||
"Habsburger", "Lothringer", "Leitzenberger", "Luyderer", "Preiner", "Radinger", "Seefelder", "Staribacher", "Gschmeidler",
|
|
||||||
"Hannover", "Münster", "Salzgitter", "Speyer", "Trier"];
|
|
||||||
|
|
||||||
private static readonly HashSet<string> StreetPersonTitles = [
|
|
||||||
"St.", "Familie",
|
|
||||||
"Dr.", "DDr.", "Hofrat", "Baurat", "Kommerzialrat", "Dir.", "Ing.", "Prof.", "Mag.", "DI", "OSR", "Präsident",
|
|
||||||
"Landeshauptmann", "LH", "Bürgermeister", "Bgm.", "Minister",
|
|
||||||
"Kaiser", "Kaiserin", "König", "Königin", "Erzherzog", "Erzherzogin", "Herzog", "Fürst", "Graf", "Gräfin", "Markgraf", "Kronprinz", "Prinz", "Ritter", "Freiherr", "Lord",
|
|
||||||
"Abt", "Bischof", "Propst", "Dechant", "Kardinal", "Monsignore", "Pfarrer", "Pater", "Prälat",
|
|
||||||
"Oberst"];
|
|
||||||
|
|
||||||
private static readonly HashSet<string> StreetGivenNames = [
|
|
||||||
"Adalbert", "Adam", "Adele", "Adelheid", "Adolf", "Adolph", "Adrian", "Albert", "Albrecht", "Alexander", "Alfons", "Alfred", "Alois", "Aloisia",
|
|
||||||
"Andreas", "Andrea", "Andre", "Anna", "Anton", "Arnold", "Arthur", "August", "Augustin", "Augustine", "Agnes", "Angelika", "Ada", "Adelheid", "Anni", "Anita",
|
|
||||||
"Barbara", "Beate", "Beatrix", "Benedikt", "Bernhard", "Berta", "Bertha", "Berthold", "Brüder", "Bruno", "Brigitte",
|
|
||||||
"Camillo", "Carl", "Caspar", "Catharina", "Christian", "Christine", "Christof", "Christoph", "Clara", "Clemens", "Conrad", "Claus", "Camillo", "Claudia",
|
|
||||||
"Daniel", "Dietmar", "Dietrich",
|
|
||||||
"Edgar", "Edi", "Edith", "Edmund", "Egon", "Elsa", "Eduard", "Emmerich", "Erhard", "Erich", "Ernst", "Erwin", "Eugen", "Ewald", "Eberhard",
|
|
||||||
"Elisabeth", "Emanuel", "Emerich", "Emil", "Emma", "Engelbert", "Elias",
|
|
||||||
"Franz", "Ferdinand", "Friedrich", "Felix", "Florian", "Fritz", "Franziska", "Fred",
|
|
||||||
"Georg", "Gregor", "Gustav", "Gabriel", "Gebrüder", "Gabriele", "Gerhard", "Gerhart", "Gertrude", "Gottfried", "Gottlieb", "Grete",
|
|
||||||
"Günther", "Günter",
|
|
||||||
"Hans", "Hanns", "Heinrich", "Heinz", "Helmut", "Helmuth", "Hermann", "Herta", "Herbert", "Hubert", "Harald", "Horst", "Helene", "Helga",
|
|
||||||
"Hieronymus", "Hilde", "Hugo",
|
|
||||||
"Isabelle", "Ignaz", "Ilse", "Ingeborg", "Isidor",
|
|
||||||
"Josef", "Josefine", "Joseph", "Johann", "Johanna", "Johan", "Johannes", "Hannes", "Harry", "Jakob", "Jacob", "Jan", "Julian", "Julius", "Julia", "Jürgen",
|
|
||||||
"Karl", "Kasimir", "Konrad", "Klemens", "Klara", "Katharina", "Kurt", "Kaspar", "Klaus", "Koloman", "Konstantin", "Killian",
|
|
||||||
"Leopold", "Leo", "Lorenz", "Lothar", "Louise", "Ludmilla", "Ludwig", "Lukas", "Ladislaus", "Lambert", "Laurenz", "Liese",
|
|
||||||
"Lise", "Lilly", "Lina", "Lothar", "Lotte", "Luise", "Leonhard", "Lotte", "Martha",
|
|
||||||
"Maria", "Marie", "Michael", "Martin", "Max", "Maximilian", "Manuel", "Manuela", "Moritz", "Marianne", "Manfred", "Marc",
|
|
||||||
"Mathias", "Matthias", "Matthäus",
|
|
||||||
"Margarete", "Margarethe",
|
|
||||||
"Nico", "Niko", "Niklas", "Niclas", "Nikolaus", "Norbert",
|
|
||||||
"Otto", "Ottokar", "Oskar", "Olga", "Oswald", "Othmar",
|
|
||||||
"Paul", "Pauline", "Patrick", "Pepi", "Peter", "Philipp", "Philip", "Petrus",
|
|
||||||
"Robert", "Rudolf", "Richard", "Ruprecht", "Raffael", "Rolf", "Roman", "Rosa", "Rosalia", "Rupert", "Raimund",
|
|
||||||
"Sigmund", "Siegfried", "Simon", "Stanislaus", "Stefan", "Stephan", "Sepp", "Samuel", "Sebastian", "Susi",
|
|
||||||
"Theodor", "Thomas", "Theresia", "Thaddäus", "Theo", "Theophil", "Tina", "Titus", "Toni", "Trude",
|
|
||||||
"Ullrich", "Ulrich", "Udo",
|
|
||||||
"Viktor", "Vinzenz", "Victor",
|
|
||||||
"Wolfgang", "Willibald", "Wilhelm", "Willhelm", "Wilhelmine", "Walter", "Walther", "Wenzel", "Werner", "Willi",
|
|
||||||
"Zacharias"];
|
|
||||||
|
|
||||||
private static readonly HashSet<string> LocalityNames = [
|
|
||||||
"Groß-Enzersdorf",
|
|
||||||
"Groß Burgstall", "Klein Eberharts", "Klein-Engersdorf", "Groß-Enzersdorf", "Klein-Erlauf",
|
|
||||||
"Groß Gerungs", "Klein Gundholz", "Klein-Harras", "Klein-Heinrichschlag", "Groß-Höbarten",
|
|
||||||
"Klein-Jetzelsdorf", "Klein-Mariazell", "Groß Meinharts", "Klein-Meiseldorf", "Groß-Neusiedl", "Klein-Neusiedl", "Klein-Pöchlarn",
|
|
||||||
"Groß-Radischen", "Klein-Radischen", "Groß Raßberg", "Klein Reinprechts", "Klein-Reinprechtsdorf", "Groß-Reipersdorf", "Klein-Ruprechts",
|
|
||||||
"Groß-Schollach", "Klein-Schollach", "Groß-Schweinbarth", "Groß-Siegharts", "Klein-Siegharts", "Groß Sierning",
|
|
||||||
"Klein-Ulrichschlag", "Klein Weinberg", "Klein Wetzles", "Klein-Wien",
|
|
||||||
];
|
|
||||||
|
|
||||||
private static bool IsGivenName(this string word) {
|
|
||||||
return StreetGivenNames.Contains(word);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool IsFamilyName(this string word) {
|
|
||||||
if (StreetLastNames.Contains(word))
|
|
||||||
return true;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool IsPersonalName(this string word) {
|
|
||||||
return word.IsGivenName() || word.IsFamilyName();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool IsGeographicalDerivativeName(this string word) {
|
|
||||||
if (!word.EndsWith("er") || word.IsPersonalName() || word == "Weißer")
|
|
||||||
return false;
|
|
||||||
return word.StartsWith("St. ") || word.StartsWith("Ober ") || word.StartsWith("Unter ") || word.StartsWith("Maria") ||
|
|
||||||
word.EndsWith("sdorfer") || word.EndsWith("ndorfer") || word.EndsWith("ldorfer") ||
|
|
||||||
word.EndsWith("felder") ||
|
|
||||||
word.EndsWith("sthaler") || word.EndsWith("nthaler") || word.EndsWith("lthaler") ||
|
|
||||||
word.EndsWith("dauer") || word.EndsWith("lauer") || word.EndsWith("mauer") || word.EndsWith("nauer") || word.EndsWith("ßauer") ||
|
|
||||||
word.EndsWith("lbacher") || word.EndsWith("nbacher") || word.EndsWith("ßbacher") ||
|
|
||||||
word.EndsWith("ringer") || word.EndsWith("singer") ||
|
|
||||||
word.EndsWith("sbrunner") || word.EndsWith("nbrunner") || word.EndsWith("lbrunner") || word.EndsWith("abrunner") || word.EndsWith("ingbrunner") ||
|
|
||||||
word.EndsWith("sburger") || word.EndsWith("nburger") || word.EndsWith("mburger") || word.EndsWith("lburger") || word.EndsWith("neuburger") ||
|
|
||||||
word.EndsWith("berger") ||
|
|
||||||
word.EndsWith("winkler") ||
|
|
||||||
word.EndsWith("lsteiner") || word.EndsWith("nsteiner") ||
|
|
||||||
word.EndsWith("städter") ||
|
|
||||||
word.EndsWith("stättner") || word.EndsWith("stettner") ||
|
|
||||||
word.EndsWith("brücker") ||
|
|
||||||
word.EndsWith("further") || word.EndsWith("furter") ||
|
|
||||||
word.EndsWith("aaer") ||
|
|
||||||
word.EndsWith("seer") || word.EndsWith("leer") ||
|
|
||||||
word.EndsWith("tzner") ||
|
|
||||||
word.EndsWith("zeller") ||
|
|
||||||
word.EndsWith("rther") ||
|
|
||||||
word.EndsWith("sdner") ||
|
|
||||||
word.EndsWith("gerner") || word.EndsWith("berner") ||
|
|
||||||
word.EndsWith("frieder") ||
|
|
||||||
word.EndsWith("litzer") || word.EndsWith("mitzer") || word.EndsWith("eutzer") ||
|
|
||||||
word.EndsWith("loner") ||
|
|
||||||
word.EndsWith("skirchner") || word.EndsWith("nkirchner") || word.EndsWith("ingkirchner") ||
|
|
||||||
word.EndsWith("ziger") ||
|
|
||||||
word.EndsWith("ließer") ||
|
|
||||||
word.EndsWith("gerer") ||
|
|
||||||
word.EndsWith("kreuzer") ||
|
|
||||||
word == "Wiener" || word == "Brünner" || word == "Znaimer" || word == "Triester" || word == "Prager" || word == "Berliner" || word == "Basler" ||
|
|
||||||
word == "Retzer" || word == "Tullner" || word == "Badner" ||
|
|
||||||
word == "Gruber" || word == "Sulzer" || word == "Harraser" || word == "Dörfleser" || word == "Neusiedler" ||
|
|
||||||
word == "Dornauer" || word == "Siebenhauser" || word == "Alser" ||
|
|
||||||
word == "Bockenheimer";
|
|
||||||
}
|
|
||||||
|
|
||||||
public static string NormalizeAddress(string address, string? locality = null) {
|
|
||||||
var idx = address.IndexOf(',');
|
|
||||||
if (idx >= 0) address = address[..idx];
|
|
||||||
var (name, nr) = Utils.SplitAddress(address);
|
|
||||||
return (NormalizeStreetName(name, locality) + " " + nr).Trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static string NormalizeStreetName(string name, string? locality = null) {
|
|
||||||
name = name.Trim().ToLowerInvariant();
|
|
||||||
if (name == "") {
|
|
||||||
return "";
|
|
||||||
} else if (name == "nr.") {
|
|
||||||
if (locality == null)
|
|
||||||
return "Nr.";
|
|
||||||
name = locality.Trim().ToLowerInvariant();
|
|
||||||
}
|
|
||||||
|
|
||||||
name = name.Replace("hautp", "haupt")
|
|
||||||
.Replace("leop.", "leopold ").Replace("ferd.", "ferdinand ").Replace("gottfr.", "gottfried ")
|
|
||||||
.Replace("heinr.", "heinrich").Replace("joh.", "johann ").Replace("jos.", "josef ")
|
|
||||||
.Replace("msgr.", "monsignore ").Replace("pf.", "pfarrer ")
|
|
||||||
.Replace("präs.", "präsident ");
|
|
||||||
name = name.Replace("str.", "straße").Replace("strasse", "straße")
|
|
||||||
.Replace("bruecke", "brücke").Replace("pl.", "platz")
|
|
||||||
.Replace("gr.", "groß").Replace("kl.", "klein")
|
|
||||||
.Replace("sankt-", "st.").Replace("sankt ", "st.")
|
|
||||||
.Replace("wr.", "wiener ")
|
|
||||||
.Replace(".", ". ");
|
|
||||||
List<string> words = [.. StreetNameWordsRegex.Split(name)
|
|
||||||
.Where(w => !string.IsNullOrWhiteSpace(w))
|
|
||||||
.Select(w => StreetArticles.Contains(w) || StreetPrepositions.Contains(w) ? w : string.Concat(w[0..1].ToUpper(), w.AsSpan(1)))
|
|
||||||
.Select(w => w == "Ddr." ? "DDr." : w == "Lh" || w == "Osr" ? w.ToUpper() : w)
|
|
||||||
];
|
|
||||||
if (words[0] == "Di") words[0] = "DI";
|
|
||||||
|
|
||||||
var temp = "|" + string.Join('|', words) + "|";
|
|
||||||
temp = temp.Replace("|Dipl.|Ing.|", "|DI|").Replace("|Dipl|Ing.|", "|DI|")
|
|
||||||
.Replace("|Kaiser|Ebersdorf|", "|Kaiser-Ebersdorf|")
|
|
||||||
.Replace("|Kalk|Deutz|", "|Kalk-Deutz|").Replace("|Kalk|Deutzer|", "|Kalk-Deutzer|")
|
|
||||||
.Replace("|Hohe|Wand|", "|Hohe Wand|").Replace("|Hohen|Wand|", "|Hohen Wand|").Replace("|Hohewand|", "|Hohe Wand|")
|
|
||||||
.Replace("|Alten|Markt|", "|Altenmarkt|")
|
|
||||||
.Replace("|Kirch|Hof|", "|Kirchhof|").Replace("|Bisc|Hof|", "|Bischof|")
|
|
||||||
.Replace("|Wiener|Neustadt|", "|Wiener Neustadt|").Replace("|Wiener|Neustädter|", "|Wiener Neustädter|")
|
|
||||||
.Replace("|St.|Pölten|", "|St. Pölten|").Replace("|St.|Pöltner|", "|St. Pöltner|")
|
|
||||||
.Replace("|Gross|", "|Groß|")
|
|
||||||
.Replace("|Nr|", "|Nr.|").Replace("|Und|", "|und|");
|
|
||||||
words = [.. temp.Trim('|').Split('|')];
|
|
||||||
|
|
||||||
if (words.Count > 1 && (words[0] == "Groß" || words[0] == "Klein") && !StreetTypes.Contains(words[1])) {
|
|
||||||
var w = words[0] + words[1].ToLowerInvariant();
|
|
||||||
words.RemoveRange(0, 2);
|
|
||||||
words.Insert(0, w);
|
|
||||||
}
|
|
||||||
if (words[0].StartsWith("Groß") || words[0].StartsWith("Klein")) {
|
|
||||||
var repl = LocalityNames.FirstOrDefault(n => n.Replace(" ", "").Replace("-", "").Equals(words[0], StringComparison.InvariantCultureIgnoreCase));
|
|
||||||
if (repl != null) words[0] = repl;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (words.Count > 2 && words[^2] == "in") {
|
|
||||||
// remove suffix "in ..."
|
|
||||||
words.RemoveRange(words.Count - 2, 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
char sep = name.Contains('-') ? '-' : ' ';
|
|
||||||
if (words.Count <= 1) {
|
|
||||||
// single word
|
|
||||||
} else if (StreetTypes.Contains(words[0]) && !StreetTypes.Contains(words[^1])) {
|
|
||||||
// "Straße der ..." / "Straße des ..."
|
|
||||||
sep = ' ';
|
|
||||||
} else if (StreetTypes.Contains(words[^1])) {
|
|
||||||
// "... Straße" / "...straße"
|
|
||||||
var type = words[^1];
|
|
||||||
var isCompound = true;
|
|
||||||
var isAdjective = StreetAdjectives.Contains(words[^2].ToLowerInvariant());
|
|
||||||
var isGeographical = false;
|
|
||||||
var isPerson = false;
|
|
||||||
|
|
||||||
var geo = words.FindLastIndex(IsGeographicalDerivativeName);
|
|
||||||
if (geo >= 0 && geo < words.Count - 2 && words[^2] != "Haupt" && words[^2] != "Bundes" && words[^2] != "Keller") {
|
|
||||||
isPerson = true;
|
|
||||||
isGeographical = true;
|
|
||||||
} else if (words.Any(w => w.Contains(' ') && !w.IsGeographicalDerivativeName())) {
|
|
||||||
isPerson = true;
|
|
||||||
isGeographical = true;
|
|
||||||
} else if (StreetNumbers.Contains(words[0])) {
|
|
||||||
isPerson = true;
|
|
||||||
isGeographical = true;
|
|
||||||
} else if (!StreetPrepositions.Contains(words[0]) && !StreetArticles.Contains(words[0]) && words.FindIndex(StreetPrepositions.Contains) > 0) {
|
|
||||||
isPerson = true;
|
|
||||||
isGeographical = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (words.Count(w => w.Contains('.')) >= 2 || words.Contains("van") || words.Contains("von") || words.Contains("St.") ||
|
|
||||||
StreetPersonTitles.Contains(words[0]) || words.Any(w => w.IsGivenName()))
|
|
||||||
{
|
|
||||||
isPerson = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isPerson && isAdjective || StreetArticles.Contains(words[^2]) || StreetPrepositions.Contains(words[^2])) {
|
|
||||||
isCompound = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isPerson && words[^2].EndsWith("er") && !StreetLastNames.Contains(words[^2])) {
|
|
||||||
isGeographical = IsGeographicalDerivativeName(words[^2]);
|
|
||||||
} else if (words.Count >= 3 && words.Contains("Bad")) {
|
|
||||||
isPerson = true;
|
|
||||||
isGeographical = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
sep = isPerson ? '-' : ' ';
|
|
||||||
|
|
||||||
if (isPerson && words.Count == 2 && !isGeographical) {
|
|
||||||
isPerson = false;
|
|
||||||
isCompound = true;
|
|
||||||
}
|
|
||||||
if (isGeographical || isPerson) {
|
|
||||||
isCompound = false;
|
|
||||||
}
|
|
||||||
if (isCompound) {
|
|
||||||
var w = words[^2] + type.ToLowerInvariant();
|
|
||||||
words.RemoveRange(words.Count - 2, 2);
|
|
||||||
words.Add(w);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isPerson) {
|
|
||||||
words = [.. words.Select(w => w.Replace(' ', '-'))];
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// unknown
|
|
||||||
}
|
|
||||||
|
|
||||||
if (sep == '-' && StreetPrepositions.Contains(words[0]) && words[0] != "von" && words[0] != "van") {
|
|
||||||
sep = ' ';
|
|
||||||
int i;
|
|
||||||
for (i = 0; StreetPrepositions.Contains(words[i]) && i < words.Count; i++);
|
|
||||||
var word = string.Join('-', words.Skip(i));
|
|
||||||
words = [.. words.Take(i).Append(word)];
|
|
||||||
}
|
|
||||||
|
|
||||||
var norm = string.Join(sep, words);
|
|
||||||
return string.Concat(norm[0..1].ToUpperInvariant(), norm.AsSpan(1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,40 +1,55 @@
|
|||||||
using Elwig.Services;
|
using Elwig.Services;
|
||||||
using Elwig.Windows;
|
using Elwig.Windows;
|
||||||
using System;
|
using System;
|
||||||
|
using System.Drawing.Printing;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace Elwig.Helpers.Printing {
|
namespace Elwig.Helpers.Printing {
|
||||||
public static class Pdf {
|
public static class Pdf {
|
||||||
|
|
||||||
public static void Init(Action? evtHandler = null) {
|
public static Task Init(Action? evtHandler = null) {
|
||||||
PdfiumNative.FPDF_InitLibrary();
|
PdfiumNative.FPDF_InitLibrary();
|
||||||
evtHandler?.Invoke();
|
evtHandler?.Invoke();
|
||||||
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void Cleanup() {
|
public static Task Cleanup() {
|
||||||
PdfiumNative.FPDF_DestroyLibrary();
|
PdfiumNative.FPDF_DestroyLibrary();
|
||||||
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void Show(TempFile file, string title) {
|
public static void Show(TempFile file, string title) {
|
||||||
App.Current.Dispatcher.BeginInvoke(() => {
|
App.MainDispatcher.BeginInvoke(() => {
|
||||||
var w = new DocumentViewerWindow(title, file);
|
var w = new DocumentViewerWindow(title, file);
|
||||||
w.Show();
|
w.Show();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void Show(string path, string title) {
|
public static void Show(string path, string title) {
|
||||||
App.Current.Dispatcher.BeginInvoke(() => {
|
App.MainDispatcher.BeginInvoke(() => {
|
||||||
var w = new DocumentViewerWindow(title, path);
|
var w = new DocumentViewerWindow(title, path);
|
||||||
w.Show();
|
w.Show();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void Print(string path, int copies = 1, bool doublePaged = false) {
|
public static async Task Print(string path, int copies = 1, bool doublePaged = false) {
|
||||||
|
await Print(path, new() {
|
||||||
|
Copies = (short)copies,
|
||||||
|
Collate = true,
|
||||||
|
Duplex = doublePaged ? Duplex.Vertical : Duplex.Simplex,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Task Print(string path, PrinterSettings settings) {
|
||||||
try {
|
try {
|
||||||
var printer = new PdfPrinter();
|
using var printDoc = new PdfPrintDocument(path) {
|
||||||
printer.Print(path, copies, doublePaged);
|
PrinterSettings = settings,
|
||||||
|
};
|
||||||
|
printDoc.Print();
|
||||||
} catch (Exception exc) {
|
} catch (Exception exc) {
|
||||||
InteractionService.ShowException("Fehler beim Drucken", "Beim Drucken ist ein Fehler aufgetreten", exc);
|
InteractionService.ShowException("Fehler beim Drucken", "Beim Drucken ist ein Fehler aufgetreten", exc);
|
||||||
}
|
}
|
||||||
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
using System;
|
||||||
|
using System.Drawing;
|
||||||
|
using System.Drawing.Imaging;
|
||||||
|
using System.Drawing.Printing;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
namespace Elwig.Helpers.Printing {
|
||||||
|
public class PdfPrintDocument : PrintDocument {
|
||||||
|
|
||||||
|
private readonly IntPtr _handle;
|
||||||
|
private readonly int _pageCount;
|
||||||
|
private readonly double _dpi;
|
||||||
|
|
||||||
|
private int _currentPage;
|
||||||
|
|
||||||
|
public PdfPrintDocument(string path, string? password = null, double dpi = 300.0) :
|
||||||
|
base() {
|
||||||
|
_handle = PdfiumNative.FPDF_LoadDocument(path, password);
|
||||||
|
_pageCount = PdfiumNative.FPDF_GetPageCount(_handle);
|
||||||
|
_dpi = dpi;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void Dispose(bool disposing) {
|
||||||
|
PdfiumNative.FPDF_CloseDocument(_handle);
|
||||||
|
base.Dispose(disposing);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnBeginPrint(PrintEventArgs evt) {
|
||||||
|
_currentPage = (PrinterSettings.FromPage != 0) ? (PrinterSettings.FromPage - 1) : 0;
|
||||||
|
base.OnBeginPrint(evt);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnPrintPage(PrintPageEventArgs evt) {
|
||||||
|
if (_currentPage < _pageCount) {
|
||||||
|
IntPtr page = PdfiumNative.FPDF_LoadPage(_handle, _currentPage);
|
||||||
|
double width = PdfiumNative.FPDF_GetPageWidth(page);
|
||||||
|
double height = PdfiumNative.FPDF_GetPageHeight(page);
|
||||||
|
int pixelWidth = (int)(width / 72.0 * _dpi);
|
||||||
|
int pixelHeight = (int)(height / 72.0 * _dpi);
|
||||||
|
|
||||||
|
IntPtr bitmap = PdfiumNative.FPDFBitmap_Create(pixelWidth, pixelHeight, 1);
|
||||||
|
PdfiumNative.FPDF_RenderPageBitmap(bitmap, page, 0, 0, pixelWidth, pixelHeight, 0, 0);
|
||||||
|
|
||||||
|
IntPtr buffer = PdfiumNative.FPDFBitmap_GetBuffer(bitmap);
|
||||||
|
int stride = PdfiumNative.FPDFBitmap_GetStride(bitmap);
|
||||||
|
using (var bmp = new Bitmap(pixelWidth, pixelHeight, stride, PixelFormat.Format32bppArgb, buffer)) {
|
||||||
|
evt.Graphics?.DrawImage(bmp, evt.PageBounds);
|
||||||
|
}
|
||||||
|
_currentPage++;
|
||||||
|
|
||||||
|
PdfiumNative.FPDFBitmap_Destroy(bitmap);
|
||||||
|
PdfiumNative.FPDF_ClosePage(page);
|
||||||
|
}
|
||||||
|
evt.HasMorePages = _currentPage < ((PrinterSettings.ToPage == 0) ? _pageCount : Math.Min(PrinterSettings.ToPage, _pageCount));
|
||||||
|
base.OnPrintPage(evt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal partial class PdfiumNative {
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial void FPDF_InitLibrary();
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial void FPDF_DestroyLibrary();
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll", StringMarshalling = StringMarshalling.Utf8)]
|
||||||
|
public static partial IntPtr FPDF_LoadDocument(string filePath, string? password);
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial void FPDF_CloseDocument(IntPtr document);
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial int FPDF_GetPageCount(IntPtr document);
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial IntPtr FPDF_LoadPage(IntPtr document, int pageIndex);
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial void FPDF_ClosePage(IntPtr page);
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial double FPDF_GetPageWidth(IntPtr page);
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial double FPDF_GetPageHeight(IntPtr page);
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial IntPtr FPDFBitmap_Create(int width, int height, int alpha);
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial void FPDFBitmap_Destroy(IntPtr bitmap);
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial IntPtr FPDFBitmap_GetBuffer(IntPtr bitmap);
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial int FPDFBitmap_GetStride(IntPtr bitmap);
|
||||||
|
|
||||||
|
[LibraryImport("pdfium.dll")]
|
||||||
|
public static partial void FPDF_RenderPageBitmap(IntPtr bitmap, IntPtr page, int start_x, int start_y, int size_x, int size_y, int rotate, int flags);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.IO;
|
|
||||||
using System.Printing;
|
|
||||||
|
|
||||||
namespace Elwig.Helpers.Printing {
|
|
||||||
public class PdfPrinter {
|
|
||||||
|
|
||||||
public string PrinterName { get; init; }
|
|
||||||
|
|
||||||
public PdfPrinter(string? printerName = null) {
|
|
||||||
PrinterName = printerName ?? GetDefaultPrinterName() ?? throw new InvalidOperationException("No default Windows printer is configured.");
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Print(string pdfPath, int copies = 1, bool doublePaged = false) {
|
|
||||||
if (!File.Exists(pdfPath)) throw new FileNotFoundException("PDF file not found.", pdfPath);
|
|
||||||
|
|
||||||
IntPtr document = PdfiumNative.FPDF_LoadDocument(pdfPath, null);
|
|
||||||
if (document == IntPtr.Zero) throw new InvalidOperationException("PDFium could not open the PDF.");
|
|
||||||
|
|
||||||
try {
|
|
||||||
int pageCount = PdfiumNative.FPDF_GetPageCount(document);
|
|
||||||
if (pageCount <= 0)
|
|
||||||
return;
|
|
||||||
|
|
||||||
using var printer = new Win32Printer.Printer(PrinterName);
|
|
||||||
printer.TrySetDuplex(doublePaged ? Duplexing.TwoSidedLongEdge : Duplexing.OneSided);
|
|
||||||
printer.StartDocument(Path.GetFileName(pdfPath));
|
|
||||||
bool documentStarted = true;
|
|
||||||
try {
|
|
||||||
for (int i = 0; i < copies; i++) {
|
|
||||||
for (int j = 0; j < pageCount; j++) {
|
|
||||||
PrintPage(document, printer, j);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
printer.EndDocument();
|
|
||||||
documentStarted = false;
|
|
||||||
} finally {
|
|
||||||
if (documentStarted) printer.AbortDocument();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
PdfiumNative.FPDF_CloseDocument(document);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void PrintPage(IntPtr document, Win32Printer.Printer printer, int pageIndex) {
|
|
||||||
if (!PdfiumNative.FPDF_GetPageSizeByIndex(document, pageIndex, out double pageWidthPt, out double pageHeightPt)) {
|
|
||||||
throw new InvalidOperationException($"Unable to obtain PDF page {pageIndex} size.");
|
|
||||||
}
|
|
||||||
|
|
||||||
IntPtr page = PdfiumNative.FPDF_LoadPage(document, pageIndex);
|
|
||||||
if (page == IntPtr.Zero)
|
|
||||||
throw new InvalidOperationException($"Unable to load PDF page {pageIndex}.");
|
|
||||||
|
|
||||||
try {
|
|
||||||
int renderWidth = (int)Math.Round(pageWidthPt / 72.0 * printer.DpiX);
|
|
||||||
int renderHeight = (int)Math.Round(pageHeightPt / 72.0 * printer.DpiY);
|
|
||||||
int offsetX = (printer.PrintableWidth - renderWidth) / 2;
|
|
||||||
int offsetY = (printer.PrintableHeight - renderHeight) / 2;
|
|
||||||
|
|
||||||
printer.StartPage();
|
|
||||||
try {
|
|
||||||
PdfiumNative.FPDF_RenderPage(printer.Hdc, page, offsetX, offsetY, renderWidth, renderHeight, 0, PdfiumNative.FPDF_PRINTING | PdfiumNative.FPDF_ANNOT);
|
|
||||||
} finally {
|
|
||||||
printer.EndPage();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
PdfiumNative.FPDF_ClosePage(page);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string? GetDefaultPrinterName() {
|
|
||||||
using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Windows");
|
|
||||||
string? printer = key?.GetValue("Device") as string;
|
|
||||||
if (string.IsNullOrWhiteSpace(printer))
|
|
||||||
return null;
|
|
||||||
|
|
||||||
// Device has the form:
|
|
||||||
// Printer Name,winspool,PORT
|
|
||||||
int comma = printer.IndexOf(',');
|
|
||||||
return comma >= 0 ? printer[..comma] : printer;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Runtime.InteropServices;
|
|
||||||
|
|
||||||
namespace Elwig.Helpers.Printing {
|
|
||||||
internal partial class PdfiumNative {
|
|
||||||
|
|
||||||
public const int FPDF_ANNOT = 0x01;
|
|
||||||
public const int FPDF_PRINTING = 0x800;
|
|
||||||
|
|
||||||
[LibraryImport("pdfium.dll")]
|
|
||||||
public static partial void FPDF_InitLibrary();
|
|
||||||
|
|
||||||
[LibraryImport("pdfium.dll")]
|
|
||||||
public static partial void FPDF_DestroyLibrary();
|
|
||||||
|
|
||||||
[LibraryImport("pdfium.dll", StringMarshalling = StringMarshalling.Utf8)]
|
|
||||||
public static partial IntPtr FPDF_LoadDocument(string filePath, string? password);
|
|
||||||
|
|
||||||
[LibraryImport("pdfium.dll")]
|
|
||||||
public static partial void FPDF_CloseDocument(IntPtr document);
|
|
||||||
|
|
||||||
[LibraryImport("pdfium.dll")]
|
|
||||||
public static partial int FPDF_GetPageCount(IntPtr document);
|
|
||||||
|
|
||||||
[LibraryImport("pdfium.dll")]
|
|
||||||
public static partial IntPtr FPDF_LoadPage(IntPtr document, int pageIndex);
|
|
||||||
|
|
||||||
[LibraryImport("pdfium.dll")]
|
|
||||||
public static partial void FPDF_ClosePage(IntPtr page);
|
|
||||||
|
|
||||||
[LibraryImport("pdfium.dll")]
|
|
||||||
[return: MarshalAs(UnmanagedType.Bool)]
|
|
||||||
public static partial bool FPDF_GetPageSizeByIndex(IntPtr document, int pageIndex, out double width, out double height);
|
|
||||||
|
|
||||||
[LibraryImport("pdfium.dll")]
|
|
||||||
public static partial void FPDF_RenderPage(IntPtr hdc, IntPtr page, int startX, int startY, int sizeX, int sizeY, int rotate, int flags);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,239 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.ComponentModel;
|
|
||||||
using System.Printing;
|
|
||||||
using System.Runtime.InteropServices;
|
|
||||||
|
|
||||||
namespace Elwig.Helpers.Printing {
|
|
||||||
public partial class Win32Printer {
|
|
||||||
|
|
||||||
private const int DM_OUT_BUFFER = 2;
|
|
||||||
|
|
||||||
private const int HORZRES = 8;
|
|
||||||
private const int VERTRES = 10;
|
|
||||||
private const int LOGPIXELSX = 88;
|
|
||||||
private const int LOGPIXELSY = 90;
|
|
||||||
private const int PHYSICALWIDTH = 110;
|
|
||||||
private const int PHYSICALHEIGHT = 111;
|
|
||||||
private const int PHYSICALOFFSETX = 112;
|
|
||||||
private const int PHYSICALOFFSETY = 113;
|
|
||||||
|
|
||||||
private const int DM_DUPLEX = 0x1000;
|
|
||||||
private const short DMDUP_SIMPLEX = 1;
|
|
||||||
private const short DMDUP_VERTICAL = 2;
|
|
||||||
private const short DMDUP_HORIZONTAL = 3;
|
|
||||||
|
|
||||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
||||||
private struct DOCINFO {
|
|
||||||
public int cbSize;
|
|
||||||
|
|
||||||
[MarshalAs(UnmanagedType.LPWStr)]
|
|
||||||
public string? lpszDocName;
|
|
||||||
|
|
||||||
[MarshalAs(UnmanagedType.LPWStr)]
|
|
||||||
public string? lpszOutput;
|
|
||||||
|
|
||||||
[MarshalAs(UnmanagedType.LPWStr)]
|
|
||||||
public string? lpszDatatype;
|
|
||||||
}
|
|
||||||
|
|
||||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
||||||
private struct DEVMODE {
|
|
||||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
|
|
||||||
public string dmDeviceName;
|
|
||||||
|
|
||||||
public short dmSpecVersion;
|
|
||||||
public short dmDriverVersion;
|
|
||||||
public short dmSize;
|
|
||||||
public short dmDriverExtra;
|
|
||||||
public int dmFields;
|
|
||||||
|
|
||||||
public short dmOrientation;
|
|
||||||
public short dmPaperSize;
|
|
||||||
public short dmPaperLength;
|
|
||||||
public short dmPaperWidth;
|
|
||||||
public short dmScale;
|
|
||||||
public short dmCopies;
|
|
||||||
public short dmDefaultSource;
|
|
||||||
public short dmPrintQuality;
|
|
||||||
public short dmColor;
|
|
||||||
public short dmDuplex;
|
|
||||||
public short dmYResolution;
|
|
||||||
public short dmTTOption;
|
|
||||||
public short dmCollate;
|
|
||||||
|
|
||||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
|
|
||||||
public string dmFormName;
|
|
||||||
|
|
||||||
public short dmLogPixels;
|
|
||||||
public int dmBitsPerPel;
|
|
||||||
public int dmPelsWidth;
|
|
||||||
public int dmPelsHeight;
|
|
||||||
public int dmDisplayFlags;
|
|
||||||
public int dmDisplayFrequency;
|
|
||||||
public int dmICMMethod;
|
|
||||||
public int dmICMIntent;
|
|
||||||
public int dmMediaType;
|
|
||||||
public int dmDitherType;
|
|
||||||
public int dmReserved1;
|
|
||||||
public int dmReserved2;
|
|
||||||
public int dmPanningWidth;
|
|
||||||
public int dmPanningHeight;
|
|
||||||
}
|
|
||||||
|
|
||||||
[DllImport("winspool.drv", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
||||||
private static extern bool OpenPrinter(string pPrinterName, out IntPtr phPrinter, IntPtr pDefault);
|
|
||||||
|
|
||||||
[DllImport("winspool.drv", SetLastError = true)]
|
|
||||||
private static extern bool ClosePrinter(IntPtr hPrinter);
|
|
||||||
|
|
||||||
[DllImport("winspool.drv", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
||||||
private static extern int DocumentProperties(IntPtr hwnd, IntPtr hPrinter, string pDeviceName, IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode);
|
|
||||||
|
|
||||||
[DllImport("gdi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
||||||
private static extern IntPtr CreateDC(string? pDriver, string? pDevice, string? pOutput, IntPtr pInitData);
|
|
||||||
|
|
||||||
[DllImport("gdi32.dll", SetLastError = true)]
|
|
||||||
private static extern bool DeleteDC(IntPtr hdc);
|
|
||||||
|
|
||||||
[DllImport("gdi32.dll", SetLastError = true)]
|
|
||||||
private static extern int GetDeviceCaps(IntPtr hdc, int index);
|
|
||||||
|
|
||||||
[DllImport("gdi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
||||||
private static extern int StartDoc(IntPtr hdc, ref DOCINFO lpdi);
|
|
||||||
|
|
||||||
[DllImport("gdi32.dll", SetLastError = true)]
|
|
||||||
private static extern int EndDoc(IntPtr hdc);
|
|
||||||
|
|
||||||
[DllImport("gdi32.dll", SetLastError = true)]
|
|
||||||
private static extern int AbortDoc(IntPtr hdc);
|
|
||||||
|
|
||||||
[DllImport("gdi32.dll", SetLastError = true)]
|
|
||||||
private static extern int StartPage(IntPtr hdc);
|
|
||||||
|
|
||||||
[DllImport("gdi32.dll", SetLastError = true)]
|
|
||||||
private static extern int EndPage(IntPtr hdc);
|
|
||||||
|
|
||||||
[DllImport("kernel32.dll", SetLastError = true)]
|
|
||||||
private static extern IntPtr GlobalAlloc(uint uFlags, UIntPtr dwBytes);
|
|
||||||
|
|
||||||
[DllImport("kernel32.dll", SetLastError = true)]
|
|
||||||
private static extern IntPtr GlobalFree(IntPtr hMem);
|
|
||||||
|
|
||||||
[DllImport("kernel32.dll")]
|
|
||||||
private static extern IntPtr GlobalLock(IntPtr hMem);
|
|
||||||
|
|
||||||
[DllImport("kernel32.dll")]
|
|
||||||
private static extern bool GlobalUnlock(IntPtr hMem);
|
|
||||||
|
|
||||||
public class Printer : IDisposable {
|
|
||||||
private readonly string _printerName;
|
|
||||||
private readonly IntPtr _printerHandle;
|
|
||||||
private readonly IntPtr _devMode;
|
|
||||||
private readonly IntPtr _hdc;
|
|
||||||
|
|
||||||
public IntPtr Hdc => _hdc;
|
|
||||||
|
|
||||||
public int PrintableWidth => GetDeviceCaps(_hdc, HORZRES);
|
|
||||||
public int PrintableHeight => GetDeviceCaps(_hdc, VERTRES);
|
|
||||||
public int DpiX => GetDeviceCaps(_hdc, LOGPIXELSX);
|
|
||||||
public int DpiY => GetDeviceCaps(_hdc, LOGPIXELSY);
|
|
||||||
public int PhysicalWidth => GetDeviceCaps(_hdc, PHYSICALWIDTH);
|
|
||||||
public int PhysicalHeight => GetDeviceCaps(_hdc, PHYSICALHEIGHT);
|
|
||||||
public int PhysicalOffsetX => GetDeviceCaps(_hdc, PHYSICALOFFSETX);
|
|
||||||
public int PhysicalOffsetY => GetDeviceCaps(_hdc, PHYSICALOFFSETY);
|
|
||||||
|
|
||||||
public Printer(string printerName) {
|
|
||||||
_printerName = printerName;
|
|
||||||
|
|
||||||
if (!OpenPrinter(_printerName, out _printerHandle, IntPtr.Zero)) {
|
|
||||||
throw new Win32Exception(Marshal.GetLastWin32Error(), $"Unable to open printer '{printerName}'.");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
_devMode = CreateDevMode();
|
|
||||||
_hdc = CreateDC(null, _printerName, null, _devMode);
|
|
||||||
if (_hdc == IntPtr.Zero)
|
|
||||||
throw new Win32Exception(Marshal.GetLastWin32Error(), $"Unable to create printer DC for '{_printerName}'.");
|
|
||||||
} catch {
|
|
||||||
if (_devMode != IntPtr.Zero) Marshal.FreeHGlobal(_devMode);
|
|
||||||
ClosePrinter(_printerHandle);
|
|
||||||
throw;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool TrySetDuplex(Duplexing duplex) {
|
|
||||||
var devMode = Marshal.PtrToStructure<DEVMODE>(_devMode);
|
|
||||||
switch (duplex) {
|
|
||||||
case Duplexing.OneSided: devMode.dmDuplex = DMDUP_SIMPLEX; break;
|
|
||||||
case Duplexing.TwoSidedShortEdge: devMode.dmDuplex = DMDUP_HORIZONTAL; break;
|
|
||||||
case Duplexing.TwoSidedLongEdge: devMode.dmDuplex = DMDUP_VERTICAL; break;
|
|
||||||
}
|
|
||||||
if ((devMode.dmFields & DM_DUPLEX) != 0) {
|
|
||||||
Marshal.StructureToPtr(devMode, _devMode, false);
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
devMode.dmFields |= DM_DUPLEX;
|
|
||||||
Marshal.StructureToPtr(devMode, _devMode, false);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private IntPtr CreateDevMode() {
|
|
||||||
int size = DocumentProperties(IntPtr.Zero, _printerHandle, _printerName, IntPtr.Zero, IntPtr.Zero, 0);
|
|
||||||
if (size <= 0)
|
|
||||||
throw new Win32Exception(Marshal.GetLastWin32Error(), "DocumentProperties failed.");
|
|
||||||
|
|
||||||
IntPtr devMode = Marshal.AllocHGlobal(size);
|
|
||||||
int result = DocumentProperties(IntPtr.Zero, _printerHandle, _printerName, devMode, IntPtr.Zero, DM_OUT_BUFFER);
|
|
||||||
if (result < 0) {
|
|
||||||
Marshal.FreeHGlobal(devMode);
|
|
||||||
throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to obtain printer DEVMODE.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return devMode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void StartDocument(string documentName) {
|
|
||||||
var docInfo = new DOCINFO {
|
|
||||||
cbSize = Marshal.SizeOf<DOCINFO>(),
|
|
||||||
lpszDocName = documentName,
|
|
||||||
lpszDatatype = null,
|
|
||||||
lpszOutput = null
|
|
||||||
};
|
|
||||||
|
|
||||||
if (StartDoc(_hdc, ref docInfo) <= 0)
|
|
||||||
throw new Win32Exception(Marshal.GetLastWin32Error(), "StartDoc failed.");
|
|
||||||
}
|
|
||||||
|
|
||||||
public void StartPage() {
|
|
||||||
if (Win32Printer.StartPage(_hdc) <= 0)
|
|
||||||
throw new Win32Exception(Marshal.GetLastWin32Error(), "StartPage failed.");
|
|
||||||
}
|
|
||||||
|
|
||||||
public void EndPage() {
|
|
||||||
if (Win32Printer.EndPage(_hdc) <= 0)
|
|
||||||
throw new Win32Exception(Marshal.GetLastWin32Error(), "EndPage failed.");
|
|
||||||
}
|
|
||||||
|
|
||||||
public void EndDocument() {
|
|
||||||
if (EndDoc(_hdc) <= 0)
|
|
||||||
throw new Win32Exception( Marshal.GetLastWin32Error(), "EndDoc failed.");
|
|
||||||
}
|
|
||||||
|
|
||||||
public void AbortDocument() {
|
|
||||||
AbortDoc(_hdc);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose() {
|
|
||||||
if (_hdc != IntPtr.Zero)
|
|
||||||
DeleteDC(_hdc);
|
|
||||||
|
|
||||||
if (_devMode != IntPtr.Zero)
|
|
||||||
Marshal.FreeHGlobal(_devMode);
|
|
||||||
|
|
||||||
if (_printerHandle != IntPtr.Zero)
|
|
||||||
ClosePrinter(_printerHandle);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -26,7 +26,7 @@ namespace Elwig.Helpers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void OnDeviceArrived(object sender, EventArrivedEventArgs evt) {
|
private void OnDeviceArrived(object sender, EventArrivedEventArgs evt) {
|
||||||
App.Current.Dispatcher.Invoke(() => {
|
App.MainDispatcher.Invoke(() => {
|
||||||
// "synchronized"
|
// "synchronized"
|
||||||
string[] currentPorts = SerialPort.GetPortNames();
|
string[] currentPorts = SerialPort.GetPortNames();
|
||||||
var newPorts = currentPorts.Except(_knownPorts).ToArray();
|
var newPorts = currentPorts.Except(_knownPorts).ToArray();
|
||||||
@@ -37,7 +37,7 @@ namespace Elwig.Helpers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void OnDeviceRemoved(object sender, EventArrivedEventArgs evt) {
|
private void OnDeviceRemoved(object sender, EventArrivedEventArgs evt) {
|
||||||
App.Current.Dispatcher.Invoke(() => {
|
App.MainDispatcher.Invoke(() => {
|
||||||
// "synchronized"
|
// "synchronized"
|
||||||
string[] currentPorts = SerialPort.GetPortNames();
|
string[] currentPorts = SerialPort.GetPortNames();
|
||||||
var removedPorts = _knownPorts.Except(currentPorts).ToArray();
|
var removedPorts = _knownPorts.Except(currentPorts).ToArray();
|
||||||
|
|||||||
@@ -38,9 +38,9 @@ namespace Elwig.Helpers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void Delete() {
|
private void Delete() {
|
||||||
if (Usages < 0) return;
|
if (FilePath == null) return;
|
||||||
File.Delete(FilePath);
|
File.Delete(FilePath);
|
||||||
Usages = -1;
|
FilePath = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+50
-88
@@ -45,6 +45,7 @@ namespace Elwig.Helpers {
|
|||||||
public static int CurrentNextSeason => DateTime.Now.Year - (DateTime.Now.Month <= 3 ? 1 : 0);
|
public static int CurrentNextSeason => DateTime.Now.Year - (DateTime.Now.Month <= 3 ? 1 : 0);
|
||||||
public static int CurrentLastSeason => DateTime.Now.Year - (DateTime.Now.Month <= 6 ? 1 : 0);
|
public static int CurrentLastSeason => DateTime.Now.Year - (DateTime.Now.Month <= 6 ? 1 : 0);
|
||||||
public static int FollowingSeason => DateTime.Now.Year + (DateTime.Now.Month >= 11 ? 1 : 0);
|
public static int FollowingSeason => DateTime.Now.Year + (DateTime.Now.Month >= 11 ? 1 : 0);
|
||||||
|
public static DateTime Today => (DateTime.Now.Hour >= 3) ? DateTime.Today : DateTime.Today.AddDays(-1);
|
||||||
|
|
||||||
[GeneratedRegex("^serial://([A-Za-z0-9]+):([0-9]+)(,([5-9]),([NOEMSnoems]),(0|1|1\\.5|2|))?$", RegexOptions.Compiled)]
|
[GeneratedRegex("^serial://([A-Za-z0-9]+):([0-9]+)(,([5-9]),([NOEMSnoems]),(0|1|1\\.5|2|))?$", RegexOptions.Compiled)]
|
||||||
private static partial Regex GeneratedSerialRegex();
|
private static partial Regex GeneratedSerialRegex();
|
||||||
@@ -74,9 +75,6 @@ namespace Elwig.Helpers {
|
|||||||
private static partial Regex GeneratedInvalidFileNamePartsRegex();
|
private static partial Regex GeneratedInvalidFileNamePartsRegex();
|
||||||
public static readonly Regex InvalidFileNamePartsRegex = GeneratedInvalidFileNamePartsRegex();
|
public static readonly Regex InvalidFileNamePartsRegex = GeneratedInvalidFileNamePartsRegex();
|
||||||
|
|
||||||
[GeneratedRegex(".{4}")]
|
|
||||||
private static partial Regex IbanRegex { get; }
|
|
||||||
|
|
||||||
public static readonly string GroupSeparator = "\u202F";
|
public static readonly string GroupSeparator = "\u202F";
|
||||||
public static readonly string UnitSeparator = "\u00A0";
|
public static readonly string UnitSeparator = "\u00A0";
|
||||||
|
|
||||||
@@ -209,7 +207,7 @@ namespace Elwig.Helpers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static string FormatIban(string iban) {
|
public static string FormatIban(string iban) {
|
||||||
return IbanRegex.Replace(iban.Trim(), "$0 ").Trim();
|
return Regex.Replace(iban.Trim(), ".{4}", "$0 ").Trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void RunBackground(string title, Func<Task> function) {
|
public static void RunBackground(string title, Func<Task> function) {
|
||||||
@@ -306,11 +304,6 @@ namespace Elwig.Helpers {
|
|||||||
return d.ShowDialog() == true ? (d.Weight, d.Reason) : null;
|
return d.ShowDialog() == true ? (d.Weight, d.Reason) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static int? ShowTareCorrectionDialog(int? actualTare, int? targetTare = null) {
|
|
||||||
var d = new TareCorrectionDialog(actualTare, targetTare);
|
|
||||||
return d.ShowDialog() == true ? d.TargetTare - d.ActualTare : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static (string?, int[])? ShowDeliverySplittingDialog(Delivery delivery) {
|
public static (string?, int[])? ShowDeliverySplittingDialog(Delivery delivery) {
|
||||||
var d = new DeliverySplittingDialog(delivery);
|
var d = new DeliverySplittingDialog(delivery);
|
||||||
return d.ShowDialog() == true ? (d.MgNr?.ToString() ?? d.LsNr, d.Weights ?? []) : null;
|
return d.ShowDialog() == true ? (d.MgNr?.ToString() ?? d.LsNr, d.Weights ?? []) : null;
|
||||||
@@ -325,14 +318,19 @@ namespace Elwig.Helpers {
|
|||||||
return new Footer(lineBreak, separator);
|
return new Footer(lineBreak, separator);
|
||||||
}
|
}
|
||||||
|
|
||||||
public class Footer(string lineBreak, string separator) {
|
public class Footer {
|
||||||
private readonly List<List<List<object>>> Items = [[[]]];
|
private readonly List<List<object>> Items = [[]];
|
||||||
private readonly string LineBreak = lineBreak;
|
private readonly string LineBreak;
|
||||||
private readonly string Separator = separator;
|
private readonly string Separator;
|
||||||
|
|
||||||
|
public Footer(string lineBreak, string separator) {
|
||||||
|
LineBreak = lineBreak;
|
||||||
|
Separator = separator;
|
||||||
|
}
|
||||||
|
|
||||||
public Footer Item(object? text) {
|
public Footer Item(object? text) {
|
||||||
if (text == null) return this;
|
if (text == null) return this;
|
||||||
Items[^1][^1].Add(text);
|
Items[^1].Add(text);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -340,38 +338,13 @@ namespace Elwig.Helpers {
|
|||||||
return text == null ? this : Item($"{name}: {text}");
|
return text == null ? this : Item($"{name}: {text}");
|
||||||
}
|
}
|
||||||
|
|
||||||
public Footer NextGroup() {
|
|
||||||
Items[^1].Add([]);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Footer NextLine() {
|
public Footer NextLine() {
|
||||||
Items.Add([[]]);
|
Items.Add([]);
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Footer RebalanceLines() {
|
|
||||||
for (int i = 0; i < Items.Count - 1; i++) {
|
|
||||||
var groups = Items[i];
|
|
||||||
var nextGroups = Items[i + 1];
|
|
||||||
if (groups.Count <= 1) continue;
|
|
||||||
var g = groups[^1];
|
|
||||||
var gl = g.Sum(i => (i is Text txt ? txt.GetText().Length : i.ToString()?.Length ?? 0) + Separator.Length);
|
|
||||||
var l1a = groups.SelectMany(g => g).Sum(i => (i is Text txt ? txt.GetText().Length : i.ToString()?.Length ?? 0) + Separator.Length) - Separator.Length;
|
|
||||||
var l2a = nextGroups.SelectMany(g => g).Sum(i => (i is Text txt ? txt.GetText().Length : i.ToString()?.Length ?? 0) + Separator.Length) - Separator.Length;
|
|
||||||
var l1b = l1a - gl;
|
|
||||||
var l2b = l2a + gl;
|
|
||||||
if (Math.Abs(l1b - l2b) <= Math.Abs(l1a - l2a)) {
|
|
||||||
Items[i].Remove(g);
|
|
||||||
Items[i + 1].Insert(0, g);
|
|
||||||
i--;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString() {
|
public override string ToString() {
|
||||||
return string.Join(LineBreak, Items.Select(l => string.Join(Separator, l.SelectMany(g => g).ToString())));
|
return string.Join(LineBreak, Items.Select(l => string.Join(Separator, l.ToString())));
|
||||||
}
|
}
|
||||||
|
|
||||||
public IList<ILeafElement> ToLeafElements() {
|
public IList<ILeafElement> ToLeafElements() {
|
||||||
@@ -380,12 +353,10 @@ namespace Elwig.Helpers {
|
|||||||
foreach (var line in Items) {
|
foreach (var line in Items) {
|
||||||
if (!first1) l.Add(new Text(LineBreak));
|
if (!first1) l.Add(new Text(LineBreak));
|
||||||
var first2 = true;
|
var first2 = true;
|
||||||
foreach (var group in line) {
|
foreach (var item in line) {
|
||||||
foreach (var item in group) {
|
if (!first2) l.Add(new Text(Separator));
|
||||||
if (!first2) l.Add(new Text(Separator));
|
l.Add(item as ILeafElement ?? new Text(item.ToString() ?? ""));
|
||||||
l.Add(item as ILeafElement ?? new Text(item.ToString() ?? ""));
|
first2 = false;
|
||||||
first2 = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
first1 = false;
|
first1 = false;
|
||||||
}
|
}
|
||||||
@@ -481,38 +452,35 @@ namespace Elwig.Helpers {
|
|||||||
return InternetGetConnectedState(out var _, 0);
|
return InternetGetConnectedState(out var _, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static string ReplaceUmlaute(string s) {
|
public static HttpClient GetHttpClient(string? username = null, string? password = null, string? accept = null) {
|
||||||
return s
|
|
||||||
.Replace("ä", "ae").Replace("Ä", "Ae")
|
|
||||||
.Replace("ö", "oe").Replace("Ö", "Oe")
|
|
||||||
.Replace("ü", "ue").Replace("Ü", "Ue")
|
|
||||||
.Replace("ß", "ss").Replace("ẞ", "SS");
|
|
||||||
}
|
|
||||||
|
|
||||||
public static HttpClient GetHttpClient(string? username = null, ReadOnlyMemory<char> password = default, string? accept = null) {
|
|
||||||
var client = new HttpClient() {
|
var client = new HttpClient() {
|
||||||
Timeout = TimeSpan.FromSeconds(5),
|
Timeout = TimeSpan.FromSeconds(5),
|
||||||
};
|
};
|
||||||
client.DefaultRequestHeaders.UserAgent.Clear();
|
client.DefaultRequestHeaders.UserAgent.Clear();
|
||||||
client.DefaultRequestHeaders.UserAgent.ParseAdd($"Elwig/{App.Version} ({App.Client.NameToken}, {ReplaceUmlaute(App.BranchName)}, {Environment.MachineName}, {Environment.OSVersion})");
|
client.DefaultRequestHeaders.UserAgent.ParseAdd($"Elwig/{App.Version} ({App.Client?.NameToken}, {App.BranchName}, {Environment.MachineName}, {Environment.OSVersion})");
|
||||||
client.DefaultRequestHeaders.Accept.Clear();
|
client.DefaultRequestHeaders.Accept.Clear();
|
||||||
if (accept != null)
|
if (accept != null)
|
||||||
client.DefaultRequestHeaders.Accept.Add(new(accept));
|
client.DefaultRequestHeaders.Accept.Add(new(accept));
|
||||||
if (username != null || !password.IsEmpty)
|
if (username != null || password != null)
|
||||||
client.DefaultRequestHeaders.Authorization = new("Basic", Convert.ToBase64String(Utils.UTF8.GetBytes($"{username}:{password}")));
|
client.DefaultRequestHeaders.Authorization = new("Basic", Convert.ToBase64String(Utils.UTF8.GetBytes($"{username}:{password}")));
|
||||||
return client;
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<(string Version, string Url, long Size)> GetLatestInstallerUrl(string url) {
|
public static async Task<(string Version, string Url, long Size)?> GetLatestInstallerUrl(string url) {
|
||||||
using var client = GetHttpClient(accept: "application/json");
|
try {
|
||||||
using var res = await client.GetAsync(url);
|
using var client = GetHttpClient(accept: "application/json");
|
||||||
res.EnsureSuccessStatusCode();
|
using var res = await client.GetAsync(url);
|
||||||
var resJson = JsonNode.Parse(await res.Content.ReadAsStringAsync());
|
if (!res.IsSuccessStatusCode)
|
||||||
var data = resJson!["data"]!.AsArray()[^1]!;
|
return null;
|
||||||
return ((string)data["version"]!, (string)data["url"]!, (long)data["size"]!);
|
var resJson = JsonNode.Parse(await res.Content.ReadAsStringAsync());
|
||||||
|
var data = resJson!["data"]!.AsArray()[^1]!;
|
||||||
|
return ((string)data["version"]!, (string)data["url"]!, (long)data["size"]!);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task UploadExportData(string zip, string url, string username, ReadOnlyMemory<char> password) {
|
public static async Task UploadExportData(string zip, string url, string username, string password) {
|
||||||
if (url.StartsWith("https://elwig.at/clients/"))
|
if (url.StartsWith("https://elwig.at/clients/"))
|
||||||
url = "https://sync.elwig.at/" + url[25..];
|
url = "https://sync.elwig.at/" + url[25..];
|
||||||
if (!url.EndsWith('/')) url += "/";
|
if (!url.EndsWith('/')) url += "/";
|
||||||
@@ -523,7 +491,7 @@ namespace Elwig.Helpers {
|
|||||||
res.EnsureSuccessStatusCode();
|
res.EnsureSuccessStatusCode();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<JsonArray> GetExportMetaData(string url, string username, ReadOnlyMemory<char> password) {
|
public static async Task<JsonArray> GetExportMetaData(string url, string username, string password) {
|
||||||
if (url.StartsWith("https://elwig.at/clients/"))
|
if (url.StartsWith("https://elwig.at/clients/"))
|
||||||
url = "https://sync.elwig.at/" + url[25..];
|
url = "https://sync.elwig.at/" + url[25..];
|
||||||
using var client = GetHttpClient(username, password, accept: "application/json");
|
using var client = GetHttpClient(username, password, accept: "application/json");
|
||||||
@@ -548,10 +516,10 @@ namespace Elwig.Helpers {
|
|||||||
public static async Task<SmtpClient?> GetSmtpClient() {
|
public static async Task<SmtpClient?> GetSmtpClient() {
|
||||||
if (App.Config.Smtp == null)
|
if (App.Config.Smtp == null)
|
||||||
return null;
|
return null;
|
||||||
var (host, port, mode, username, password, _, _) = App.Config.Smtp.Value;
|
var (host, port, mode, username, password, _) = App.Config.Smtp.Value;
|
||||||
var client = new SmtpClient();
|
var client = new SmtpClient();
|
||||||
await client.ConnectAsync(host, port, mode == "starttls" ? SecureSocketOptions.StartTls : SecureSocketOptions.None);
|
await client.ConnectAsync(host, port, mode == "starttls" ? SecureSocketOptions.StartTls : SecureSocketOptions.None);
|
||||||
await client.AuthenticateAsync(username, password.ToString());
|
await client.AuthenticateAsync(username, password);
|
||||||
return client;
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -568,7 +536,6 @@ namespace Elwig.Helpers {
|
|||||||
msg.From.Add(new MailboxAddress(App.Client.NameFull, App.Config.Smtp.Value.From));
|
msg.From.Add(new MailboxAddress(App.Client.NameFull, App.Config.Smtp.Value.From));
|
||||||
msg.To.AddRange(member.EmailAddresses.OrderBy(a => a.Nr).Select(a => new MailboxAddress(member.AdministrativeName, a.Address)));
|
msg.To.AddRange(member.EmailAddresses.OrderBy(a => a.Nr).Select(a => new MailboxAddress(member.AdministrativeName, a.Address)));
|
||||||
msg.Subject = subject;
|
msg.Subject = subject;
|
||||||
msg.Date = DateTime.Now;
|
|
||||||
var body = new Multipart("mixed") {
|
var body = new Multipart("mixed") {
|
||||||
new TextPart("plain") { Text = text }
|
new TextPart("plain") { Text = text }
|
||||||
};
|
};
|
||||||
@@ -577,12 +544,12 @@ namespace Elwig.Helpers {
|
|||||||
body.Add(doc.AsEmailAttachment($"{name}.pdf"));
|
body.Add(doc.AsEmailAttachment($"{name}.pdf"));
|
||||||
}
|
}
|
||||||
msg.Body = body;
|
msg.Body = body;
|
||||||
await client!.SendAsync(new SmtpSendRequest(msg));
|
await client!.SendAsync(msg);
|
||||||
await AddSentMails([(
|
await AddSentMails([(
|
||||||
"email", member.MgNr, member.AdministrativeName,
|
"email", member.MgNr, member.AdministrativeName,
|
||||||
member.EmailAddresses.OrderBy(a => a.Nr).Select(a => a.Address).ToArray(),
|
member.EmailAddresses.OrderBy(a => a.Nr).Select(a => a.Address).ToArray(),
|
||||||
subject, docs.Select(d => d.Title).ToArray()
|
subject, docs.Select(d => d.Title).ToArray()
|
||||||
)]);
|
)]);
|
||||||
} catch (Exception exc) {
|
} catch (Exception exc) {
|
||||||
InteractionService.ShowException(exc);
|
InteractionService.ShowException(exc);
|
||||||
return false;
|
return false;
|
||||||
@@ -655,7 +622,7 @@ namespace Elwig.Helpers {
|
|||||||
} else if (obj is IEnumerable list && obj is not string) {
|
} else if (obj is IEnumerable list && obj is not string) {
|
||||||
var arr = list.Cast<object>().Select(GetEntityIdentifier).ToArray();
|
var arr = list.Cast<object>().Select(GetEntityIdentifier).ToArray();
|
||||||
return ((IStructuralEquatable)arr).GetHashCode(EqualityComparer<int?>.Default);
|
return ((IStructuralEquatable)arr).GetHashCode(EqualityComparer<int?>.Default);
|
||||||
} else if (obj.GetType().GetCustomAttribute<PrimaryKeyAttribute>(true) is PrimaryKeyAttribute pkAttr) {
|
} else if (obj.GetType().GetCustomAttribute(typeof(PrimaryKeyAttribute), true) is PrimaryKeyAttribute pkAttr) {
|
||||||
var pk = pkAttr.PropertyNames.Select(name => obj.GetType().GetProperty(name)!.GetValue(obj)?.GetHashCode() ?? 0).ToArray();
|
var pk = pkAttr.PropertyNames.Select(name => obj.GetType().GetProperty(name)!.GetValue(obj)?.GetHashCode() ?? 0).ToArray();
|
||||||
return ((IStructuralEquatable)pk).GetHashCode(EqualityComparer<int>.Default);
|
return ((IStructuralEquatable)pk).GetHashCode(EqualityComparer<int>.Default);
|
||||||
} else {
|
} else {
|
||||||
@@ -663,16 +630,16 @@ namespace Elwig.Helpers {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Expression<Func<AreaCmt, bool>> ActiveAreaCommitments() => ActiveAreaCommitments(CurrentYear);
|
public static Expression<Func<AreaCom, bool>> ActiveAreaCommitments() => ActiveAreaCommitments(CurrentYear);
|
||||||
public static Expression<Func<AreaCmt, bool>> ActiveAreaCommitments(int year) =>
|
public static Expression<Func<AreaCom, bool>> ActiveAreaCommitments(int year) =>
|
||||||
c => (c.YearFrom == null || c.YearFrom <= year) && (c.YearTo == null || c.YearTo >= year);
|
c => (c.YearFrom == null || c.YearFrom <= year) && (c.YearTo == null || c.YearTo >= year);
|
||||||
|
|
||||||
public static IQueryable<AreaCmt> ActiveAreaCommitments(IQueryable<AreaCmt> query) => ActiveAreaCommitments(query, CurrentYear);
|
public static IQueryable<AreaCom> ActiveAreaCommitments(IQueryable<AreaCom> query) => ActiveAreaCommitments(query, CurrentYear);
|
||||||
public static IQueryable<AreaCmt> ActiveAreaCommitments(IQueryable<AreaCmt> query, int year) =>
|
public static IQueryable<AreaCom> ActiveAreaCommitments(IQueryable<AreaCom> query, int year) =>
|
||||||
query.Where(ActiveAreaCommitments(year));
|
query.Where(ActiveAreaCommitments(year));
|
||||||
|
|
||||||
public static IEnumerable<AreaCmt> ActiveAreaCommitments(IEnumerable<AreaCmt> query) => ActiveAreaCommitments(query, CurrentYear);
|
public static IEnumerable<AreaCom> ActiveAreaCommitments(IEnumerable<AreaCom> query) => ActiveAreaCommitments(query, CurrentYear);
|
||||||
public static IEnumerable<AreaCmt> ActiveAreaCommitments(IEnumerable<AreaCmt> query, int year) =>
|
public static IEnumerable<AreaCom> ActiveAreaCommitments(IEnumerable<AreaCom> query, int year) =>
|
||||||
query.Where(c => ActiveAreaCommitments(year).Invoke(c));
|
query.Where(c => ActiveAreaCommitments(year).Invoke(c));
|
||||||
|
|
||||||
public static async Task<(DateTime DateTime, string Type, int MgNr, string Name, string[] Addresses, string Subject, string[] Attachments)[]> GetSentMails(DateOnly? fromDate = null, DateOnly? toDate = null) {
|
public static async Task<(DateTime DateTime, string Type, int MgNr, string Name, string[] Addresses, string Subject, string[] Attachments)[]> GetSentMails(DateOnly? fromDate = null, DateOnly? toDate = null) {
|
||||||
@@ -703,7 +670,7 @@ namespace Elwig.Helpers {
|
|||||||
p[2],
|
p[2],
|
||||||
int.Parse(p[3]),
|
int.Parse(p[3]),
|
||||||
p[4],
|
p[4],
|
||||||
[.. p[5].Split(',').Select(a => a.Replace(" | ", "\n"))],
|
p[5].Split(',').Select(a => a.Replace(" | ", "\n")).ToArray(),
|
||||||
p[6],
|
p[6],
|
||||||
p[7].Split(',')
|
p[7].Split(',')
|
||||||
));
|
));
|
||||||
@@ -745,10 +712,5 @@ namespace Elwig.Helpers {
|
|||||||
var filename = Path.Combine(App.MailsPath, $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{NormalizeFileName(subject)}.txt");
|
var filename = Path.Combine(App.MailsPath, $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{NormalizeFileName(subject)}.txt");
|
||||||
await File.WriteAllTextAsync(filename, $"# {subject}\r\n# Vorgesehene Empfänger: {recipients}\r\n\r\n" + body, Utils.UTF8);
|
await File.WriteAllTextAsync(filename, $"# {subject}\r\n# Vorgesehene Empfänger: {recipients}\r\n\r\n" + body, Utils.UTF8);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static string GetTitle(string window, IEnumerable<string> filterNames, IEnumerable<string> filter) {
|
|
||||||
var f = string.Join(" / ", filterNames.Union(filter.Select(f => $"\"{f}\"")));
|
|
||||||
return window + (f.Length == 0 ? "" : ": " + f) + " - Elwig";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -577,7 +577,7 @@ namespace Elwig.Helpers {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ValidationResult CheckFbNr(TextBox input, bool required, AreaCmtContract? c) {
|
public static ValidationResult CheckFbNr(TextBox input, bool required, AreaComContract? c) {
|
||||||
var res = CheckInteger(input, required);
|
var res = CheckInteger(input, required);
|
||||||
if (!res.IsValid) {
|
if (!res.IsValid) {
|
||||||
return res;
|
return res;
|
||||||
@@ -623,37 +623,6 @@ namespace Elwig.Helpers {
|
|||||||
return new(true, null);
|
return new(true, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ValidationResult CheckOrganicOperatorId(TextBox input, bool required) {
|
|
||||||
string text = "";
|
|
||||||
int pos = input.CaretIndex;
|
|
||||||
for (int i = 0, v = 0; i < input.Text.Length; i++) {
|
|
||||||
char ch = input.Text[i];
|
|
||||||
if (char.IsAsciiDigit(ch)) {
|
|
||||||
if (v == 3 && text[^1] != '-')
|
|
||||||
text += "-";
|
|
||||||
v++;
|
|
||||||
text += ch;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (i == input.CaretIndex - 1) {
|
|
||||||
pos = text.Length;
|
|
||||||
} else if (v >= 10) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
input.Text = text;
|
|
||||||
input.CaretIndex = pos;
|
|
||||||
|
|
||||||
if (text.Length == 0) {
|
|
||||||
return required ? new(false, "OOC-ID ist nicht optional") : new(true, null);
|
|
||||||
} else if (!text.StartsWith("040-") || text.Length != 11) {
|
|
||||||
return new(false, "OOC-ID ist ungültig");
|
|
||||||
}
|
|
||||||
|
|
||||||
return new(true, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static ValidationResult CheckOrganicAuthorityCode(TextBox input, bool required) {
|
public static ValidationResult CheckOrganicAuthorityCode(TextBox input, bool required) {
|
||||||
string text = "";
|
string text = "";
|
||||||
int pos = input.CaretIndex;
|
int pos = input.CaretIndex;
|
||||||
@@ -662,18 +631,15 @@ namespace Elwig.Helpers {
|
|||||||
if (v < 2 && char.IsAsciiLetter(ch)) {
|
if (v < 2 && char.IsAsciiLetter(ch)) {
|
||||||
v++;
|
v++;
|
||||||
text += ch;
|
text += ch;
|
||||||
} else if ((v == 2 || v == 5) && ch == '-' && text[^1] != '-') {
|
} else if ((v == 2 || v == 6) && ch == '-') {
|
||||||
|
v++;
|
||||||
text += ch;
|
text += ch;
|
||||||
} else if (v >= 2 && v <= 4 && char.IsLetter(ch)) {
|
} else if (v >= 2 && char.IsLetterOrDigit(ch)) {
|
||||||
if (v == 2 && text[^1] != '-')
|
|
||||||
text += "-";
|
|
||||||
if (text.StartsWith("AT")) {
|
if (text.StartsWith("AT")) {
|
||||||
if (v == 2 && ch == 'B' || v == 3 && ch == 'I' || v == 4 && ch == 'O') {
|
if (v == 3 && ch == 'B' || v == 4 && ch == 'I' || v == 5 && ch == 'O') {
|
||||||
v++;
|
v++;
|
||||||
text += ch;
|
text += ch;
|
||||||
}
|
} else if (v > 6 && char.IsAsciiDigit(ch)) {
|
||||||
} else if (text.StartsWith("DE")) {
|
|
||||||
if (v == 2 && ch == 'Ö' || v == 3 && ch == 'K' || v == 4 && ch == 'O') {
|
|
||||||
v++;
|
v++;
|
||||||
text += ch;
|
text += ch;
|
||||||
}
|
}
|
||||||
@@ -681,16 +647,11 @@ namespace Elwig.Helpers {
|
|||||||
v++;
|
v++;
|
||||||
text += ch;
|
text += ch;
|
||||||
}
|
}
|
||||||
} else if (v >= 5 && v <= 7 && char.IsAsciiDigit(ch)) {
|
|
||||||
if (v == 5 && text[^1] != '-')
|
|
||||||
text += "-";
|
|
||||||
v++;
|
|
||||||
text += ch;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (i == input.CaretIndex - 1) {
|
if (i == input.CaretIndex - 1) {
|
||||||
pos = text.Length;
|
pos = text.Length;
|
||||||
} else if ((text.StartsWith("AT") || text.StartsWith("DE")) && v >= 10) {
|
} else if (text.StartsWith("AT") && v >= 10) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -701,7 +662,7 @@ namespace Elwig.Helpers {
|
|||||||
if (text.Length == 0)
|
if (text.Length == 0)
|
||||||
return required ? new(false, "Bio-Kontrollstellen-Code ist nicht optional") : new(true, null);
|
return required ? new(false, "Bio-Kontrollstellen-Code ist nicht optional") : new(true, null);
|
||||||
|
|
||||||
if (text.StartsWith("AT") || text.StartsWith("DE")) {
|
if (text.StartsWith("AT")) {
|
||||||
if (text.Length != 10) {
|
if (text.Length != 10) {
|
||||||
return new(false, "Bio-Kontrollstellen-Code ist ungültig");
|
return new(false, "Bio-Kontrollstellen-Code ist ungültig");
|
||||||
}
|
}
|
||||||
@@ -711,25 +672,5 @@ namespace Elwig.Helpers {
|
|||||||
|
|
||||||
return new(true, null);
|
return new(true, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ValidationResult CheckAddress(TextBox input, bool required, string? locality = null) {
|
|
||||||
var text = input.Text;
|
|
||||||
var (name, nr) = Utils.SplitAddress(text);
|
|
||||||
if (!string.IsNullOrWhiteSpace(nr)) {
|
|
||||||
var street = Normalizer.NormalizeStreetName(name.Replace(",", ""), locality);
|
|
||||||
var idx = input.CaretIndex;
|
|
||||||
input.Text = $"{street} {nr}".Trim();
|
|
||||||
if (idx >= (text.Length - nr.Length)) {
|
|
||||||
input.CaretIndex = street.Length + (idx - (text.Length - nr.Length)) + 1;
|
|
||||||
} else if (idx > 0) {
|
|
||||||
input.CaretIndex = idx;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (text.Length == 0)
|
|
||||||
return required ? new(false, "Adresse ist nicht optional") : new(true, null);
|
|
||||||
|
|
||||||
return new(true, null);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,8 +9,9 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
public class AveryEventScale : Scale, IEventScale, IDisposable {
|
public class AveryEventScale : Scale, IEventScale, IDisposable {
|
||||||
|
|
||||||
public string Manufacturer => "Avery";
|
public string Manufacturer => "Avery";
|
||||||
|
public int InternalScaleNr => 1;
|
||||||
public string Model { get; private set; }
|
public string Model { get; private set; }
|
||||||
public string ScaleTerminalId { get; private set; }
|
public string ScaleId { get; private set; }
|
||||||
public bool IsReady { get; private set; }
|
public bool IsReady { get; private set; }
|
||||||
public bool HasFillingClearance { get; private set; }
|
public bool HasFillingClearance { get; private set; }
|
||||||
|
|
||||||
@@ -18,11 +19,13 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
|
|
||||||
private bool IsRunning = true;
|
private bool IsRunning = true;
|
||||||
private readonly Thread BackgroundThread;
|
private readonly Thread BackgroundThread;
|
||||||
|
private readonly string Connection;
|
||||||
|
|
||||||
public AveryEventScale(string id, string model, string cnx, string? log = null, bool required = true) :
|
public AveryEventScale(string id, string model, string cnx, string? log = null, bool required = true) :
|
||||||
base(cnx, null, null, null, log, true, !required) {
|
base(cnx, null, null, null, log, true, !required) {
|
||||||
ScaleTerminalId = id;
|
ScaleId = id;
|
||||||
Model = model;
|
Model = model;
|
||||||
|
Connection = cnx;
|
||||||
IsReady = true;
|
IsReady = true;
|
||||||
HasFillingClearance = false;
|
HasFillingClearance = false;
|
||||||
Stream.WriteTimeout = -1;
|
Stream.WriteTimeout = -1;
|
||||||
|
|||||||
+17
-17
@@ -5,17 +5,18 @@ using System.Text;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace Elwig.Helpers.Weighing {
|
namespace Elwig.Helpers.Weighing {
|
||||||
public class GassnerEnqScale : Scale, ICommandScale {
|
public class GassnerScale : Scale, ICommandScale {
|
||||||
|
|
||||||
public string Manufacturer => "Gassner";
|
public string Manufacturer => "Gassner";
|
||||||
|
public int InternalScaleNr => 1;
|
||||||
public string Model { get; private set; }
|
public string Model { get; private set; }
|
||||||
public string ScaleTerminalId { get; private set; }
|
public string ScaleId { get; private set; }
|
||||||
public bool IsReady { get; private set; }
|
public bool IsReady { get; private set; }
|
||||||
public bool HasFillingClearance { get; private set; }
|
public bool HasFillingClearance { get; private set; }
|
||||||
|
|
||||||
public GassnerEnqScale(string id, string model, string cnx, string? empty = null, string? filling = null, int? limit = null, string? log = null) :
|
public GassnerScale(string id, string model, string cnx, string? empty = null, string? filling = null, int? limit = null, string? log = null) :
|
||||||
base(cnx, empty, filling, limit, log) {
|
base(cnx, empty, filling, limit, log) {
|
||||||
ScaleTerminalId = id;
|
ScaleId = id;
|
||||||
Model = model;
|
Model = model;
|
||||||
IsReady = true;
|
IsReady = true;
|
||||||
HasFillingClearance = false;
|
HasFillingClearance = false;
|
||||||
@@ -23,9 +24,10 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
Stream.ReadTimeout = 11000;
|
Stream.ReadTimeout = 11000;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Task SendCommand(string command) => SendCommand(Encoding.ASCII.GetBytes(command));
|
protected Task SendCommand(char command) => SendCommand(Convert.ToByte(command));
|
||||||
|
|
||||||
protected async Task SendCommand(byte[] cmd) {
|
protected async Task SendCommand(byte command) {
|
||||||
|
byte[] cmd = [command];
|
||||||
await Stream.WriteAsync(cmd);
|
await Stream.WriteAsync(cmd);
|
||||||
if (LogPath != null) await File.AppendAllTextAsync(LogPath, Encoding.ASCII.GetString(cmd));
|
if (LogPath != null) await File.AppendAllTextAsync(LogPath, Encoding.ASCII.GetString(cmd));
|
||||||
}
|
}
|
||||||
@@ -51,15 +53,15 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
return line[1..^1];
|
return line[1..^1];
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async Task<WeighingResult> Weigh(int? internalScaleNr, bool incIdentNr, bool retry = true) {
|
protected async Task<WeighingResult> Weigh(bool incIdentNr, bool retry = true) {
|
||||||
string record;
|
string record;
|
||||||
try {
|
try {
|
||||||
await SendCommand(incIdentNr ? "\x05" : "?");
|
await SendCommand(incIdentNr ? '\x05' : '?');
|
||||||
record = await ReceiveResponse();
|
record = await ReceiveResponse();
|
||||||
} catch (IOException) {
|
} catch (IOException) {
|
||||||
if (!retry || Tcp == null) throw;
|
if (!retry || Tcp == null) throw;
|
||||||
ReconnectTcp();
|
ReconnectTcp();
|
||||||
return await Weigh(internalScaleNr, incIdentNr, false);
|
return await Weigh(incIdentNr, false);
|
||||||
}
|
}
|
||||||
if (record.Length != 45)
|
if (record.Length != 45)
|
||||||
throw new FormatException("Invalid response from scale: Received record has invalid size");
|
throw new FormatException("Invalid response from scale: Received record has invalid size");
|
||||||
@@ -78,7 +80,6 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
GrossWeight = int.Parse(brutto),
|
GrossWeight = int.Parse(brutto),
|
||||||
TareWeight = int.Parse(tara),
|
TareWeight = int.Parse(tara),
|
||||||
NetWeight = int.Parse(netto),
|
NetWeight = int.Parse(netto),
|
||||||
ScaleId = scaleNr,
|
|
||||||
WeighingId = identNr,
|
WeighingId = identNr,
|
||||||
FullWeighingId = identNr,
|
FullWeighingId = identNr,
|
||||||
Date = DateOnly.TryParseExact(date, "yyyyMMdd", out var d) ? d : null,
|
Date = DateOnly.TryParseExact(date, "yyyyMMdd", out var d) ? d : null,
|
||||||
@@ -86,12 +87,12 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<WeighingResult> Weigh(int? scaleNr = null) {
|
public async Task<WeighingResult> Weigh() {
|
||||||
return await Weigh(scaleNr, true);
|
return await Weigh(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<WeighingResult> GetCurrentWeight(int? scaleNr = null) {
|
public async Task<WeighingResult> GetCurrentWeight() {
|
||||||
return await Weigh(scaleNr, false);
|
return await Weigh(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task Empty() {
|
public async Task Empty() {
|
||||||
@@ -125,9 +126,8 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
await SetFillingClearance(false);
|
await SetFillingClearance(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task SetDateAndTime(DateTime dateTime) {
|
public Task SetDateAndTime(DateTime dateTime) {
|
||||||
await SendCommand($"C{dateTime:yyyyMMddHHmmss}\r");
|
throw new NotImplementedException("Für Waagen vom Typ 'Gassner' ist diese Funktion noch nicht implementiert");
|
||||||
await ReceiveResponse();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,13 +10,13 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
/// Get the current weight on the scale without performing a weighing process
|
/// Get the current weight on the scale without performing a weighing process
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>Result of the weighing process (probably without a weighing id)</returns>
|
/// <returns>Result of the weighing process (probably without a weighing id)</returns>
|
||||||
Task<WeighingResult> GetCurrentWeight(int? scaleNr = null);
|
Task<WeighingResult> GetCurrentWeight();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Perform a weighing process
|
/// Perform a weighing process
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>Result of the weighing process (including a weighing id)</returns>
|
/// <returns>Result of the weighing process (including a weighing id)</returns>
|
||||||
Task<WeighingResult> Weigh(int? scaleNr = null);
|
Task<WeighingResult> Weigh();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Empty the scale container or grant clearance to do so
|
/// Empty the scale container or grant clearance to do so
|
||||||
|
|||||||
@@ -18,7 +18,12 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Unique identificator of the scale
|
/// Unique identificator of the scale
|
||||||
/// </summary>
|
/// </summary>
|
||||||
string ScaleTerminalId { get; }
|
string ScaleId { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Internal identifying number of the scale in its system
|
||||||
|
/// </summary>
|
||||||
|
int InternalScaleNr { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Indicates if the scale is currently processing a request or not
|
/// Indicates if the scale is currently processing a request or not
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
|
|
||||||
public string Manufacturer => "NONE";
|
public string Manufacturer => "NONE";
|
||||||
public string Model => "NONE";
|
public string Model => "NONE";
|
||||||
public string ScaleTerminalId => id;
|
public string ScaleId => id;
|
||||||
|
public int InternalScaleNr => 0;
|
||||||
public bool IsReady => false;
|
public bool IsReady => false;
|
||||||
public bool HasFillingClearance => false;
|
public bool HasFillingClearance => false;
|
||||||
public int? WeightLimit => null;
|
public int? WeightLimit => null;
|
||||||
|
|||||||
@@ -28,10 +28,10 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
int? limit = config.Limit != null ? int.Parse(config.Limit) : null;
|
int? limit = config.Limit != null ? int.Parse(config.Limit) : null;
|
||||||
if (config.Type == "SysTec-IT") {
|
if (config.Type == "SysTec-IT") {
|
||||||
return new SysTecITScale(config.Id, config.Model!, config.Connection!, config.Empty, config.Filling, limit, config.Log);
|
return new SysTecITScale(config.Id, config.Model!, config.Connection!, config.Empty, config.Filling, limit, config.Log);
|
||||||
} else if (config.Type == "Gassner-Enq" || config.Type == "Gassner") {
|
} else if (config.Type == "Avery-Async") {
|
||||||
return new GassnerEnqScale(config.Id, config.Model!, config.Connection!, config.Empty, config.Filling, limit, config.Log);
|
|
||||||
} else if (config.Type == "Avery-Event" || config.Type == "Avery-Async") {
|
|
||||||
return new AveryEventScale(config.Id, config.Model!, config.Connection!, config.Log, config.Required);
|
return new AveryEventScale(config.Id, config.Model!, config.Connection!, config.Log, config.Required);
|
||||||
|
} else if (config.Type == "Gassner") {
|
||||||
|
return new GassnerScale(config.Id, config.Model!, config.Connection!, config.Empty, config.Filling, limit, config.Log);
|
||||||
} else {
|
} else {
|
||||||
throw new ArgumentException($"Invalid scale type: \"{config.Type}\"");
|
throw new ArgumentException($"Invalid scale type: \"{config.Type}\"");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,14 +8,15 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
public class SysTecITScale : Scale, ICommandScale {
|
public class SysTecITScale : Scale, ICommandScale {
|
||||||
|
|
||||||
public string Manufacturer => "SysTec";
|
public string Manufacturer => "SysTec";
|
||||||
|
public int InternalScaleNr => 1;
|
||||||
public string Model { get; private set; }
|
public string Model { get; private set; }
|
||||||
public string ScaleTerminalId { get; private set; }
|
public string ScaleId { get; private set; }
|
||||||
public bool IsReady { get; private set; }
|
public bool IsReady { get; private set; }
|
||||||
public bool HasFillingClearance { get; private set; }
|
public bool HasFillingClearance { get; private set; }
|
||||||
|
|
||||||
public SysTecITScale(string id, string model, string cnx, string? empty = null, string? filling = null, int? limit = null, string? log = null) :
|
public SysTecITScale(string id, string model, string cnx, string? empty = null, string? filling = null, int? limit = null, string? log = null) :
|
||||||
base(cnx, empty, filling, limit, log) {
|
base(cnx, empty, filling, limit, log) {
|
||||||
ScaleTerminalId = id;
|
ScaleId = id;
|
||||||
Model = model;
|
Model = model;
|
||||||
IsReady = true;
|
IsReady = true;
|
||||||
HasFillingClearance = false;
|
HasFillingClearance = false;
|
||||||
@@ -61,7 +62,7 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
throw new WeighingException($"Fehler {error}: {msg}");
|
throw new WeighingException($"Fehler {error}: {msg}");
|
||||||
} else if (error[0] == '3') {
|
} else if (error[0] == '3') {
|
||||||
switch (error[1]) {
|
switch (error[1]) {
|
||||||
case '1': msg = "Übertragungsfehler"; break;
|
case '1': msg = "Übertragunsfehler"; break;
|
||||||
case '2': msg = "Ungültiger Befehl"; break;
|
case '2': msg = "Ungültiger Befehl"; break;
|
||||||
case '3': msg = "Ungültiger Parameter"; break;
|
case '3': msg = "Ungültiger Parameter"; break;
|
||||||
}
|
}
|
||||||
@@ -73,15 +74,15 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
return line[1..^3];
|
return line[1..^3];
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async Task<WeighingResult> Weigh(int internalScalNr, bool incIdentNr, bool retry = true) {
|
protected async Task<WeighingResult> Weigh(bool incIdentNr, bool retry = true) {
|
||||||
string record;
|
string record;
|
||||||
try {
|
try {
|
||||||
await SendCommand(incIdentNr ? $"RN{internalScalNr}" : $"RM{internalScalNr}");
|
await SendCommand(incIdentNr ? $"RN{InternalScaleNr}" : $"RM{InternalScaleNr}");
|
||||||
record = await ReceiveResponse();
|
record = await ReceiveResponse();
|
||||||
} catch (IOException) {
|
} catch (IOException) {
|
||||||
if (!retry || Tcp == null) throw;
|
if (!retry || Tcp == null) throw;
|
||||||
ReconnectTcp();
|
ReconnectTcp();
|
||||||
return await Weigh(internalScalNr, incIdentNr, false);
|
return await Weigh(incIdentNr, false);
|
||||||
}
|
}
|
||||||
if (record.Length != 62)
|
if (record.Length != 62)
|
||||||
throw new FormatException("Invalid response from scale: Received record has invalid size");
|
throw new FormatException("Invalid response from scale: Received record has invalid size");
|
||||||
@@ -113,7 +114,6 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
GrossWeight = int.Parse(brutto),
|
GrossWeight = int.Parse(brutto),
|
||||||
TareWeight = int.Parse(tara),
|
TareWeight = int.Parse(tara),
|
||||||
NetWeight = int.Parse(netto),
|
NetWeight = int.Parse(netto),
|
||||||
ScaleId = scaleNr,
|
|
||||||
WeighingId = identNr,
|
WeighingId = identNr,
|
||||||
FullWeighingId = identNr != null ? $"{parsedDate:yyyy-MM-dd}/{identNr}" : null,
|
FullWeighingId = identNr != null ? $"{parsedDate:yyyy-MM-dd}/{identNr}" : null,
|
||||||
Date = parsedDate,
|
Date = parsedDate,
|
||||||
@@ -121,12 +121,12 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<WeighingResult> Weigh(int? scaleNr = 1) {
|
public async Task<WeighingResult> Weigh() {
|
||||||
return await Weigh(scaleNr ?? 1, true);
|
return await Weigh(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<WeighingResult> GetCurrentWeight(int? scaleNr = 1) {
|
public async Task<WeighingResult> GetCurrentWeight() {
|
||||||
return await Weigh(scaleNr ?? 1, false);
|
return await Weigh(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task Empty() {
|
public async Task Empty() {
|
||||||
|
|||||||
@@ -21,11 +21,6 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public int? NetWeight;
|
public int? NetWeight;
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Reported id of the scale
|
|
||||||
/// </summary>
|
|
||||||
public string? ScaleId;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Weighing id (or IdentNr) provided by the scale
|
/// Weighing id (or IdentNr) provided by the scale
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -49,12 +44,11 @@ namespace Elwig.Helpers.Weighing {
|
|||||||
/// <returns><[GrossWeight-TaraWeight=]NetWeight/WeighingId/Date/Time></returns>
|
/// <returns><[GrossWeight-TaraWeight=]NetWeight/WeighingId/Date/Time></returns>
|
||||||
public override readonly string ToString() {
|
public override readonly string ToString() {
|
||||||
var w = NetWeight != null ? (GrossWeight != null && TareWeight != null ? $"{GrossWeight}-{TareWeight}=" : "") + $"{NetWeight}kg" : "";
|
var w = NetWeight != null ? (GrossWeight != null && TareWeight != null ? $"{GrossWeight}-{TareWeight}=" : "") + $"{NetWeight}kg" : "";
|
||||||
return $"<{w}/{WeighingId}/{Date:yyyy-MM-dd}/{Time:HH:mm:ss}>";
|
return $"<{w}/{WeighingId}/{Date:yyyy-MM-dd}/{Time:HH:mm}>";
|
||||||
}
|
}
|
||||||
|
|
||||||
public readonly JsonObject ToJson() {
|
public readonly JsonObject ToJson() {
|
||||||
var obj = new JsonObject();
|
var obj = new JsonObject();
|
||||||
if (ScaleId != null) obj["scale"] = ScaleId;
|
|
||||||
if (FullWeighingId != null) obj["id"] = FullWeighingId;
|
if (FullWeighingId != null) obj["id"] = FullWeighingId;
|
||||||
if (WeighingId != null) obj["nr"] = int.Parse(WeighingId);
|
if (WeighingId != null) obj["nr"] = int.Parse(WeighingId);
|
||||||
if (Date != null) obj["date"] = $"{Date:yyyy-MM-dd}";
|
if (Date != null) obj["date"] = $"{Date:yyyy-MM-dd}";
|
||||||
|
|||||||
+9
-9
@@ -5,7 +5,7 @@ using System.Linq;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace Elwig.Models.Dtos {
|
namespace Elwig.Models.Dtos {
|
||||||
public class AreaCmtUnderDeliveryData : DataTable<AreaCmtUnderDeliveryRow> {
|
public class AreaComUnderDeliveryData : DataTable<AreaComUnderDeliveryRow> {
|
||||||
|
|
||||||
private static readonly (string, string, string?, int)[] FieldNames = [
|
private static readonly (string, string, string?, int)[] FieldNames = [
|
||||||
("MgNr", "MgNr.", null, 12),
|
("MgNr", "MgNr.", null, 12),
|
||||||
@@ -21,19 +21,19 @@ namespace Elwig.Models.Dtos {
|
|||||||
("UnderDeliveries", "Unterliefert", "kg|%", 34),
|
("UnderDeliveries", "Unterliefert", "kg|%", 34),
|
||||||
];
|
];
|
||||||
|
|
||||||
public AreaCmtUnderDeliveryData(IEnumerable<AreaCmtUnderDeliveryRow> rows, int year) :
|
public AreaComUnderDeliveryData(IEnumerable<AreaComUnderDeliveryRow> rows, int year) :
|
||||||
base($"Unterlieferungen FB", $"Unterlieferungen laut Flächenbindungen {year}", rows, FieldNames) {
|
base($"Unterlieferungen FB", $"Unterlieferungen laut Flächenbindungen {year}", rows, FieldNames) {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<AreaCmtUnderDeliveryData> ForSeason(DbSet<AreaCmtUnderDeliveryRowSingle> table, int year) {
|
public static async Task<AreaComUnderDeliveryData> ForSeason(DbSet<AreaComUnderDeliveryRowSingle> table, int year) {
|
||||||
return new AreaCmtUnderDeliveryData(
|
return new AreaComUnderDeliveryData(
|
||||||
(await FromDbSet(table, year)).GroupBy(
|
(await FromDbSet(table, year)).GroupBy(
|
||||||
r => r.MgNr,
|
r => r.MgNr,
|
||||||
(k, g) => new AreaCmtUnderDeliveryRow(g)
|
(k, g) => new AreaComUnderDeliveryRow(g)
|
||||||
), year);
|
), year);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task<IEnumerable<AreaCmtUnderDeliveryRowSingle>> FromDbSet(DbSet<AreaCmtUnderDeliveryRowSingle> table, int year) {
|
private static async Task<IEnumerable<AreaComUnderDeliveryRowSingle>> FromDbSet(DbSet<AreaComUnderDeliveryRowSingle> table, int year) {
|
||||||
return await table.FromSql($"""
|
return await table.FromSql($"""
|
||||||
SELECT m.mgnr, m.name AS name_1,
|
SELECT m.mgnr, m.name AS name_1,
|
||||||
COALESCE(m.prefix || ' ', '') || m.given_name ||
|
COALESCE(m.prefix || ' ', '') || m.given_name ||
|
||||||
@@ -51,7 +51,7 @@ namespace Elwig.Models.Dtos {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class AreaCmtUnderDeliveryRow {
|
public class AreaComUnderDeliveryRow {
|
||||||
public int MgNr;
|
public int MgNr;
|
||||||
public string Name1;
|
public string Name1;
|
||||||
public string? Name2;
|
public string? Name2;
|
||||||
@@ -66,7 +66,7 @@ namespace Elwig.Models.Dtos {
|
|||||||
.Select(v => v.First < v.Second ? ((int?, double?))(v.First - v.Second, v.First * 100.0 / v.Second - 100.0) : (null, null))
|
.Select(v => v.First < v.Second ? ((int?, double?))(v.First - v.Second, v.First * 100.0 / v.Second - 100.0) : (null, null))
|
||||||
.ToArray();
|
.ToArray();
|
||||||
|
|
||||||
public AreaCmtUnderDeliveryRow(IEnumerable<AreaCmtUnderDeliveryRowSingle> rows) {
|
public AreaComUnderDeliveryRow(IEnumerable<AreaComUnderDeliveryRowSingle> rows) {
|
||||||
var f = rows.First();
|
var f = rows.First();
|
||||||
MgNr = f.MgNr;
|
MgNr = f.MgNr;
|
||||||
Name1 = f.Name1;
|
Name1 = f.Name1;
|
||||||
@@ -82,7 +82,7 @@ namespace Elwig.Models.Dtos {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Keyless]
|
[Keyless]
|
||||||
public class AreaCmtUnderDeliveryRowSingle {
|
public class AreaComUnderDeliveryRowSingle {
|
||||||
[Column("mgnr")]
|
[Column("mgnr")]
|
||||||
public int MgNr { get; set; }
|
public int MgNr { get; set; }
|
||||||
[Column("name_1")]
|
[Column("name_1")]
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Data;
|
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
|
|
||||||
@@ -10,14 +9,13 @@ namespace Elwig.Models.Dtos {
|
|||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
public string FullName { get; set; }
|
public string FullName { get; set; }
|
||||||
public string? Subtitle { get; set; }
|
public string? Subtitle { get; set; }
|
||||||
public IEnumerable<(string? Name, IEnumerable<T> Rows)> Sections { get; private set; }
|
public IEnumerable<T> Rows { get; private set; }
|
||||||
public IEnumerable<T> Rows => Sections.SelectMany(s => s.Rows);
|
|
||||||
public int RowNum => Rows.Count();
|
public int RowNum => Rows.Count();
|
||||||
public int ColNum => ColumnNames.Count();
|
public int ColNum => ColumnNames.Count();
|
||||||
|
|
||||||
public IEnumerable<(string Name, Type? Type)> ColumnDefs => _map.Select(m => (m.Name, m.PInfo?.PropertyType ?? m.FInfo?.FieldType));
|
public IEnumerable<(string, Type?)> ColumnDefs => _map.Select(m => (m.Item1, m.Item2?.PropertyType ?? m.Item3?.FieldType));
|
||||||
public IEnumerable<string> ColumnNames => ColumnDefs.Select(m => m.Name);
|
public IEnumerable<string> ColumnNames => ColumnDefs.Select(m => m.Item1);
|
||||||
public IEnumerable<Type?> ColumnTypes => ColumnDefs.Select(m => m.Type);
|
public IEnumerable<Type?> ColumnTypes => ColumnDefs.Select(m => m.Item2);
|
||||||
public IEnumerable<Type?> ColumnFlatTypes { get; private set; }
|
public IEnumerable<Type?> ColumnFlatTypes { get; private set; }
|
||||||
public IEnumerable<int> ColumnSpans { get; private set; }
|
public IEnumerable<int> ColumnSpans { get; private set; }
|
||||||
public IEnumerable<int?> ColumnWidths { get; private set; }
|
public IEnumerable<int?> ColumnWidths { get; private set; }
|
||||||
@@ -25,87 +23,70 @@ namespace Elwig.Models.Dtos {
|
|||||||
|
|
||||||
private readonly PropertyInfo[] _properties;
|
private readonly PropertyInfo[] _properties;
|
||||||
private readonly FieldInfo[] _fields;
|
private readonly FieldInfo[] _fields;
|
||||||
private readonly (string Name, PropertyInfo? PInfo, FieldInfo? FInfo)[] _map;
|
private readonly (string, PropertyInfo?, FieldInfo?)[] _map;
|
||||||
|
|
||||||
public DataTable(string name, string fullName, string subtitle, IEnumerable<(string? Name, IEnumerable<T> Rows)> sections, IEnumerable<(string Property, string Name, string? Unit, int? Width)>? colNames = null) :
|
public DataTable(string name, string fullName, string subtitle, IEnumerable<T> rows, IEnumerable<(string, string, string?, int?)>? colNames = null) :
|
||||||
this(name, fullName, sections, colNames) {
|
this(name, fullName, rows, colNames) {
|
||||||
Subtitle = subtitle;
|
Subtitle = subtitle;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DataTable(string name, string fullName, string subtitle, IEnumerable<T> rows, IEnumerable<(string Property, string Name, string? Unit, int? Width)>? colNames = null) :
|
public DataTable(string name, string fullName, IEnumerable<T> rows, IEnumerable<(string, string, string?, int?)>? colNames = null) {
|
||||||
this(name, fullName, subtitle, [(null, rows)], colNames) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public DataTable(string name, string fullName, IEnumerable<(string? Name, IEnumerable<T> Rows)> sections, IEnumerable<(string Property, string Name, string? Unit, int? Width)>? colNames = null) {
|
|
||||||
_fields = typeof(T).GetFields();
|
_fields = typeof(T).GetFields();
|
||||||
_properties = typeof(T).GetProperties();
|
_properties = typeof(T).GetProperties();
|
||||||
colNames ??= [.. _properties.Select(p => p.Name).Union(_fields.Select(f => f.Name)).Select(i => (i, i, (string?)null, (int?)null))];
|
colNames ??= _properties.Select(p => p.Name).Union(_fields.Select(f => f.Name)).Select(i => (i, i, (string?)null, (int?)null)).ToList();
|
||||||
_map = [.. colNames.Select(n => (n.Name, _properties.FirstOrDefault(p => p?.Name == n.Property, null), _fields.FirstOrDefault(f => f?.Name == n.Property, null)))];
|
_map = colNames.Select(n => (n.Item2, _properties.FirstOrDefault(p => p?.Name == n.Item1, null), _fields.FirstOrDefault(f => f?.Name == n.Item1, null))).ToArray();
|
||||||
Name = name;
|
Name = name;
|
||||||
FullName = fullName;
|
FullName = fullName;
|
||||||
Sections = sections;
|
Rows = rows;
|
||||||
ColumnFlatTypes = [.. ColumnTypes.SelectMany(type => {
|
ColumnFlatTypes = ColumnTypes.SelectMany(type => {
|
||||||
var elType = type?.GetElementType();
|
var elType = type?.GetElementType();
|
||||||
return type != null && type.IsValueType && type.Name.StartsWith("ValueTuple") ? type.GetFields().Select(f => (Type?)f.FieldType) :
|
return type != null && type.IsValueType && type.Name.StartsWith("ValueTuple") ? type.GetFields().Select(f => f.FieldType) :
|
||||||
type != null && elType != null && type.IsArray && elType.IsValueType && elType.Name.StartsWith("ValueTuple") ? elType.GetFields().Select(f => (Type?)f.FieldType) :
|
type != null && elType != null && type.IsArray && elType.IsValueType && elType.Name.StartsWith("ValueTuple") ? elType.GetFields().Select(f => f.FieldType) :
|
||||||
[type];
|
[type];
|
||||||
})];
|
}).ToList();
|
||||||
ColumnSpans = [.. ColumnTypes.Select(type => {
|
ColumnSpans = ColumnTypes.Select(type => {
|
||||||
var elType = type?.GetElementType();
|
var elType = type?.GetElementType();
|
||||||
return type != null && type.IsValueType && type.Name.StartsWith("ValueTuple") ? type.GetFields().Length :
|
return type != null && type.IsValueType && type.Name.StartsWith("ValueTuple") ? type.GetFields().Length :
|
||||||
type != null && elType != null && type.IsArray && elType.IsValueType && elType.Name.StartsWith("ValueTuple") ? elType.GetFields().Length :
|
type != null && elType != null && type.IsArray && elType.IsValueType && elType.Name.StartsWith("ValueTuple") ? elType.GetFields().Length : 1;
|
||||||
1;
|
}).ToList();
|
||||||
})];
|
ColumnWidths = colNames.Select(c => c.Item4).ToList();
|
||||||
ColumnWidths = [.. colNames.Select(c => c.Width)];
|
ColumnUnits = colNames.Select(c => c.Item3?.Split("|").Select(p => p.Length == 0 ? null : p).ToArray() ?? []).ToList();
|
||||||
ColumnUnits = [.. colNames.Select(c => c.Unit?.Split("|").Select(p => p.Length == 0 ? null : p).ToArray() ?? [])];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public DataTable(string name, string fullName, IEnumerable<T> rows, IEnumerable<(string Property, string Name, string? Unit, int? Width)>? colNames = null) :
|
public DataTable(string name, string fullName, IEnumerable<T> rows, IEnumerable<(string, string, string?)>? colNames = null) :
|
||||||
this(name, fullName, [(null, rows)], colNames) {
|
this(name, fullName, rows, colNames?.Select(c => (c.Item1, c.Item2, c.Item3, (int?)null))) {
|
||||||
}
|
}
|
||||||
|
|
||||||
public DataTable(string name, string fullName, IEnumerable<T> rows, IEnumerable<(string Property, string Name, string? Unit)>? colNames = null) :
|
public DataTable(string name, IEnumerable<T> rows, IEnumerable<(string, string, string?)>? colNames = null) :
|
||||||
this(name, fullName, rows, colNames?.Select(c => (c.Property, c.Name, c.Unit, (int?)null))) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public DataTable(string name, string fullName, IEnumerable<T> rows, IEnumerable<(string Property, string Name, string? Unit, int Width)>? colNames = null) :
|
|
||||||
this(name, fullName, rows, colNames?.Select(c => (c.Property, c.Name, c.Unit, (int?)c.Width))) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public DataTable(string name, IEnumerable<T> rows, IEnumerable<(string Property, string Name, string? Unit, int? Width)>? colNames = null) :
|
|
||||||
this(name, name, rows, colNames) {
|
this(name, name, rows, colNames) {
|
||||||
}
|
}
|
||||||
|
|
||||||
public DataTable(string name, IEnumerable<T> rows, IEnumerable<(string Property, string Name, string? Unit)>? colNames = null) :
|
public DataTable(string name, IEnumerable<T> rows, IEnumerable<(string, string, string?, int?)>? colNames = null) :
|
||||||
this(name, name, rows, colNames) {
|
this(name, name, rows, colNames) {
|
||||||
}
|
}
|
||||||
|
|
||||||
public DataTable(string name, IEnumerable<T> rows, IEnumerable<(string Property, string Name, string? Unit, int Width)>? colNames = null) :
|
public DataTable(string name, IEnumerable<T> rows, IEnumerable<(string, string, string?, int)>? colNames = null) :
|
||||||
this(name, name, rows, colNames) {
|
this(name, name, rows, colNames) {
|
||||||
}
|
}
|
||||||
|
|
||||||
public DataTable(string name, string fullName, IEnumerable<(string? Name, IEnumerable<T> Rows)> sections, IEnumerable<(string Property, string Name, string? Unit)>? colNames = null) :
|
public DataTable(string name, string fullName, IEnumerable<T> rows, IEnumerable<(string, string, string?, int)>? colNames = null) :
|
||||||
this(name, fullName, sections, colNames?.Select(c => (c.Property, c.Name, c.Unit, (int?)null))) {
|
this(name, fullName, rows, colNames?.Select(c => (c.Item1, c.Item2, c.Item3, (int?)c.Item4))) {
|
||||||
}
|
}
|
||||||
|
|
||||||
public DataTable(string name, string fullName, IEnumerable<(string? Name, IEnumerable<T> Rows)> sections, IEnumerable<(string Property, string Name, string? Unit, int Width)>? colNames = null) :
|
protected IEnumerable<(string, object?)> GetNamedRowData(T row) {
|
||||||
this(name, fullName, sections, colNames?.Select(c => (c.Property, c.Name, c.Unit, (int?)c.Width))) {
|
return _map.Select(i => (i.Item1, i.Item2?.GetValue(row) ?? i.Item3?.GetValue(row)));
|
||||||
}
|
}
|
||||||
|
|
||||||
protected IEnumerable<(string Name, object? Value)> GetNamedRowValues(T row) {
|
protected IEnumerable<object?> GetRowData(T row) {
|
||||||
return _map.Select(i => (i.Name, i.PInfo?.GetValue(row) ?? i.FInfo?.GetValue(row)));
|
return GetNamedRowData(row).Select(i => i.Item2);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected IEnumerable<object?> GetRowValues(T row) {
|
public IEnumerable<IEnumerable<object?>> GetData() {
|
||||||
return GetNamedRowValues(row).Select(i => i.Value);
|
return Rows.Select(GetRowData);
|
||||||
}
|
}
|
||||||
|
|
||||||
public IEnumerable<(string? Name, IEnumerable<IEnumerable<object?>> Rows)> GetData() {
|
public IEnumerable<IEnumerable<(string, object?)>> GetNamedData() {
|
||||||
return Sections.Select(s => (s.Name, s.Rows.Select(GetRowValues)));
|
return Rows.Select(GetNamedRowData);
|
||||||
}
|
|
||||||
|
|
||||||
public IEnumerable<(string? Name, IEnumerable<IEnumerable<(string Name, object? Value)>> Rows)> GetNamedData() {
|
|
||||||
return Sections.Select(s => (s.Name, s.Rows.Select(GetNamedRowValues)));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -45,6 +45,8 @@ namespace Elwig.Models.Dtos {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static async Task<IEnumerable<DeliveryPart>> FromDbSet(DbSet<DeliveryPart> table, int? year = null, int? mgnr = null) {
|
private static async Task<IEnumerable<DeliveryPart>> FromDbSet(DbSet<DeliveryPart> table, int? year = null, int? mgnr = null) {
|
||||||
|
var y = year?.ToString() ?? "NULL";
|
||||||
|
var m = mgnr?.ToString() ?? "NULL";
|
||||||
IQueryable<DeliveryPart> q = table;
|
IQueryable<DeliveryPart> q = table;
|
||||||
if (year != null) q = q.Where(p => p.Year == year);
|
if (year != null) q = q.Where(p => p.Year == year);
|
||||||
if (mgnr != null) q = q.Where(p => p.Delivery.MgNr == mgnr);
|
if (mgnr != null) q = q.Where(p => p.Delivery.MgNr == mgnr);
|
||||||
@@ -53,11 +55,11 @@ namespace Elwig.Models.Dtos {
|
|||||||
.Include(p => p.Buckets)
|
.Include(p => p.Buckets)
|
||||||
.Include(p => p.PartModifiers).ThenInclude(m => m.Modifier)
|
.Include(p => p.PartModifiers).ThenInclude(m => m.Modifier)
|
||||||
.LoadAsync();
|
.LoadAsync();
|
||||||
return await table.FromSql($"""
|
return await table.FromSqlRaw($"""
|
||||||
SELECT p.*
|
SELECT p.*
|
||||||
FROM v_delivery v
|
FROM v_delivery v
|
||||||
JOIN delivery_part p ON (p.year, p.did, p.dpnr) = (v.year, v.did, v.dpnr)
|
JOIN delivery_part p ON (p.year, p.did, p.dpnr) = (v.year, v.did, v.dpnr)
|
||||||
WHERE (p.year = {year} OR {year} IS NULL) AND (v.mgnr = {mgnr} OR {mgnr} IS NULL)
|
WHERE (p.year = {y} OR {y} IS NULL) AND (v.mgnr = {m} OR {m} IS NULL)
|
||||||
ORDER BY p.year, v.mgnr, v.sortid, v.abgewertet ASC, v.attribute_prio DESC, COALESCE(v.attrid, '~'), v.kmw DESC, v.lsnr, v.dpnr
|
ORDER BY p.year, v.mgnr, v.sortid, v.abgewertet ASC, v.attribute_prio DESC, COALESCE(v.attrid, '~'), v.kmw DESC, v.lsnr, v.dpnr
|
||||||
""").IgnoreAutoIncludes().ToListAsync();
|
""").IgnoreAutoIncludes().ToListAsync();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,87 +0,0 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.ComponentModel.DataAnnotations.Schema;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace Elwig.Models.Dtos {
|
|
||||||
class MemberAreaCmtsData : DataTable<MemberAreaCmtsRow> {
|
|
||||||
|
|
||||||
private static readonly (string, string, string?, int)[] FieldNames = [
|
|
||||||
("MgNr", "MgNr.", null, 12),
|
|
||||||
("Name1", "Name", null, 40),
|
|
||||||
("Name2", "Vorname", null, 40),
|
|
||||||
("Address", "Adresse", null, 60),
|
|
||||||
("Plz", "PLZ", null, 10),
|
|
||||||
("Locality", "Ort", null, 60),
|
|
||||||
("SortId", "Sorte", null, 12),
|
|
||||||
("AttrId", "Attribut", null, 16),
|
|
||||||
("CultId", "Bewirt.", null, 16),
|
|
||||||
("GstNr", "Parzelle(n)", null, 25),
|
|
||||||
("Area", "Fläche", "m²", 22),
|
|
||||||
("MinKg", "Lieferpflicht", "kg", 22),
|
|
||||||
("MaxKg", "Lieferrecht", "kg", 22),
|
|
||||||
];
|
|
||||||
|
|
||||||
public MemberAreaCmtsData(IEnumerable<MemberAreaCmtsRow> rows, int year) :
|
|
||||||
base($"Flächenbindungen", $"Flächenbindungen pro Mitglied {year}", rows, FieldNames) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task<MemberAreaCmtsData> ForSeason(DbSet<MemberAreaCmtsRow> table, int year) {
|
|
||||||
return new MemberAreaCmtsData(await FromDbSet(table, year), year);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<IEnumerable<MemberAreaCmtsRow>> FromDbSet(DbSet<MemberAreaCmtsRow> table, int year) {
|
|
||||||
return await table.FromSql($"""
|
|
||||||
SELECT m.mgnr, m.name AS name_1,
|
|
||||||
COALESCE(m.prefix || ' ', '') || m.given_name ||
|
|
||||||
COALESCE(' ' || m.middle_names, '') || COALESCE(' ' || m.suffix, '') AS name_2,
|
|
||||||
p.plz, o.name AS ort, m.address,
|
|
||||||
t.sortid, t.attrid, c.cultid,
|
|
||||||
c.gstnr, c.area,
|
|
||||||
CAST(ROUND(area * COALESCE(t.min_kg_per_ha, 0) / 10000.0, 0) AS INTEGER) AS min_kg,
|
|
||||||
CAST(ROUND(area * MIN(COALESCE(a.max_kg_per_ha, s.max_kg_per_ha), s.max_kg_per_ha) / 10000.0, 0) AS INTEGER) AS max_kg
|
|
||||||
FROM v_virtual_season s, area_commitment c
|
|
||||||
JOIN area_commitment_type t ON t.vtrgid = c.vtrgid
|
|
||||||
LEFT JOIN wine_attribute a ON a.attrid = t.attrid
|
|
||||||
LEFT JOIN member m ON m.mgnr = c.mgnr
|
|
||||||
LEFT JOIN AT_plz_dest p ON p.id = m.postal_dest
|
|
||||||
LEFT JOIN AT_ort o ON o.okz = p.okz
|
|
||||||
WHERE s.year = {year} AND
|
|
||||||
(year_from IS NULL OR year_from <= s.year) AND
|
|
||||||
(year_to IS NULL OR year_to >= s.year)
|
|
||||||
ORDER BY c.mgnr, t.sortid, t.attrid, c.cultid, c.gstnr;
|
|
||||||
""").ToListAsync();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Keyless]
|
|
||||||
public class MemberAreaCmtsRow {
|
|
||||||
[Column("mgnr")]
|
|
||||||
public int MgNr { get; set; }
|
|
||||||
[Column("name_1")]
|
|
||||||
public required string Name1 { get; set; }
|
|
||||||
[Column("name_2")]
|
|
||||||
public string? Name2 { get; set; }
|
|
||||||
[Column("address")]
|
|
||||||
public required string Address { get; set; }
|
|
||||||
[Column("plz")]
|
|
||||||
public int Plz { get; set; }
|
|
||||||
[Column("ort")]
|
|
||||||
public required string Locality { get; set; }
|
|
||||||
[Column("sortid")]
|
|
||||||
public required string SortId { get; set; }
|
|
||||||
[Column("attrid")]
|
|
||||||
public string? AttrId { get; set; }
|
|
||||||
[Column("cultid")]
|
|
||||||
public string? CultId { get; set; }
|
|
||||||
[Column("gstnr")]
|
|
||||||
public required string GstNr { get; set; }
|
|
||||||
[Column("area")]
|
|
||||||
public int Area { get; set; }
|
|
||||||
[Column("min_kg")]
|
|
||||||
public int MinKg { get; set; }
|
|
||||||
[Column("max_kg")]
|
|
||||||
public int MaxKg { get; set; }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+15
-15
@@ -5,7 +5,7 @@ using System.Linq;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace Elwig.Models.Dtos {
|
namespace Elwig.Models.Dtos {
|
||||||
class MemberAreaCmtTotalsData : DataTable<MemberAreaCmtTotalsRow> {
|
class MemberAreaComsData : DataTable<MemberAreaComsRow> {
|
||||||
|
|
||||||
private static readonly (string, string, string?, int)[] FieldNames = [
|
private static readonly (string, string, string?, int)[] FieldNames = [
|
||||||
("MgNr", "MgNr.", null, 12),
|
("MgNr", "MgNr.", null, 12),
|
||||||
@@ -21,19 +21,19 @@ namespace Elwig.Models.Dtos {
|
|||||||
("DeliveryRights", "Lieferrecht", "kg", 22),
|
("DeliveryRights", "Lieferrecht", "kg", 22),
|
||||||
];
|
];
|
||||||
|
|
||||||
public MemberAreaCmtTotalsData(IEnumerable<MemberAreaCmtTotalsRow> rows, int year) :
|
public MemberAreaComsData(IEnumerable<MemberAreaComsRow> rows, int year) :
|
||||||
base($"Gebundene Fläche", $"Gebundene Fläche pro Mitglied {year}", rows, FieldNames) {
|
base($"Flächenbindungen", $"Flächenbindungen pro Mitglied {year}", rows, FieldNames) {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<MemberAreaCmtTotalsData> ForSeason(DbSet<MemberAreaCmtTotalsRowSingle> table, int year) {
|
public static async Task<MemberAreaComsData> ForSeason(DbSet<MemberAreaComsRowSingle> table, int year) {
|
||||||
return new MemberAreaCmtTotalsData(
|
return new MemberAreaComsData(
|
||||||
(await FromDbSet(table, year)).GroupBy(
|
(await FromDbSet(table, year)).GroupBy(
|
||||||
r => r.MgNr,
|
r => r.MgNr,
|
||||||
(k, g) => new MemberAreaCmtTotalsRow(g)
|
(k, g) => new MemberAreaComsRow(g)
|
||||||
), year);
|
), year);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task<IEnumerable<MemberAreaCmtTotalsRowSingle>> FromDbSet(DbSet<MemberAreaCmtTotalsRowSingle> table, int year) {
|
private static async Task<IEnumerable<MemberAreaComsRowSingle>> FromDbSet(DbSet<MemberAreaComsRowSingle> table, int year) {
|
||||||
return await table.FromSql($"""
|
return await table.FromSql($"""
|
||||||
SELECT m.mgnr, m.name AS name_1,
|
SELECT m.mgnr, m.name AS name_1,
|
||||||
COALESCE(m.prefix || ' ', '') || m.given_name ||
|
COALESCE(m.prefix || ' ', '') || m.given_name ||
|
||||||
@@ -50,7 +50,7 @@ namespace Elwig.Models.Dtos {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class MemberAreaCmtTotalsRow {
|
public class MemberAreaComsRow {
|
||||||
public int MgNr;
|
public int MgNr;
|
||||||
public string Name1;
|
public string Name1;
|
||||||
public string? Name2;
|
public string? Name2;
|
||||||
@@ -63,7 +63,7 @@ namespace Elwig.Models.Dtos {
|
|||||||
public int[] DeliveryObligations;
|
public int[] DeliveryObligations;
|
||||||
public int[] DeliveryRights;
|
public int[] DeliveryRights;
|
||||||
|
|
||||||
public MemberAreaCmtTotalsRow(IEnumerable<MemberAreaCmtTotalsRowSingle> rows) {
|
public MemberAreaComsRow(IEnumerable<MemberAreaComsRowSingle> rows) {
|
||||||
var f = rows.First();
|
var f = rows.First();
|
||||||
MgNr = f.MgNr;
|
MgNr = f.MgNr;
|
||||||
Name1 = f.Name1;
|
Name1 = f.Name1;
|
||||||
@@ -71,16 +71,16 @@ namespace Elwig.Models.Dtos {
|
|||||||
Address = f.Address;
|
Address = f.Address;
|
||||||
Plz = f.Plz;
|
Plz = f.Plz;
|
||||||
Locality = f.Locality.Split(",")[0];
|
Locality = f.Locality.Split(",")[0];
|
||||||
SortIds = [.. rows.Select(r => r.VtrgId[..2])];
|
SortIds = rows.Select(r => r.VtrgId[..2]).ToArray();
|
||||||
AttrIds = [.. rows.Select(r => r.VtrgId[2..])];
|
AttrIds = rows.Select(r => r.VtrgId[2..]).ToArray();
|
||||||
Areas = [.. rows.Select(r => r.Area)];
|
Areas = rows.Select(r => r.Area).ToArray();
|
||||||
DeliveryObligations = [.. rows.Select(r => r.MinKg)];
|
DeliveryObligations = rows.Select(r => r.MinKg).ToArray();
|
||||||
DeliveryRights = [.. rows.Select(r => r.MaxKg)];
|
DeliveryRights = rows.Select(r => r.MaxKg).ToArray();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[Keyless]
|
[Keyless]
|
||||||
public class MemberAreaCmtTotalsRowSingle {
|
public class MemberAreaComsRowSingle {
|
||||||
[Column("mgnr")]
|
[Column("mgnr")]
|
||||||
public int MgNr { get; set; }
|
public int MgNr { get; set; }
|
||||||
[Column("name_1")]
|
[Column("name_1")]
|
||||||
@@ -25,7 +25,7 @@ namespace Elwig.Models.Dtos {
|
|||||||
("BillingPlz", "PLZ", null, 10),
|
("BillingPlz", "PLZ", null, 10),
|
||||||
("BillingLocality", "Ort", null, 60),
|
("BillingLocality", "Ort", null, 60),
|
||||||
("LfbisNr", "Betr.-Nr.", null, 20),
|
("LfbisNr", "Betr.-Nr.", null, 20),
|
||||||
("IsAccounting", "buchf.", null, 15),
|
("IsBuchführend", "buchf.", null, 15),
|
||||||
("IsOrganic", "Bio", null, 15),
|
("IsOrganic", "Bio", null, 15),
|
||||||
("IsActive", "aktiv", null, 15),
|
("IsActive", "aktiv", null, 15),
|
||||||
("EntryDate", "Eintritt", null, 20),
|
("EntryDate", "Eintritt", null, 20),
|
||||||
@@ -46,15 +46,15 @@ namespace Elwig.Models.Dtos {
|
|||||||
base(MemberList.Name, MemberList.Name, string.Join(" / ", filterNames), rows, FieldNames) {
|
base(MemberList.Name, MemberList.Name, string.Join(" / ", filterNames), rows, FieldNames) {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<MemberListData> FromQuery(IQueryable<Member> query, List<string> filterNames, IEnumerable<string> filterAreaCmt) {
|
public static async Task<MemberListData> FromQuery(IQueryable<Member> query, List<string> filterNames, IEnumerable<string> filterAreaCom) {
|
||||||
var areaCmts = await query.Include(m => m.AreaCommitments).ToDictionaryAsync(m => m.MgNr, m => Utils.ActiveAreaCommitments(m.AreaCommitments));
|
var areaComs = await query.Include(m => m.AreaCommitments).ToDictionaryAsync(m => m.MgNr, m => Utils.ActiveAreaCommitments(m.AreaCommitments));
|
||||||
return new((await query
|
return new((await query
|
||||||
.Include(m => m.Branch)
|
.Include(m => m.Branch)
|
||||||
.Include(m => m.TelephoneNumbers)
|
.Include(m => m.TelephoneNumbers)
|
||||||
.Include(m => m.EmailAddresses)
|
.Include(m => m.EmailAddresses)
|
||||||
.ToListAsync()).Select(m => new MemberListRow(m,
|
.ToListAsync()).Select(m => new MemberListRow(m,
|
||||||
areaCmts[m.MgNr].Sum(c => c.Area),
|
areaComs[m.MgNr].Sum(c => c.Area),
|
||||||
areaCmts[m.MgNr].Where(c => filterAreaCmt.Contains(c.VtrgId)).GroupBy(c => c.VtrgId).ToDictionary(g => g.Key, g => g.Sum(c => c.Area)))),
|
areaComs[m.MgNr].Where(c => filterAreaCom.Contains(c.VtrgId)).GroupBy(c => c.VtrgId).ToDictionary(g => g.Key, g => g.Sum(c => c.Area)))),
|
||||||
filterNames);
|
filterNames);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -83,7 +83,7 @@ namespace Elwig.Models.Dtos {
|
|||||||
public string? Bic;
|
public string? Bic;
|
||||||
public int? AreaCommitment;
|
public int? AreaCommitment;
|
||||||
public (string VtrgId, int Area)[] AreaCommitmentsFiltered;
|
public (string VtrgId, int Area)[] AreaCommitmentsFiltered;
|
||||||
public bool IsAccounting;
|
public bool IsBuchführend;
|
||||||
public bool IsOrganic;
|
public bool IsOrganic;
|
||||||
public bool IsActive;
|
public bool IsActive;
|
||||||
public DateOnly? EntryDate;
|
public DateOnly? EntryDate;
|
||||||
@@ -94,7 +94,7 @@ namespace Elwig.Models.Dtos {
|
|||||||
public string? AdditionalContact;
|
public string? AdditionalContact;
|
||||||
public string? Comment;
|
public string? Comment;
|
||||||
|
|
||||||
public MemberListRow(Member m, int? areaCmt = null, Dictionary<string, int>? filtered = null) {
|
public MemberListRow(Member m, int? areaCom = null, Dictionary<string, int>? filtered = null) {
|
||||||
MgNr = m.MgNr;
|
MgNr = m.MgNr;
|
||||||
Name1 = m.Name;
|
Name1 = m.Name;
|
||||||
AdminName1 = m.AdministrativeName1;
|
AdminName1 = m.AdministrativeName1;
|
||||||
@@ -118,7 +118,7 @@ namespace Elwig.Models.Dtos {
|
|||||||
UstIdNr = m.UstIdNr;
|
UstIdNr = m.UstIdNr;
|
||||||
Iban = m.Iban != null ? Utils.FormatIban(m.Iban) : null;
|
Iban = m.Iban != null ? Utils.FormatIban(m.Iban) : null;
|
||||||
Bic = m.Bic;
|
Bic = m.Bic;
|
||||||
IsAccounting = m.IsAccounting;
|
IsBuchführend = m.IsBuchführend;
|
||||||
IsOrganic = m.IsOrganic;
|
IsOrganic = m.IsOrganic;
|
||||||
IsActive = m.IsActive;
|
IsActive = m.IsActive;
|
||||||
EntryDate = m.EntryDate;
|
EntryDate = m.EntryDate;
|
||||||
@@ -133,7 +133,7 @@ namespace Elwig.Models.Dtos {
|
|||||||
.Distinct()
|
.Distinct()
|
||||||
.Concat(m.EmailAddresses.OrderBy(a => a.Nr).Select(a => a.Address).Except([EmailAddress])));
|
.Concat(m.EmailAddresses.OrderBy(a => a.Nr).Select(a => a.Address).Except([EmailAddress])));
|
||||||
Comment = m.Comment;
|
Comment = m.Comment;
|
||||||
AreaCommitment = areaCmt == 0 ? null : areaCmt;
|
AreaCommitment = areaCom == 0 ? null : areaCom;
|
||||||
AreaCommitmentsFiltered = filtered != null ? filtered.OrderBy(f => f.Key).Select(f => (f.Key, f.Value)).ToArray() : [];
|
AreaCommitmentsFiltered = filtered != null ? filtered.OrderBy(f => f.Key).Select(f => (f.Key, f.Value)).ToArray() : [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,142 +0,0 @@
|
|||||||
using Elwig.Helpers;
|
|
||||||
using Elwig.Models.Entities;
|
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
|
|
||||||
namespace Elwig.Models.Dtos {
|
|
||||||
public class MemberMovementData : DataTable<MemberMovementDataRow> {
|
|
||||||
|
|
||||||
private static readonly (string, string, string?, int)[] FieldNames = [
|
|
||||||
("Type", "\u2026 durch", null, 30),
|
|
||||||
("MgNr", "MgNr.", null, 12),
|
|
||||||
("Name1", "Name", null, 40),
|
|
||||||
("Name2", "Vorname", null, 25),
|
|
||||||
("Address", "Adresse", null, 50),
|
|
||||||
("Plz", "PLZ", null, 10),
|
|
||||||
("Locality", "Ort", null, 50),
|
|
||||||
("Date", "Datum", null, 20),
|
|
||||||
("SharesOld", "GA\nalt", null, 10),
|
|
||||||
("SharesDiff", "GA\nDiff.", null, 10),
|
|
||||||
("SharesNew", "GA\nneu", null, 10),
|
|
||||||
("Costs", "Kosten", "€", 15),
|
|
||||||
];
|
|
||||||
|
|
||||||
private MemberMovementData(string name, IEnumerable<(string? Name, IEnumerable<MemberMovementDataRow> Rows)> sections) :
|
|
||||||
base("Mitgl.-Bewegungen", name, sections, FieldNames) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public static MemberMovementData FromMemberHistory(string name, IEnumerable<MemberHistory> rows, Dictionary<int, SortedDictionary<DateOnly, MemberHistoryPoint>> history) {
|
|
||||||
(string? Name, List<MemberMovementDataRow> Rows)[] sections = [
|
|
||||||
("Beitritt", []),
|
|
||||||
("Nachzeichnung (GA)", []),
|
|
||||||
("Überschreibung", []),
|
|
||||||
("Kündigung (GA)", []),
|
|
||||||
("Austritt", []),
|
|
||||||
];
|
|
||||||
foreach (var h in rows.OrderBy(r => r.DateNotice).ThenBy(r => r.ToMgNr).ThenBy(r => r.FromMgNr)) {
|
|
||||||
|
|
||||||
int cat;
|
|
||||||
if (h.ToMgNr == h.FromMgNr) {
|
|
||||||
// Umwandlung
|
|
||||||
if (h.ToType == BusinessShareType.Dormant) {
|
|
||||||
// Kündigung (GA)
|
|
||||||
cat = 3;
|
|
||||||
} else if (h.FromType == h.ToType) {
|
|
||||||
// Überschreibung
|
|
||||||
cat = 2;
|
|
||||||
} else {
|
|
||||||
throw new NotImplementedException();
|
|
||||||
}
|
|
||||||
} else if (h.DateNotice <= h.ToMember?.EntryDate && h.DateNotice >= h.FromMember?.ExitDate) {
|
|
||||||
// Überschreibung
|
|
||||||
cat = 2;
|
|
||||||
} else if (h.DateNotice <= h.ToMember?.EntryDate) {
|
|
||||||
// Beitritt
|
|
||||||
cat = 0;
|
|
||||||
} else if (h.DateNotice >= h.FromMember?.ExitDate) {
|
|
||||||
// Austritt
|
|
||||||
cat = 4;
|
|
||||||
} else if (h.ToMember == null) {
|
|
||||||
// Auszahlung
|
|
||||||
continue;
|
|
||||||
} else {
|
|
||||||
// Nachzeichnung (GA)
|
|
||||||
cat = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
Member a;
|
|
||||||
Member? b = null;
|
|
||||||
if (h.FromMember != null && h.ToMember != null) {
|
|
||||||
if (cat <= 1) {
|
|
||||||
a = h.ToMember;
|
|
||||||
b = h.FromMember;
|
|
||||||
} else {
|
|
||||||
a = h.FromMember;
|
|
||||||
b = h.ToMember;
|
|
||||||
}
|
|
||||||
} else if (h.FromMember != null) {
|
|
||||||
a = h.FromMember;
|
|
||||||
} else if (h.ToMember != null) {
|
|
||||||
a = h.ToMember;
|
|
||||||
} else {
|
|
||||||
throw new ArgumentException();
|
|
||||||
}
|
|
||||||
|
|
||||||
var oldA = history[a.MgNr].GetValueOrDefault(h.DateNotice);
|
|
||||||
var d = new MemberMovementDataRow {
|
|
||||||
Type = [h.ReasonPretty],
|
|
||||||
|
|
||||||
MgNr = [a.MgNr],
|
|
||||||
Name1 = [a.Name],
|
|
||||||
Name2 = [a.AdministrativeName2],
|
|
||||||
Address = [a.Address],
|
|
||||||
Plz = [a.PostalDest.AtPlz!.Plz],
|
|
||||||
Locality = [a.PostalDest.AtPlz.Ort.Name],
|
|
||||||
|
|
||||||
Date = h.DateNotice,
|
|
||||||
SharesOld = [oldA.Shares + oldA.SharesRed + oldA.SharesWhite],
|
|
||||||
SharesDiff = [cat != 3 && a == h.ToMember ? h.Shares : -h.Shares],
|
|
||||||
Costs = [h.FromMember == null ? h.TotalValue : null],
|
|
||||||
};
|
|
||||||
d.SharesNew = [d.SharesOld[^1] + (h.FromMgNr == h.ToMgNr ? 0 : d.SharesDiff[^1])];
|
|
||||||
|
|
||||||
if (b != null) {
|
|
||||||
var oldB = history[b.MgNr].GetValueOrDefault(h.DateNotice);
|
|
||||||
d.Type = [..d.Type, "\u2026 " + (cat <= 1 ? "von" : "an")];
|
|
||||||
|
|
||||||
d.MgNr = [.. d.MgNr, b.MgNr];
|
|
||||||
d.Name1 = [.. d.Name1, b.Name];
|
|
||||||
d.Name2 = [.. d.Name2, b.AdministrativeName2];
|
|
||||||
d.Address = [.. d.Address, b.Address];
|
|
||||||
d.Plz = [.. d.Plz, b.PostalDest.AtPlz!.Plz];
|
|
||||||
d.Locality = [.. d.Locality, b.PostalDest.AtPlz.Ort.Name];
|
|
||||||
|
|
||||||
d.SharesOld = [.. d.SharesOld, oldB.Shares + oldB.SharesRed + oldB.SharesWhite];
|
|
||||||
d.SharesDiff = [.. d.SharesDiff, b == h.ToMember ? h.Shares : -h.Shares];
|
|
||||||
d.SharesNew = [.. d.SharesNew, d.SharesOld[^1] + d.SharesDiff[^1]];
|
|
||||||
}
|
|
||||||
|
|
||||||
sections[cat].Rows.Add(d);
|
|
||||||
}
|
|
||||||
return new MemberMovementData($"Mitglieder-Bewegungen {name}", sections.Select(s => (s.Name, (IEnumerable<MemberMovementDataRow>)s.Rows)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public class MemberMovementDataRow {
|
|
||||||
public string[] Type = [];
|
|
||||||
|
|
||||||
public int[] MgNr = [];
|
|
||||||
public string[] Name1 = [];
|
|
||||||
public string?[] Name2 = [];
|
|
||||||
public string[] Address = [];
|
|
||||||
public int[] Plz = [];
|
|
||||||
public string[] Locality = [];
|
|
||||||
|
|
||||||
public DateOnly Date;
|
|
||||||
public int?[] SharesOld = [];
|
|
||||||
public int[] SharesDiff = [];
|
|
||||||
public int?[] SharesNew = [];
|
|
||||||
public decimal?[] Costs = [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -18,9 +18,9 @@ namespace Elwig.Models.Dtos {
|
|||||||
("Cultivation", "Bewirt.", null, 20),
|
("Cultivation", "Bewirt.", null, 20),
|
||||||
("QualityLevel", "Qualitätsstufe", null, 30),
|
("QualityLevel", "Qualitätsstufe", null, 30),
|
||||||
("Oe", "Gradation", "°Oe", 20),
|
("Oe", "Gradation", "°Oe", 20),
|
||||||
("UnCtrd", "ungebunden", "kg|€/kg|€/kg", 60),
|
("Ungeb", "ungebunden", "kg|€/kg|€/kg", 60),
|
||||||
("LowCtrd", "attributlos gebunden", "kg|€/kg|€/kg", 60),
|
("LowGeb", "attributlos gebunden", "kg|€/kg|€/kg", 60),
|
||||||
("Ctrd", "gebunden", "kg|€/kg|€/kg", 60),
|
("Geb", "gebunden", "kg|€/kg|€/kg", 60),
|
||||||
("Amount", "Gesamt", "€", 25),
|
("Amount", "Gesamt", "€", 25),
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -31,9 +31,9 @@ namespace Elwig.Models.Dtos {
|
|||||||
string? Cultivation,
|
string? Cultivation,
|
||||||
string QualityLevel,
|
string QualityLevel,
|
||||||
double Oe,
|
double Oe,
|
||||||
(int Weight, decimal? MinPrice, decimal? MaxPrice) UnCtrd,
|
(int Weight, decimal? MinPrice, decimal? MaxPrice) Ungeb,
|
||||||
(int Weight, decimal? MinPrice, decimal? MaxPrice) LowCtrd,
|
(int Weight, decimal? MinPrice, decimal? MaxPrice) LowGeb,
|
||||||
(int Weight, decimal? MinPrice, decimal? MaxPrice) Ctrd,
|
(int Weight, decimal? MinPrice, decimal? MaxPrice) Geb,
|
||||||
decimal Amount
|
decimal Amount
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -44,9 +44,9 @@ namespace Elwig.Models.Dtos {
|
|||||||
public static async Task<PaymentVariantSummaryData> ForPaymentVariant(PaymentVar v, DbSet<PaymentVariantSummaryRow> table) {
|
public static async Task<PaymentVariantSummaryData> ForPaymentVariant(PaymentVar v, DbSet<PaymentVariantSummaryRow> table) {
|
||||||
return new(v, (await FromDbSet(table, v.Year, v.AvNr))
|
return new(v, (await FromDbSet(table, v.Year, v.AvNr))
|
||||||
.Select(r => new PaymentRow(r.Type, r.Variety, r.Attribute, r.Cultivation, r.QualityLevel, r.Oe,
|
.Select(r => new PaymentRow(r.Type, r.Variety, r.Attribute, r.Cultivation, r.QualityLevel, r.Oe,
|
||||||
(r.WeightUnCtrd, r.MinPriceUnCtrd != null ? Utils.DecFromDb(r.MinPriceUnCtrd.Value, v.Season.Precision) : null, r.MaxPriceUnCtrd != null ? Utils.DecFromDb(r.MaxPriceUnCtrd.Value, v.Season.Precision) : null),
|
(r.WeightUngeb, r.MinPriceUngeb != null ? Utils.DecFromDb(r.MinPriceUngeb.Value, v.Season.Precision) : null, r.MaxPriceUngeb != null ? Utils.DecFromDb(r.MaxPriceUngeb.Value, v.Season.Precision) : null),
|
||||||
(r.WeightLowCtrd, r.MinPriceLowCtrd != null ? Utils.DecFromDb(r.MinPriceLowCtrd.Value, v.Season.Precision) : null, r.MaxPriceLowCtrd != null ? Utils.DecFromDb(r.MaxPriceLowCtrd.Value, v.Season.Precision) : null),
|
(r.WeightLowGeb, r.MinPriceLowGeb != null ? Utils.DecFromDb(r.MinPriceLowGeb.Value, v.Season.Precision) : null, r.MaxPriceLowGeb != null ? Utils.DecFromDb(r.MaxPriceLowGeb.Value, v.Season.Precision) : null),
|
||||||
(r.WeightCtrd, r.MinPriceCtrd != null ? Utils.DecFromDb(r.MinPriceCtrd.Value, v.Season.Precision) : null, r.MaxPriceCtrd != null ? Utils.DecFromDb(r.MaxPriceCtrd.Value, v.Season.Precision) : null),
|
(r.WeightGeb, r.MinPriceGeb != null ? Utils.DecFromDb(r.MinPriceGeb.Value, v.Season.Precision) : null, r.MaxPriceGeb != null ? Utils.DecFromDb(r.MaxPriceGeb.Value, v.Season.Precision) : null),
|
||||||
Utils.DecFromDb(r.Amount, v.Season.Precision)))
|
Utils.DecFromDb(r.Amount, v.Season.Precision)))
|
||||||
.ToArray());
|
.ToArray());
|
||||||
}
|
}
|
||||||
@@ -59,15 +59,15 @@ namespace Elwig.Models.Dtos {
|
|||||||
c.name AS cultivation,
|
c.name AS cultivation,
|
||||||
q.name AS quality_level,
|
q.name AS quality_level,
|
||||||
ROUND(kmw * (4.54 + 0.022 * kmw)) AS oe,
|
ROUND(kmw * (4.54 + 0.022 * kmw)) AS oe,
|
||||||
SUM(IIF(w.discr = '_', w.value, 0)) AS weight_unctrd,
|
SUM(IIF(w.discr = '_', w.value, 0)) AS weight_ungeb,
|
||||||
MIN(IIF(w.discr = '_', b.price, NULL)) AS min_price_unctrd,
|
MIN(IIF(w.discr = '_', b.price, NULL)) AS min_price_ungeb,
|
||||||
MAX(IIF(w.discr = '_', b.price, NULL)) AS max_price_unctrd,
|
MAX(IIF(w.discr = '_', b.price, NULL)) AS max_price_ungeb,
|
||||||
SUM(IIF(w.discr NOT IN (COALESCE(p.attrid, ''), '_'), w.value, 0)) AS weight_lowctrd,
|
SUM(IIF(w.discr NOT IN (COALESCE(p.attrid, ''), '_'), w.value, 0)) AS weight_lowgeb,
|
||||||
MIN(IIF(w.discr NOT IN (COALESCE(p.attrid, ''), '_'), b.price, NULL)) AS min_price_lowctrd,
|
MIN(IIF(w.discr NOT IN (COALESCE(p.attrid, ''), '_'), b.price, NULL)) AS min_price_lowgeb,
|
||||||
MAX(IIF(w.discr NOT IN (COALESCE(p.attrid, ''), '_'), b.price, NULL)) AS max_price_lowctrd,
|
MAX(IIF(w.discr NOT IN (COALESCE(p.attrid, ''), '_'), b.price, NULL)) AS max_price_lowgeb,
|
||||||
SUM(IIF(w.discr = COALESCE(p.attrid, ''), w.value, 0)) AS weight_ctrd,
|
SUM(IIF(w.discr = COALESCE(p.attrid, ''), w.value, 0)) AS weight_geb,
|
||||||
MIN(IIF(w.discr = COALESCE(p.attrid, ''), b.price, NULL)) AS min_price_ctrd,
|
MIN(IIF(w.discr = COALESCE(p.attrid, ''), b.price, NULL)) AS min_price_geb,
|
||||||
MAX(IIF(w.discr = COALESCE(p.attrid, ''), b.price, NULL)) AS max_price_ctrd,
|
MAX(IIF(w.discr = COALESCE(p.attrid, ''), b.price, NULL)) AS max_price_geb,
|
||||||
SUM(b.amount) AS amount
|
SUM(b.amount) AS amount
|
||||||
FROM payment_delivery_part_bucket b
|
FROM payment_delivery_part_bucket b
|
||||||
LEFT JOIN delivery_part_bucket w ON (w.year, w.did, w.dpnr, w.bktnr) = (b.year, b.did, b.dpnr, b.bktnr)
|
LEFT JOIN delivery_part_bucket w ON (w.year, w.did, w.dpnr, w.bktnr) = (b.year, b.did, b.dpnr, b.bktnr)
|
||||||
@@ -97,24 +97,24 @@ namespace Elwig.Models.Dtos {
|
|||||||
public required string QualityLevel { get; set; }
|
public required string QualityLevel { get; set; }
|
||||||
[Column("oe")]
|
[Column("oe")]
|
||||||
public double Oe { get; set; }
|
public double Oe { get; set; }
|
||||||
[Column("weight_unctrd")]
|
[Column("weight_ungeb")]
|
||||||
public int WeightUnCtrd { get; set; }
|
public int WeightUngeb { get; set; }
|
||||||
[Column("min_price_unctrd")]
|
[Column("min_price_ungeb")]
|
||||||
public long? MinPriceUnCtrd { get; set; }
|
public long? MinPriceUngeb { get; set; }
|
||||||
[Column("max_price_unctrd")]
|
[Column("max_price_ungeb")]
|
||||||
public long? MaxPriceUnCtrd { get; set; }
|
public long? MaxPriceUngeb { get; set; }
|
||||||
[Column("weight_lowctrd")]
|
[Column("weight_lowgeb")]
|
||||||
public int WeightLowCtrd { get; set; }
|
public int WeightLowGeb { get; set; }
|
||||||
[Column("min_price_lowctrd")]
|
[Column("min_price_lowgeb")]
|
||||||
public long? MinPriceLowCtrd { get; set; }
|
public long? MinPriceLowGeb { get; set; }
|
||||||
[Column("max_price_lowctrd")]
|
[Column("max_price_lowgeb")]
|
||||||
public long? MaxPriceLowCtrd { get; set; }
|
public long? MaxPriceLowGeb { get; set; }
|
||||||
[Column("weight_ctrd")]
|
[Column("weight_geb")]
|
||||||
public int WeightCtrd { get; set; }
|
public int WeightGeb { get; set; }
|
||||||
[Column("min_price_ctrd")]
|
[Column("min_price_geb")]
|
||||||
public long? MinPriceCtrd { get; set; }
|
public long? MinPriceGeb { get; set; }
|
||||||
[Column("max_price_ctrd")]
|
[Column("max_price_geb")]
|
||||||
public long? MaxPriceCtrd { get; set; }
|
public long? MaxPriceGeb { get; set; }
|
||||||
[Column("amount")]
|
[Column("amount")]
|
||||||
public long Amount { get; set; }
|
public long Amount { get; set; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ namespace Elwig.Models.Dtos {
|
|||||||
("AttrId", "Attr.", null, 10),
|
("AttrId", "Attr.", null, 10),
|
||||||
("CultId", "Bewirt.", null, 15),
|
("CultId", "Bewirt.", null, 15),
|
||||||
("QualId", "Qual.", null, 15),
|
("QualId", "Qual.", null, 15),
|
||||||
("Contracted", "gebunden", null, 20),
|
("Geb", "gebunden", null, 20),
|
||||||
("Weight", "Menge", "kg", 20),
|
("Weight", "Menge", "kg", 20),
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -26,13 +26,14 @@ namespace Elwig.Models.Dtos {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static async Task<IEnumerable<WeightBreakdownRow>> FromDbSet(DbSet<WeightBreakdownRow> table, int year, string? zwstid) {
|
private static async Task<IEnumerable<WeightBreakdownRow>> FromDbSet(DbSet<WeightBreakdownRow> table, int year, string? zwstid) {
|
||||||
return await table.FromSql($"""
|
zwstid = zwstid == null ? "NULL" : $"'{zwstid}'";
|
||||||
SELECT type, sortid, attrid, cultid, v.qualid, contracted, SUM(weight) AS weight
|
return await table.FromSqlRaw($"""
|
||||||
|
SELECT type, sortid, attrid, cultid, v.qualid, geb, SUM(weight) AS weight
|
||||||
FROM v_stat_total v
|
FROM v_stat_total v
|
||||||
LEFT JOIN wine_quality_level q ON q.qualid = v.qualid
|
LEFT JOIN wine_quality_level q ON q.qualid = v.qualid
|
||||||
WHERE year = {year} AND ({zwstid} IS NULL OR zwstid = {zwstid})
|
WHERE year = {year} AND ({zwstid} IS NULL OR zwstid = {zwstid})
|
||||||
GROUP BY type, sortid, attrid, cultid, v.qualid, contracted
|
GROUP BY type, sortid, attrid, cultid, v.qualid, geb
|
||||||
ORDER BY type DESC, sortid, attrid, cultid, q.min_kmw, contracted
|
ORDER BY type DESC, sortid, attrid, cultid, q.min_kmw, geb
|
||||||
""").ToListAsync();
|
""").ToListAsync();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -49,8 +50,8 @@ namespace Elwig.Models.Dtos {
|
|||||||
public string? CultId { get; set; }
|
public string? CultId { get; set; }
|
||||||
[Column("qualid")]
|
[Column("qualid")]
|
||||||
public required string QualId { get; set; }
|
public required string QualId { get; set; }
|
||||||
[Column("contracted")]
|
[Column("geb")]
|
||||||
public required string Contracted { get; set; }
|
public required string Geb { get; set; }
|
||||||
[Column("weight")]
|
[Column("weight")]
|
||||||
public int Weight { get; set; }
|
public int Weight { get; set; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,15 +6,15 @@ namespace Elwig.Models.Entities {
|
|||||||
[Table("AT_gem"), PrimaryKey("Gkz")]
|
[Table("AT_gem"), PrimaryKey("Gkz")]
|
||||||
public class AT_Gem {
|
public class AT_Gem {
|
||||||
[Column("gkz")]
|
[Column("gkz")]
|
||||||
public int Gkz { get; init; }
|
public int Gkz { get; private set; }
|
||||||
|
|
||||||
[Column("name")]
|
[Column("name")]
|
||||||
public required string Name { get; init; }
|
public string Name { get; private set; } = null!;
|
||||||
|
|
||||||
[InverseProperty(nameof(AT_Kg.Gem))]
|
[InverseProperty(nameof(AT_Kg.Gem))]
|
||||||
public virtual ICollection<AT_Kg> Kgs { get; init; } = null!;
|
public virtual ICollection<AT_Kg> Kgs { get; private set; } = null!;
|
||||||
|
|
||||||
[InverseProperty(nameof(WbGem.AtGem))]
|
[InverseProperty(nameof(WbGem.AtGem))]
|
||||||
public virtual WbGem? WbGem { get; init; }
|
public virtual WbGem? WbGem { get; private set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,18 +5,18 @@ namespace Elwig.Models.Entities {
|
|||||||
[Table("AT_kg"), PrimaryKey("KgNr")]
|
[Table("AT_kg"), PrimaryKey("KgNr")]
|
||||||
public class AT_Kg {
|
public class AT_Kg {
|
||||||
[Column("kgnr")]
|
[Column("kgnr")]
|
||||||
public int KgNr { get; init; }
|
public int KgNr { get; private set; }
|
||||||
|
|
||||||
[Column("gkz")]
|
[Column("gkz")]
|
||||||
public int Gkz { get; init; }
|
public int Gkz { get; private set; }
|
||||||
|
|
||||||
[Column("name")]
|
[Column("name")]
|
||||||
public required string Name { get; init; }
|
public string Name { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("Gkz")]
|
[ForeignKey("Gkz")]
|
||||||
public virtual AT_Gem Gem { get; init; } = null!;
|
public virtual AT_Gem Gem { get; private set; } = null!;
|
||||||
|
|
||||||
[InverseProperty(nameof(WbKg.AtKg))]
|
[InverseProperty(nameof(WbKg.AtKg))]
|
||||||
public virtual WbKg? WbKg { get; init; }
|
public virtual WbKg? WbKg { get; private set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,21 +5,21 @@ namespace Elwig.Models.Entities {
|
|||||||
[Table("AT_ort"), PrimaryKey("Okz")]
|
[Table("AT_ort"), PrimaryKey("Okz")]
|
||||||
public class AT_Ort {
|
public class AT_Ort {
|
||||||
[Column("okz")]
|
[Column("okz")]
|
||||||
public int Okz { get; init; }
|
public int Okz { get; private set; }
|
||||||
|
|
||||||
[Column("gkz")]
|
[Column("gkz")]
|
||||||
public int Gkz { get; init; }
|
public int Gkz { get; private set; }
|
||||||
|
|
||||||
[Column("kgnr")]
|
[Column("kgnr")]
|
||||||
public int? KgNr { get; init; }
|
public int? KgNr { get; private set; }
|
||||||
|
|
||||||
[Column("name")]
|
[Column("name")]
|
||||||
public required string Name { get; init; }
|
public string Name { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("Gkz")]
|
[ForeignKey("Gkz")]
|
||||||
public virtual AT_Gem Gem { get; init; } = null!;
|
public virtual AT_Gem Gem { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("KgNr")]
|
[ForeignKey("KgNr")]
|
||||||
public virtual AT_Kg? Kg { get; init; }
|
public virtual AT_Kg? Kg { get; private set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,27 +6,27 @@ namespace Elwig.Models.Entities {
|
|||||||
[Table("AT_plz"), PrimaryKey("Plz")]
|
[Table("AT_plz"), PrimaryKey("Plz")]
|
||||||
public class AT_Plz {
|
public class AT_Plz {
|
||||||
[Column("plz")]
|
[Column("plz")]
|
||||||
public int Plz { get; init; }
|
public int Plz { get; private set; }
|
||||||
|
|
||||||
[Column("ort")]
|
[Column("ort")]
|
||||||
public required string Ort { get; init; }
|
public string Ort { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("blnr")]
|
[Column("blnr")]
|
||||||
public int BlNr { get; init; }
|
public int BlNr { get; private set; }
|
||||||
|
|
||||||
[Column("type")]
|
[Column("type")]
|
||||||
public required string Type { get; init; }
|
public string Type { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("internal")]
|
[Column("internal")]
|
||||||
public bool IsInternal { get; init; }
|
public bool IsInternal { get; private set; }
|
||||||
|
|
||||||
[Column("addressable")]
|
[Column("addressable")]
|
||||||
public bool IsAddressable { get; init; }
|
public bool IsAddressable { get; private set; }
|
||||||
|
|
||||||
[Column("po_box")]
|
[Column("po_box")]
|
||||||
public bool IsPoBox { get; init; }
|
public bool IsPoBox { get; private set; }
|
||||||
|
|
||||||
[InverseProperty(nameof(AT_PlzDest.AtPlz))]
|
[InverseProperty(nameof(AT_PlzDest.AtPlz))]
|
||||||
public virtual ICollection<AT_PlzDest> Orte { get; init; } = null!;
|
public virtual ICollection<AT_PlzDest> Orte { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,30 +6,27 @@ namespace Elwig.Models.Entities {
|
|||||||
[Table("AT_plz_dest"), PrimaryKey("Id"), Index("Plz", "Okz", IsUnique = true)]
|
[Table("AT_plz_dest"), PrimaryKey("Id"), Index("Plz", "Okz", IsUnique = true)]
|
||||||
public class AT_PlzDest {
|
public class AT_PlzDest {
|
||||||
[Column("plz")]
|
[Column("plz")]
|
||||||
public int Plz { get; init; }
|
public int Plz { get; private set; }
|
||||||
|
|
||||||
[Column("okz")]
|
[Column("okz")]
|
||||||
public int Okz { get; init; }
|
public int Okz { get; private set; }
|
||||||
|
|
||||||
[Column("country")]
|
[Column("country")]
|
||||||
public int CountryNum { get; init; }
|
public int CountryNum { get; private set; }
|
||||||
|
|
||||||
[Column("id")]
|
[Column("id")]
|
||||||
public required string Id { get; init; }
|
public string Id { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("dest")]
|
[Column("dest")]
|
||||||
public required string Dest { get; init; }
|
public string Dest { get; private set; } = null!;
|
||||||
|
|
||||||
[NotMapped]
|
|
||||||
public string FullDest => $"{Ort.Name} ({Dest})";
|
|
||||||
|
|
||||||
[ForeignKey("Plz")]
|
[ForeignKey("Plz")]
|
||||||
public virtual AT_Plz AtPlz { get; init; } = null!;
|
public virtual AT_Plz AtPlz { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("Okz")]
|
[ForeignKey("Okz")]
|
||||||
public virtual AT_Ort Ort { get; init; } = null!;
|
public virtual AT_Ort Ort { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("CountryNum")]
|
[ForeignKey("CountryNum")]
|
||||||
public virtual Country Country { get; init; } = null!;
|
public virtual Country Country { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,7 @@ using System.ComponentModel.DataAnnotations.Schema;
|
|||||||
|
|
||||||
namespace Elwig.Models.Entities {
|
namespace Elwig.Models.Entities {
|
||||||
[Table("area_commitment"), PrimaryKey("FbNr", "RevNr")]
|
[Table("area_commitment"), PrimaryKey("FbNr", "RevNr")]
|
||||||
public class AreaCmt {
|
public class AreaCom {
|
||||||
[Column("fbnr")]
|
[Column("fbnr")]
|
||||||
public int FbNr { get; set; }
|
public int FbNr { get; set; }
|
||||||
|
|
||||||
@@ -65,15 +65,15 @@ namespace Elwig.Models.Entities {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[ForeignKey("FbNr")]
|
[ForeignKey("FbNr")]
|
||||||
public virtual AreaCmtContract Contract { get; init; } = null!;
|
public virtual AreaComContract Contract { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("MgNr")]
|
[ForeignKey("MgNr")]
|
||||||
public virtual Member Member { get; init; } = null!;
|
public virtual Member Member { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("VtrgId")]
|
[ForeignKey("VtrgId")]
|
||||||
public virtual AreaCmtType AreaCmtType { get; init; } = null!;
|
public virtual AreaComType AreaComType { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("CultId")]
|
[ForeignKey("CultId")]
|
||||||
public virtual WineCult? WineCult { get; init; }
|
public virtual WineCult? WineCult { get; private set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,7 @@ using System.Linq;
|
|||||||
|
|
||||||
namespace Elwig.Models.Entities {
|
namespace Elwig.Models.Entities {
|
||||||
[Table("area_commitment_contract"), PrimaryKey("FbNr")]
|
[Table("area_commitment_contract"), PrimaryKey("FbNr")]
|
||||||
public class AreaCmtContract {
|
public class AreaComContract {
|
||||||
[Column("fbnr")]
|
[Column("fbnr")]
|
||||||
public int FbNr { get; set; }
|
public int FbNr { get; set; }
|
||||||
|
|
||||||
@@ -53,16 +53,16 @@ namespace Elwig.Models.Entities {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[ForeignKey("KgNr")]
|
[ForeignKey("KgNr")]
|
||||||
public virtual WbKg Kg { get; init; } = null!;
|
public virtual WbKg Kg { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("KgNr, RdNr")]
|
[ForeignKey("KgNr, RdNr")]
|
||||||
public virtual WbRd? Rd { get; init; }
|
public virtual WbRd? Rd { get; private set; }
|
||||||
|
|
||||||
[InverseProperty(nameof(AreaCmt.Contract))]
|
[InverseProperty(nameof(AreaCom.Contract))]
|
||||||
public virtual ICollection<AreaCmt> Revisions { get; init; } = null!;
|
public virtual ICollection<AreaCom> Revisions { get; private set; } = null!;
|
||||||
|
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public AreaCmt? Latest => Revisions.OrderBy(r => r.RevNr).LastOrDefault();
|
public AreaCom? Latest => Revisions.OrderBy(r => r.RevNr).LastOrDefault();
|
||||||
|
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public int? YearFrom => Revisions.Any(r => r.YearFrom == null) ? null : Revisions.Min(r => r.YearFrom);
|
public int? YearFrom => Revisions.Any(r => r.YearFrom == null) ? null : Revisions.Min(r => r.YearFrom);
|
||||||
@@ -5,7 +5,7 @@ using IndexAttribute = Microsoft.EntityFrameworkCore.IndexAttribute;
|
|||||||
|
|
||||||
namespace Elwig.Models.Entities {
|
namespace Elwig.Models.Entities {
|
||||||
[Table("area_commitment_type"), PrimaryKey("VtrgId"), Index("SortId", "AttrId", "Discriminator", IsUnique = true)]
|
[Table("area_commitment_type"), PrimaryKey("VtrgId"), Index("SortId", "AttrId", "Discriminator", IsUnique = true)]
|
||||||
public class AreaCmtType {
|
public class AreaComType {
|
||||||
[Column("vtrgid")]
|
[Column("vtrgid")]
|
||||||
public required string VtrgId { get; set; }
|
public required string VtrgId { get; set; }
|
||||||
|
|
||||||
@@ -46,10 +46,10 @@ namespace Elwig.Models.Entities {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[ForeignKey("SortId")]
|
[ForeignKey("SortId")]
|
||||||
public virtual WineVar WineVar { get; init; } = null!;
|
public virtual WineVar WineVar { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("AttrId")]
|
[ForeignKey("AttrId")]
|
||||||
public virtual WineAttr? WineAttr { get; init; }
|
public virtual WineAttr? WineAttr { get; private set; }
|
||||||
|
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public string DisplayName => WineVar.Name + (WineAttr != null ? $" {WineAttr.Name}" : "") + (Discriminator != null ? $" ({Discriminator})" : "");
|
public string DisplayName => WineVar.Name + (WineAttr != null ? $" {WineAttr.Name}" : "") + (Discriminator != null ? $" ({Discriminator})" : "");
|
||||||
@@ -20,12 +20,12 @@ namespace Elwig.Models.Entities {
|
|||||||
public required string Address { get; set; }
|
public required string Address { get; set; }
|
||||||
|
|
||||||
[ForeignKey("MgNr")]
|
[ForeignKey("MgNr")]
|
||||||
public virtual Member Member { get; init; } = null!;
|
public virtual Member Member { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("CountryNum")]
|
[ForeignKey("CountryNum")]
|
||||||
public virtual Country Country { get; init; } = null!;
|
public virtual Country Country { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("CountryNum, PostalDestId")]
|
[ForeignKey("CountryNum, PostalDestId")]
|
||||||
public virtual PostalDest PostalDest { get; init; } = null!;
|
public virtual PostalDest PostalDest { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -22,10 +22,10 @@ namespace Elwig.Models.Entities {
|
|||||||
public string? Address { get; set; }
|
public string? Address { get; set; }
|
||||||
|
|
||||||
[ForeignKey("CountryNum")]
|
[ForeignKey("CountryNum")]
|
||||||
public virtual Country? Country { get; init; }
|
public virtual Country? Country { get; private set; }
|
||||||
|
|
||||||
[ForeignKey("CountryNum, PostalDestId")]
|
[ForeignKey("CountryNum, PostalDestId")]
|
||||||
public virtual PostalDest? PostalDest { get; init; }
|
public virtual PostalDest? PostalDest { get; private set; }
|
||||||
|
|
||||||
[Column("phone_nr")]
|
[Column("phone_nr")]
|
||||||
public string? PhoneNr { get; set; }
|
public string? PhoneNr { get; set; }
|
||||||
@@ -37,6 +37,6 @@ namespace Elwig.Models.Entities {
|
|||||||
public string? MobileNr { get; set; }
|
public string? MobileNr { get; set; }
|
||||||
|
|
||||||
[InverseProperty(nameof(Member.Branch))]
|
[InverseProperty(nameof(Member.Branch))]
|
||||||
public virtual ICollection<Member> Members { get; init; } = null!;
|
public virtual ICollection<Member> Members { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,18 +6,18 @@ namespace Elwig.Models.Entities {
|
|||||||
[Table("country"), PrimaryKey("Num"), Index("Alpha2", IsUnique = true), Index("Alpha3", IsUnique = true)]
|
[Table("country"), PrimaryKey("Num"), Index("Alpha2", IsUnique = true), Index("Alpha3", IsUnique = true)]
|
||||||
public class Country {
|
public class Country {
|
||||||
[Column("num")]
|
[Column("num")]
|
||||||
public int Num { get; init; }
|
public int Num { get; private set; }
|
||||||
|
|
||||||
[Column("alpha2")]
|
[Column("alpha2")]
|
||||||
public required string Alpha2 { get; init; }
|
public string Alpha2 { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("alpha3")]
|
[Column("alpha3")]
|
||||||
public required string Alpha3 { get; init; }
|
public string Alpha3 { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("name")]
|
[Column("name")]
|
||||||
public required string Name { get; init; }
|
public string Name { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("is_visible")]
|
[Column("is_visible")]
|
||||||
public bool IsVisible { get; init; }
|
public bool IsVisible { get; private set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -47,14 +47,14 @@ namespace Elwig.Models.Entities {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Column("vat_amount")]
|
[Column("vat_amount")]
|
||||||
public long VatAmountValue { get; init; }
|
public long VatAmountValue { get; private set; }
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public decimal VatAmount {
|
public decimal VatAmount {
|
||||||
get => Utils.DecFromDb(VatAmountValue, 2);
|
get => Utils.DecFromDb(VatAmountValue, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Column("gross_amount")]
|
[Column("gross_amount")]
|
||||||
public long GrossAmountValue { get; init; }
|
public long GrossAmountValue { get; private set; }
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public decimal GrossAmount {
|
public decimal GrossAmount {
|
||||||
get => Utils.DecFromDb(GrossAmountValue, 2);
|
get => Utils.DecFromDb(GrossAmountValue, 2);
|
||||||
@@ -77,7 +77,7 @@ namespace Elwig.Models.Entities {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Column("amount")]
|
[Column("amount")]
|
||||||
public long AmountValue { get; init; }
|
public long AmountValue { get; private set; }
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public decimal Amount {
|
public decimal Amount {
|
||||||
get => Utils.DecFromDb(AmountValue, 2);
|
get => Utils.DecFromDb(AmountValue, 2);
|
||||||
@@ -116,12 +116,12 @@ namespace Elwig.Models.Entities {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[ForeignKey("Year, AvNr, MgNr")]
|
[ForeignKey("Year, AvNr, MgNr")]
|
||||||
public virtual PaymentMember Payment { get; init; } = null!;
|
public virtual PaymentMember Payment { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("Year, AvNr")]
|
[ForeignKey("Year, AvNr")]
|
||||||
public virtual PaymentVar Variant { get; init; } = null!;
|
public virtual PaymentVar Variant { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("MgNr")]
|
[ForeignKey("MgNr")]
|
||||||
public virtual Member Member { get; init; } = null!;
|
public virtual Member Member { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,16 +6,16 @@ namespace Elwig.Models.Entities {
|
|||||||
[Table("currency"), PrimaryKey("Code")]
|
[Table("currency"), PrimaryKey("Code")]
|
||||||
public class Currency {
|
public class Currency {
|
||||||
[Column("code")]
|
[Column("code")]
|
||||||
public required string Code { get; init; }
|
public string Code { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("name")]
|
[Column("name")]
|
||||||
public required string Name { get; init; }
|
public string Name { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("symbol")]
|
[Column("symbol")]
|
||||||
public string? Symbol { get; init; }
|
public string? Symbol { get; private set; }
|
||||||
|
|
||||||
[Column("one_euro")]
|
[Column("one_euro")]
|
||||||
public long? OneEuroValue { get; init; }
|
public long? OneEuroValue { get; private set; }
|
||||||
|
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public decimal? OneEuro => OneEuroValue != null ? Utils.DecFromDb(OneEuroValue.Value, 6) : null;
|
public decimal? OneEuro => OneEuroValue != null ? Utils.DecFromDb(OneEuroValue.Value, 6) : null;
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ namespace Elwig.Models.Entities {
|
|||||||
public required string ZwstId { get; set; }
|
public required string ZwstId { get; set; }
|
||||||
|
|
||||||
[ForeignKey("ZwstId")]
|
[ForeignKey("ZwstId")]
|
||||||
public virtual Branch Branch { get; init; } = null!;
|
public virtual Branch Branch { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("lnr")]
|
[Column("lnr")]
|
||||||
public int LNr { get; set; }
|
public int LNr { get; set; }
|
||||||
@@ -58,7 +58,7 @@ namespace Elwig.Models.Entities {
|
|||||||
public int MgNr { get; set; }
|
public int MgNr { get; set; }
|
||||||
|
|
||||||
[ForeignKey("MgNr")]
|
[ForeignKey("MgNr")]
|
||||||
public virtual Member Member { get; init; } = null!;
|
public virtual Member Member { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("comment")]
|
[Column("comment")]
|
||||||
public string? Comment { get; set; }
|
public string? Comment { get; set; }
|
||||||
@@ -101,10 +101,10 @@ namespace Elwig.Models.Entities {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[ForeignKey("Year")]
|
[ForeignKey("Year")]
|
||||||
public virtual Season Season { get; init; } = null!;
|
public virtual Season Season { get; private set; } = null!;
|
||||||
|
|
||||||
[InverseProperty(nameof(DeliveryPart.Delivery))]
|
[InverseProperty(nameof(DeliveryPart.Delivery))]
|
||||||
public virtual ICollection<DeliveryPart> Parts { get; init; } = null!;
|
public virtual ICollection<DeliveryPart> Parts { get; private set; } = null!;
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public IEnumerable<DeliveryPart> FilteredParts => PartFilter == null ? Parts : Parts.Where(p => PartFilter(p));
|
public IEnumerable<DeliveryPart> FilteredParts => PartFilter == null ? Parts : Parts.Where(p => PartFilter(p));
|
||||||
|
|
||||||
|
|||||||
@@ -59,13 +59,13 @@ namespace Elwig.Models.Entities {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[ForeignKey("Year, DsNr")]
|
[ForeignKey("Year, DsNr")]
|
||||||
public virtual DeliverySchedule Schedule { get; init; } = null!;
|
public virtual DeliverySchedule Schedule { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("MgNr")]
|
[ForeignKey("MgNr")]
|
||||||
public virtual Member Member { get; init; } = null!;
|
public virtual Member Member { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("SortId")]
|
[ForeignKey("SortId")]
|
||||||
public virtual WineVar Variety { get; init; } = null!;
|
public virtual WineVar Variety { get; private set; } = null!;
|
||||||
|
|
||||||
public int SearchScore(IEnumerable<string> keywords) {
|
public int SearchScore(IEnumerable<string> keywords) {
|
||||||
return Utils.GetSearchScore([
|
return Utils.GetSearchScore([
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ namespace Elwig.Models.Entities {
|
|||||||
public int DId { get; set; }
|
public int DId { get; set; }
|
||||||
|
|
||||||
[ForeignKey("Year, DId")]
|
[ForeignKey("Year, DId")]
|
||||||
public virtual Delivery Delivery { get; init; } = null!;
|
public virtual Delivery Delivery { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("dpnr")]
|
[Column("dpnr")]
|
||||||
public int DPNr { get; set; }
|
public int DPNr { get; set; }
|
||||||
@@ -30,19 +30,19 @@ namespace Elwig.Models.Entities {
|
|||||||
public required string SortId { get; set; }
|
public required string SortId { get; set; }
|
||||||
|
|
||||||
[ForeignKey("SortId")]
|
[ForeignKey("SortId")]
|
||||||
public virtual WineVar Variety { get; init; } = null!;
|
public virtual WineVar Variety { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("attrid")]
|
[Column("attrid")]
|
||||||
public string? AttrId { get; set; }
|
public string? AttrId { get; set; }
|
||||||
|
|
||||||
[ForeignKey("AttrId")]
|
[ForeignKey("AttrId")]
|
||||||
public virtual WineAttr? Attribute { get; init; }
|
public virtual WineAttr? Attribute { get; private set; }
|
||||||
|
|
||||||
[Column("cultid")]
|
[Column("cultid")]
|
||||||
public string? CultId { get; set; }
|
public string? CultId { get; set; }
|
||||||
|
|
||||||
[ForeignKey("CultId")]
|
[ForeignKey("CultId")]
|
||||||
public virtual WineCult? Cultivation { get; init; }
|
public virtual WineCult? Cultivation { get; private set; }
|
||||||
|
|
||||||
[Column("weight")]
|
[Column("weight")]
|
||||||
public int Weight { get; set; }
|
public int Weight { get; set; }
|
||||||
@@ -59,25 +59,25 @@ namespace Elwig.Models.Entities {
|
|||||||
public required string QualId { get; set; }
|
public required string QualId { get; set; }
|
||||||
|
|
||||||
[ForeignKey("QualId")]
|
[ForeignKey("QualId")]
|
||||||
public virtual WineQualLevel Quality { get; init; } = null!;
|
public virtual WineQualLevel Quality { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("hkid")]
|
[Column("hkid")]
|
||||||
public required string HkId { get; set; }
|
public required string HkId { get; set; }
|
||||||
|
|
||||||
[ForeignKey("HkId")]
|
[ForeignKey("HkId")]
|
||||||
public virtual WineOrigin Origin { get; init; } = null!;
|
public virtual WineOrigin Origin { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("kgnr")]
|
[Column("kgnr")]
|
||||||
public int? KgNr { get; set; }
|
public int? KgNr { get; set; }
|
||||||
|
|
||||||
[ForeignKey("KgNr")]
|
[ForeignKey("KgNr")]
|
||||||
public virtual WbKg? Kg { get; init; }
|
public virtual WbKg? Kg { get; private set; }
|
||||||
|
|
||||||
[Column("rdnr")]
|
[Column("rdnr")]
|
||||||
public int? RdNr { get; set; }
|
public int? RdNr { get; set; }
|
||||||
|
|
||||||
[ForeignKey("KgNr, RdNr")]
|
[ForeignKey("KgNr, RdNr")]
|
||||||
public virtual WbRd? Rd { get; init; }
|
public virtual WbRd? Rd { get; private set; }
|
||||||
|
|
||||||
[Column("net_weight")]
|
[Column("net_weight")]
|
||||||
public bool IsNetWeight { get; set; }
|
public bool IsNetWeight { get; set; }
|
||||||
@@ -91,8 +91,8 @@ namespace Elwig.Models.Entities {
|
|||||||
[Column("hand_picked")]
|
[Column("hand_picked")]
|
||||||
public bool? IsHandPicked { get; set; }
|
public bool? IsHandPicked { get; set; }
|
||||||
|
|
||||||
[Column("contracted")]
|
[Column("gebunden")]
|
||||||
public bool? IsContracted { get; set; }
|
public bool? IsGebunden { get; set; }
|
||||||
|
|
||||||
[Column("unloading")]
|
[Column("unloading")]
|
||||||
public string? Unloading { get; set; }
|
public string? Unloading { get; set; }
|
||||||
@@ -118,28 +118,26 @@ namespace Elwig.Models.Entities {
|
|||||||
[Column("acid")]
|
[Column("acid")]
|
||||||
public double? Acid { get; set; }
|
public double? Acid { get; set; }
|
||||||
|
|
||||||
[Column("scale_terminal")]
|
[Column("scale_id")]
|
||||||
public string? ScaleTerminalId { get; set; }
|
public string? ScaleId { get; set; }
|
||||||
|
|
||||||
[Column("weighing_data")]
|
[Column("weighing_data")]
|
||||||
public string? WeighingData { get; set; }
|
public string? WeighingData { get; set; }
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public (string? ScaleId, string? Id, int? Gross, int? Tare, int? TareCorrection, int? Net, DateOnly? Date, TimeOnly? Time) WeighingInfo {
|
public (string? Id, int? Gross, int? Tare, int? Net, DateOnly? Date, TimeOnly? Time) WeighingInfo {
|
||||||
get {
|
get {
|
||||||
try {
|
try {
|
||||||
var obj = JsonNode.Parse(WeighingData!)!.AsObject();
|
var obj = JsonNode.Parse(WeighingData!)!.AsObject();
|
||||||
return (
|
return (
|
||||||
obj["scale"]?.AsValue().GetValue<string>(),
|
|
||||||
obj["id"]?.AsValue().GetValue<string>(),
|
obj["id"]?.AsValue().GetValue<string>(),
|
||||||
obj["gross_weight"]?.AsValue().GetValue<int>(),
|
obj["gross_weight"]?.AsValue().GetValue<int>(),
|
||||||
obj["tare_weight"]?.AsValue().GetValue<int>(),
|
obj["tare_weight"]?.AsValue().GetValue<int>(),
|
||||||
obj["tare_correction"]?.AsValue().GetValue<int>(),
|
|
||||||
obj["net_weight"]?.AsValue().GetValue<int>(),
|
obj["net_weight"]?.AsValue().GetValue<int>(),
|
||||||
DateOnly.TryParseExact(obj["date"]?.AsValue().GetValue<string>(), "yyyy-MM-dd", out var d) ? d : null,
|
DateOnly.TryParseExact(obj["date"]?.AsValue().GetValue<string>(), "yyyy-MM-dd", out var d) ? d : null,
|
||||||
TimeOnly.TryParseExact(obj["time"]?.AsValue().GetValue<string>(), ["HH:mm:ss", "HH:mm"], out var t) ? t : null
|
TimeOnly.TryParseExact(obj["time"]?.AsValue().GetValue<string>(), ["HH:mm:ss", "HH:mm"], out var t) ? t : null
|
||||||
);
|
);
|
||||||
} catch {
|
} catch {
|
||||||
return (null, null, null, null, null, null, null, null);
|
return (null, null, null, null, null, null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -183,18 +181,18 @@ namespace Elwig.Models.Entities {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[InverseProperty(nameof(DeliveryPartModifier.Part))]
|
[InverseProperty(nameof(DeliveryPartModifier.Part))]
|
||||||
public virtual ICollection<DeliveryPartModifier> PartModifiers { get; init; } = null!;
|
public virtual ICollection<DeliveryPartModifier> PartModifiers { get; private set; } = null!;
|
||||||
|
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public IEnumerable<Modifier> Modifiers => PartModifiers.Select(m => m.Modifier).OrderBy(m => m.Ordering);
|
public IEnumerable<Modifier> Modifiers => PartModifiers.Select(m => m.Modifier).OrderBy(m => m.Ordering);
|
||||||
|
|
||||||
[InverseProperty(nameof(PaymentDeliveryPart.DeliveryPart))]
|
[InverseProperty(nameof(PaymentDeliveryPart.DeliveryPart))]
|
||||||
public virtual PaymentDeliveryPart? Payment { get; init; }
|
public virtual PaymentDeliveryPart? Payment { get; private set; }
|
||||||
|
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public string OriginString => Origin.OriginString + "\n" + (Kg?.Gl != null ? $" / {Kg.Gl.Name}" : "") + (Kg != null ? $" / {Kg.AtKg.Gem.Name} / KG {Kg.AtKg.Name}" : "") + (Rd != null ? $" / Ried {Rd.Name}" : "");
|
public string OriginString => Origin.OriginString + "\n" + (Kg?.Gl != null ? $" / {Kg.Gl.Name}" : "") + (Kg != null ? $" / {Kg.AtKg.Gem.Name} / KG {Kg.AtKg.Name}" : "") + (Rd != null ? $" / Ried {Rd.Name}" : "");
|
||||||
|
|
||||||
[InverseProperty(nameof(DeliveryPartBucket.Part))]
|
[InverseProperty(nameof(DeliveryPartBucket.Part))]
|
||||||
public virtual ICollection<DeliveryPartBucket> Buckets { get; init; } = null!;
|
public virtual ICollection<DeliveryPartBucket> Buckets { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -23,6 +23,6 @@ namespace Elwig.Models.Entities {
|
|||||||
public int Value { get; set; }
|
public int Value { get; set; }
|
||||||
|
|
||||||
[ForeignKey("Year, DId, DPNr")]
|
[ForeignKey("Year, DId, DPNr")]
|
||||||
public virtual DeliveryPart Part { get; init; } = null!;
|
public virtual DeliveryPart Part { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,12 +14,12 @@ namespace Elwig.Models.Entities {
|
|||||||
public int DPNr { get; set; }
|
public int DPNr { get; set; }
|
||||||
|
|
||||||
[ForeignKey("Year, DId, DPNr")]
|
[ForeignKey("Year, DId, DPNr")]
|
||||||
public virtual DeliveryPart Part { get; init; } = null!;
|
public virtual DeliveryPart Part { get; private set; } = null!;
|
||||||
|
|
||||||
[Column("modid")]
|
[Column("modid")]
|
||||||
public required string ModId { get; set; }
|
public required string ModId { get; set; }
|
||||||
|
|
||||||
[ForeignKey("Year, ModId")]
|
[ForeignKey("Year, ModId")]
|
||||||
public virtual Modifier Modifier { get; init; } = null!;
|
public virtual Modifier Modifier { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -38,8 +38,6 @@ namespace Elwig.Models.Entities {
|
|||||||
|
|
||||||
[Column("cultid")]
|
[Column("cultid")]
|
||||||
public string? CultId { get; set; }
|
public string? CultId { get; set; }
|
||||||
[NotMapped]
|
|
||||||
public bool IsOrganic => Cultivation?.IsOrganic ?? false;
|
|
||||||
|
|
||||||
[Column("max_weight")]
|
[Column("max_weight")]
|
||||||
public int? MaxWeight { get; set; }
|
public int? MaxWeight { get; set; }
|
||||||
@@ -72,22 +70,22 @@ namespace Elwig.Models.Entities {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[ForeignKey("Year")]
|
[ForeignKey("Year")]
|
||||||
public virtual Season Season { get; init; } = null!;
|
public virtual Season Season { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("ZwstId")]
|
[ForeignKey("ZwstId")]
|
||||||
public virtual Branch Branch { get; init; } = null!;
|
public virtual Branch Branch { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("AttrId")]
|
[ForeignKey("AttrId")]
|
||||||
public virtual WineAttr? Attribute { get; init; }
|
public virtual WineAttr? Attribute { get; private set; }
|
||||||
|
|
||||||
[ForeignKey("CultId")]
|
[ForeignKey("CultId")]
|
||||||
public virtual WineCult? Cultivation { get; init; }
|
public virtual WineCult? Cultivation { get; private set; }
|
||||||
|
|
||||||
[InverseProperty(nameof(DeliveryScheduleWineVar.Schedule))]
|
[InverseProperty(nameof(DeliveryScheduleWineVar.Schedule))]
|
||||||
public virtual ICollection<DeliveryScheduleWineVar> Varieties { get; init; } = null!;
|
public virtual ICollection<DeliveryScheduleWineVar> Varieties { get; private set; } = null!;
|
||||||
|
|
||||||
[InverseProperty(nameof(DeliveryAncmt.Schedule))]
|
[InverseProperty(nameof(DeliveryAncmt.Schedule))]
|
||||||
public virtual ICollection<DeliveryAncmt> Announcements { get; init; } = null!;
|
public virtual ICollection<DeliveryAncmt> Announcements { get; private set; } = null!;
|
||||||
|
|
||||||
public int SearchScore(IEnumerable<string> keywords) {
|
public int SearchScore(IEnumerable<string> keywords) {
|
||||||
return Utils.GetSearchScore([Description], keywords);
|
return Utils.GetSearchScore([Description], keywords);
|
||||||
|
|||||||
@@ -18,9 +18,9 @@ namespace Elwig.Models.Entities {
|
|||||||
public int Priority { get; set; }
|
public int Priority { get; set; }
|
||||||
|
|
||||||
[ForeignKey("Year, DsNr")]
|
[ForeignKey("Year, DsNr")]
|
||||||
public virtual DeliverySchedule Schedule { get; init; } = null!;
|
public virtual DeliverySchedule Schedule { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("SortId")]
|
[ForeignKey("SortId")]
|
||||||
public virtual WineVar Variety { get; init; } = null!;
|
public virtual WineVar Variety { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -96,26 +96,20 @@ namespace Elwig.Models.Entities {
|
|||||||
[Column("ustid_nr")]
|
[Column("ustid_nr")]
|
||||||
public string? UstIdNr { get; set; }
|
public string? UstIdNr { get; set; }
|
||||||
|
|
||||||
[Column("ooc_id")]
|
|
||||||
public string? OrganicOperatorId { get; set; }
|
|
||||||
|
|
||||||
[Column("org_auth_code")]
|
|
||||||
public string? OrganicAuthorityCode { get; set; }
|
|
||||||
|
|
||||||
[Column("juridical_pers")]
|
[Column("juridical_pers")]
|
||||||
public bool IsJuridicalPerson { get; set; }
|
public bool IsJuridicalPerson { get; set; }
|
||||||
|
|
||||||
[Column("full_delivery")]
|
[Column("volllieferant")]
|
||||||
public bool IsFullDelivery { get; set; }
|
public bool IsVollLieferant { get; set; }
|
||||||
|
|
||||||
[Column("accounting")]
|
[Column("buchführend")]
|
||||||
public bool IsAccounting { get; set; }
|
public bool IsBuchführend { get; set; }
|
||||||
|
|
||||||
[Column("organic")]
|
[Column("organic")]
|
||||||
public bool IsOrganic { get; set; }
|
public bool IsOrganic { get; set; }
|
||||||
|
|
||||||
[Column("officer")]
|
[Column("funktionär")]
|
||||||
public bool IsOfficer { get; set; }
|
public bool IsFunktionär { get; set; }
|
||||||
|
|
||||||
[Column("active")]
|
[Column("active")]
|
||||||
public bool IsActive { get; set; }
|
public bool IsActive { get; set; }
|
||||||
@@ -133,10 +127,10 @@ namespace Elwig.Models.Entities {
|
|||||||
public int CountryNum { get; set; }
|
public int CountryNum { get; set; }
|
||||||
|
|
||||||
[Column("postal_dest")]
|
[Column("postal_dest")]
|
||||||
public required string PostalDestId { get; set; }
|
public string PostalDestId { get; set; } = null!;
|
||||||
|
|
||||||
[Column("address")]
|
[Column("address")]
|
||||||
public required string Address { get; set; }
|
public string Address { get; set; } = null!;
|
||||||
|
|
||||||
[Column("default_kgnr")]
|
[Column("default_kgnr")]
|
||||||
public int? DefaultKgNr { get; set; }
|
public int? DefaultKgNr { get; set; }
|
||||||
@@ -151,16 +145,16 @@ namespace Elwig.Models.Entities {
|
|||||||
public string? Comment { get; set; }
|
public string? Comment { get; set; }
|
||||||
|
|
||||||
[ForeignKey("PredecessorMgNr")]
|
[ForeignKey("PredecessorMgNr")]
|
||||||
public virtual Member? Predecessor { get; init; }
|
public virtual Member? Predecessor { get; private set; }
|
||||||
|
|
||||||
[ForeignKey("CountryNum")]
|
[ForeignKey("CountryNum")]
|
||||||
public virtual Country Country { get; init; } = null!;
|
public virtual Country Country { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("CountryNum, PostalDestId")]
|
[ForeignKey("CountryNum, PostalDestId")]
|
||||||
public virtual PostalDest PostalDest { get; init; } = null!;
|
public virtual PostalDest PostalDest { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("DefaultKgNr")]
|
[ForeignKey("DefaultKgNr")]
|
||||||
public virtual WbKg? DefaultWbKg { get; init; }
|
public virtual WbKg? DefaultWbKg { get; private set; }
|
||||||
[NotMapped]
|
[NotMapped]
|
||||||
public AT_Kg? DefaultKg => DefaultWbKg?.AtKg;
|
public AT_Kg? DefaultKg => DefaultWbKg?.AtKg;
|
||||||
|
|
||||||
@@ -197,37 +191,37 @@ namespace Elwig.Models.Entities {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[ForeignKey("ZwstId")]
|
[ForeignKey("ZwstId")]
|
||||||
public virtual Branch? Branch { get; init; }
|
public virtual Branch? Branch { get; private set; }
|
||||||
|
|
||||||
[InverseProperty(nameof(AreaCmt.Member))]
|
[InverseProperty(nameof(AreaCom.Member))]
|
||||||
public virtual ICollection<AreaCmt> AreaCommitments { get; init; } = null!;
|
public virtual ICollection<AreaCom> AreaCommitments { get; private set; } = null!;
|
||||||
|
|
||||||
public IQueryable<AreaCmt> ActiveAreaCommitments(AppDbContext ctx, int? year = null) {
|
public IQueryable<AreaCom> ActiveAreaCommitments(AppDbContext ctx, int? year = null) {
|
||||||
return ctx.AreaCommitments.Where(c => c.MgNr == MgNr).Where(Utils.ActiveAreaCommitments(year ?? Utils.CurrentYear));
|
return ctx.AreaCommitments.Where(c => c.MgNr == MgNr).Where(Utils.ActiveAreaCommitments(year ?? Utils.CurrentYear));
|
||||||
}
|
}
|
||||||
|
|
||||||
[InverseProperty(nameof(BillingAddr.Member))]
|
[InverseProperty(nameof(BillingAddr.Member))]
|
||||||
public virtual BillingAddr? BillingAddress { get; init; }
|
public virtual BillingAddr? BillingAddress { get; private set; }
|
||||||
|
|
||||||
[InverseProperty(nameof(DeliveryAncmt.Member))]
|
[InverseProperty(nameof(DeliveryAncmt.Member))]
|
||||||
public virtual ICollection<DeliveryAncmt> Announcements { get; init; } = null!;
|
public virtual ICollection<DeliveryAncmt> Announcements { get; private set; } = null!;
|
||||||
|
|
||||||
[InverseProperty(nameof(MemberHistory.FromMember))]
|
[InverseProperty(nameof(MemberHistory.FromMember))]
|
||||||
public virtual ICollection<MemberHistory> HistoryFrom { get; init; } = null!;
|
public virtual ICollection<MemberHistory> HistoryFrom { get; private set; } = null!;
|
||||||
[InverseProperty(nameof(MemberHistory.ToMember))]
|
[InverseProperty(nameof(MemberHistory.ToMember))]
|
||||||
public virtual ICollection<MemberHistory> HistoryTo { get; init; } = null!;
|
public virtual ICollection<MemberHistory> HistoryTo { get; private set; } = null!;
|
||||||
|
|
||||||
[InverseProperty(nameof(Delivery.Member))]
|
[InverseProperty(nameof(Delivery.Member))]
|
||||||
public virtual ICollection<Delivery> Deliveries { get; init; } = null!;
|
public virtual ICollection<Delivery> Deliveries { get; private set; } = null!;
|
||||||
|
|
||||||
[InverseProperty(nameof(Credit.Member))]
|
[InverseProperty(nameof(Credit.Member))]
|
||||||
public virtual ICollection<Credit> Credits { get; init; } = null!;
|
public virtual ICollection<Credit> Credits { get; private set; } = null!;
|
||||||
|
|
||||||
[InverseProperty(nameof(MemberTelNr.Member))]
|
[InverseProperty(nameof(MemberTelNr.Member))]
|
||||||
public virtual ICollection<MemberTelNr> TelephoneNumbers { get; init; } = null!;
|
public virtual ICollection<MemberTelNr> TelephoneNumbers { get; private set; } = null!;
|
||||||
|
|
||||||
[InverseProperty(nameof(MemberEmailAddr.Member))]
|
[InverseProperty(nameof(MemberEmailAddr.Member))]
|
||||||
public virtual ICollection<MemberEmailAddr> EmailAddresses { get; init; } = null!;
|
public virtual ICollection<MemberEmailAddr> EmailAddresses { get; private set; } = null!;
|
||||||
|
|
||||||
public string FullAddress => $"{Address}, {PostalDest.AtPlz?.Plz} {PostalDest.AtPlz?.Ort.Name}";
|
public string FullAddress => $"{Address}, {PostalDest.AtPlz?.Plz} {PostalDest.AtPlz?.Ort.Name}";
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,6 @@ namespace Elwig.Models.Entities {
|
|||||||
public string? Comment { get; set; }
|
public string? Comment { get; set; }
|
||||||
|
|
||||||
[ForeignKey("MgNr")]
|
[ForeignKey("MgNr")]
|
||||||
public virtual Member Member { get; init; } = null!;
|
public virtual Member Member { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -76,10 +76,7 @@ namespace Elwig.Models.Entities {
|
|||||||
[Column("shares")]
|
[Column("shares")]
|
||||||
public int Shares { get; set; }
|
public int Shares { get; set; }
|
||||||
|
|
||||||
[Column("signed_company")]
|
[Column("signed")]
|
||||||
public bool CompanyHasSigned { get; set; }
|
|
||||||
|
|
||||||
[Column("signed_member")]
|
|
||||||
public bool MemberHasSigned { get; set; }
|
public bool MemberHasSigned { get; set; }
|
||||||
|
|
||||||
[Column("value_per_share")]
|
[Column("value_per_share")]
|
||||||
@@ -104,10 +101,10 @@ namespace Elwig.Models.Entities {
|
|||||||
|
|
||||||
public string FormatReasonPhrase(int mgnr) {
|
public string FormatReasonPhrase(int mgnr) {
|
||||||
if (Reason == REASON_TRANSFER) {
|
if (Reason == REASON_TRANSFER) {
|
||||||
if (ToMgNr == mgnr) {
|
if (FromMgNr == mgnr) {
|
||||||
return $"{ReasonPretty} von {FromMember?.FullAdministrativeName ?? "Vorgänger"}" + (Comment != null ? $", {Comment}" : "");
|
|
||||||
} else if (FromMgNr == mgnr) {
|
|
||||||
return $"{ReasonPretty} an {ToMember?.FullAdministrativeName ?? "Nachfolger"}" + (Comment != null ? $", {Comment}" : "");
|
return $"{ReasonPretty} an {ToMember?.FullAdministrativeName ?? "Nachfolger"}" + (Comment != null ? $", {Comment}" : "");
|
||||||
|
} else if (ToMgNr == mgnr) {
|
||||||
|
return $"{ReasonPretty} von {FromMember?.FullAdministrativeName ?? "Vorgänger"}" + (Comment != null ? $", {Comment}" : "");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return ReasonPretty + (Comment != null ? $", {Comment}" : "");
|
return ReasonPretty + (Comment != null ? $", {Comment}" : "");
|
||||||
@@ -119,12 +116,12 @@ namespace Elwig.Models.Entities {
|
|||||||
public string PoVReasonPhrase => FormatReasonPhrase(PoVMgNr ?? 0);
|
public string PoVReasonPhrase => FormatReasonPhrase(PoVMgNr ?? 0);
|
||||||
|
|
||||||
[ForeignKey("FromMgNr")]
|
[ForeignKey("FromMgNr")]
|
||||||
public virtual Member? FromMember { get; init; } = null!;
|
public virtual Member? FromMember { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("ToMgNr")]
|
[ForeignKey("ToMgNr")]
|
||||||
public virtual Member? ToMember { get; init; } = null!;
|
public virtual Member? ToMember { get; private set; } = null!;
|
||||||
|
|
||||||
[ForeignKey("CurrencyCode")]
|
[ForeignKey("CurrencyCode")]
|
||||||
public virtual Currency Currency { get; init; } = null!;
|
public virtual Currency Currency { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -20,6 +20,6 @@ namespace Elwig.Models.Entities {
|
|||||||
public string? Comment { get; set; }
|
public string? Comment { get; set; }
|
||||||
|
|
||||||
[ForeignKey("MgNr")]
|
[ForeignKey("MgNr")]
|
||||||
public virtual Member Member { get; init; } = null!;
|
public virtual Member Member { get; private set; } = null!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user