Compare commits

..
2 Commits
Author SHA1 Message Date
lorenz.stechauner b0ac5d59f5 Elwig: Update dependencies
Test / Run tests (push) Successful in 2m11s
2026-10-08 10:52:25 +02:00
lorenz.stechauner 9fdb3ff702 Utils: Fix non-ascii characters in User-Agent header
Test / Run tests (push) Successful in 3m8s
2026-10-08 10:51:01 +02:00
108 changed files with 553 additions and 1170 deletions

No files matched your search

-45
View File
@@ -2,51 +2,6 @@
Changelog
=========
[v1.2.1.0][v1.2.1.0] (2026-11-30) {#v1.2.1.0}
---------------------------------------------
### Neue Funktionen {#v1.2.1.0-features}
- Es ist nun möglich zip-Dateien zu verschlüsseln. ([#60][i60])
- Das betrifft Den Synchronisations-Dienst zwischen Zweigstellen bei dem Elwig-Export-Dateien verschlüsselt auf den Server hochgeladen werden können.
- Außerdem ist es möglich (automatische) Backups zu verschlüsseln.
- Man kann nun die maximale (oder minimale) Qualitätsstufe für die Übernahme generell oder pro Attribut unter "Stammdaten" festlegen. (065fbc2eea)
### Behobene Fehler {#v1.2.1.0-bugfixes}
- Fehler beim Starten bzw. nach Updates. Außerdem wurde auf die meisten Warnungen des Compilers eingegangen. (2cc58f8df6, bc419ce57a)
- Beim Import von Elwig-Export-Dateien konnten KGs ohne zugewiesene Großlage nicht importiert werden. (4d201aed99)
### Sonstiges {#v1.2.1.0-misc}
- Abhängigkeiten aktualisiert. (9e110a467a, d05f1408af, f388ddbe41)
- Mehr automatisierte Tests. (cc6da2f257, 51a05fe4db, f1e8907d40, 4d201aed99)
- Der Verlauf der Geschäftsanteile wird automatisch zwischen Zweigstellen synchronisiert. (a012a54362)
- Viele kleine Verbesserungen der Code-Qualität. (089ac3ce85, 6b5756a1c1)
[v1.2.1.0]: https://git.necronda.net/winzer/elwig/releases/tag/v1.2.1.0
[i60]: https://git.necronda.net/winzer/elwig/issues/60
[v1.2.0.1][v1.2.0.1] (2026-10-08) {#v1.2.0.1}
---------------------------------------------
### Behobene Fehler {#v1.2.0.1-bugfixes}
- Umlaute im HTTP-Header werden richtig behandelt. ([#76][i76])
### Sonstiges {#v1.2.0.1-misc}
- Abhängigkeiten aktualisiert. (bc47bcc784)
[v1.2.0.1]: https://git.necronda.net/winzer/elwig/releases/tag/v1.2.0.1
[i76]: https://git.necronda.net/winzer/elwig/issues/76
[v1.2.0.0][v1.2.0.0] (2026-10-03) {#v1.2.0.0}
---------------------------------------------
+22 -18
View File
@@ -24,7 +24,8 @@ using System.Windows.Threading;
namespace Elwig {
public partial class App : Application {
public static new App Current => (App)Application.Current;
public static App CurrentApp;
public static int NumWindows => CurrentApp.Windows.Count;
public static bool ForceShutdown { get; set; } = false;
private readonly DispatcherTimer _autoUpdateTimer = new() { Interval = TimeSpan.FromHours(1) };
@@ -41,8 +42,8 @@ namespace Elwig {
public static Version Version { get; private set; } = new();
public static int BranchNum { get; private set; }
public static string ZwstId { get; private set; } = "?";
public static string BranchName { get; private set; } = "Unbekannt";
public static string ZwstId { get; private set; }
public static string BranchName { get; private set; }
public static int? BranchPlz { get; private set; }
public static string? BranchLocation { get; private set; }
public static string? BranchAddress { get; private set; }
@@ -53,8 +54,9 @@ namespace Elwig {
public static IList<IScale> Scales { get; private set; } = [];
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 ClientParameters Client { get; set; } = new();
public static ClientParameters Client { get; set; }
public static Dispatcher MainDispatcher { get; private set; }
private DateTime LastChanged;
private static DateTime CurrentLastWrite => File.GetLastWriteTime(Config.DatabaseFile);
private readonly DispatcherTimer ContextTimer = new() { Interval = TimeSpan.FromSeconds(2) };
@@ -64,7 +66,9 @@ namespace Elwig {
Directory.CreateDirectory(TempPath);
Directory.CreateDirectory(DataPath);
Directory.CreateDirectory(MailsPath);
MainDispatcher = Dispatcher;
Scales = [];
CurrentApp = this;
Utils.OverrideCulture();
var args = Environment.GetCommandLineArgs();
@@ -82,7 +86,7 @@ namespace Elwig {
}
private static void OnContextChanged() {
Current.Dispatcher.BeginInvoke(HintContextChange);
MainDispatcher.BeginInvoke(HintContextChange);
}
protected override async void OnStartup(StartupEventArgs evt) {
@@ -255,21 +259,21 @@ namespace Elwig {
}
public static void HintContextChange() {
if (Current == null) return;
if (CurrentApp == null) return;
var ch = CurrentLastWrite;
if (ch > Current.LastChanged)
Current.LastChanged = ch;
Current.Dispatcher.Invoke(() => {
foreach (Window w in Current.Windows) {
if (ch > CurrentApp.LastChanged)
CurrentApp.LastChanged = ch;
MainDispatcher.Invoke(() => {
foreach (Window w in CurrentApp.Windows) {
if (w is not ContextWindow c) continue;
Current.Dispatcher.Invoke(c.HintContextChange);
Current.Dispatcher.BeginInvoke(c.TryContextReload);
MainDispatcher.Invoke(c.HintContextChange);
MainDispatcher.BeginInvoke(c.TryContextReload);
}
});
}
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 (Utils.HasInternetConnectivity()) {
@@ -326,7 +330,7 @@ namespace Elwig {
}
public static void UpdateScales() {
foreach (Window w in Current.Windows) {
foreach (Window w in CurrentApp.Windows) {
if (w is DeliveryAdminWindow t && t.ViewModel.IsReceipt) {
t.UpdateScales();
}
@@ -338,7 +342,7 @@ namespace Elwig {
try {
var latest = await Utils.GetLatestInstallerUrl(Config.UpdateUrl);
if (new Version(latest.Version) > Version) {
await Current.Dispatcher.BeginInvoke(() => {
await MainDispatcher.BeginInvoke(() => {
var d = new UpdateDialog(latest.Version, latest.Url, latest.Size);
if (d.ShowDialog() == true) {
ShutdownNow();
@@ -353,10 +357,10 @@ namespace Elwig {
}
}
public static async Task ReplaceDatabase(string filename, IEnumerable<ReadOnlyMemory<char>>? keys = null) {
public static async Task ReplaceDatabase(string filename) {
try {
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!");
ShutdownNow();
@@ -366,7 +370,7 @@ namespace Elwig {
}
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 (t.WindowState == WindowState.Minimized)
t.WindowState = WindowState.Normal;
+3 -3
View File
@@ -4,10 +4,10 @@ using System.Globalization;
namespace Elwig.Controls {
public class BoolToValueConverter<T> : IValueConverter {
public required T FalseValue { get; set; }
public required T TrueValue { get; set; }
public T FalseValue { 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;
}
+4 -4
View File
@@ -74,7 +74,7 @@ namespace Elwig.Controls {
private bool _viewHandled;
private bool _modelHandled;
private TextBlock? _textBox;
private TextBlock _textBox;
public CheckComboBox() {
SelectionMode = SelectionMode.Multiple;
@@ -131,11 +131,11 @@ namespace Elwig.Controls {
AllItemsSelected = null;
}
if (SelectedItems.Count > 1 && SelectedItems.Count == ItemsSource.Cast<object>().Count() && AllItemsSelectedContent != null) {
_textBox?.Text = AllItemsSelectedContent;
_textBox.Text = AllItemsSelectedContent;
} else if (SelectedItems.Count == 0) {
_textBox?.Text = "";
_textBox.Text = "";
} else {
_textBox?.Text = string.Join(Delimiter,
_textBox.Text = string.Join(Delimiter,
dmp == null ? SelectedItems.Cast<object>() :
SelectedItems.Cast<object>()
.Select(i => i.GetType().GetProperty(dmp)?.GetValue(i))
+1 -1
View File
@@ -13,7 +13,7 @@ namespace Elwig.Dialogs {
public bool DeletePaymentData { get; set; }
public DeleteMemberDialog(int mgnr, string name, int numAreaCmts, 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();
Title += " - " + name;
AreaCmtInput.IsEnabled = numAreaCmts != 0;
@@ -13,7 +13,7 @@ namespace Elwig.Dialogs {
public partial class DeliverySplittingDialog : ContextWindow {
public class Row {
public required DeliveryPart Part { get; set; }
public DeliveryPart Part { get; set; }
public bool SplitCompletely { get; set; }
public string? SplitWeightString { get; set; }
public int? SplitWeight {
@@ -27,18 +27,18 @@ namespace Elwig.Dialogs {
public int? MgNr { 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 DeliverySplittingDialog(Delivery d) {
_delivery = d;
DeliveryParts = [with([.. d.Parts.Select(p => new Row {
DeliveryParts = new(d.Parts.Select(p => new Row {
Part = p,
SplitCompletely = false,
SplitWeight = null,
SplitWeightEnabled = true,
})])];
}).ToList());
InitializeComponent();
}
+8 -3
View File
@@ -343,17 +343,22 @@ namespace Elwig.Documents {
return t;
}
private class EventHandler(Document doc) : AbstractPdfDocumentEventHandler {
private class EventHandler : AbstractPdfDocumentEventHandler {
private const float _fontSize = 10;
private const float _placeholderWidth = 50 * PtInMM;
private readonly Document _doc = doc;
private readonly List<PdfFormXObject> _pageNumPlaceholders = [];
private readonly Document _doc;
private readonly List<PdfFormXObject> _pageNumPlaceholders;
public int NumberOfPages { get; private set; }
public EventHandler(Document doc) {
_doc = doc;
_pageNumPlaceholders = [];
}
protected override void OnAcceptedEvent(AbstractPdfDocumentEvent evt) {
if (evt.GetType() == PdfDocumentEvent.START_PAGE) {
OnPageStart((PdfDocumentEvent)evt);
+14 -14
View File
@@ -2,14 +2,14 @@
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net11.0-windows</TargetFramework>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x64</PlatformTarget>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
<PreserveCompilationContext>true</PreserveCompilationContext>
<ApplicationIcon>Resources\Images\Elwig.ico</ApplicationIcon>
<Version>1.2.1.0</Version>
<Version>1.2.0.0</Version>
<SatelliteResourceLanguages>de-AT</SatelliteResourceLanguages>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationManifest>App.manifest</ApplicationManifest>
@@ -23,21 +23,21 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="bblanchon.PDFium.Win32" Version="160.0.8179" />
<PackageReference Include="bblanchon.PDFium.Win32" Version="157.0.8086" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageReference Include="itext" Version="9.8.1.1" />
<PackageReference Include="itext.bouncy-castle-adapter" Version="9.8.1.1" />
<PackageReference Include="LinqKit" Version="1.4.2" />
<PackageReference Include="MailKit" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="11.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Ini" Version="11.0.0" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4370.26" />
<PackageReference Include="NJsonSchema" Version="11.6.2" />
<PackageReference Include="itext" Version="9.8.0" />
<PackageReference Include="itext.bouncy-castle-adapter" Version="9.8.0" />
<PackageReference Include="LinqKit" Version="1.4.0" />
<PackageReference Include="MailKit" Version="4.18.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.12" />
<PackageReference Include="Microsoft.Extensions.Configuration.Ini" Version="10.0.12" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4258.31" />
<PackageReference Include="NJsonSchema" Version="11.6.1" />
<PackageReference Include="ScottPlot.WPF" Version="5.1.59" />
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" />
<PackageReference Include="System.IO.Hashing" Version="11.0.0" />
<PackageReference Include="System.IO.Ports" Version="11.0.0" />
<PackageReference Include="System.Management" Version="11.0.0" />
<PackageReference Include="System.IO.Hashing" Version="10.0.12" />
<PackageReference Include="System.IO.Ports" Version="10.0.12" />
<PackageReference Include="System.Management" Version="10.0.12" />
</ItemGroup>
</Project>
+6 -2
View File
@@ -2,10 +2,14 @@ using System;
using System.Windows.Input;
namespace Elwig.Helpers {
public class ActionCommand(Action action) : ICommand {
public class ActionCommand : ICommand {
public event EventHandler? CanExecuteChanged;
private readonly Action Action = action;
private readonly Action Action;
public ActionCommand(Action action) {
Action = action;
}
public void Execute(object? parameter) {
Action();
+1 -3
View File
@@ -111,7 +111,7 @@ namespace Elwig.Helpers {
private static readonly Func<AppDbContext, bool, IAsyncEnumerable<WineQualLevel>> _compiledQueryWineQualityLevels =
EF.CompileAsyncQuery<AppDbContext, bool, WineQualLevel>((ctx, includePredicate) => ctx.WineQualityLevels
.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 =
EF.CompileAsyncQuery<AppDbContext, int?, bool, Modifier>((ctx, year, incudeNotActive) => ctx.Modifiers
@@ -217,8 +217,6 @@ namespace Elwig.Helpers {
modelBuilder.Entity<BillingAddr>().Navigation(a => a.PostalDest).AutoInclude();
modelBuilder.Entity<Modifier>().Navigation(m => m.Season).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<PaymentDeliveryPart>().Navigation(p => p.Variant).AutoInclude();
modelBuilder.Entity<Credit>().Navigation(c => c.Payment).AutoInclude();
+1 -1
View File
@@ -12,7 +12,7 @@ namespace Elwig.Helpers {
public static class AppDbUpdater {
// Don't forget to update value in Tests/fetch-resources.bat!
public static readonly int RequiredSchemaVersion = 43;
public static readonly int RequiredSchemaVersion = 42;
private static int VersionOffset = 0;
+8 -8
View File
@@ -251,23 +251,23 @@ namespace Elwig.Helpers.Billing {
try {
return new JsonObject() {
["15kmw"] = Math.Round((decimal)y.Distinct().Single(), prec)
["15kmw"] = Math.Round(y.Distinct().Single(), prec)
};
} catch { }
var data = new JsonObject();
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++) {
var d1 = Math.Round((decimal)(y[i] - y[i - 1]), prec);
var d2 = Math.Round((decimal)(y[i + 1] - y[i]), prec);
var d1 = Math.Round(y[i] - y[i - 1], prec);
var d2 = Math.Round(y[i + 1] - y[i], prec);
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]) {
data[$"{x[^1]}{mode}"] = Math.Round((decimal)y[^1], prec);
data[$"{x[^1]}{mode}"] = Math.Round(y[^1], prec);
}
return data;
}
@@ -275,7 +275,7 @@ namespace Elwig.Helpers.Billing {
protected static JsonNode GraphEntryToJson(GraphEntry entry) {
try {
if (entry.ContractedFlatBonus == 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 { }
@@ -287,7 +287,7 @@ namespace Elwig.Helpers.Billing {
curve["data"] = GraphToJson(entry.DataGraph, entry.Mode.ToString().ToLower());
if (entry.ContractedFlatBonus != null) {
curve["ctrd"] = Math.Round((decimal)entry.ContractedFlatBonus, entry.ContractedGraph?.Precision ?? entry.DataGraph.Precision);
curve["ctrd"] = (decimal)entry.ContractedFlatBonus;
} else if (entry.ContractedGraph != null) {
curve["ctrd"] = GraphToJson(entry.ContractedGraph, entry.Mode.ToString().ToLower());
}
+3 -3
View File
@@ -63,9 +63,9 @@ namespace Elwig.Helpers.Billing {
((Variety != null || Attribute != null) && Cultivation != null ? " " : "") + $"{Cultivation?.Name}";
public Varibute(RawVaribute raw) :
this(raw.SortId != null ? new WineVar { SortId = raw.SortId, Name = raw.SortId, MaxQualId = "QUW", Type = "?" } : 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) {
this(raw.SortId != null ? new WineVar(raw.SortId, raw.SortId) : 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) {
}
public Varibute(RawVaribute raw, Dictionary<string, WineVar> vars, Dictionary<string, WineAttr> attrs, Dictionary<string, WineCult> cults) :
+1 -25
View File
@@ -81,27 +81,9 @@ namespace Elwig.Helpers {
public int ExportEbicsVersion;
public int ExportEbicsAddress;
public string? ReceiptMaxQualId;
public (int? AllowanceKg, double? AllowanceShares, int? AllowanceKgPerShare, double? AllowancePercent, int? MinShares) AutoAdjustShares;
public static readonly Dictionary<string, string?> DefaultParameters = new() {
{ "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(AppDbContext ctx) : this(ctx.ClientParameters.ToDictionary(e => e.Param, e => e.Value)) { }
public ClientParameters(Dictionary<string, string?> parameters) {
try {
@@ -213,11 +195,6 @@ namespace Elwig.Helpers {
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(';');
AutoAdjustShares = autoAdjust.Length == 5 ? (
int.TryParse(autoAdjust[0], out var v1) ? v1 : null,
@@ -329,7 +306,6 @@ namespace Elwig.Helpers {
("MAIL_ORDERING", mailOrdering),
("EXPORT_EBICS_VERSION", ExportEbicsVersion.ToString()),
("EXPORT_EBICS_ADDRESS", exportEbicsAddress),
("RECEIPT_MAX_QUALID", ReceiptMaxQualId),
("AUTOADJUST_BUSINESSSHARES", autoAdjust),
];
}
+6 -17
View File
@@ -2,7 +2,6 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using Microsoft.Extensions.Configuration;
namespace Elwig.Helpers {
@@ -56,32 +55,24 @@ namespace Elwig.Helpers {
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 bool UpdateAuto = false;
public string? SyncUrl = null;
public string SyncUsername = "";
private string _syncPassword = "";
public ReadOnlyMemory<char> SyncPassword => _syncPassword.AsMemory();
public string SyncPassword = "";
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 int? SmtpPort = null;
public string? SmtpMode = null;
public string? SmtpUsername = null;
private string? _smtpPassword = null;
public ReadOnlyMemory<char> SmtpPassword => _smtpPassword.AsMemory();
public string? SmtpPassword = null;
public string? SmtpFrom = null;
public double SmtpWait = 0;
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.IsEmpty || SmtpFrom == null ?
public (string Host, int Port, string Mode, string Username, string Password, string From, double Wait)? Smtp =>
SmtpHost == null || SmtpPort == null || SmtpMode == null || SmtpUsername == null || SmtpPassword == null || SmtpFrom == null ?
null : (SmtpHost, (int)SmtpPort, SmtpMode, SmtpUsername, SmtpPassword, SmtpFrom, SmtpWait);
public IList<ScaleConfig> Scales;
@@ -110,22 +101,20 @@ namespace Elwig.Helpers {
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"];
UpdateAuto = TrueValues.Contains(config["update:auto"]?.ToLower());
SyncUrl = config["sync:url"];
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"];
SmtpPort = config["smtp:port"]?.All(char.IsAsciiDigit) == true && config["smtp:port"]?.Length > 0 ? int.Parse(config["smtp:port"]!) : null;
SmtpMode = config["smtp:mode"];
SmtpUsername = config["smtp:username"];
_smtpPassword = config["smtp:password"];
SmtpPassword = config["smtp:password"];
SmtpFrom = config["smtp:from"];
SmtpWait = double.TryParse(config["smtp:wait"], out var res) ? res : 0;
+22 -26
View File
@@ -17,21 +17,21 @@ namespace Elwig.Helpers.Export {
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";
try {
File.Delete(tmp);
if (zipFile) {
using var zip = await ZipFile.OpenAsync(tmp, ZipArchiveMode.Create);
using var zip = ZipFile.Open(tmp, ZipArchiveMode.Create);
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");
}
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)) {
using (var writer = new StreamWriter(meta.Open(), Utils.UTF8)) {
var obj = new JsonObject {
["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}",
["zwstid"] = App.ZwstId,
@@ -46,9 +46,7 @@ namespace Elwig.Helpers.Export {
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);
var db = zip.CreateEntryFromFile(App.Config.DatabaseFile, "database.sqlite3", CompressionLevel.SmallestSize);
} else {
File.Copy(App.Config.DatabaseFile, tmp);
}
@@ -58,21 +56,21 @@ namespace Elwig.Helpers.Export {
}
}
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";
try {
File.Delete(tmp);
if (zipFile) {
using var zip = await ZipFile.OpenAsync(tmp, ZipArchiveMode.Create);
using var zip = ZipFile.Open(tmp, ZipArchiveMode.Create);
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");
}
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)) {
using (var writer = new StreamWriter(meta.Open(), Utils.UTF8)) {
var obj = new JsonObject {
["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}",
["zwstid"] = App.ZwstId,
@@ -87,10 +85,8 @@ namespace Elwig.Helpers.Export {
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
}
var sql = password.IsEmpty ?
zip.CreateEntry("database.sql", CompressionLevel.SmallestSize) :
zip.CreateEntry("database.sql", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
using (var writer = new StreamWriter(await sql.OpenAsync(), Utils.UTF8)) {
var sql = zip.CreateEntry("database.sql", CompressionLevel.SmallestSize);
using (var writer = new StreamWriter(sql.Open(), Utils.UTF8)) {
await ExportSql(writer);
}
} else {
@@ -182,27 +178,27 @@ namespace Elwig.Helpers.Export {
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")) {
await ImportSql(filename, false);
} else if (filename.EndsWith(".sql.zip")) {
await ImportSql(filename, true, passwords);
await ImportSql(filename, true);
} else if (filename.EndsWith(".sqlite3")) {
await ImportSqlite(filename, false);
} else if (filename.EndsWith(".sqlite3.zip")) {
await ImportSqlite(filename, true, passwords);
await ImportSqlite(filename, true);
} else {
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) {
using var zip = await ZipFile.OpenAsync(filename, ZipArchiveMode.Read);
var password = await zip.CheckIntegrity(passwords ?? []);
using var zip = ZipFile.Open(filename, ZipArchiveMode.Read);
await zip.CheckIntegrity();
foreach (var entry in zip.Entries) {
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);
await ImportSql(reader);
return;
@@ -216,15 +212,15 @@ 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, bool keepSource = true) {
if (zipFile) {
var newName = Path.ChangeExtension(App.Config.DatabaseFile, ".new.sqlite3");
try {
using var zip = await ZipFile.OpenAsync(filename, ZipArchiveMode.Read);
var password = await zip.CheckIntegrity(passwords ?? []);
using var zip = ZipFile.Open(filename, ZipArchiveMode.Read);
await zip.CheckIntegrity();
foreach (var entry in zip.Entries) {
if (entry.Name.EndsWith(".sqlite3")) {
entry.ExtractToFile(newName, new ZipExtractionOptions { Password = password });
entry.ExtractToFile(newName);
await ImportSqlite(newName, keepSource: false);
return;
}
+39 -47
View File
@@ -30,9 +30,9 @@ namespace Elwig.Helpers.Export {
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 {
Dictionary<string, Branch> branches;
Dictionary<int, AT_Kg> kgs;
@@ -89,19 +89,20 @@ namespace Elwig.Helpers.Export {
})));
var r = data[^1];
using var zip = await ZipFile.OpenReadAsync(filename);
var password = await zip.CheckIntegrity(passwords ?? []);
// TODO read encrypted files
using var zip = ZipFile.Open(filename, ZipArchiveMode.Read);
await zip.CheckIntegrity();
string[] acceptableVersions = ["1", "2"];
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();
if (!v.StartsWith("elwig:") || !acceptableVersions.Contains(v[6..]))
throw new FileFormatException($"Ungültige Elwig-Export-Datei ({filename})");
}
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 memberFilters = meta!["members"]?["filters"]?.AsArray().Select(f => f!.AsValue().GetValue<string>()).ToArray();
var areaCmtCount = meta!["area_commitment_contracts"]?["count"]?.AsValue().GetValue<int>();
@@ -116,7 +117,7 @@ namespace Elwig.Helpers.Export {
var wbKgsJson = zip.GetEntry("wb_kgs.json");
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;
while ((line = await reader.ReadLineAsync()) != null) {
var obj = JsonNode.Parse(line)!.AsObject();
@@ -124,7 +125,7 @@ namespace Elwig.Helpers.Export {
r.WbKgs.Add(k);
currentWbKgs[k.KgNr] = k;
if (g != null) {
currentWbGls.Add(g);
currentWbGls[g.GlNr] = g;
r.WbGls.Add(g);
}
}
@@ -132,7 +133,7 @@ namespace Elwig.Helpers.Export {
var membersJson = zip.GetEntry("members.json");
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;
while ((line = await reader.ReadLineAsync()) != null) {
var obj = JsonNode.Parse(line)!.AsObject();
@@ -148,7 +149,7 @@ namespace Elwig.Helpers.Export {
var historyJson = zip.GetEntry("member_history.json");
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;
while ((line = await reader.ReadLineAsync()) != null) {
var obj = JsonNode.Parse(line)!.AsObject();
@@ -160,7 +161,7 @@ namespace Elwig.Helpers.Export {
// legacy area commitments
var areaCmtsJson = zip.GetEntry("area_commitments.json");
if (areaCmtsJson != null) {
using var reader = new StreamReader(await areaCmtsJson.OpenAsync(password.Span), Utils.UTF8);
using var reader = new StreamReader(areaCmtsJson.Open(), Utils.UTF8);
string? line;
while ((line = await reader.ReadLineAsync()) != null) {
var obj = JsonNode.Parse(line)!.AsObject();
@@ -179,7 +180,7 @@ namespace Elwig.Helpers.Export {
var contractsJson = zip.GetEntry("area_commitment_contracts.json");
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;
while ((line = await reader.ReadLineAsync()) != null) {
var obj = JsonNode.Parse(line)!.AsObject();
@@ -200,7 +201,7 @@ namespace Elwig.Helpers.Export {
var deliveriesJson = zip.GetEntry("deliveries.json");
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;
while ((line = await reader.ReadLineAsync()) != null) {
var obj = JsonNode.Parse(line)!.AsObject();
@@ -449,14 +450,14 @@ namespace Elwig.Helpers.Export {
$"Flächenbindungen: {importedAreaCmts.Sum(d => d.New + d.Overwritten)}",
..importedAreaCmts.Select(d =>
$" {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" +
$" Filter: {d.Filters}"),
$"Lieferungen: {importedDeliveries.Sum(d => d.New + d.Overwritten)}",
..importedDeliveries.Select(d =>
$" {d.FileName} ({d.New + d.Overwritten})\n" +
$" ({d.New} neu, {d.Overwritten} überschrieben, {d.NotImported} nicht importiert)\n" +
$" Zweigstelle: {branches[d.ZwstId].Name} (Gerät {d.Device})\n" +
$" ({d.New} neu, {d.Overwritten} überschr., {d.NotImported} nicht importiert)\n" +
$" Zwst.: {branches[d.ZwstId].Name} (Gerät {d.Device})\n" +
$" Filter: {d.Filters}")
]));
} catch (Exception exc) {
@@ -472,28 +473,28 @@ namespace Elwig.Helpers.Export {
$"{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 {
Members = (members, filters),
History = (history, ["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<AreaCmtContract> areaCmts, IEnumerable<WbKg> wbKgs, IEnumerable<string> filters) {
return new ElwigExport {
Members = (members, filters),
History = (history, ["von exportierten Mitgliedern"]),
AreaCmts = (areaCmts, ["von exportierten Mitgliedern"]),
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 {
Deliveries = (deliveries, filters),
WbKgs = (wbKgs, ["von exportierten Lieferungen"]),
}.Export(filename, password);
}.Export(filename);
}
public class ElwigExport {
@@ -503,17 +504,17 @@ namespace Elwig.Helpers.Export {
public (IEnumerable<AreaCmtContract> AreaCmts, IEnumerable<string> Filters)? AreaCmts { 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);
using var zip = await ZipFile.OpenAsync(filename, ZipArchiveMode.Create);
using var zip = ZipFile.Open(filename, ZipArchiveMode.Create);
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");
}
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 {
["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}",
["zwstid"] = App.ZwstId,
@@ -549,47 +550,38 @@ namespace Elwig.Helpers.Export {
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
}
// TODO encrypt files
if (WbKgs != null) {
var json = password.IsEmpty ?
zip.CreateEntry("wb_kgs.json", CompressionLevel.SmallestSize) :
zip.CreateEntry("wb_kgs.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
using var writer = new StreamWriter(await json.OpenAsync(), Utils.UTF8);
var json = zip.CreateEntry("wb_kgs.json", CompressionLevel.SmallestSize);
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
foreach (var k in WbKgs.Value.WbKgs) {
await writer.WriteLineAsync(k.ToJson().ToJsonString(Utils.JsonOpts));
}
}
if (Members != null) {
var json = password.IsEmpty ?
zip.CreateEntry("members.json", CompressionLevel.SmallestSize) :
zip.CreateEntry("members.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
using var writer = new StreamWriter(await json.OpenAsync(), Utils.UTF8);
var json = zip.CreateEntry("members.json", CompressionLevel.SmallestSize);
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
foreach (var m in Members.Value.Members) {
await writer.WriteLineAsync(m.ToJson().ToJsonString(Utils.JsonOpts));
}
}
if (History != null) {
var json = password.IsEmpty ?
zip.CreateEntry("member_history.json", CompressionLevel.SmallestSize) :
zip.CreateEntry("member_history.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
using var writer = new StreamWriter(await json.OpenAsync(), Utils.UTF8);
var json = zip.CreateEntry("member_history.json", CompressionLevel.SmallestSize);
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
foreach (var h in History.Value.History) {
await writer.WriteLineAsync(h.ToJson().ToJsonString(Utils.JsonOpts));
}
}
if (AreaCmts != null) {
var json = password.IsEmpty ?
zip.CreateEntry("area_commitment_contracts.json", CompressionLevel.SmallestSize) :
zip.CreateEntry("area_commitment_contracts.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
using var writer = new StreamWriter(await json.OpenAsync(), Utils.UTF8);
var json = zip.CreateEntry("area_commitment_contracts.json", CompressionLevel.SmallestSize);
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
foreach (var c in AreaCmts.Value.AreaCmts) {
await writer.WriteLineAsync(c.ToJson().ToJsonString(Utils.JsonOpts));
}
}
if (Deliveries != null) {
var json = password.IsEmpty ?
zip.CreateEntry("deliveries.json", CompressionLevel.SmallestSize) :
zip.CreateEntry("deliveries.json", CompressionLevel.SmallestSize, password.Span, ZipEncryptionMethod.Aes256);
using var writer = new StreamWriter(await json.OpenAsync(), Utils.UTF8);
var json = zip.CreateEntry("deliveries.json", CompressionLevel.SmallestSize);
using var writer = new StreamWriter(json.Open(), Utils.UTF8);
foreach (var d in Deliveries.Value.Deliveries) {
await writer.WriteLineAsync(d.ToJson().ToJsonString(Utils.JsonOpts));
}
@@ -616,7 +608,7 @@ namespace Elwig.Helpers.Export {
GlNr = (gls.Count == 0 ? 1 : gls.Max(g => g.GlNr)) + 1,
Name = grosslage,
};
gls.Add(gl);
gls[gl.GlNr] = gl;
}
}
return (new WbKg {
+6 -6
View File
@@ -32,12 +32,12 @@ namespace Elwig.Helpers.Export {
private async Task AddHeader() {
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");
}
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("""
<?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">
@@ -52,7 +52,7 @@ namespace Elwig.Helpers.Export {
}
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("""
<?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">
@@ -62,7 +62,7 @@ namespace Elwig.Helpers.Export {
}
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");
await writer.WriteAsync($"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
@@ -80,7 +80,7 @@ namespace Elwig.Helpers.Export {
}
var content = ZipArchive.CreateEntry("content.xml");
Content = new StreamWriter(await content.OpenAsync(), Utils.UTF8);
Content = new StreamWriter(content.Open(), Utils.UTF8);
await Content.WriteAsync("""
<?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">
@@ -168,7 +168,7 @@ namespace Elwig.Helpers.Export {
Content = null;
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("""
<?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">
+8 -24
View File
@@ -62,7 +62,7 @@ namespace Elwig.Helpers {
var buf = new char[512];
int bufSize = 0;
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)
return null;
buf[bufSize++] = tmpBuf[0];
@@ -106,30 +106,14 @@ namespace Elwig.Helpers {
progress.Report(100.0);
}
public static async Task<ReadOnlyMemory<char>> FindPassword(this ZipArchive zip, IEnumerable<ReadOnlyMemory<char>> passwords) {
foreach (var pwd in passwords) {
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];
public static async Task CheckIntegrity(this ZipArchive zip) {
var crc = new Crc32();
foreach (var entry in zip.Entries) {
using var stream = await entry.OpenAsync(password.Span);
while (await stream.ReadAsync(buffer) > 0);
crc.Reset();
using var stream = entry.Open();
await crc.AppendAsync(stream);
if (crc.GetCurrentHashAsUInt32() != entry.Crc32)
throw new InvalidDataException($"CRC-32 mismatch in '{entry.FullName}'");
}
}
+2 -2
View File
@@ -15,14 +15,14 @@ namespace Elwig.Helpers.Printing {
}
public static void Show(TempFile file, string title) {
App.Current.Dispatcher.BeginInvoke(() => {
App.MainDispatcher.BeginInvoke(() => {
var w = new DocumentViewerWindow(title, file);
w.Show();
});
}
public static void Show(string path, string title) {
App.Current.Dispatcher.BeginInvoke(() => {
App.MainDispatcher.BeginInvoke(() => {
var w = new DocumentViewerWindow(title, path);
w.Show();
});
+2 -2
View File
@@ -26,7 +26,7 @@ namespace Elwig.Helpers {
}
private void OnDeviceArrived(object sender, EventArrivedEventArgs evt) {
App.Current.Dispatcher.Invoke(() => {
App.MainDispatcher.Invoke(() => {
// "synchronized"
string[] currentPorts = SerialPort.GetPortNames();
var newPorts = currentPorts.Except(_knownPorts).ToArray();
@@ -37,7 +37,7 @@ namespace Elwig.Helpers {
}
private void OnDeviceRemoved(object sender, EventArrivedEventArgs evt) {
App.Current.Dispatcher.Invoke(() => {
App.MainDispatcher.Invoke(() => {
// "synchronized"
string[] currentPorts = SerialPort.GetPortNames();
var removedPorts = _knownPorts.Except(currentPorts).ToArray();
+2 -2
View File
@@ -38,9 +38,9 @@ namespace Elwig.Helpers {
}
private void Delete() {
if (Usages < 0) return;
if (FilePath == null) return;
File.Delete(FilePath);
Usages = -1;
FilePath = null;
}
}
}
+17 -15
View File
@@ -74,9 +74,6 @@ namespace Elwig.Helpers {
private static partial Regex 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 UnitSeparator = "\u00A0";
@@ -209,7 +206,7 @@ namespace Elwig.Helpers {
}
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) {
@@ -325,10 +322,15 @@ namespace Elwig.Helpers {
return new Footer(lineBreak, separator);
}
public class Footer(string lineBreak, string separator) {
public class Footer {
private readonly List<List<List<object>>> Items = [[[]]];
private readonly string LineBreak = lineBreak;
private readonly string Separator = separator;
private readonly string LineBreak;
private readonly string Separator;
public Footer(string lineBreak, string separator) {
LineBreak = lineBreak;
Separator = separator;
}
public Footer Item(object? text) {
if (text == null) return this;
@@ -489,16 +491,16 @@ namespace Elwig.Helpers {
.Replace("ß", "ss").Replace("ẞ", "SS");
}
public static HttpClient GetHttpClient(string? username = null, ReadOnlyMemory<char> password = default, string? accept = null) {
public static HttpClient GetHttpClient(string? username = null, string? password = null, string? accept = null) {
var client = new HttpClient() {
Timeout = TimeSpan.FromSeconds(5),
};
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}, {ReplaceUmlaute(App.BranchName)}, {Environment.MachineName}, {Environment.OSVersion})");
client.DefaultRequestHeaders.Accept.Clear();
if (accept != null)
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}")));
return client;
}
@@ -512,7 +514,7 @@ namespace Elwig.Helpers {
return ((string)data["version"]!, (string)data["url"]!, (long)data["size"]!);
}
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/"))
url = "https://sync.elwig.at/" + url[25..];
if (!url.EndsWith('/')) url += "/";
@@ -523,7 +525,7 @@ namespace Elwig.Helpers {
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/"))
url = "https://sync.elwig.at/" + url[25..];
using var client = GetHttpClient(username, password, accept: "application/json");
@@ -551,7 +553,7 @@ namespace Elwig.Helpers {
var (host, port, mode, username, password, _, _) = App.Config.Smtp.Value;
var client = new SmtpClient();
await client.ConnectAsync(host, port, mode == "starttls" ? SecureSocketOptions.StartTls : SecureSocketOptions.None);
await client.AuthenticateAsync(username, password.ToString());
await client.AuthenticateAsync(username, password);
return client;
}
@@ -577,7 +579,7 @@ namespace Elwig.Helpers {
body.Add(doc.AsEmailAttachment($"{name}.pdf"));
}
msg.Body = body;
await client!.SendAsync(new SmtpSendRequest(msg));
await client!.SendAsync(msg);
await AddSentMails([(
"email", member.MgNr, member.AdministrativeName,
member.EmailAddresses.OrderBy(a => a.Nr).Select(a => a.Address).ToArray(),
@@ -655,7 +657,7 @@ namespace Elwig.Helpers {
} else if (obj is IEnumerable list && obj is not string) {
var arr = list.Cast<object>().Select(GetEntityIdentifier).ToArray();
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();
return ((IStructuralEquatable)pk).GetHashCode(EqualityComparer<int>.Default);
} else {
@@ -45,6 +45,8 @@ namespace Elwig.Models.Dtos {
}
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;
if (year != null) q = q.Where(p => p.Year == year);
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.PartModifiers).ThenInclude(m => m.Modifier)
.LoadAsync();
return await table.FromSql($"""
return await table.FromSqlRaw($"""
SELECT p.*
FROM v_delivery v
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
""").IgnoreAutoIncludes().ToListAsync();
}
+2 -1
View File
@@ -26,7 +26,8 @@ namespace Elwig.Models.Dtos {
}
private static async Task<IEnumerable<WeightBreakdownRow>> FromDbSet(DbSet<WeightBreakdownRow> table, int year, string? zwstid) {
return await table.FromSql($"""
zwstid = zwstid == null ? "NULL" : $"'{zwstid}'";
return await table.FromSqlRaw($"""
SELECT type, sortid, attrid, cultid, v.qualid, contracted, SUM(weight) AS weight
FROM v_stat_total v
LEFT JOIN wine_quality_level q ON q.qualid = v.qualid
+4 -4
View File
@@ -6,15 +6,15 @@ namespace Elwig.Models.Entities {
[Table("AT_gem"), PrimaryKey("Gkz")]
public class AT_Gem {
[Column("gkz")]
public int Gkz { get; init; }
public int Gkz { get; private set; }
[Column("name")]
public required string Name { get; init; }
public string Name { get; private set; } = null!;
[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))]
public virtual WbGem? WbGem { get; init; }
public virtual WbGem? WbGem { get; private set; }
}
}
+5 -5
View File
@@ -5,18 +5,18 @@ namespace Elwig.Models.Entities {
[Table("AT_kg"), PrimaryKey("KgNr")]
public class AT_Kg {
[Column("kgnr")]
public int KgNr { get; init; }
public int KgNr { get; private set; }
[Column("gkz")]
public int Gkz { get; init; }
public int Gkz { get; private set; }
[Column("name")]
public required string Name { get; init; }
public string Name { get; private set; } = null!;
[ForeignKey("Gkz")]
public virtual AT_Gem Gem { get; init; } = null!;
public virtual AT_Gem Gem { get; private set; } = null!;
[InverseProperty(nameof(WbKg.AtKg))]
public virtual WbKg? WbKg { get; init; }
public virtual WbKg? WbKg { get; private set; }
}
}
+6 -6
View File
@@ -5,21 +5,21 @@ namespace Elwig.Models.Entities {
[Table("AT_ort"), PrimaryKey("Okz")]
public class AT_Ort {
[Column("okz")]
public int Okz { get; init; }
public int Okz { get; private set; }
[Column("gkz")]
public int Gkz { get; init; }
public int Gkz { get; private set; }
[Column("kgnr")]
public int? KgNr { get; init; }
public int? KgNr { get; private set; }
[Column("name")]
public required string Name { get; init; }
public string Name { get; private set; } = null!;
[ForeignKey("Gkz")]
public virtual AT_Gem Gem { get; init; } = null!;
public virtual AT_Gem Gem { get; private set; } = null!;
[ForeignKey("KgNr")]
public virtual AT_Kg? Kg { get; init; }
public virtual AT_Kg? Kg { get; private set; }
}
}
+8 -8
View File
@@ -6,27 +6,27 @@ namespace Elwig.Models.Entities {
[Table("AT_plz"), PrimaryKey("Plz")]
public class AT_Plz {
[Column("plz")]
public int Plz { get; init; }
public int Plz { get; private set; }
[Column("ort")]
public required string Ort { get; init; }
public string Ort { get; private set; } = null!;
[Column("blnr")]
public int BlNr { get; init; }
public int BlNr { get; private set; }
[Column("type")]
public required string Type { get; init; }
public string Type { get; private set; } = null!;
[Column("internal")]
public bool IsInternal { get; init; }
public bool IsInternal { get; private set; }
[Column("addressable")]
public bool IsAddressable { get; init; }
public bool IsAddressable { get; private set; }
[Column("po_box")]
public bool IsPoBox { get; init; }
public bool IsPoBox { get; private set; }
[InverseProperty(nameof(AT_PlzDest.AtPlz))]
public virtual ICollection<AT_PlzDest> Orte { get; init; } = null!;
public virtual ICollection<AT_PlzDest> Orte { get; private set; } = null!;
}
}
+8 -8
View File
@@ -6,30 +6,30 @@ namespace Elwig.Models.Entities {
[Table("AT_plz_dest"), PrimaryKey("Id"), Index("Plz", "Okz", IsUnique = true)]
public class AT_PlzDest {
[Column("plz")]
public int Plz { get; init; }
public int Plz { get; private set; }
[Column("okz")]
public int Okz { get; init; }
public int Okz { get; private set; }
[Column("country")]
public int CountryNum { get; init; }
public int CountryNum { get; private set; }
[Column("id")]
public required string Id { get; init; }
public string Id { get; private set; } = null!;
[Column("dest")]
public required string Dest { get; init; }
public string Dest { get; private set; } = null!;
[NotMapped]
public string FullDest => $"{Ort.Name} ({Dest})";
[ForeignKey("Plz")]
public virtual AT_Plz AtPlz { get; init; } = null!;
public virtual AT_Plz AtPlz { get; private set; } = null!;
[ForeignKey("Okz")]
public virtual AT_Ort Ort { get; init; } = null!;
public virtual AT_Ort Ort { get; private set; } = null!;
[ForeignKey("CountryNum")]
public virtual Country Country { get; init; } = null!;
public virtual Country Country { get; private set; } = null!;
}
}
+4 -4
View File
@@ -65,15 +65,15 @@ namespace Elwig.Models.Entities {
}
[ForeignKey("FbNr")]
public virtual AreaCmtContract Contract { get; init; } = null!;
public virtual AreaCmtContract Contract { get; private set; } = null!;
[ForeignKey("MgNr")]
public virtual Member Member { get; init; } = null!;
public virtual Member Member { get; private set; } = null!;
[ForeignKey("VtrgId")]
public virtual AreaCmtType AreaCmtType { get; init; } = null!;
public virtual AreaCmtType AreaCmtType { get; private set; } = null!;
[ForeignKey("CultId")]
public virtual WineCult? WineCult { get; init; }
public virtual WineCult? WineCult { get; private set; }
}
}
+3 -3
View File
@@ -53,13 +53,13 @@ namespace Elwig.Models.Entities {
}
[ForeignKey("KgNr")]
public virtual WbKg Kg { get; init; } = null!;
public virtual WbKg Kg { get; private set; } = null!;
[ForeignKey("KgNr, RdNr")]
public virtual WbRd? Rd { get; init; }
public virtual WbRd? Rd { get; private set; }
[InverseProperty(nameof(AreaCmt.Contract))]
public virtual ICollection<AreaCmt> Revisions { get; init; } = null!;
public virtual ICollection<AreaCmt> Revisions { get; private set; } = null!;
[NotMapped]
public AreaCmt? Latest => Revisions.OrderBy(r => r.RevNr).LastOrDefault();
+2 -2
View File
@@ -46,10 +46,10 @@ namespace Elwig.Models.Entities {
}
[ForeignKey("SortId")]
public virtual WineVar WineVar { get; init; } = null!;
public virtual WineVar WineVar { get; private set; } = null!;
[ForeignKey("AttrId")]
public virtual WineAttr? WineAttr { get; init; }
public virtual WineAttr? WineAttr { get; private set; }
[NotMapped]
public string DisplayName => WineVar.Name + (WineAttr != null ? $" {WineAttr.Name}" : "") + (Discriminator != null ? $" ({Discriminator})" : "");
+3 -3
View File
@@ -20,12 +20,12 @@ namespace Elwig.Models.Entities {
public required string Address { get; set; }
[ForeignKey("MgNr")]
public virtual Member Member { get; init; } = null!;
public virtual Member Member { get; private set; } = null!;
[ForeignKey("CountryNum")]
public virtual Country Country { get; init; } = null!;
public virtual Country Country { get; private set; } = null!;
[ForeignKey("CountryNum, PostalDestId")]
public virtual PostalDest PostalDest { get; init; } = null!;
public virtual PostalDest PostalDest { get; private set; } = null!;
}
}
+3 -3
View File
@@ -22,10 +22,10 @@ namespace Elwig.Models.Entities {
public string? Address { get; set; }
[ForeignKey("CountryNum")]
public virtual Country? Country { get; init; }
public virtual Country? Country { get; private set; }
[ForeignKey("CountryNum, PostalDestId")]
public virtual PostalDest? PostalDest { get; init; }
public virtual PostalDest? PostalDest { get; private set; }
[Column("phone_nr")]
public string? PhoneNr { get; set; }
@@ -37,6 +37,6 @@ namespace Elwig.Models.Entities {
public string? MobileNr { get; set; }
[InverseProperty(nameof(Member.Branch))]
public virtual ICollection<Member> Members { get; init; } = null!;
public virtual ICollection<Member> Members { get; private set; } = null!;
}
}
+5 -5
View File
@@ -6,18 +6,18 @@ namespace Elwig.Models.Entities {
[Table("country"), PrimaryKey("Num"), Index("Alpha2", IsUnique = true), Index("Alpha3", IsUnique = true)]
public class Country {
[Column("num")]
public int Num { get; init; }
public int Num { get; private set; }
[Column("alpha2")]
public required string Alpha2 { get; init; }
public string Alpha2 { get; private set; } = null!;
[Column("alpha3")]
public required string Alpha3 { get; init; }
public string Alpha3 { get; private set; } = null!;
[Column("name")]
public required string Name { get; init; }
public string Name { get; private set; } = null!;
[Column("is_visible")]
public bool IsVisible { get; init; }
public bool IsVisible { get; private set; }
}
}
+6 -6
View File
@@ -47,14 +47,14 @@ namespace Elwig.Models.Entities {
}
[Column("vat_amount")]
public long VatAmountValue { get; init; }
public long VatAmountValue { get; private set; }
[NotMapped]
public decimal VatAmount {
get => Utils.DecFromDb(VatAmountValue, 2);
}
[Column("gross_amount")]
public long GrossAmountValue { get; init; }
public long GrossAmountValue { get; private set; }
[NotMapped]
public decimal GrossAmount {
get => Utils.DecFromDb(GrossAmountValue, 2);
@@ -77,7 +77,7 @@ namespace Elwig.Models.Entities {
}
[Column("amount")]
public long AmountValue { get; init; }
public long AmountValue { get; private set; }
[NotMapped]
public decimal Amount {
get => Utils.DecFromDb(AmountValue, 2);
@@ -116,12 +116,12 @@ namespace Elwig.Models.Entities {
}
[ForeignKey("Year, AvNr, MgNr")]
public virtual PaymentMember Payment { get; init; } = null!;
public virtual PaymentMember Payment { get; private set; } = null!;
[ForeignKey("Year, AvNr")]
public virtual PaymentVar Variant { get; init; } = null!;
public virtual PaymentVar Variant { get; private set; } = null!;
[ForeignKey("MgNr")]
public virtual Member Member { get; init; } = null!;
public virtual Member Member { get; private set; } = null!;
}
}
+4 -4
View File
@@ -6,16 +6,16 @@ namespace Elwig.Models.Entities {
[Table("currency"), PrimaryKey("Code")]
public class Currency {
[Column("code")]
public required string Code { get; init; }
public string Code { get; private set; } = null!;
[Column("name")]
public required string Name { get; init; }
public string Name { get; private set; } = null!;
[Column("symbol")]
public string? Symbol { get; init; }
public string? Symbol { get; private set; }
[Column("one_euro")]
public long? OneEuroValue { get; init; }
public long? OneEuroValue { get; private set; }
[NotMapped]
public decimal? OneEuro => OneEuroValue != null ? Utils.DecFromDb(OneEuroValue.Value, 6) : null;
+4 -4
View File
@@ -46,7 +46,7 @@ namespace Elwig.Models.Entities {
public required string ZwstId { get; set; }
[ForeignKey("ZwstId")]
public virtual Branch Branch { get; init; } = null!;
public virtual Branch Branch { get; private set; } = null!;
[Column("lnr")]
public int LNr { get; set; }
@@ -58,7 +58,7 @@ namespace Elwig.Models.Entities {
public int MgNr { get; set; }
[ForeignKey("MgNr")]
public virtual Member Member { get; init; } = null!;
public virtual Member Member { get; private set; } = null!;
[Column("comment")]
public string? Comment { get; set; }
@@ -101,10 +101,10 @@ namespace Elwig.Models.Entities {
}
[ForeignKey("Year")]
public virtual Season Season { get; init; } = null!;
public virtual Season Season { get; private set; } = null!;
[InverseProperty(nameof(DeliveryPart.Delivery))]
public virtual ICollection<DeliveryPart> Parts { get; init; } = null!;
public virtual ICollection<DeliveryPart> Parts { get; private set; } = null!;
[NotMapped]
public IEnumerable<DeliveryPart> FilteredParts => PartFilter == null ? Parts : Parts.Where(p => PartFilter(p));
+3 -3
View File
@@ -59,13 +59,13 @@ namespace Elwig.Models.Entities {
}
[ForeignKey("Year, DsNr")]
public virtual DeliverySchedule Schedule { get; init; } = null!;
public virtual DeliverySchedule Schedule { get; private set; } = null!;
[ForeignKey("MgNr")]
public virtual Member Member { get; init; } = null!;
public virtual Member Member { get; private set; } = null!;
[ForeignKey("SortId")]
public virtual WineVar Variety { get; init; } = null!;
public virtual WineVar Variety { get; private set; } = null!;
public int SearchScore(IEnumerable<string> keywords) {
return Utils.GetSearchScore([
+11 -11
View File
@@ -21,7 +21,7 @@ namespace Elwig.Models.Entities {
public int DId { get; set; }
[ForeignKey("Year, DId")]
public virtual Delivery Delivery { get; init; } = null!;
public virtual Delivery Delivery { get; private set; } = null!;
[Column("dpnr")]
public int DPNr { get; set; }
@@ -30,19 +30,19 @@ namespace Elwig.Models.Entities {
public required string SortId { get; set; }
[ForeignKey("SortId")]
public virtual WineVar Variety { get; init; } = null!;
public virtual WineVar Variety { get; private set; } = null!;
[Column("attrid")]
public string? AttrId { get; set; }
[ForeignKey("AttrId")]
public virtual WineAttr? Attribute { get; init; }
public virtual WineAttr? Attribute { get; private set; }
[Column("cultid")]
public string? CultId { get; set; }
[ForeignKey("CultId")]
public virtual WineCult? Cultivation { get; init; }
public virtual WineCult? Cultivation { get; private set; }
[Column("weight")]
public int Weight { get; set; }
@@ -59,25 +59,25 @@ namespace Elwig.Models.Entities {
public required string QualId { get; set; }
[ForeignKey("QualId")]
public virtual WineQualLevel Quality { get; init; } = null!;
public virtual WineQualLevel Quality { get; private set; } = null!;
[Column("hkid")]
public required string HkId { get; set; }
[ForeignKey("HkId")]
public virtual WineOrigin Origin { get; init; } = null!;
public virtual WineOrigin Origin { get; private set; } = null!;
[Column("kgnr")]
public int? KgNr { get; set; }
[ForeignKey("KgNr")]
public virtual WbKg? Kg { get; init; }
public virtual WbKg? Kg { get; private set; }
[Column("rdnr")]
public int? RdNr { get; set; }
[ForeignKey("KgNr, RdNr")]
public virtual WbRd? Rd { get; init; }
public virtual WbRd? Rd { get; private set; }
[Column("net_weight")]
public bool IsNetWeight { get; set; }
@@ -183,18 +183,18 @@ namespace Elwig.Models.Entities {
}
[InverseProperty(nameof(DeliveryPartModifier.Part))]
public virtual ICollection<DeliveryPartModifier> PartModifiers { get; init; } = null!;
public virtual ICollection<DeliveryPartModifier> PartModifiers { get; private set; } = null!;
[NotMapped]
public IEnumerable<Modifier> Modifiers => PartModifiers.Select(m => m.Modifier).OrderBy(m => m.Ordering);
[InverseProperty(nameof(PaymentDeliveryPart.DeliveryPart))]
public virtual PaymentDeliveryPart? Payment { get; init; }
public virtual PaymentDeliveryPart? Payment { get; private set; }
[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}" : "");
[InverseProperty(nameof(DeliveryPartBucket.Part))]
public virtual ICollection<DeliveryPartBucket> Buckets { get; init; } = null!;
public virtual ICollection<DeliveryPartBucket> Buckets { get; private set; } = null!;
}
}
+1 -1
View File
@@ -23,6 +23,6 @@ namespace Elwig.Models.Entities {
public int Value { get; set; }
[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; }
[ForeignKey("Year, DId, DPNr")]
public virtual DeliveryPart Part { get; init; } = null!;
public virtual DeliveryPart Part { get; private set; } = null!;
[Column("modid")]
public required string ModId { get; set; }
[ForeignKey("Year, ModId")]
public virtual Modifier Modifier { get; init; } = null!;
public virtual Modifier Modifier { get; private set; } = null!;
}
}
+6 -6
View File
@@ -72,22 +72,22 @@ namespace Elwig.Models.Entities {
}
[ForeignKey("Year")]
public virtual Season Season { get; init; } = null!;
public virtual Season Season { get; private set; } = null!;
[ForeignKey("ZwstId")]
public virtual Branch Branch { get; init; } = null!;
public virtual Branch Branch { get; private set; } = null!;
[ForeignKey("AttrId")]
public virtual WineAttr? Attribute { get; init; }
public virtual WineAttr? Attribute { get; private set; }
[ForeignKey("CultId")]
public virtual WineCult? Cultivation { get; init; }
public virtual WineCult? Cultivation { get; private set; }
[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))]
public virtual ICollection<DeliveryAncmt> Announcements { get; init; } = null!;
public virtual ICollection<DeliveryAncmt> Announcements { get; private set; } = null!;
public int SearchScore(IEnumerable<string> keywords) {
return Utils.GetSearchScore([Description], keywords);
@@ -18,9 +18,9 @@ namespace Elwig.Models.Entities {
public int Priority { get; set; }
[ForeignKey("Year, DsNr")]
public virtual DeliverySchedule Schedule { get; init; } = null!;
public virtual DeliverySchedule Schedule { get; private set; } = null!;
[ForeignKey("SortId")]
public virtual WineVar Variety { get; init; } = null!;
public virtual WineVar Variety { get; private set; } = null!;
}
}
+16 -16
View File
@@ -133,10 +133,10 @@ namespace Elwig.Models.Entities {
public int CountryNum { get; set; }
[Column("postal_dest")]
public required string PostalDestId { get; set; }
public string PostalDestId { get; set; } = null!;
[Column("address")]
public required string Address { get; set; }
public string Address { get; set; } = null!;
[Column("default_kgnr")]
public int? DefaultKgNr { get; set; }
@@ -151,16 +151,16 @@ namespace Elwig.Models.Entities {
public string? Comment { get; set; }
[ForeignKey("PredecessorMgNr")]
public virtual Member? Predecessor { get; init; }
public virtual Member? Predecessor { get; private set; }
[ForeignKey("CountryNum")]
public virtual Country Country { get; init; } = null!;
public virtual Country Country { get; private set; } = null!;
[ForeignKey("CountryNum, PostalDestId")]
public virtual PostalDest PostalDest { get; init; } = null!;
public virtual PostalDest PostalDest { get; private set; } = null!;
[ForeignKey("DefaultKgNr")]
public virtual WbKg? DefaultWbKg { get; init; }
public virtual WbKg? DefaultWbKg { get; private set; }
[NotMapped]
public AT_Kg? DefaultKg => DefaultWbKg?.AtKg;
@@ -197,37 +197,37 @@ namespace Elwig.Models.Entities {
}
[ForeignKey("ZwstId")]
public virtual Branch? Branch { get; init; }
public virtual Branch? Branch { get; private set; }
[InverseProperty(nameof(AreaCmt.Member))]
public virtual ICollection<AreaCmt> AreaCommitments { get; init; } = null!;
public virtual ICollection<AreaCmt> AreaCommitments { get; private set; } = null!;
public IQueryable<AreaCmt> ActiveAreaCommitments(AppDbContext ctx, int? year = null) {
return ctx.AreaCommitments.Where(c => c.MgNr == MgNr).Where(Utils.ActiveAreaCommitments(year ?? Utils.CurrentYear));
}
[InverseProperty(nameof(BillingAddr.Member))]
public virtual BillingAddr? BillingAddress { get; init; }
public virtual BillingAddr? BillingAddress { get; private set; }
[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))]
public virtual ICollection<MemberHistory> HistoryFrom { get; init; } = null!;
public virtual ICollection<MemberHistory> HistoryFrom { get; private set; } = null!;
[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))]
public virtual ICollection<Delivery> Deliveries { get; init; } = null!;
public virtual ICollection<Delivery> Deliveries { get; private set; } = null!;
[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))]
public virtual ICollection<MemberTelNr> TelephoneNumbers { get; init; } = null!;
public virtual ICollection<MemberTelNr> TelephoneNumbers { get; private set; } = null!;
[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}";
+1 -1
View File
@@ -17,6 +17,6 @@ namespace Elwig.Models.Entities {
public string? Comment { get; set; }
[ForeignKey("MgNr")]
public virtual Member Member { get; init; } = null!;
public virtual Member Member { get; private set; } = null!;
}
}
+3 -3
View File
@@ -119,12 +119,12 @@ namespace Elwig.Models.Entities {
public string PoVReasonPhrase => FormatReasonPhrase(PoVMgNr ?? 0);
[ForeignKey("FromMgNr")]
public virtual Member? FromMember { get; init; } = null!;
public virtual Member? FromMember { get; private set; } = null!;
[ForeignKey("ToMgNr")]
public virtual Member? ToMember { get; init; } = null!;
public virtual Member? ToMember { get; private set; } = null!;
[ForeignKey("CurrencyCode")]
public virtual Currency Currency { get; init; } = null!;
public virtual Currency Currency { get; private set; } = null!;
}
}
+1 -1
View File
@@ -20,6 +20,6 @@ namespace Elwig.Models.Entities {
public string? Comment { get; set; }
[ForeignKey("MgNr")]
public virtual Member Member { get; init; } = null!;
public virtual Member Member { get; private set; } = null!;
}
}
+1 -1
View File
@@ -42,7 +42,7 @@ namespace Elwig.Models.Entities {
}
[ForeignKey("Year")]
public virtual Season Season { get; init; } = null!;
public virtual Season Season { get; private set; } = null!;
public string ValueStr =>
(Abs != null) ? $"{Utils.GetSign(Abs.Value)}{Math.Abs(Abs.Value).ToString("0." + string.Concat(Enumerable.Repeat('0', Season.Precision)))}\u00a0{Season.Currency.Symbol}/kg" :
+2 -2
View File
@@ -42,9 +42,9 @@ namespace Elwig.Models.Entities {
public string? Comment { get; set; }
[ForeignKey("Year")]
public virtual Season Season { get; init; } = null!;
public virtual Season Season { get; private set; } = null!;
[ForeignKey("MgNr")]
public virtual Member Member { get; init; } = null!;
public virtual Member Member { get; private set; } = null!;
}
}
+3 -3
View File
@@ -41,14 +41,14 @@ namespace Elwig.Models.Entities {
}
[Column("amount")]
public long AmountValue { get; init; }
public long AmountValue { get; private set; }
[NotMapped]
public decimal Amount => Variant.Season.DecFromDb(AmountValue);
[ForeignKey("Year, AvNr")]
public virtual PaymentVar Variant { get; init; } = null!;
public virtual PaymentVar Variant { get; private set; } = null!;
[ForeignKey("Year, DId, DPNr")]
public virtual DeliveryPart DeliveryPart { get; init; } = null!;
public virtual DeliveryPart DeliveryPart { get; private set; } = null!;
}
}
@@ -36,9 +36,9 @@ namespace Elwig.Models.Entities {
}
[ForeignKey("Year, AvNr")]
public virtual PaymentVar Variant { get; init; } = null!;
public virtual PaymentVar Variant { get; private set; } = null!;
[ForeignKey("Year, DId, DPNr")]
public virtual DeliveryPart DeliveryPart { get; init; } = null!;
public virtual DeliveryPart DeliveryPart { get; private set; } = null!;
}
}
+4 -4
View File
@@ -38,17 +38,17 @@ namespace Elwig.Models.Entities {
}
[Column("amount")]
public long AmountValue { get; init; }
public long AmountValue { get; private set; }
[NotMapped]
public decimal Amount => Variant.Season.DecFromDb(AmountValue);
[ForeignKey("Year, AvNr")]
public virtual PaymentVar Variant { get; init; } = null!;
public virtual PaymentVar Variant { get; private set; } = null!;
[ForeignKey("MgNr")]
public virtual Member Member { get; init; } = null!;
public virtual Member Member { get; private set; } = null!;
[InverseProperty(nameof(Credit.Payment))]
public virtual Credit? Credit { get; init; }
public virtual Credit? Credit { get; private set; }
}
}
+4 -4
View File
@@ -78,15 +78,15 @@ namespace Elwig.Models.Entities {
}
[ForeignKey("Year")]
public virtual Season Season { get; init; } = null!;
public virtual Season Season { get; private set; } = null!;
[InverseProperty(nameof(PaymentMember.Variant))]
public virtual ICollection<PaymentMember> MemberPayments { get; init; } = null!;
public virtual ICollection<PaymentMember> MemberPayments { get; private set; } = null!;
[InverseProperty(nameof(PaymentDeliveryPart.Variant))]
public virtual ICollection<PaymentDeliveryPart> DeliveryPartPayments { get; init; } = null!;
public virtual ICollection<PaymentDeliveryPart> DeliveryPartPayments { get; private set; } = null!;
[InverseProperty(nameof(Credit.Variant))]
public virtual ICollection<Credit> Credits { get; init; } = null!;
public virtual ICollection<Credit> Credits { get; private set; } = null!;
}
}
+4 -4
View File
@@ -5,15 +5,15 @@ namespace Elwig.Models.Entities {
[Table("postal_dest"), PrimaryKey("CountryNum", "Id")]
public class PostalDest {
[Column("country")]
public int CountryNum { get; init; }
public int CountryNum { get; private set; }
[Column("id")]
public required string Id { get; init; }
public string Id { get; private set; } = null!;
[ForeignKey("CountryNum")]
public virtual Country Country { get; init; } = null!;
public virtual Country Country { get; private set; } = null!;
[ForeignKey("Id")]
public virtual AT_PlzDest? AtPlz { get; init; }
public virtual AT_PlzDest? AtPlz { get; private set; }
}
}
+4 -4
View File
@@ -123,16 +123,16 @@ namespace Elwig.Models.Entities {
}
[ForeignKey("CurrencyCode")]
public virtual Currency Currency { get; init; } = null!;
public virtual Currency Currency { get; private set; } = null!;
[InverseProperty(nameof(Modifier.Season))]
public virtual ICollection<Modifier> Modifiers { get; init; } = null!;
public virtual ICollection<Modifier> Modifiers { get; private set; } = null!;
[InverseProperty(nameof(PaymentVar.Season))]
public virtual ICollection<PaymentVar> PaymentVariants { get; init; } = null!;
public virtual ICollection<PaymentVar> PaymentVariants { get; private set; } = null!;
[InverseProperty(nameof(Delivery.Season))]
public virtual ICollection<Delivery> Deliveries { get; init; } = null!;
public virtual ICollection<Delivery> Deliveries { get; private set; } = null!;
public decimal DecFromDb(long value) {
return Utils.DecFromDb(value, Precision);
+4 -4
View File
@@ -5,15 +5,15 @@ namespace Elwig.Models.Entities {
[Table("wb_gem"), PrimaryKey("Gkz")]
public class WbGem {
[Column("gkz")]
public int Gkz { get; init; }
public int Gkz { get; private set; }
[Column("hkid")]
public required string HkId { get; init; }
public string HkId { get; private set; } = null!;
[ForeignKey("Gkz")]
public virtual AT_Gem AtGem { get; init; } = null!;
public virtual AT_Gem AtGem { get; private set; } = null!;
[ForeignKey("HkId")]
public virtual WineOrigin Origin { get; init; } = null!;
public virtual WineOrigin Origin { get; private set; } = null!;
}
}
+2 -2
View File
@@ -9,9 +9,9 @@ namespace Elwig.Models.Entities {
public int GlNr { get; set; }
[Column("name")]
public required string Name { get; set; }
public string Name { get; set; } = null!;
[InverseProperty(nameof(WbKg.Gl))]
public virtual ICollection<WbKg> Kgs { get; init; } = null!;
public virtual ICollection<WbKg> Kgs { get; private set; } = null!;
}
}
+4 -4
View File
@@ -12,16 +12,16 @@ namespace Elwig.Models.Entities {
public int? GlNr { get; set; }
[ForeignKey("KgNr")]
public virtual AT_Kg AtKg { get; init; } = null!;
public virtual AT_Kg AtKg { get; private set; } = null!;
[ForeignKey("GlNr")]
public virtual WbGl? Gl { get; init; } = null!;
public virtual WbGl? Gl { get; private set; } = null!;
[InverseProperty(nameof(WbRd.Kg))]
public virtual ICollection<WbRd> Rds { get; init; } = null!;
public virtual ICollection<WbRd> Rds { get; private set; } = null!;
[InverseProperty(nameof(Member.DefaultWbKg))]
public virtual ICollection<Member> Members { get; init; } = null!;
public virtual ICollection<Member> Members { get; private set; } = null!;
[NotMapped]
public WbGem Gem => AtKg.Gem.WbGem!;
+1 -1
View File
@@ -14,6 +14,6 @@ namespace Elwig.Models.Entities {
public required string Name { get; set; }
[ForeignKey("KgNr")]
public virtual WbKg Kg { get; init; } = null!;
public virtual WbKg Kg { get; private set; } = null!;
}
}
-10
View File
@@ -23,16 +23,6 @@ namespace Elwig.Models.Entities {
[Column("fill_lower")]
public int FillLower { get; set; }
[Column("min_qualid")]
public string? MinQualId { get; set; }
[ForeignKey("MinQualId")]
public virtual WineQualLevel MinQualityLevel { get; init; } = null!;
[Column("max_qualid")]
public string? MaxQualId { get; set; }
[ForeignKey("MaxQualId")]
public virtual WineQualLevel MaxQualityLevel { get; init; } = null!;
public override string ToString() {
return Name;
}
+8 -8
View File
@@ -9,27 +9,27 @@ namespace Elwig.Models.Entities {
[Table("wine_origin"), PrimaryKey("HkId"), Index("Name", IsUnique = true)]
public class WineOrigin {
[Column("hkid")]
public required string HkId { get; init; }
public string HkId { get; private set; } = null!;
[Column("parent_hkid")]
public string? ParentHkId { get; init; }
public string? ParentHkId { get; private set; }
[ForeignKey("ParentHkId")]
public virtual WineOrigin? Parent { get; init; }
public virtual WineOrigin? Parent { get; private set; }
[Column("name")]
public required string Name { get; init; }
public string Name { get; private set; } = null!;
[Column("blnr")]
public int? BlNr { get; init; }
public int? BlNr { get; private set; }
[InverseProperty(nameof(WbGem.Origin))]
public virtual ICollection<WbGem> Gems { get; init; } = null!;
public virtual ICollection<WbGem> Gems { get; private set; } = null!;
[InverseProperty(nameof(Parent))]
public virtual ICollection<WineOrigin> RealChildren { get; init; } = null!;
public virtual ICollection<WineOrigin> RealChildren { get; private set; } = null!;
[NotMapped]
public List<WineOrigin> Children { get; init; } = [];
public List<WineOrigin> Children { get; private set; } = [];
public int Level => (Parent?.Level + 1) ?? 0;
+5 -5
View File
@@ -7,22 +7,22 @@ namespace Elwig.Models.Entities {
[Table("wine_quality_level"), PrimaryKey("QualId")]
public class WineQualLevel : IEquatable<WineQualLevel> {
[Column("qualid")]
public required string QualId { get; init; }
public string QualId { get; private set; } = null!;
[Column("origin_level")]
public int? OriginLevel { get; init; }
public int? OriginLevel { get; private set; }
[Column("predicate")]
public bool IsPredicate { get; init; }
public bool IsPredicate { get; private set; }
[Column("min_kmw")]
public double? MinKmw { get; init; }
public double? MinKmw { get; private set; }
[NotMapped]
public double? MinOe => MinKmw != null ? Utils.KmwToOe((double)MinKmw) : null;
[Column("name")]
public required string Name { get; init; }
public string Name { get; private set; } = null!;
public string MinKmwStr => (MinKmw == null) ? "" : $"(mind. {MinKmw:#.0}°)";
+14 -6
View File
@@ -6,22 +6,22 @@ namespace Elwig.Models.Entities {
[Table("wine_variety"), PrimaryKey("SortId")]
public class WineVar {
[Column("sortid")]
public required string SortId { get; init; }
public string SortId { get; private set; } = null!;
[Column("type")]
public required string Type { get; init; }
public string Type { get; private set; } = null!;
[Column("max_qualid")]
public required string MaxQualId { get; init; }
public string MaxQualId { get; private set; } = null!;
[ForeignKey("MaxQualId")]
public virtual WineQualLevel MaxQualityLevel { get; init; } = null!;
public virtual WineQualLevel MaxQualityLevel { get; private set; } = null!;
[Column("name")]
public required string Name { get; init; }
public string Name { get; private set; } = null!;
[Column("comment")]
public string? Comment { get; init; }
public string? Comment { get; private set; }
public string SortIdFormat => IsQuw ? SortId : $"({SortId})";
public string CommentFormat => (Comment != null) ? $" ({Comment})" : "";
@@ -31,6 +31,14 @@ namespace Elwig.Models.Entities {
public bool IsQuw => MaxQualId == "QUW";
public Brush? Color => IsWhite ? Brushes.DarkGreen : IsRed ? Brushes.DarkRed : null;
public WineVar() { }
public WineVar(string sortId, string name) {
SortId = sortId;
Name = name;
MaxQualId = "QUW";
}
public override string ToString() {
return Name;
}
@@ -9,7 +9,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
<PublishDir>bin\Publish</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<_TargetId>Folder</_TargetId>
<TargetFramework>net11.0-windows</TargetFramework>
<TargetFramework>net10.0-windows</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>false</PublishSingleFile>
-24
View File
@@ -1,24 +0,0 @@
-- schema version 42 to 43
ALTER TABLE wine_attribute ADD COLUMN min_qualid TEXT DEFAULT NULL;
ALTER TABLE wine_attribute ADD COLUMN max_qualid TEXT DEFAULT NULL;
UPDATE wine_attribute SET min_qualid = 'KAB', max_qualid = 'KAB' WHERE name LIKE '%Kabinett%';
UPDATE wine_attribute SET min_qualid = 'QUW' WHERE name LIKE '%DAC%';
UPDATE wine_attribute SET max_qualid = 'RSW' WHERE name LIKE '%wei%gepresst%' OR name LIKE '%saft%';
PRAGMA writable_schema = ON;
UPDATE sqlite_schema SET sql = REPLACE(sql, '
) STRICT', ',
CONSTRAINT fk_wine_attribute_wine_quality_level_min FOREIGN KEY (min_qualid) REFERENCES wine_quality_level (qualid)
ON UPDATE CASCADE
ON DELETE RESTRICT,
CONSTRAINT fk_wine_attribute_wine_quality_level_max FOREIGN KEY (max_qualid) REFERENCES wine_quality_level (qualid)
ON UPDATE CASCADE
ON DELETE RESTRICT
) STRICT')
WHERE type = 'table' AND name = 'wine_attribute';
PRAGMA schema_version = 4201;
PRAGMA writable_schema = OFF;
+2 -2
View File
@@ -28,7 +28,7 @@ namespace Elwig.Services {
}
public static async Task BackupDatabase() {
await Database.ExportSql(Path.Combine(App.Config.BackupPath, $"{File.GetLastWriteTime(App.Config.DatabaseFile):yyyy-MM-dd_HH-mm-ss}.sql.zip"), true, App.Config.BackupEncryptionKey);
await Database.ExportSql(Path.Combine(App.Config.BackupPath, $"{File.GetLastWriteTime(App.Config.DatabaseFile):yyyy-MM-dd_HH-mm-ss}.sql.zip"), true);
}
public static void PruneBackups() {
@@ -122,7 +122,7 @@ namespace Elwig.Services {
if (!InteractionService.AskContinue("Datenbank wiederherstellen", "Soll die Datenbank wirklich unwiederruflich durch die wiederhergestellte Version ersetzt werden?"))
return;
Mouse.OverrideCursor = Cursors.Wait;
await App.ReplaceDatabase(d.FileName, App.Config.BackupDecryptionKeys);
await App.ReplaceDatabase(d.FileName);
}
} catch (Exception exc) {
InteractionService.ShowException(exc);
+1 -1
View File
@@ -833,7 +833,7 @@ namespace Elwig.Services {
}
} else if (mode == ExportMode.Upload && App.Config.SyncUrl != null) {
await Utils.RunForeground(async () => {
await SyncService.Upload(App.Config.SyncUrl, App.Config.SyncUrl, App.Config.SyncPassword, query, filterNames, App.Config.SyncEncryptionKey);
await SyncService.Upload(App.Config.SyncUrl, App.Config.SyncUrl, App.Config.SyncPassword, query, filterNames);
});
} else {
await Utils.RunForeground(async () => {
+8 -13
View File
@@ -2,20 +2,19 @@ using Microsoft.Data.Sqlite;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows;
namespace Elwig.Services {
public static class InteractionService {
public static Func<string, string, string, string?>? Override { get; set; }
public static Action<string, string>? NextInformation { get; set; }
public static Action<string, string>? NextWarning { get; set; }
public static Action<string, string>? NextError { get; set; }
public static Func<string, string, bool>? NextContinue { get; set; }
public static Func<string, string, bool>? NextConfirmation { get; set; }
public static Func<string, string, bool>? NextQuestion { get; set; }
public static Func<string, string, string?>? NextSave { get; set; }
public static Func<string, string, string, string?>? Override;
public static Action<string, string>? NextInformation;
public static Action<string, string>? NextWarning;
public static Action<string, string>? NextError;
public static Func<string, string, bool>? NextContinue;
public static Func<string, string, bool>? NextConfirmation;
public static Func<string, string, bool>? NextQuestion;
public static Func<string, string, string?>? NextSave;
public static readonly Dictionary<string, string> ExtensionFilters = new() {
["pdf"] = "PDF-Datei (*.pdf)|*.pdf",
@@ -148,10 +147,6 @@ namespace Elwig.Services {
text += exc.Message + (showExcType ? $" ({exc.GetType().Name})" : "");
if (exc.InnerException != null) text += "\n\n" + exc.InnerException.Message;
}
if (App.Config.Debug && exc.StackTrace != null) {
var m = Regex.Match(exc.StackTrace, @"\\([^:\\]*):line ([0-9]+)");
if (m != null) text += "\n\n" + m.Groups[1] + ": line " + m.Groups[2];
}
if (isError) {
ShowError(title, text);
} else {
+6 -5
View File
@@ -172,7 +172,8 @@ namespace Elwig.Services {
vm.StatusAreaCommitmentToolTip = null;
Utils.RunBackground("Mitgliederdaten laden", async () => {
if (App.Current?.Dispatcher == null) return;
if (App.MainDispatcher == null)
return;
using var ctx = new AppDbContext();
var d1 = ctx.Deliveries.Where(d => d.Year == Utils.CurrentLastSeason - 1 && d.MgNr == m.MgNr);
@@ -196,7 +197,7 @@ namespace Elwig.Services {
.GroupBy(d => d.Year)
.ToDictionaryAsync(g => g.Key, g => g.Any());
await App.Current.Dispatcher.BeginInvoke(() => {
await App.MainDispatcher.BeginInvoke(() => {
if (m.MgNr != vm.MgNr)
return;
var (d1Grid, _) = DeliveryService.GenerateToolTip(d1GridData, []);
@@ -223,9 +224,9 @@ namespace Elwig.Services {
} else {
vm.OrganicDetails = "...";
Utils.RunBackground("Bio-Zertifikatsdaten laden", async () => {
if (App.Current?.Dispatcher == null) return;
if (App.MainDispatcher == null) return;
var certs = await OrganicService.GetTracesCertificates(m);
await App.Current.Dispatcher.BeginInvoke(() => {
await App.MainDispatcher.BeginInvoke(() => {
if (m.MgNr != vm.MgNr) return;
vm.FillOrganicInputs(certs.FirstOrDefault(c => c.IsValidForWineProduction));
});
@@ -601,7 +602,7 @@ namespace Elwig.Services {
}
} else if (mode == ExportMode.Upload && App.Config.SyncUrl != null) {
await Utils.RunForeground(async () => {
await SyncService.Upload(App.Config.SyncUrl, App.Config.SyncUrl, App.Config.SyncPassword, query, filterNames, App.Config.SyncEncryptionKey);
await SyncService.Upload(App.Config.SyncUrl, App.Config.SyncUrl, App.Config.SyncPassword, query, filterNames);
});
} else {
await Utils.RunForeground(async () => {
+4 -2
View File
@@ -112,6 +112,8 @@ namespace Elwig.Services {
}
private static async Task UpdateSums(this PaymentVariantsViewModel vm, PaymentVar v) {
if (App.MainDispatcher == null)
return;
var modText = "-";
var totalText = "-";
var vatText = "-";
@@ -131,7 +133,7 @@ namespace Elwig.Services {
.SumAsync(p => p.AmountValue);
totalText = $"{v.Season.DecFromDb(totalSum):N2} {sym}";
await App.Current.Dispatcher.BeginInvoke(() => {
await App.MainDispatcher.BeginInvoke(() => {
if (vm.SelectedPaymentVariant != v)
return;
vm.StatusModifierSum = modText;
@@ -173,7 +175,7 @@ namespace Elwig.Services {
paymentText = $"{Utils.DecFromDb(await credits.SumAsync(c => c.AmountValue), 2):N2} {sym}";
}
await App.Current.Dispatcher.BeginInvoke(() => {
await App.MainDispatcher.BeginInvoke(() => {
if (vm.SelectedPaymentVariant != v)
return;
vm.StatusModifierSum = modText;
+13 -26
View File
@@ -18,7 +18,7 @@ namespace Elwig.Services {
public static readonly Expression<Func<AreaCmtContract, bool>> ChangedAreaCmtContracts = (c) => ((c.XTime == null && c.MTime > 1751328000) || c.MTime > c.XTime) && (c.ITime == null || c.MTime > c.ITime);
public static readonly Expression<Func<Delivery, bool>> ChangedDeliveries = (d) => ((d.XTime == null && d.MTime > 1751328000) || d.MTime > d.XTime) && (d.ITime == null || d.MTime > d.ITime);
public static async Task Upload(string url, string username, ReadOnlyMemory<char> password, IQueryable<Member> query, IEnumerable<string> filterNames, ReadOnlyMemory<char> key = default) {
public static async Task Upload(string url, string username, string password, IQueryable<Member> query, IEnumerable<string> filterNames) {
try {
var filename = $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{App.ZwstId}.elwig.zip";
var path = Path.Combine(App.TempPath, filename);
@@ -54,7 +54,7 @@ namespace Elwig.Services {
InteractionService.ShowError("Mitglieder hochladen", "Es wurden keine Mitglieder zum Hochladen ausgewählt!");
} else {
var exportedAt = DateTime.Now;
await ElwigData.Export(path, members, history, areaCmts, wbKgs, filterNames, key);
await ElwigData.Export(path, members, history, areaCmts, wbKgs, filterNames);
await Utils.UploadExportData(path, url, username, password);
await UpdateExportedAt(members, areaCmts, [], exportedAt);
InteractionService.ShowInformation("Mitglieder hochgeladen", $"Hochladen von {members.Count:N0} Mitgliedern erfolgreich!");
@@ -68,7 +68,7 @@ namespace Elwig.Services {
}
}
public static async Task Upload(string url, string username, ReadOnlyMemory<char> password, IQueryable<DeliveryPart> query, IEnumerable<string> filterNames, ReadOnlyMemory<char> key = default) {
public static async Task Upload(string url, string username, string password, IQueryable<DeliveryPart> query, IEnumerable<string> filterNames) {
try {
var filename = $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{App.ZwstId}.elwig.zip";
var path = Path.Combine(App.TempPath, filename);
@@ -88,7 +88,7 @@ namespace Elwig.Services {
InteractionService.ShowError("Lieferungen hochladen", "Es wurden keine Lieferungen zum Hochladen ausgewählt!");
} else {
var exportedAt = DateTime.Now;
await ElwigData.Export(path, list, wbKgs, filterNames, key);
await ElwigData.Export(path, list, wbKgs, filterNames);
await Utils.UploadExportData(path, url, username, password);
await UpdateExportedAt([], [], list, exportedAt);
InteractionService.ShowInformation("Lieferungen hochgeladen", $"Hochladen von {list.Count:N0} Lieferungen erfolgreich!");
@@ -102,11 +102,10 @@ namespace Elwig.Services {
}
}
public static async Task UploadModified(string url, string username, ReadOnlyMemory<char> password, ReadOnlyMemory<char> key = default) {
public static async Task UploadModified(string url, string username, string password) {
try {
var path = Path.Combine(App.TempPath, $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{App.ZwstId}.elwig.zip");
List<Member> members;
List<MemberHistory> history;
List<AreaCmtContract> areaCmts;
List<Delivery> deliveries;
using (var ctx = new AppDbContext()) {
@@ -116,17 +115,6 @@ namespace Elwig.Services {
.Include(m => m.EmailAddresses)
.OrderBy(m => m.MgNr)
.ToListAsync();
var history1 = await ctx.Members.IgnoreAutoIncludes()
.Where(ChangedMembers)
.SelectMany(m => m.HistoryFrom)
.ToListAsync();
var history2 = await ctx.Members.IgnoreAutoIncludes()
.Where(ChangedMembers)
.SelectMany(m => m.HistoryTo)
.ToListAsync();
history = [.. history1.Union(history2)
.DistinctBy(h => h.HistNr)
.OrderBy(h => h.DateNotice).ThenBy(h => h.HistNr)];
areaCmts = await ctx.AreaCommitmentContracts
.Where(ChangedAreaCmtContracts)
.Include(c => c.Revisions)
@@ -154,11 +142,10 @@ namespace Elwig.Services {
var exportedAt = DateTime.Now;
await (new ElwigData.ElwigExport {
Members = (members, ["geändert seit letztem Export"]),
History = (history, ["von exportierten Mitgliedern"]),
AreaCmts = (areaCmts, ["geändert seit letztem Export"]),
Deliveries = (deliveries, ["geändert seit letzem Export"]),
WbKgs = (wbKgs, ["von exportierten Mitgliedern, Flächenbindungen und Lieferungen"]),
}).Export(path, key);
}).Export(path);
await Utils.UploadExportData(path, url, username, password);
await UpdateExportedAt(members, areaCmts, deliveries, exportedAt);
InteractionService.ShowInformation("Mitglieder und Lieferungen hochladen", $"Hochladen von {members.Count:N0} Mitgliedern, {areaCmts.Count:N0} Flächenbindungsverträgen, und {deliveries.Count:N0} Lieferungen erfolgreich!");
@@ -172,7 +159,7 @@ namespace Elwig.Services {
}
}
public static async Task UploadBranchDeliveries(string url, string username, ReadOnlyMemory<char> password, int? year = null, ReadOnlyMemory<char> key = default) {
public static async Task UploadBranchDeliveries(string url, string username, string password, int? year = null) {
try {
year ??= Utils.CurrentLastSeason;
var path = Path.Combine(App.TempPath, $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{App.ZwstId}.elwig.zip");
@@ -192,7 +179,7 @@ namespace Elwig.Services {
InteractionService.ShowError("Lieferungen hochladen", "Es gibt keine Lieferungen, die hochgeladen werden können!");
} else {
var exportedAt = DateTime.Now;
await ElwigData.Export(path, deliveries, wbKgs, [$"{year}", $"Zweigstelle {App.BranchName}"], key);
await ElwigData.Export(path, deliveries, wbKgs, [$"{year}", $"Zweigstelle {App.BranchName}"]);
await Utils.UploadExportData(path, url, username, password);
await UpdateExportedAt([], [], deliveries, exportedAt);
InteractionService.ShowInformation("Lieferungen hochladen", $"Hochladen von {deliveries.Count:N0} Lieferungen erfolgreich!");
@@ -206,7 +193,7 @@ namespace Elwig.Services {
}
}
public static async Task<List<(string Name, string Url)>> GetFilesToImport(string url, string username, ReadOnlyMemory<char> password) {
public static async Task<List<(string Name, string Url)>> GetFilesToImport(string url, string username, string password) {
var data = await Utils.GetExportMetaData(url, username, password);
var files = data
.Select(f => new {
@@ -227,7 +214,7 @@ namespace Elwig.Services {
];
}
public static async Task Download(string url, string username, ReadOnlyMemory<char> password, bool confirmImports, IEnumerable<ReadOnlyMemory<char>>? keys = null) {
public static async Task Download(string url, string username, string password, bool confirmImports) {
try {
var import = await GetFilesToImport(url, username, password);
var paths = new List<string>();
@@ -239,7 +226,7 @@ namespace Elwig.Services {
paths.Add(filename);
}
}
await ElwigData.Import(paths, confirmImports ? ElwigData.ImportMode.Interactively : ElwigData.ImportMode.FromBranches, keys);
await ElwigData.Import(paths, confirmImports ? ElwigData.ImportMode.Interactively : ElwigData.ImportMode.FromBranches);
} catch (HttpRequestException exc) {
InteractionService.ShowException("Daten herunterladen", "Eventuell Internetverbindung prüfen!", exc);
} catch (TaskCanceledException exc) {
@@ -270,7 +257,7 @@ namespace Elwig.Services {
App.HintContextChange();
}
public static async Task<bool> ChangesAvailable(AppDbContext ctx, string url, string username, ReadOnlyMemory<char> password) {
public static async Task<bool> ChangesAvailable(AppDbContext ctx, string url, string username, string password) {
try {
return await ctx.Members.Where(ChangedMembers).AnyAsync() || await ctx.AreaCommitmentContracts.Where(ChangedAreaCmtContracts).AnyAsync() || await ctx.Deliveries.Where(ChangedDeliveries).AnyAsync() || (Utils.HasInternetConnectivity() && (await GetFilesToImport(url, username, password)).Count > 0);
} catch {
@@ -278,7 +265,7 @@ namespace Elwig.Services {
}
}
public static async Task<bool> ChangesAvailable(AppDbContext ctx, string url, string username, ReadOnlyMemory<char> password, int? year = null) {
public static async Task<bool> ChangesAvailable(AppDbContext ctx, string url, string username, string password, int? year = null) {
try {
year ??= Utils.CurrentLastSeason;
return await ctx.Deliveries.Where(d => d.ZwstId == App.ZwstId && d.Year == year).Where(ChangedDeliveries).AnyAsync() || (Utils.HasInternetConnectivity() && (await GetFilesToImport(url, username, password)).Count > 0);
+1 -2
View File
@@ -1,6 +1,5 @@
using CommunityToolkit.Mvvm.ComponentModel;
using Elwig.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
@@ -16,7 +15,7 @@ namespace Elwig.ViewModels {
[ObservableProperty]
public partial string? SearchQuery { get; set; } = "";
public List<string> TextFilter {
get => [.. SearchQuery?.ToLower().Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? []];
get => [.. SearchQuery?.ToLower().Split(' ').ToList().FindAll(e => e.Length > 0) ?? []];
set => SearchQuery = string.Join(' ', value.Where(e => e.Length > 0));
}
+1 -2
View File
@@ -1,7 +1,6 @@
using CommunityToolkit.Mvvm.ComponentModel;
using Elwig.Helpers;
using Elwig.Models.Entities;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
@@ -19,7 +18,7 @@ namespace Elwig.ViewModels {
[ObservableProperty]
public partial string? SearchQuery { get; set; } = "";
public List<string> TextFilter => [.. SearchQuery?.ToLower().Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? []];
public List<string> TextFilter => [.. SearchQuery?.ToLower().Split(' ').ToList().FindAll(e => e.Length > 0) ?? []];
[ObservableProperty]
public partial string? LastScaleError { get; set; }
@@ -1,6 +1,5 @@
using CommunityToolkit.Mvvm.ComponentModel;
using Elwig.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
@@ -14,7 +13,7 @@ namespace Elwig.ViewModels {
[ObservableProperty]
public partial string? SearchQuery { get; set; } = "";
public List<string> TextFilter => [.. SearchQuery?.ToLower().Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? []];
public List<string> TextFilter => [.. SearchQuery?.ToLower().Split(' ').ToList().FindAll(e => e.Length > 0) ?? []];
[ObservableProperty]
public partial bool FilterOnlyUpcoming { get; set; }
@@ -11,7 +11,7 @@ namespace Elwig.ViewModels {
[ObservableProperty]
public partial string? SearchQuery { get; set; } = "";
public List<string> TextFilter => [.. SearchQuery?.ToLower().Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? []];
public List<string> TextFilter => [.. SearchQuery?.ToLower().Split(' ').ToList().FindAll(e => e.Length > 0) ?? []];
[ObservableProperty]
public partial bool FilterOnlyUpcoming { get; set; }
+2 -3
View File
@@ -1,7 +1,6 @@
using CommunityToolkit.Mvvm.ComponentModel;
using Elwig.Helpers;
using Elwig.Models.Entities;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
@@ -18,11 +17,11 @@ namespace Elwig.ViewModels {
public int? TransferPredecessorAreaCmts { get; set; } = null;
public int? CancelAreaCmts { get; set; } = null;
public ObservableCollection<KeyValuePair<string, string>> PhoneNrTypes { get; set; } = [with(Utils.PhoneNrTypes)];
public ObservableCollection<KeyValuePair<string, string>> PhoneNrTypes { get; set; } = new(Utils.PhoneNrTypes);
[ObservableProperty]
public partial string? SearchQuery { get; set; } = "";
public List<string> TextFilter => [.. SearchQuery?.ToLower().Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? []];
public List<string> TextFilter => [.. SearchQuery?.ToLower().Split(' ').ToList().FindAll(e => e.Length > 0) ?? []];
[ObservableProperty]
public partial bool ShowOnlyActiveMembers { get; set; } = true;
+1 -1
View File
@@ -415,7 +415,7 @@ namespace Elwig.Windows {
private void RevisionList_SelectionChanged(object? sender, SelectionChangedEventArgs? evt) {
RefreshInputs();
if (RevisionList.SelectedItem is AreaCmt) {
if (RevisionList.SelectedItem is AreaCmt c) {
EditAreaCommitmentButton.IsEnabled = true;
} else {
EditAreaCommitmentButton.IsEnabled = false;
+16 -49
View File
@@ -247,8 +247,6 @@
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="110"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Label Content="Identifikator:" Margin="10,10,0,10"/>
@@ -260,28 +258,10 @@
TextChanged="WineAttribute_Changed"/>
<CheckBox x:Name="WineAttributeActiveInput" Content="In Übernahme-Fenster anzeigen"
Grid.Column="1" Grid.ColumnSpan="3" Margin="0,74,10,10" HorizontalAlignment="Left" VerticalAlignment="Top"
Grid.Column="1" Margin="0,74,10,10" HorizontalAlignment="Left" VerticalAlignment="Top"
Checked="WineAttribute_Changed" Unchecked="WineAttribute_Changed"/>
<Label Content="Niedrigste Qual.:" Margin="10,10,0,10" Grid.Column="2"/>
<ComboBox x:Name="WineAttributeMinQualityLevelInput" Grid.Column="3" Margin="0,10,10,10" HorizontalAlignment="Stretch"
TextSearch.TextPath="Name"
SelectionChanged="WineAttribute_Changed">
<ComboBox.ItemTemplateSelector>
<ctrl:WineQualityLevelTemplateSelector/>
</ComboBox.ItemTemplateSelector>
</ComboBox>
<Label Content="Höchste Qual.:" Margin="10,40,0,10" Grid.Column="2"/>
<ComboBox x:Name="WineAttributeMaxQualityLevelInput" Grid.Column="3" Margin="0,40,10,10" HorizontalAlignment="Stretch"
TextSearch.TextPath="Name"
SelectionChanged="WineAttribute_Changed">
<ComboBox.ItemTemplateSelector>
<ctrl:WineQualityLevelTemplateSelector/>
</ComboBox.ItemTemplateSelector>
</ComboBox>
<GroupBox Header="Auszahlung" Grid.ColumnSpan="4" Margin="10,100,10,10">
<GroupBox Header="Auszahlung" Grid.ColumnSpan="2" Margin="10,100,10,10">
<Grid>
<Label Content="Max. Ertrag:" Margin="10,10,0,10"/>
<ctrl:UnitTextBox x:Name="WineAttributeMaxKgPerHaInput" Unit="kg/ha" TextChanged="WineAttributeMaxKgPerHaInput_TextChanged"
@@ -571,34 +551,21 @@
</TabItem>
<TabItem Header="Parameter">
<StackPanel>
<StackPanel Orientation="Horizontal">
<GroupBox x:Name="ParameterBusinessShare" Header="Geschäftsanteile" Margin="10,10,10,0" VerticalAlignment="Stretch">
<Grid>
<Label Content="Modus:" Margin="10,10,10,10"/>
<ComboBox x:Name="ParameterBusinessShareModeInput" Margin="160,10,10,10" Width="100"
HorizontalAlignment="Left">
<ComboBoxItem IsSelected="True">Normal</ComboBoxItem>
<ComboBoxItem>Rot/weiß</ComboBoxItem>
</ComboBox>
<GroupBox x:Name="ParameterBusinessShare" Header="Geschäftsanteile" Margin="10,10,10,0" VerticalAlignment="Top">
<Grid>
<Label Content="Modus:" Margin="10,10,10,10"/>
<ComboBox x:Name="ParameterBusinessShareModeInput" Margin="160,10,10,10" Width="100"
HorizontalAlignment="Left">
<ComboBoxItem IsSelected="True">Normal</ComboBoxItem>
<ComboBoxItem>Rot/weiß</ComboBoxItem>
</ComboBox>
<Label Content="Mitgliederbewegungen:" Margin="10,40,10,10"/>
<CheckBox x:Name="ParameterBusinessShareHistoryInput" Content="Mit Elwig erfassen" Margin="160,45,10,15"
HorizontalAlignment="Left"
Checked="CheckBox_Changed" Unchecked="CheckBox_Changed"/>
</Grid>
</GroupBox>
<GroupBox x:Name="ParameterReceipt" Header="Übernahme" Margin="10,10,10,0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Grid>
<Label Content="Höchste Qualitätsstufe:" Margin="10,10,0,10" Grid.Column="2"/>
<ComboBox x:Name="ParameterReceiptMaxQualityLevelInput" Grid.Column="3" Margin="150,10,10,10" Width="130"
TextSearch.TextPath="Name">
<ComboBox.ItemTemplateSelector>
<ctrl:WineQualityLevelTemplateSelector/>
</ComboBox.ItemTemplateSelector>
</ComboBox>
</Grid>
</GroupBox>
</StackPanel>
<Label Content="Mitgliederbewegungen:" Margin="10,40,10,10"/>
<CheckBox x:Name="ParameterBusinessShareHistoryInput" Content="Mit Elwig erfassen" Margin="160,45,10,15"
HorizontalAlignment="Left"
Checked="CheckBox_Changed" Unchecked="CheckBox_Changed"/>
</Grid>
</GroupBox>
<GroupBox x:Name="ParameterAreaCmtGroup" Header="Berechnung Flächenbindungen (aktuelle Saison)" Margin="10,10,10,0" VerticalAlignment="Top">
<Grid>
<CheckBox x:Name="ParameterAllowAttrIntoLowerInput" Content="Erlauben Lieferungen auch auf (konfigurierte) &quot;schlechtere&quot; Flächenbindungen aufzuteilen"
@@ -19,9 +19,9 @@ namespace Elwig.Windows {
private bool _actUpdate = false;
private async Task AreaCommitmentTypesInitEditing(AppDbContext ctx) {
_actList = [with(await ctx.AreaCommitmentTypes
_actList = new(await ctx.AreaCommitmentTypes
.OrderBy(v => v.VtrgId)
.ToListAsync())];
.ToListAsync());
_acts = _actList.ToDictionary(v => v.VtrgId, v => (string?)v.VtrgId);
_actIds = _actList.ToDictionary(v => v, v => v.VtrgId);
ControlUtils.RenewItemsSource(AreaCommitmentTypeList, _actList);
@@ -56,7 +56,7 @@ namespace Elwig.Windows {
.Where(_actIds.ContainsKey)
.Select(t => {
t.VtrgId = _actIds[t];
ctx.Entry(t).State = EntityState.Modified;
ctx.Entry(t).State = EntityState.Added;
return t;
}));
await ctx.SaveChangesAsync();
+2 -2
View File
@@ -19,7 +19,7 @@ namespace Elwig.Windows {
private bool _branchUpdate = false;
private async Task BranchesInitEditing(AppDbContext ctx) {
_branchList = [with(await ctx.FetchBranches().ToListAsync())];
_branchList = new(await ctx.FetchBranches().ToListAsync());
_branches = _branchList.ToDictionary(b => b.ZwstId, b => (string?)b.ZwstId);
_branchIds = _branchList.ToDictionary(b => b, b => b.ZwstId);
ControlUtils.RenewItemsSource(BranchList, _branchList);
@@ -50,7 +50,7 @@ namespace Elwig.Windows {
.Where(_branchIds.ContainsKey)
.Select(b => {
b.ZwstId = _branchIds[b];
ctx.Entry(b).State = EntityState.Modified;
ctx.Entry(b).State = EntityState.Added;
return b;
}));
await ctx.SaveChangesAsync();
+2 -2
View File
@@ -22,7 +22,7 @@ namespace Elwig.Windows {
private async Task ModifiersInitEditing(AppDbContext ctx) {
SeasonList.IsEnabled = false;
var year = (SeasonList.SelectedItem as Season)?.Year;
_modList = [with(await ctx.FetchModifiers(year ?? 0).ToListAsync())];
_modList = new(await ctx.FetchModifiers(year ?? 0).ToListAsync());
_mods = _modList.ToDictionary(m => m.ModId, m => (string?)m.ModId);
_modIds = _modList.ToDictionary(m => m, m => m.ModId);
ControlUtils.RenewItemsSource(SeasonModifierList, _modList);
@@ -61,7 +61,7 @@ namespace Elwig.Windows {
.Where(_modIds.ContainsKey)
.Select(m => {
m.ModId = _modIds[m];
ctx.Entry(m).State = EntityState.Modified;
ctx.Entry(m).State = EntityState.Added;
return m;
}));
await ctx.SaveChangesAsync();
+2 -11
View File
@@ -19,7 +19,7 @@ namespace Elwig.Windows {
private bool _attrUpdate = false;
private async Task WineAttributesInitEditing(AppDbContext ctx) {
_attrList = [with(await ctx.FetchWineAttributes().ToListAsync())];
_attrList = new(await ctx.FetchWineAttributes().ToListAsync());
_attrs = _attrList.ToDictionary(a => a.AttrId, a => (string?)a.AttrId);
_attrIds = _attrList.ToDictionary(a => a, a => a.AttrId);
ControlUtils.RenewItemsSource(WineAttributeList, _attrList);
@@ -50,7 +50,7 @@ namespace Elwig.Windows {
.Where(_attrIds.ContainsKey)
.Select(a => {
a.AttrId = _attrIds[a];
ctx.Entry(a).State = EntityState.Modified;
ctx.Entry(a).State = EntityState.Added;
return a;
}));
await ctx.SaveChangesAsync();
@@ -73,18 +73,13 @@ namespace Elwig.Windows {
WineAttributeIdInput.Text = "";
WineAttributeNameInput.Text = "";
WineAttributeActiveInput.IsChecked = false;
WineAttributeMinQualityLevelInput.SelectedIndex = 0;
WineAttributeMaxQualityLevelInput.SelectedIndex = 0;
WineAttributeMaxKgPerHaInput.Text = "";
WineAttributeStrictInput.IsChecked = false;
WineAttributeFillLowerInput.SelectedItem = null;
} else {
WineAttributeIdInput.Text = attr.AttrId;
WineAttributeNameInput.Text = attr.Name;
WineAttributeActiveInput.IsChecked = attr.IsActive;
ControlUtils.SelectItemWithPk(WineAttributeMinQualityLevelInput, attr.MinQualId);
ControlUtils.SelectItemWithPk(WineAttributeMaxQualityLevelInput, attr.MaxQualId);
WineAttributeMaxKgPerHaInput.Text = attr.MaxKgPerHa?.ToString() ?? "";
WineAttributeStrictInput.IsChecked = attr.IsStrict;
WineAttributeFillLowerInput.SelectedIndex = attr.FillLower;
@@ -118,8 +113,6 @@ namespace Elwig.Windows {
WineAttributeIdInput.Text != attr.AttrId ||
WineAttributeNameInput.Text != attr.Name ||
WineAttributeActiveInput.IsChecked != attr.IsActive ||
WineAttributeMinQualityLevelInput.SelectedItem as WineQualLevel != attr.MinQualityLevel ||
WineAttributeMaxQualityLevelInput.SelectedItem as WineQualLevel != attr.MaxQualityLevel ||
WineAttributeMaxKgPerHaInput.Text != attr.MaxKgPerHa?.ToString() ||
WineAttributeStrictInput.IsChecked != attr.IsStrict ||
WineAttributeFillLowerInput.SelectedIndex != attr.FillLower;
@@ -130,8 +123,6 @@ namespace Elwig.Windows {
attr.AttrId = id;
attr.Name = WineAttributeNameInput.Text ?? "";
attr.IsActive = WineAttributeActiveInput.IsChecked ?? false;
attr.MinQualId = (WineAttributeMinQualityLevelInput.SelectedItem as WineQualLevel)?.QualId;
attr.MaxQualId = (WineAttributeMaxQualityLevelInput.SelectedItem as WineQualLevel)?.QualId;
attr.MaxKgPerHa = WineAttributeMaxKgPerHaInput.Text.Length > 0 ? int.Parse(WineAttributeMaxKgPerHaInput.Text) : null;
attr.IsStrict = WineAttributeStrictInput.IsChecked ?? false;
attr.FillLower = WineAttributeFillLowerInput.SelectedIndex;
@@ -19,7 +19,7 @@ namespace Elwig.Windows {
private bool _cultUpdate = false;
private async Task WineCultivationsInitEditing(AppDbContext ctx) {
_cultList = [with(await ctx.FetchWineCultivations().ToListAsync())];
_cultList = new(await ctx.FetchWineCultivations().ToListAsync());
_cults = _cultList.ToDictionary(c => c.CultId, c => (string?)c.CultId);
_cultIds = _cultList.ToDictionary(c => c, c => c.CultId);
ControlUtils.RenewItemsSource(WineCultivationList, _cultList);
@@ -50,7 +50,7 @@ namespace Elwig.Windows {
.Where(_cultIds.ContainsKey)
.Select(c => {
c.CultId = _cultIds[c];
ctx.Entry(c).State = EntityState.Modified;
ctx.Entry(c).State = EntityState.Added;
return c;
}));
await ctx.SaveChangesAsync();
+5 -22
View File
@@ -24,7 +24,6 @@ namespace Elwig.Windows {
BranchIdInput, BranchNameInput, BranchPlzInput, BranchOrtInput,
BranchAddressInput, BranchPhoneNrInput, BranchFaxNrInput, BranchMobileNrInput,
WineAttributeIdInput, WineAttributeNameInput, WineAttributeActiveInput,
WineAttributeMinQualityLevelInput, WineAttributeMaxQualityLevelInput,
WineAttributeMaxKgPerHaInput, WineAttributeStrictInput, WineAttributeFillLowerInput,
WineCultivationIdInput, WineCultivationNameInput, WineCultivationDescriptionInput, WineCultivationOrganicInput,
AreaCommitmentTypeIdInput, AreaCommitmentTypeWineVariantInput, AreaCommitmentTypeWineAttributeInput,
@@ -61,8 +60,6 @@ namespace Elwig.Windows {
WineAttributeIdInput.IsReadOnly = true;
WineAttributeNameInput.IsReadOnly = true;
WineAttributeActiveInput.IsEnabled = false;
WineAttributeMinQualityLevelInput.IsEnabled = false;
WineAttributeMaxQualityLevelInput.IsEnabled = false;
WineAttributeMaxKgPerHaInput.IsReadOnly = true;
WineAttributeStrictInput.IsEnabled = false;
WineAttributeFillLowerInput.IsEnabled = false;
@@ -112,8 +109,6 @@ namespace Elwig.Windows {
WineAttributeIdInput.IsReadOnly = false;
WineAttributeNameInput.IsReadOnly = false;
WineAttributeActiveInput.IsEnabled = true;
WineAttributeMinQualityLevelInput.IsEnabled = true;
WineAttributeMaxQualityLevelInput.IsEnabled = true;
WineAttributeMaxKgPerHaInput.IsReadOnly = false;
WineAttributeStrictInput.IsEnabled = true;
WineAttributeFillLowerInput.IsEnabled = true;
@@ -150,30 +145,20 @@ namespace Elwig.Windows {
protected override async Task OnRenewContext(AppDbContext ctx) {
await base.OnRenewContext(ctx);
var qualList = await ctx.FetchWineQualityLevels(includePredicate: false).Cast<object>().ToListAsync();
var fullQualList = await ctx.FetchWineQualityLevels().Cast<object>().ToListAsync();
qualList.Insert(0, new NullItem("- Keine -"));
fullQualList.Insert(0, new NullItem("- Keine -"));
ControlUtils.RenewItemsSource(WineAttributeMinQualityLevelInput, fullQualList);
ControlUtils.RenewItemsSource(WineAttributeMaxQualityLevelInput, fullQualList);
ControlUtils.RenewItemsSource(ParameterReceiptMaxQualityLevelInput, qualList);
ControlUtils.RenewItemsSource(AreaCommitmentTypeWineVariantInput, await ctx.FetchWineVarieties().ToListAsync());
var attrList = await ctx.FetchWineAttributes().Cast<object>().ToListAsync();
attrList.Insert(0, new NullItem(""));
ControlUtils.RenewItemsSource(AreaCommitmentTypeWineAttributeInput, attrList);
FillInputs(App.Client, await ctx.FetchSeasons(Utils.CurrentLastSeason).SingleOrDefaultAsync());
ControlUtils.RenewItemsSource(SeasonList, await ctx.FetchSeasons(includeModifiers: true).ToListAsync(), null, ControlUtils.RenewSourceDefault.First);
var year = (SeasonList.SelectedItem as Season)?.Year;
ControlUtils.RenewItemsSource(BranchList, await ctx.FetchBranches().ToListAsync(), null, ControlUtils.RenewSourceDefault.First);
ControlUtils.RenewItemsSource(WineAttributeList, await ctx.FetchWineAttributes().ToListAsync(), null, ControlUtils.RenewSourceDefault.First);
ControlUtils.RenewItemsSource(AreaCommitmentTypeWineVariantInput, await ctx.FetchWineVarieties().ToListAsync());
var attrList = await ctx.FetchWineAttributes().Cast<object>().ToListAsync();
attrList.Insert(0, new NullItem(""));
ControlUtils.RenewItemsSource(AreaCommitmentTypeWineAttributeInput, attrList);
ControlUtils.RenewItemsSource(AreaCommitmentTypeList, await ctx.AreaCommitmentTypes
.OrderBy(t => t.VtrgId)
.ToListAsync(), null, ControlUtils.RenewSourceDefault.First);
ControlUtils.RenewItemsSource(WineCultivationList, await ctx.FetchWineCultivations().ToListAsync(), null, ControlUtils.RenewSourceDefault.First);
ControlUtils.RenewItemsSource(SeasonModifierList, await ctx.FetchModifiers(year ?? 0).ToListAsync(), null, ControlUtils.RenewSourceDefault.First);
FillInputs(App.Client, await ctx.FetchSeasons(Utils.CurrentLastSeason).SingleOrDefaultAsync());
}
protected override void UpdateButtons() {
@@ -366,7 +351,6 @@ namespace Elwig.Windows {
ParameterBusinessShareModeInput.SelectedIndex = p.ModeBusinessShares;
ParameterBusinessShareHistoryInput.IsChecked = p.EnableMemberHistory;
ControlUtils.SelectItemWithPk(ParameterReceiptMaxQualityLevelInput, p.ReceiptMaxQualId);
ParameterAllowAttrIntoLowerInput.IsChecked = s?.Billing_AllowAttrsIntoLower ?? false;
ParameterAvoidUnderDeliveriesInput.IsChecked = s?.Billing_AvoidUnderDeliveries ?? false;
ParameterHonorContractedInput.IsChecked = s?.Billing_HonorContracted ?? false;
@@ -406,7 +390,6 @@ namespace Elwig.Windows {
p.ExportEbicsVersion = ParameterExportEbicsVersion.SelectedIndex + 3;
p.ExportEbicsAddress = ParameterExportEbicsAddress.SelectedIndex;
p.ReceiptMaxQualId = (ParameterReceiptMaxQualityLevelInput.SelectedItem as WineQualLevel)?.QualId;
await p.UpdateValues();
}
+1 -1
View File
@@ -514,7 +514,7 @@
<ComboBox x:Name="AttributeInput" SelectedItem="{Binding WineAttrObj, Mode=TwoWay}" ItemsSource="{Binding WineAttrSource, Mode=TwoWay}"
Grid.Row="1" Grid.Column="1" Margin="0,40,5,10"
DisplayMemberPath="Name"
SelectionChanged="AttributeInput_SelectionChanged" KeyUp="Input_KeyUp"/>
KeyUp="Input_KeyUp"/>
<ComboBox x:Name="CultivationInput" SelectedItem="{Binding WineCultObj, Mode=TwoWay}" ItemsSource="{Binding WineCultSource, Mode=TwoWay}"
Grid.Row="1" Grid.Column="2" Margin="0,40,10,10"
DisplayMemberPath="Name"
+19 -24
View File
@@ -695,7 +695,7 @@ namespace Elwig.Windows {
private void Scale_Weighing(object sender, WeighingEventArgs evt) {
if (sender is not IScale scale) return;
App.Current.Dispatcher.BeginInvoke(() => OnWeighingResult(scale, evt.Result));
App.MainDispatcher.BeginInvoke(() => OnWeighingResult(scale, evt.Result));
}
private async void SearchInput_TextChanged(object sender, RoutedEventArgs evt) {
@@ -1307,50 +1307,39 @@ namespace Elwig.Windows {
ViewModel.SortId = s.SortId;
UpdateWineQualityLevels();
if (!ViewModel.WineVar?.IsQuw ?? false) {
App.Current.Dispatcher.BeginInvoke(() => {
App.MainDispatcher.BeginInvoke(() => {
InteractionService.ShowWarning("Kein Qualitätswein", "Die eingegebene Sorte darf nicht als Qualitätswein\nübernommen werden!");
});
}
}
private void AttributeInput_SelectionChanged(object sender, SelectionChangedEventArgs evt) {
UpdateWineQualityLevels();
}
private WineQualLevel? GetWineQualityLevel(double kmw, string? minQualId, string? maxQualId) {
double? min = WineQualityLevels.Where(q => q.QualId == minQualId).Min(q => q.MinKmw);
double? max = WineQualityLevels.Where(q => q.QualId == maxQualId).Max(q => q.MinKmw) ??
WineQualityLevels.Where(q => q.QualId == App.Client.ReceiptMaxQualId).Max(q => q.MinKmw);
if (kmw < min || max < min) return null;
private WineQualLevel GetWineQualityLevel(double kmw, string? maxQualId = null) {
return WineQualityLevels
.Where(q => (!q.IsPredicate || q.QualId == maxQualId) && (q.MinKmw == null || kmw >= q.MinKmw))
.Where(q => max == null || q.MinKmw == null || q.MinKmw <= max)
.Where(q => !q.IsPredicate && (q.MinKmw == null || q.MinKmw <= kmw))
.Where(q => maxQualId == null || q.QualId == "WEI" || q.QualId == maxQualId)
.OrderBy(q => q.MinKmw)
.LastOrDefault();
.Last();
}
private void UpdateWineQualityLevels() {
if (!GetInputValid(GradationKmwInput) || !ViewModel.GradationKmw.HasValue) {
if (!GetInputValid(GradationKmwInput)) {
UnsetDefaultValue(WineQualityLevelInput);
ComboBox_SelectionChanged(WineQualityLevelInput, null);
WineQualityLevelInput.ItemsSource = WineQualityLevels;
WineQualityLevelInput.SelectedItem = null;
return;
}
var kmw = (double)ViewModel.GradationKmw;
var minA = ViewModel.WineAttr?.MinQualId;
var maxA = ViewModel.WineAttr?.MaxQualId;
var maxV = ViewModel.WineVar?.MaxQualId;
var kmw = (double)ViewModel.GradationKmw!;
var max = ViewModel.WineVar?.MaxQualId;
var quw = ViewModel.WineVar?.IsQuw ?? true;
WineQualityLevelInput.ItemsSource = WineQualityLevels
.Where(q => q.MinKmw == null || q.MinKmw <= kmw)
.Where(q => quw || q.MinKmw == null || q.QualId == maxV)
.Where(q => quw || q.QualId == "WEI" || q.QualId == max)
.ToList();
var qual = GetWineQualityLevel(kmw, minA, !quw ? maxV : maxA);
var qual = GetWineQualityLevel(kmw, !quw ? max : null);
SetDefaultValue(WineQualityLevelInput, qual);
if (WineQualityLevelInput.SelectedItem == null || (WineQualityLevelInput.SelectedItem is WineQualLevel selected && !selected.IsPredicate)) {
ControlUtils.SelectItem(WineQualityLevelInput, qual);
ValidateRequiredInputs();
}
}
@@ -1406,7 +1395,7 @@ namespace Elwig.Windows {
if (App.Client.IsMatzen) {
var kl = mod.Where(m => m.Name.StartsWith("Klasse "));
if (kl.Count() > 1) {
App.Current.Dispatcher.BeginInvoke(() => {
App.MainDispatcher.BeginInvoke(() => {
foreach (var r in kl.Take(kl.Count() - 1))
ViewModel.Modifiers.Remove(r);
});
@@ -1515,7 +1504,13 @@ namespace Elwig.Windows {
private void UpdateAbgewertet() {
if (!GetInputValid(GradationKmwInput))
return;
AbgewertetInput.IsChecked = WineQualityLevelInput.SelectedItem is WineQualLevel { QualId: "WEI" };
var qual = WineQualityLevelInput.SelectedItem as WineQualLevel;
if (qual == null) {
AbgewertetInput.IsChecked = false;
return;
}
var defQual = GetWineQualityLevel(ViewModel.GradationKmw!.Value, !(ViewModel.WineVar?.IsQuw ?? true) ? ViewModel.WineVar?.MaxQualId : null);
AbgewertetInput.IsChecked = !qual.IsPredicate && defQual != qual;
}
private void WeightInput_TextChanged(object sender, TextChangedEventArgs evt) {
+1 -1
View File
@@ -35,7 +35,7 @@ namespace Elwig.Windows {
})
.OrderByDescending(e => e.Event.TimeGenerated)
.ToList();
await App.Current.Dispatcher.BeginInvoke(() => {
await App.MainDispatcher.BeginInvoke(() => {
EventList.ItemsSource = list;
EventList.SelectedIndex = 0;
});
+21 -16
View File
@@ -443,7 +443,7 @@ namespace Elwig.Windows {
private async Task UpdateRecipients(AppDbContext ctx) {
if (RecipientsCustomInput.IsChecked == true) {
Recipients = [.. MemberCustomInput.SelectedItems.Cast<Member>()];
Recipients = MemberCustomInput.SelectedItems.Cast<Member>().ToList();
} else {
IQueryable<Member> query = ctx.Members;
if (MemberBranchInput.SelectedItems.Count != MemberBranchInput.Items.Count) {
@@ -653,27 +653,32 @@ namespace Elwig.Windows {
IEnumerable<Member> recipients = Recipients;
if (OrderMgNrInput.IsChecked == true) {
recipients = [.. recipients.OrderBy(m => m.MgNr)];
recipients = recipients
.OrderBy(m => m.MgNr)
.ToList();
} else if (OrderNameInput.IsChecked == true) {
recipients = [.. recipients
recipients = recipients
.OrderBy(m => m.Name)
.ThenBy(m => m.GivenName)
.ThenBy(m => m.MgNr)];
.ThenBy(m => m.MgNr)
.ToList();
} else if (OrderPlzInput.IsChecked == true) {
if (docs.Any(d => d.Type == DocType.DeliveryConfirmation || d.Type == DocType.CreditNote)) {
recipients = [.. recipients
recipients = recipients
.OrderBy(m => m.BillingAddress?.PostalDest.AtPlz?.Plz ?? m.PostalDest.AtPlz?.Plz)
.ThenBy(m => m.BillingAddress?.PostalDest.AtPlz?.Ort.Name ?? m.PostalDest.AtPlz?.Ort.Name)
.ThenBy(m => m.Name)
.ThenBy(m => m.GivenName)
.ThenBy(m => m.MgNr)];
.ThenBy(m => m.MgNr)
.ToList();
} else {
recipients = [.. recipients
recipients = recipients
.OrderBy(m => m.PostalDest.AtPlz?.Plz)
.ThenBy(m => m.PostalDest.AtPlz?.Ort.Name)
.ThenBy(m => m.Name)
.ThenBy(m => m.GivenName)
.ThenBy(m => m.MgNr)];
.ThenBy(m => m.MgNr)
.ToList();
}
}
@@ -698,7 +703,7 @@ namespace Elwig.Windows {
}
private async Task<bool> GenerateDocuments(bool doublePaged, string location, List<SelectedDoc> docs, IEnumerable<Member> recipients, DateOnly postalDate, int printMode, int emailMode) {
App.Current.Dispatcher.Invoke(() => {
App.MainDispatcher.Invoke(() => {
ProgressBar.Value = 0.0;
});
using var ctx = new AppDbContext();
@@ -726,7 +731,7 @@ namespace Elwig.Windows {
}
}
var (printNum, emailNum) = App.Current.Dispatcher.Invoke(() => {
var (printNum, emailNum) = App.MainDispatcher.Invoke(() => {
double printNum = printMode == 3 ? PostalAllCount : printMode == 2 ? PostalWishCount : printMode == 1 ? PostalNoEmailCount : 0;
double emailNum = emailMode == 2 ? EmailAllCount : emailMode == 1 ? EmailWishCount : 0;
return (printNum, emailNum);
@@ -738,7 +743,7 @@ namespace Elwig.Windows {
Member = m,
Docs = docs.SelectMany<SelectedDoc, GeneratedDoc>(doc => {
try {
App.Current.Dispatcher.Invoke(() => {
App.MainDispatcher.Invoke(() => {
ProgressBar.Value = offset + 100.0 * i / 2 / totalNum;
});
if (doc.Type == DocType.Custom) {
@@ -773,7 +778,7 @@ namespace Elwig.Windows {
InteractionService.ShowException(exc);
return [];
} finally {
App.Current.Dispatcher.Invoke(() => {
App.MainDispatcher.Invoke(() => {
ProgressBar.Value = offset + 100.0 * (i + 1) / 2 / totalNum;
});
}
@@ -806,7 +811,7 @@ namespace Elwig.Windows {
var emailRecipients = email.Select(d => d.Key.MgNr).ToHashSet();
foreach (var item1 in email.Select((e, i) => new { Index = i, e.Key, e.Value })) {
foreach (var item2 in item1.Value.Select((d, i) => new { Index = i, Doc = d })) {
await item2.Doc.Generate(ctx, CancelGeneration?.Token, new Progress<double>(v => App.Current.Dispatcher.Invoke(() => {
await item2.Doc.Generate(ctx, CancelGeneration?.Token, new Progress<double>(v => App.MainDispatcher.Invoke(() => {
ProgressBar.Value = offset + v * (item2.Index + 1) / item1.Value.Count / totalNum + 100.0 * item1.Index / totalNum;
})));
}
@@ -840,7 +845,7 @@ namespace Elwig.Windows {
if (printDocs.Count > 0) {
var print = Document.Merge(printDocs);
await print.Generate(ctx, CancelGeneration?.Token, new Progress<double>(v => App.Current.Dispatcher.Invoke(() => {
await print.Generate(ctx, CancelGeneration?.Token, new Progress<double>(v => App.MainDispatcher.Invoke(() => {
ProgressBar.Value = offset + v * printNum / totalNum;
})));
PrintDocument = print;
@@ -849,7 +854,7 @@ namespace Elwig.Windows {
PrintDocument = null;
PrintMemberDocuments = null;
}
App.Current.Dispatcher.Invoke(() => {
App.MainDispatcher.Invoke(() => {
ProgressBar.Value = 100.0;
});
return hasPreviewDocs;
@@ -949,7 +954,7 @@ namespace Elwig.Windows {
body.Add(doc.AsEmailAttachment($"{name}.pdf"));
}
msg.Body = body;
await client!.SendAsync(new SmtpSendRequest(msg));
await client!.SendAsync(msg);
await Utils.AddSentMails([(
"email", m.MgNr, m.AdministrativeName,
m.EmailAddresses.OrderBy(a => a.Nr).Select(a => a.Address).ToArray(),
+16 -16
View File
@@ -51,14 +51,14 @@ namespace Elwig.Windows {
}
private void Window_Closing(object sender, CancelEventArgs evt) {
if (App.Current.Windows.Count > 1 && !App.ForceShutdown) {
if (App.NumWindows > 1 && !App.ForceShutdown) {
foreach (var w in Application.Current.Windows.Cast<Window>().Where(w => w is AdministrationWindow adm && (adm.IsEditing || adm.IsCreating))) {
try {
w.Close();
} catch { }
}
Thread.Sleep(100);
if (App.Current.Windows.Count > 1) {
if (App.NumWindows > 1) {
var areAdminWindowsOpen = Application.Current.Windows.Cast<Window>().Any(w => w is AdministrationWindow adm && (adm.IsEditing || adm.IsCreating));
if (areAdminWindowsOpen && !InteractionService.AskConfirmation("Elwig beenden", "Es sind noch weitere Fenster geöffnet.\nSollen alle Fenster geschlossen werden?")) {
evt.Cancel = true;
@@ -66,7 +66,7 @@ namespace Elwig.Windows {
}
}
}
App.Current.ShutdownGracefully();
App.CurrentApp.ShutdownGracefully();
}
private void Menu_Help_About_Click(object sender, RoutedEventArgs evt) {
@@ -187,11 +187,11 @@ namespace Elwig.Windows {
Mouse.OverrideCursor = Cursors.Wait;
await Task.Run(async () => {
if (App.Config.SyncMain) {
await SyncService.Download(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, true, App.Config.SyncDecryptionKeys);
await SyncService.UploadModified(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, App.Config.SyncEncryptionKey);
await SyncService.Download(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, true);
await SyncService.UploadModified(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword);
} else {
await SyncService.Download(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, false, App.Config.SyncDecryptionKeys);
await SyncService.UploadBranchDeliveries(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, key: App.Config.SyncEncryptionKey);
await SyncService.Download(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, false);
await SyncService.UploadBranchDeliveries(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword);
}
});
Mouse.OverrideCursor = null;
@@ -202,7 +202,7 @@ namespace Elwig.Windows {
return;
Mouse.OverrideCursor = Cursors.Wait;
await Task.Run(async () => {
await SyncService.Download(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, App.Config.SyncMain, App.Config.SyncDecryptionKeys);
await SyncService.Download(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, App.Config.SyncMain);
});
Mouse.OverrideCursor = null;
}
@@ -212,7 +212,7 @@ namespace Elwig.Windows {
return;
Mouse.OverrideCursor = Cursors.Wait;
await Task.Run(async () => {
await SyncService.UploadBranchDeliveries(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, key: App.Config.SyncEncryptionKey);
await SyncService.UploadBranchDeliveries(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword);
});
Mouse.OverrideCursor = null;
}
@@ -226,7 +226,7 @@ namespace Elwig.Windows {
}
Mouse.OverrideCursor = Cursors.Wait;
await Task.Run(async () => {
await SyncService.UploadModified(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, App.Config.SyncEncryptionKey);
await SyncService.UploadModified(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword);
});
Mouse.OverrideCursor = null;
}
@@ -273,8 +273,8 @@ namespace Elwig.Windows {
"Wenn Sie unsicher sind sprechen Sie sich mit dem Benutzer des Hauptgerätes ab!"))
return;
await App.Current.Dispatcher.BeginInvoke(async () => {
await App.ReplaceDatabase(filename, App.Config.SyncDecryptionKeys);
await App.MainDispatcher.BeginInvoke(async () => {
await App.ReplaceDatabase(filename);
});
} catch (HttpRequestException exc) {
InteractionService.ShowException("Datenbank herunterladen", "Eventuell Internetverbindung prüfen!", exc);
@@ -292,7 +292,7 @@ namespace Elwig.Windows {
return;
if (!App.Config.SyncMain) {
InteractionService.ShowInformation("Datenbank hochladen", "Hochladen nicht möglich:\nDieses Gerät ist nicht das Hauptgerät!");
InteractionService.ShowInformation("Datenbank hochladen", "Hochladen nicht möglich: Dieses Gerät ist nicht das Hauptgerät!");
return;
}
@@ -303,7 +303,7 @@ namespace Elwig.Windows {
await Task.Run(async () => {
try {
var path = Path.Combine(App.TempPath, "database.sql.zip");
await Database.ExportSql(path, true, App.Config.SyncEncryptionKey);
await Database.ExportSql(path, true);
await Utils.UploadExportData(path, App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword);
InteractionService.ShowInformation("Datenbank hochladen", $"Hochladen der gesamten Datenbank erfolgreich!");
} catch (HttpRequestException exc) {
@@ -373,7 +373,7 @@ namespace Elwig.Windows {
ch = await SyncService.ChangesAvailable(ctx, App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, default);
}
}
await App.Current.Dispatcher.BeginInvoke(() => {
await App.MainDispatcher.BeginInvoke(() => {
if (ch) {
SyncButton_1.Text = "\uEA6A";
SyncButton_2.Text = "\uEA81";
@@ -419,7 +419,7 @@ namespace Elwig.Windows {
var weightTotal = await ctx.DeliveryParts.Where(p => p.Year == year).SumAsync(p => p.Weight);
var ctrdWeight = await ctx.DeliveryPartBuckets.Where(b => b.Year == year && b.Discr != "_").SumAsync(b => b.Value);
var area = await areaCmts.SumAsync(c => c.Area);
await App.Current.Dispatcher.BeginInvoke(() => {
await App.MainDispatcher.BeginInvoke(() => {
if (year != SeasonInput.Value) return;
SeasonStatMembersTotal.Text = $"{membersTotal:N0}";
SeasonStatMembersCtrd.Text = $"{membersCtrd:N0}";
+4 -3
View File
@@ -135,7 +135,7 @@ namespace Elwig.Windows {
if (!m.IsActive) {
ViewModel.ShowOnlyActiveMembers = false;
}
App.Current.Dispatcher.BeginInvoke(async () => {
App.MainDispatcher.BeginInvoke(async () => {
await Task.Delay(500);
FocusMember(mgnr);
});
@@ -450,7 +450,7 @@ namespace Elwig.Windows {
private void MemberList_SelectionChanged(object sender, RoutedEventArgs evt) {
RefreshInputs();
if (MemberList.SelectedItem is Member) {
if (MemberList.SelectedItem is Member m) {
Menu_Export_ExportSelected.IsEnabled = !IsEditing && !IsCreating;
Menu_Export_UploadSelected.IsEnabled = !IsEditing && !IsCreating && App.Config.SyncUrl != null;
Menu_Contacts_Selected.IsEnabled = !IsEditing && !IsCreating;
@@ -1064,8 +1064,9 @@ namespace Elwig.Windows {
ViewModel.OrganicDetails = "...";
var lfbisNr = ViewModel.LfbisNr;
Utils.RunBackground("Bio-Zertifikatsdaten laden", async () => {
if (App.MainDispatcher == null) return;
var certs = await OrganicService.FetchTracesCertificates(lfbisNr: lfbisNr);
await App.Current.Dispatcher.BeginInvoke(() => {
await App.MainDispatcher.BeginInvoke(() => {
if (certs.Length == 0) {
ViewModel.FillOrganicInputs(null);
} else {
@@ -62,7 +62,7 @@ namespace Elwig.Windows {
var history = await ctx.MemberHistory
.Where(h => h.DeductYear == Year)
.GroupBy(h => h.ToMember)
.ToDictionaryAsync(h => h.Key!.MgNr, h => h.Sum(g => g.Shares));
.ToDictionaryAsync(h => h.Key.MgNr, h => h.Sum(g => g.Shares));
var list = members
.Select(m => new {
@@ -79,7 +79,7 @@ namespace Elwig.Windows {
Weight = weight.GetValueOrDefault(m.MgNr, 0),
OverUnder = weight.TryGetValue(m.MgNr, out int v1) ?
(v1 < m.DeliveryObligation ? (int?)v1 - m.DeliveryObligation :
v1 > m.DeliveryRight ? (int?)v1 - m.DeliveryRight : 0)
v1 > m.DeliveryRight ? (int?)v1 - m.DeliveryRight : null)
: (m.IsActive ? -m.DeliveryObligation : null),
m.Adjust,
AdjustAmount = m.Adjust * -season.BusinessShareValue,
@@ -93,10 +93,10 @@ namespace Elwig.Windows {
(season.PenaltyPerShareAmount * Math.Floor(m.OverUnder / season.MinKgPerShare ?? 0m) ?? 0) +
(m.Weight == 0 ? (-season.PenaltyNone ?? 0) + (-season.PenaltyPerShareNone * m.SharesActive ?? 0) : 0)
: (decimal?)null,
PenaltyAc = areaCmts.TryGetValue(m.MgNr, out var c) ? c.Sum(r => {
PenaltyAc = areaCmts.TryGetValue(m.MgNr, out var c) ? c.Select(r => {
var con = contracts[r.Key];
return (r.Value.Kg * con.PenaltyPerKg ?? 0) + (r.Value.Kg < 0 ? con.PenaltyAmount ?? 0 : 0) + (r.Value.Percent == -100 ? con.PenaltyNone ?? 0 : 0);
}) : (decimal?)null,
}).Sum() : (decimal?)null,
m.Adjust,
m.AdjustAmount,
Custom = CustomPayments!.GetValueOrDefault(m.MgNr, null),
-4
View File
@@ -18,8 +18,6 @@ file = database.sqlite3
;retain_days = 8
;retain_weeks = 6
;retain_months = 18
; keys may not contain ","! Do NOT quote the strings (""), spaces before/after the string are trimmed!
;key = current encryption key, old decryption key, another old key
[update]
url = https://elwig.at/files/elwig/latest
@@ -29,8 +27,6 @@ auto = true
;url = https://elwig.at/clients/WGX/
;username = ""
;password = ""
; keys may not contain ","! Do NOT quote the strings (""), spaces before/after the string are trimmed!
;key = current encryption key, old decryption key, another old key
[smtp]
;host =
+2 -2
View File
@@ -13,7 +13,7 @@ About
**Product:** Elwig
**Description:** Electronic Management for Vintners' Cooperatives
**Type:** ERP system
**Version:** 1.2.1.0 ([Changelog](./CHANGELOG.md))
**Version:** 1.2.0.0 ([Changelog](./CHANGELOG.md))
**License:** [GNU General Public License 3.0 (GPLv3)](./LICENSE)
**Website:** https://elwig.at/
**Source code:** https://git.necronda.net/winzer/elwig
@@ -33,7 +33,7 @@ Packaging: [WiX Toolset](https://www.firegiant.com/wixtoolset/)
**Produkt:** Elwig
**Beschreibung:** Elektronische Winzergenossenschaftsverwaltung
**Typ:** Warenwirtschaftssystem (ERP-System)
**Version:** 1.2.1.0 ([Änderungsprotokoll](./CHANGELOG.md))
**Version:** 1.2.0.0 ([Änderungsprotokoll](./CHANGELOG.md))
**Lizenz:** [GNU General Public License 3.0 (GPLv3)](./LICENSE)
**Website:** https://elwig.at/
**Quellcode:** https://git.necronda.net/winzer/elwig
+2 -2
View File
@@ -14,7 +14,7 @@
</Target>
<ItemGroup>
<ProjectReference Include="..\Installer\Installer.wixproj" />
<PackageReference Include="WixToolset.Bal.wixext" Version="7.0.1" />
<PackageReference Include="WixToolset.Util.wixext" Version="7.0.1" />
<PackageReference Include="WixToolset.Bal.wixext" Version="7.0.0" />
<PackageReference Include="WixToolset.Util.wixext" Version="7.0.0" />
</ItemGroup>
</Project>
+1 -1
View File
@@ -6,7 +6,7 @@ namespace Tests.E2ETests {
public const int WINDOW_OPEN_SLEEP = 2000;
public static readonly string ApplicationPath = Path.GetFullPath(@"..\..\..\..\Elwig\bin\Debug\net11.0-windows\Elwig.exe");
public static readonly string ApplicationPath = Path.GetFullPath(@"..\..\..\..\Elwig\bin\Debug\net10.0-windows\Elwig.exe");
public static readonly string ConfigPath = Path.GetFullPath(@"..\..\..\..\Tests\config.test.ini");
public static readonly string TestDatabasePath = Path.GetFullPath(@"..\..\..\..\Tests\ElwigTestDB.sqlite3");
-3
View File
@@ -4,8 +4,5 @@ DELETE FROM delivery_schedule;
DELETE FROM payment_variant;
DELETE FROM delivery;
DELETE FROM season;
DELETE FROM area_commitment;
DELETE FROM area_commitment_contract;
DELETE FROM area_commitment_type;
DELETE FROM wine_attribute;
DELETE FROM wine_cultivation;
-16
View File
@@ -7,23 +7,8 @@ INSERT INTO wine_attribute (attrid, name, active, max_kg_per_ha, strict, fill_lo
('K', 'Kabinett', TRUE, NULL, FALSE, 0);
INSERT INTO season (year, currency, min_kg_per_share, max_kg_per_share, start_date, end_date) VALUES
(2019, 'EUR', 1000, 2000, NULL, NULL),
(2020, 'EUR', 1000, 2000, NULL, NULL);
INSERT INTO area_commitment_type (vtrgid, sortid, attrid, disc) VALUES
('GV', 'GV', NULL, NULL),
('WR', 'WR', NULL, NULL);
INSERT INTO area_commitment_contract (fbnr, kgnr) VALUES
(1, 15224),
(2, 15224),
(3, 15224);
INSERT INTO area_commitment (fbnr, revnr, mgnr, vtrgid, cultid, area, gstnr, year_from, year_to) VALUES
(1, 1, 103, 'GV', NULL, 5670, '1234', 2020, NULL),
(2, 1, 103, 'WR', NULL, 6780, '1235', 2020, NULL),
(3, 1, 101, 'GV', NULL, 2340, '3456', 2020, NULL);
INSERT INTO delivery_schedule (year, dsnr, date, zwstid, description, max_weight, ancmt_from, ancmt_to) VALUES
(2020, 1, '2020-10-01', 'X', 'GV Kabinettaktion', 100000, NULL, NULL);
@@ -37,7 +22,6 @@ INSERT INTO delivery_announcement (year, dsnr, mgnr, sortid, weight, type) VALUE
(2020, 1, 104, 'GV', 2000, 'manual');
INSERT INTO modifier (year, modid, ordering, name, abs, rel, active) VALUES
(2019, 'S', 0, 'Geschädigte Trauben', NULL, -0.1, TRUE),
(2020, 'S', 0, 'Geschädigte Trauben', NULL, -0.1, TRUE),
(2020, 'A', 0, 'Keine Voranmeldung', -1000, NULL, TRUE);
+1 -7
View File
@@ -1,12 +1,10 @@
-- inserts for DatabaseSetup
INSERT INTO AT_gem (gkz, name) VALUES
(30824, 'Groß-Schweinbarth'),
(30828, 'Hohenruppersdorf'),
(31655, 'Wolkersdorf im Weinviertel');
INSERT INTO AT_kg (kgnr, gkz, name) VALUES
(06021, 30824, 'Großschweinbarth'),
(06109, 30828, 'Hohenruppersdorf'),
(15209, 31655, 'Münichsthal'),
(15211, 31655, 'Obersdorf'),
@@ -15,7 +13,6 @@ INSERT INTO AT_kg (kgnr, gkz, name) VALUES
(15224, 31655, 'Wolkersdorf');
INSERT INTO AT_ort (okz, gkz, kgnr, name) VALUES
(03516, 30824, 06021, 'Groß-Schweinbarth'),
(03524, 30828, 06109, 'Hohenruppersdorf'),
(05092, 31655, 15211, 'Obersdorf'),
(05135, 31655, 15209, 'Münichsthal'),
@@ -24,13 +21,11 @@ INSERT INTO AT_ort (okz, gkz, kgnr, name) VALUES
(05138, 31655, 15224, 'Wolkersdorf im Weinviertel');
INSERT INTO AT_plz (plz, ort, blnr, type, internal, addressable, po_box) VALUES
(2221, 'Groß-Schweinbarth', 3, 'PLZ-Adressierung', FALSE, TRUE, FALSE),
(2223, 'Hohenruppersdorf', 3, 'PLZ-Adressierung', FALSE, TRUE, FALSE),
(2120, 'Wolkersdorf im Weinviertel', 3, 'PLZ-Adressierung', FALSE, TRUE, TRUE ),
(2122, 'Ulrichskirchen', 3, 'PLZ-Adressierung', FALSE, TRUE, FALSE);
INSERT INTO AT_plz_dest (plz, okz, dest) VALUES
(2221, 03516, 'Groß-Schweinbarth'),
(2223, 03524, 'Hohenruppersdorf'),
(2120, 05092, 'Obersdorf'),
(2120, 05138, 'Wolkersdorf im Weinviertel'),
@@ -60,7 +55,6 @@ INSERT INTO wb_gl (glnr, name) VALUES
(2, 'Wolkersdorfer Hochleithen');
INSERT INTO wb_gem (gkz, hkid) VALUES
(30824, 'WLWV'),
(30828, 'WLWV'),
(31655, 'WLWV');
@@ -75,7 +69,7 @@ INSERT INTO wb_kg (kgnr, glnr) VALUES
INSERT INTO member (mgnr, given_name, name, zwstid, full_delivery, accounting, country, postal_dest, address, default_kgnr, iban, lfbis_nr, ustid_nr, org_auth_code) VALUES
(101, 'Max', 'Mustermann', 'X', FALSE, FALSE, 40, 222303524, 'Winzerstraße 1', 06109, 'AT811234567890123457', '0123463', NULL , NULL ),
(102, 'Wernhardt', 'Weinbauer', 'X', FALSE, FALSE, 40, 222303524, 'Winzerstraße 2', 06109, 'AT541234567890123458', '0123471', 'ATU12345684', NULL ),
(103, 'Matthäus', 'Musterbauer', 'X', TRUE , FALSE, 40, 212005138, 'Brünner Straße 10', 15224, 'AT271234567890123459', '0123480', NULL , 'AT-BIO-302'),
(103, 'Matthäus', 'Musterbauer', 'X', FALSE, FALSE, 40, 212005138, 'Brünner Straße 10', 15224, 'AT271234567890123459', '0123480', NULL , 'AT-BIO-302'),
(104, 'Waltraud', 'Winzer', 'X', FALSE, TRUE , 40, 212005138, 'Wiener Straße 15', 15224, 'AT971234567890123460', '0123498', 'ATU12345693', NULL );
INSERT INTO member_billing_address (mgnr, name, country, postal_dest, address) VALUES
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more