Compare commits

..
3 Commits
Author SHA1 Message Date
lorenz.stechauner 7ad5aa90af Tests: Update dependencies
Test / Run tests (push) Successful in 2m11s
2026-07-08 23:32:56 +02:00
lorenz.stechauner f974408011 Elwig: Update dependencies 2026-07-08 23:32:40 +02:00
lorenz.stechauner a33860443b [#20] MemberAdminWindow: Add MemberBusinessSharesAdminWindow to manage member shares
Test / Run tests (push) Successful in 2m40s
2026-07-08 22:04:20 +02:00
74 changed files with 648 additions and 1667 deletions
+1 -1
View File
@@ -2,7 +2,7 @@ name: Test
on: on:
push: push:
branches: ["**"] branches: ["**"]
paths: ["Elwig/**", "Tests/**", ".gitea/workflows/test.yaml"] paths: ["Elwig/**", "Tests/**", "Installer/Files/*.exe", ".gitea/workflows/test.yaml"]
jobs: jobs:
test: test:
name: Run tests name: Run tests
+1 -163
View File
@@ -2,168 +2,6 @@
Changelog Changelog
========= =========
[v1.1.2.1][v1.1.2.1] (2026-08-27) {#v1.1.2.1}
---------------------------------------------
### Behobene Fehler {#v1.1.2.1-bugfixes}
* Im Anmeldungen-Fenster (`DeliveryAncmtAdminWindow`) und im Leseplanung-Fenster (`DeliveryScheduleAdminWindow`) kam es seit [v1.1.1.2](#v1.1.1.2) (2026-08-25) zu einem Absturz. (f0745eae4e)
### Sonstiges {#v1.1.2.1-misc}
* Bei E-Mails wird ab jetzt auch Datum und Uhrzeit gesetzt. (848a6d1ce0)
[v1.1.2.1]: https://git.necronda.net/winzer/elwig/releases/tag/v1.1.2.1
[v1.1.2.0][v1.1.2.0] (2026-08-26) {#v1.1.2.0}
---------------------------------------------
### Neue Funktionen {#v1.1.2.0-features}
* Eine Automatische Backup-/Sicherungs-Funktion für die Datenbank wurde hinzugefügt. (ca5b719630, cadac4302d)
### Behobene Fehler {#v1.1.2.0-bugfixes}
* Wenn am heutigen Tag noch keine Lieferung übernommen wurde, wurden im Lieferungen-/Übernahme-Fenster (`DeliveryAdminWindow`) mit dem Filter "Nur heute" auch Lieferungen des vorhergehenden Tages angezeigt. (c1690bf104)
### Sonstiges {#v1.1.2.0-misc}
* Abhängigkeiten aktualisiert. (2360402124, 7add96dfd5)
[v1.1.2.0]: https://git.necronda.net/winzer/elwig/releases/tag/v1.1.2.0
[v1.1.1.2][v1.1.1.2] (2026-08-25) {#v1.1.1.2}
---------------------------------------------
### Behobene Fehler {#v1.1.1.2-bugfixes}
* Auf Lieferscheinen (`DeliveryNote`) waren die Mengenangaben nicht rechtsbündig. (ff71e9fb7f)
* Beim Importieren von Mitgliedern mit Stamm-KG ohne Großlage kam es zu einem Fehler, obwohl die Großlage automatisch hätte zugewiesen werden müssen. (edf3678154)
### Sonstiges {#v1.1.1.2-misc}
* In Matzen werden für Planenw./Kipper und Lesewagen die Klassen automatisch gesetzt. (3366cc25eb)
* Im Lieferungen-Fenster (`DeliveryAdminWindow`) wird für "Nur heute" nicht mehr nur das Datum, sondern die letzten zusammenhängenden Lieferungen verwendet. (46e596ae23)
* Für Pamhagen wird als standard Wiege-Methode "brutto" verwendet. (0c4611024f)
* Für Waagen kann das automatische setzen von Datum und Uhrzeit nun per Opt-out ausgeschalten werden (Konfigurationsdatei -> `[scale.X]` -> `synctime = false`). (f450dc35b1)
[v1.1.1.2]: https://git.necronda.net/winzer/elwig/releases/tag/v1.1.1.2
[v1.1.1.1][v1.1.1.1] (2026-08-24) {#v1.1.1.1}
---------------------------------------------
### Sonstiges {#v1.1.1.1-misc}
* Beim Export der Flächenbindungen im Haupt-Fenster (`MainWindow`) werden neben der zusammengefassten gebundenen Fläche nun auch die jeweiligen Flächenindungen exportiert. (b468bbce31)
[v1.1.1.1]: https://git.necronda.net/winzer/elwig/releases/tag/v1.1.1.1
[v1.1.1.0][v1.1.1.0] (2026-08-19) {#v1.1.1.0}
---------------------------------------------
### Sonstiges {#v1.1.1.0-misc}
* Bei der BKI-Traubentransportscheinliste werden Volllieferanten/Vollablieferer nun auch als solche markiert. (20b6e11b7f)
[v1.1.1.0]: https://git.necronda.net/winzer/elwig/releases/tag/v1.1.1.0
[v1.1.0.3][v1.1.0.3] (2026-08-17) {#v1.1.0.3}
---------------------------------------------
### Sonstiges {#v1.1.0.3-misc}
* Beim Drucken mehrerer Kopien einer PDF-Datei wird nun nur mehr ein einzelner Druck-Auftrag verwendet. (fc5ad82686)
* Beim Synchronisieren können Geräte als Hauptgerät festgelegt werden. (eaddf0c3cb)
* Abhängigkeiten aktualisiert. (e6e140dc08, 58bfb4f56d)
[v1.1.0.3]: https://git.necronda.net/winzer/elwig/releases/tag/v1.1.0.3
[v1.1.0.2][v1.1.0.2] (2026-08-11) {#v1.1.0.2}
---------------------------------------------
### Neue Funktionen {#v1.1.0.2-features}
* Es ist nun möglich zwischen dem Senden von E-Mail einige Sekunden zu warten (Konfigurationsdatei -> `[smtp]` -> `wait = 0.5`). (76ea3513ac)
### Behobene Fehler {#v1.1.0.2-bugfixes}
* Beim Drucken von Dokumenten waren die Seitenränder nicht korrekt. (f13a836ebd, 20b19775b1, 470c6e09e5, 07b197958d)
[v1.1.0.2]: https://git.necronda.net/winzer/elwig/releases/tag/v1.1.0.2
[v1.1.0.1][v1.1.0.1] (2026-08-05) {#v1.1.0.1}
---------------------------------------------
### Neue Funktionen {#v1.1.0.1-features}
* Auf Lieferscheinen sind nun Waage und Terminal angegeben. (309f118739)
* Beim Starten von Elwig wird Datum/Uhrzeit auf allen angeschlossenen Waagen gesetzt. (2a3999f300)
### Behobene Fehler {#v1.1.0.1-bugfixes}
* Im Stammdaten-Fenster (`BaseDataWindow`) war es nach einem Fehler beim Bearbeiten bis zum Schließen des Fensters nicht mehr möglich zu speichern. ([#82][i82])
### Sonstiges {#v1.1.0.1-misc}
* Im Auszahlungsvarianten-Fenster (`PaymentVariantsWindow`)...
* wurde auf 3 Knöpfen das Symbol "in neuem Fenster öffnen" hinzugefügt. (88616b2c0b)
* wird beim "Speichern" die Variante automatisch auch berechnet um Fehler/Missverständnisse zu vermeiden. ([#83][i83])
* Abhängigkeiten aktualisiert. (b445928c4d, 668030fbff, a8cc3c9cb9)
[v1.1.0.1]: https://git.necronda.net/winzer/elwig/releases/tag/v1.1.0.1
[i82]: https://git.necronda.net/winzer/elwig/issues/82
[i83]: https://git.necronda.net/winzer/elwig/issues/83
[v1.1.0.0][v1.1.0.0] (2026-07-09) {#v1.1.0.0}
---------------------------------------------
### Neue Funktionen {#v1.1.0.0-features}
* Per Opt-In Einstellung in den Stammdaten ist es nun möglich Mitgliederbewegungen und Verläufe von Geschäftsanteilen mit Elwig zu erfassen. ([#20][i20])
* Es wird nun unterstützt verschiedene Typen von Geschäftsanteilen pro Mitglied zu erfassen (normal, rot, weiß, ruhend). ([#80][i80])
### Behobene Fehler {#v1.1.0.0-bugfixes}
* Falls die Datenbank für die momentan verwndete Elwig-Version zu neu war kam es beim Überprüfen auf ein Update zu einem Fehler. (4ebe07f579)
* Im Stammdatenblatt (`MemberDataSheet`) wurde die Stamm-Zweigstelle nicht angeführt. (a71c41af5c)
### Sonstiges {#v1.1.0.0-misc}
* In der Buchungsliste (`CreditNoteData`) wird nun auch das Buchhaltungskonto der Mitglieder angeführt. (000117dc67)
* Viele kleine Verbesserungen der Code-Qualität. (u.a. fcd0555e4d, 69efca1cc3, beacba6bd9, 1169ba5101)
* Abhängigkeiten aktualisiert. (e8789aff37, 2350b55cea)
[v1.1.0.0]: https://git.necronda.net/winzer/elwig/releases/tag/v1.1.0.0
[i20]: https://git.necronda.net/winzer/elwig/issues/20
[i80]: https://git.necronda.net/winzer/elwig/issues/80
[v1.0.5.6][v1.0.5.6] (2026-06-25) {#v1.0.5.6} [v1.0.5.6][v1.0.5.6] (2026-06-25) {#v1.0.5.6}
--------------------------------------------- ---------------------------------------------
@@ -426,7 +264,7 @@ Changelog
[v1.0.3.0]: https://git.necronda.net/winzer/elwig/releases/tag/v1.0.3.0 [v1.0.3.0]: https://git.necronda.net/winzer/elwig/releases/tag/v1.0.3.0
[i50]: https://git.necronda.net/winzer/elwig/issues/50 [i50]: https://git.necronda.net/winzer/elwig/issues/50
[i66]: https://git.necronda.net/winzer/elwig/issues/66 [i66]: https://git.necronda.net/winzer/elwig/issues/60
[i71]: https://git.necronda.net/winzer/elwig/issues/71 [i71]: https://git.necronda.net/winzer/elwig/issues/71
[i73]: https://git.necronda.net/winzer/elwig/issues/73 [i73]: https://git.necronda.net/winzer/elwig/issues/73
+2 -1
View File
@@ -2,7 +2,8 @@
x:Class="Elwig.App" x:Class="Elwig.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctrl="clr-namespace:Elwig.Controls"> xmlns:ctrl="clr-namespace:Elwig.Controls"
Exit="Application_Exit">
<Application.Resources> <Application.Resources>
<ctrl:BoolToStringConverter x:Key="BoolToStarConverter" FalseValue="" TrueValue="*"/> <ctrl:BoolToStringConverter x:Key="BoolToStarConverter" FalseValue="" TrueValue="*"/>
<ctrl:WidthToMarginConverter x:Key="WidthToMarginConverter"/> <ctrl:WidthToMarginConverter x:Key="WidthToMarginConverter"/>
+12 -47
View File
@@ -25,10 +25,9 @@ namespace Elwig {
protected static App CurrentApp; protected static App CurrentApp;
public static int NumWindows => CurrentApp.Windows.Count; public static int NumWindows => CurrentApp.Windows.Count;
public static bool ForceShutdown { get; set; } = false; public static bool ForceShutdown { get; private set; } = false;
private readonly DispatcherTimer _autoUpdateTimer = new() { Interval = TimeSpan.FromHours(1) }; private readonly DispatcherTimer _autoUpdateTimer = new() { Interval = TimeSpan.FromHours(1) };
private readonly DispatcherTimer _autoBackupTimer = new() { Interval = TimeSpan.FromMinutes(10) };
public readonly SerialPortWatcher SerialPortWatcher = new(); public readonly SerialPortWatcher SerialPortWatcher = new();
public static readonly string DataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Elwig"); public static readonly string DataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Elwig");
@@ -75,7 +74,7 @@ namespace Elwig {
Config = new(Path.GetFullPath(args[1])); Config = new(Path.GetFullPath(args[1]));
} }
ContextTimer.Tick += (sender, evt) => { ContextTimer.Tick += (object? sender, EventArgs evt) => {
var ch = CurrentLastWrite; var ch = CurrentLastWrite;
if (ch > LastChanged) { if (ch > LastChanged) {
LastChanged = ch; LastChanged = ch;
@@ -93,15 +92,11 @@ namespace Elwig {
try { try {
await AppDbUpdater.CheckDb(); await AppDbUpdater.CheckDb();
} catch (FileNotFoundException exc) {
InteractionService.ShowException("Datenbank nicht gefunden", "Die Datenbank konnte nicht gefunden werden", exc);
} catch (Exception exc) { } catch (Exception exc) {
if (Config.UpdateUrl != null && Utils.HasInternetConnectivity()) { if (Config.UpdateUrl != null && Utils.HasInternetConnectivity()) {
await CheckForUpdates(); await CheckForUpdates();
} }
InteractionService.ShowException("Fehlerhafte Datenbank", "Schwerwiegender Fehler in der Datenbank, unbedingt den Programmierern melden!", exc); InteractionService.ShowException("Fehlerhafte Datenbank", "Fehlerhafte Datenbank", exc);
if (InteractionService.AskQuestion("Backup wiederherstellen", "Soll die Datenbank aus einem Backup wiederhergestellt werden?\n\nAchtung: Das kann zu Datenverlust führen!", false))
await BackupService.RestoreDatabase();
Shutdown(); Shutdown();
return; return;
} }
@@ -111,14 +106,13 @@ namespace Elwig {
Dictionary<string, (string, string, int?, string?, string?, string?, string?, string?)> branches = []; Dictionary<string, (string, string, int?, string?, string?, string?, string?, string?)> branches = [];
using (var ctx = new AppDbContext()) { using (var ctx = new AppDbContext()) {
branches = await ctx.FetchBranches() branches = ctx.FetchBranches()
.ToDictionaryAsync(b => b.Name.ToLower(), b => (b.ZwstId, b.Name, b.PostalDest?.AtPlz?.Plz, b.PostalDest?.AtPlz?.Ort.Name, b.Address, b.PhoneNr, b.FaxNr, b.MobileNr)); .ToDictionaryAsync(b => b.Name.ToLower(), b => (b.ZwstId, b.Name, b.PostalDest?.AtPlz?.Plz, b.PostalDest?.AtPlz?.Ort.Name, b.Address, b.PhoneNr, b.FaxNr, b.MobileNr))
.GetAwaiter().GetResult();
try { try {
Client = new(ctx); Client = new(ctx);
} catch (Exception exc) { } catch (Exception exc) {
InteractionService.ShowException("Fehler", "Fehler beim Laden der Mandantendaten, unbedingt den Programmierern melden!", exc); InteractionService.ShowException("Fehler", "Fehler beim Laden der Mandantendaten", exc);
if (InteractionService.AskQuestion("Backup wiederherstellen", "Soll die Datenbank aus einem Backup wiederhergestellt werden?\n\nAchtung: Das kann zu Datenverlust führen!", false))
await BackupService.RestoreDatabase();
Shutdown(); Shutdown();
return; return;
} }
@@ -130,23 +124,9 @@ namespace Elwig {
return Task.CompletedTask; return Task.CompletedTask;
}); });
Utils.RunBackground("PDF Initialization", async () => Pdf.Init()); Utils.RunBackground("PDF Initialization", () => Pdf.Init());
Utils.RunBackground("JSON Schema Initialization", BillingData.Init); Utils.RunBackground("JSON Schema Initialization", BillingData.Init);
if (Config.BackupAuto) {
Utils.RunBackground("Automatisches Backup", async () => {
Directory.CreateDirectory(Config.BackupPath);
await Task.Delay(500);
await BackupService.TryDatabaseBackup();
});
_autoBackupTimer.Tick += new EventHandler((sender, evt) => {
Utils.RunBackground("Automatisches Backup", async () => {
await BackupService.TryDatabaseBackup();
});
});
_autoBackupTimer.Start();
}
if (Config.UpdateAuto && Config.UpdateUrl != null) { if (Config.UpdateAuto && Config.UpdateUrl != null) {
if (Utils.HasInternetConnectivity()) { if (Utils.HasInternetConnectivity()) {
Utils.RunBackground("Auto Updater", async () => { Utils.RunBackground("Auto Updater", async () => {
@@ -165,13 +145,7 @@ namespace Elwig {
var list = new List<IScale>(); var list = new List<IScale>();
foreach (var s in Config.Scales) { foreach (var s in Config.Scales) {
try { try {
var scale = Scale.FromConfig(s); list.Add(Scale.FromConfig(s));
if (s.SyncTime && scale is ICommandScale cmd) {
try {
await cmd.SetDateAndTime(DateTime.Now);
} catch { }
}
list.Add(scale);
} catch (Exception exc) { } catch (Exception exc) {
list.Add(new InvalidScale(s.Id)); list.Add(new InvalidScale(s.Id));
if (s.Required) if (s.Required)
@@ -199,7 +173,7 @@ namespace Elwig {
Config.WeighingMode = WeighingMode.Net; Config.WeighingMode = WeighingMode.Net;
} else if (Client.IsHaugsdorf || Client.IsSitzendorf) { } else if (Client.IsHaugsdorf || Client.IsSitzendorf) {
Config.WeighingMode = WeighingMode.Box; Config.WeighingMode = WeighingMode.Box;
} else if (Client.IsBaden || Client.IsGrInzersdorf || Client.IsPamhagen) { } else if (Client.IsBaden || Client.IsGrInzersdorf) {
Config.WeighingMode = WeighingMode.Gross; Config.WeighingMode = WeighingMode.Gross;
} }
} }
@@ -210,21 +184,12 @@ namespace Elwig {
window.Show(); window.Show();
} }
public async Task OnClosing() { private async void Application_Exit(object sender, ExitEventArgs evt) {
try {
await BackupService.TryDatabaseBackup();
} catch (Exception exc) {
InteractionService.ShowException("Automatisches Backup", exc);
}
}
protected override void OnExit(ExitEventArgs evt) {
SerialPortWatcher.Dispose(); SerialPortWatcher.Dispose();
foreach (var s in EventScales) { foreach (var s in EventScales) {
s.Dispose(); s.Dispose();
} }
Pdf.Cleanup(); await Pdf.Cleanup();
base.OnExit(evt);
} }
public static void SetBranch(Branch b) { public static void SetBranch(Branch b) {
+3 -3
View File
@@ -147,7 +147,7 @@ namespace Elwig.Documents {
.AddCell(NewDeliveryMainTd(part.Quality.Name)) .AddCell(NewDeliveryMainTd(part.Quality.Name))
.AddCell(NewDeliveryMainTd($"{part.Oe:N0}", center: true)) .AddCell(NewDeliveryMainTd($"{part.Oe:N0}", center: true))
.AddCell(NewDeliveryMainTd($"{part.Kmw:N1}", center: true)) .AddCell(NewDeliveryMainTd($"{part.Kmw:N1}", center: true))
.AddCell(NewDeliveryMainTd($"{part.Weight:N0}", right: true)); .AddCell(NewDeliveryMainTd($"{part.Weight:N0}", center: true));
if (part.Cultivation != null) { if (part.Cultivation != null) {
var cult = new KernedParagraph(8); var cult = new KernedParagraph(8);
@@ -181,8 +181,8 @@ namespace Elwig.Documents {
} }
} else { } else {
var info = part.WeighingInfo; var info = part.WeighingInfo;
weighing.Add(Italic("Waage/Terminal:")) weighing.Add(Italic("Waage:"))
.Add(Normal(" " + (info.ScaleId ?? "?") + "/" + (part.ScaleTerminalId ?? "?") + ", ")) .Add(Normal(" " + (part.ScaleId ?? "?") + ", "))
.Add(Italic("ID:")) .Add(Italic("ID:"))
.Add(Normal(" " + (info.Id ?? "?"))); .Add(Normal(" " + (info.Id ?? "?")));
if (info.Date != null || info.Time != null) if (info.Date != null || info.Time != null)
+2 -2
View File
@@ -57,7 +57,7 @@ namespace Elwig.Documents {
public Document(string title) { public Document(string title) {
Title = title; Title = title;
Author = App.Client.NameFull; Author = App.Client.NameFull;
Date = DateOnly.FromDateTime(DateTime.Today); Date = DateOnly.FromDateTime(Utils.Today);
} }
~Document() { ~Document() {
@@ -252,7 +252,7 @@ namespace Elwig.Documents {
public async Task Print(int copies = 1) { public async Task Print(int copies = 1) {
if (PdfPath == null) throw new InvalidOperationException("Pdf file has not been generated yet"); if (PdfPath == null) throw new InvalidOperationException("Pdf file has not been generated yet");
Pdf.Print(PdfPath, copies, IsDoublePaged); await Pdf.Print(PdfPath, copies, IsDoublePaged);
} }
public void Show() { public void Show() {
+10 -10
View File
@@ -9,10 +9,10 @@
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
<PreserveCompilationContext>true</PreserveCompilationContext> <PreserveCompilationContext>true</PreserveCompilationContext>
<ApplicationIcon>Resources\Images\Elwig.ico</ApplicationIcon> <ApplicationIcon>Resources\Images\Elwig.ico</ApplicationIcon>
<Version>1.1.2.1</Version> <Version>1.0.5.6</Version>
<SatelliteResourceLanguages>de-AT</SatelliteResourceLanguages> <SatelliteResourceLanguages>de-AT</SatelliteResourceLanguages>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationManifest>App.manifest</ApplicationManifest> <ApplicationManifest>app.manifest</ApplicationManifest>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -23,21 +23,21 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="bblanchon.PDFium.Win32" Version="154.0.8021" /> <PackageReference Include="bblanchon.PDFium.Win32" Version="152.0.7934" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" /> <PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageReference Include="itext" Version="9.7.0" /> <PackageReference Include="itext" Version="9.7.0" />
<PackageReference Include="itext.bouncy-castle-adapter" Version="9.7.0" /> <PackageReference Include="itext.bouncy-castle-adapter" Version="9.7.0" />
<PackageReference Include="LinqKit" Version="1.3.11" /> <PackageReference Include="LinqKit" Version="1.3.11" />
<PackageReference Include="MailKit" Version="4.17.0" /> <PackageReference Include="MailKit" Version="4.17.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.11" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.9" />
<PackageReference Include="Microsoft.Extensions.Configuration.Ini" Version="10.0.11" /> <PackageReference Include="Microsoft.Extensions.Configuration.Ini" Version="10.0.9" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4129.50" /> <PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4078.44" />
<PackageReference Include="NJsonSchema" Version="11.6.1" /> <PackageReference Include="NJsonSchema" Version="11.6.1" />
<PackageReference Include="ScottPlot.WPF" Version="5.1.59" /> <PackageReference Include="ScottPlot.WPF" Version="5.1.59" />
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" /> <PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.3" />
<PackageReference Include="System.IO.Hashing" Version="10.0.11" /> <PackageReference Include="System.IO.Hashing" Version="10.0.9" />
<PackageReference Include="System.IO.Ports" Version="10.0.11" /> <PackageReference Include="System.IO.Ports" Version="10.0.9" />
<PackageReference Include="System.Management" Version="10.0.11" /> <PackageReference Include="System.Management" Version="10.0.9" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+1 -2
View File
@@ -69,8 +69,7 @@ namespace Elwig.Helpers {
public DbSet<OverUnderDeliveryRow> OverUnderDeliveryRows { get; private set; } public DbSet<OverUnderDeliveryRow> OverUnderDeliveryRows { get; private set; }
public DbSet<AreaComUnderDeliveryRowSingle> AreaComUnderDeliveryRows { get; private set; } public DbSet<AreaComUnderDeliveryRowSingle> AreaComUnderDeliveryRows { get; private set; }
public DbSet<MemberDeliveryPerVarietyRowSingle> MemberDeliveryPerVariantRows { get; private set; } public DbSet<MemberDeliveryPerVarietyRowSingle> MemberDeliveryPerVariantRows { get; private set; }
public DbSet<MemberAreaComTotalsRowSingle> MemberAreaComTotalsRows { get; private set; } public DbSet<MemberAreaComsRowSingle> MemberAreaComsRows { get; private set; }
public DbSet<MemberAreaComsRow> MemberAreaComsRows { get; private set; }
public DbSet<CreditNoteDeliveryRowSingle> CreditNoteDeliveryRows { get; private set; } public DbSet<CreditNoteDeliveryRowSingle> CreditNoteDeliveryRows { get; private set; }
public DbSet<CreditNoteRowSingle> CreditNoteRows { get; private set; } public DbSet<CreditNoteRowSingle> CreditNoteRows { get; private set; }
public DbSet<WeightBreakdownRow> WeightBreakDownRows { get; private set; } public DbSet<WeightBreakdownRow> WeightBreakDownRows { get; private set; }
+8 -15
View File
@@ -9,22 +9,15 @@ namespace Elwig.Helpers {
public static class AppDbUpdater { public static class AppDbUpdater {
// Don't forget to update value in Tests/fetch-resources.bat! // Don't forget to update value in Tests/fetch-resources.bat!
public static readonly int RequiredSchemaVersion = 41; public static readonly int RequiredSchemaVersion = 40;
private static int VersionOffset = 0; private static int VersionOffset = 0;
public static async Task<Version> CheckDb() { public static async Task<Version> CheckDb() {
if (!File.Exists(App.Config.DatabaseFile))
throw new FileNotFoundException($"Die Datei \"{App.Config.DatabaseFile}\" exisitiert nicht");
long? applId, schemaVers; long? applId, schemaVers;
using (var cnx = await AppDbContext.ConnectAsync()) { using (var cnx = await AppDbContext.ConnectAsync()) {
await cnx.QuickCheck();
applId = (long?)await cnx.ExecuteScalar("PRAGMA application_id") ?? 0; applId = (long?)await cnx.ExecuteScalar("PRAGMA application_id") ?? 0;
if (applId != 0x454C5747) if (applId != 0x454C5747) throw new Exception($"Invalid application_id in database (0x{applId:X08})");
throw new FileFormatException($"Invalid application_id in database (0x{applId:X08})");
schemaVers = (long?)await cnx.ExecuteScalar("PRAGMA schema_version") ?? 0; schemaVers = (long?)await cnx.ExecuteScalar("PRAGMA schema_version") ?? 0;
VersionOffset = (int)(schemaVers % 100); VersionOffset = (int)(schemaVers % 100);
@@ -83,16 +76,16 @@ namespace Elwig.Helpers {
try { try {
using var cnx = await AppDbContext.ConnectAsync(); using var cnx = await AppDbContext.ConnectAsync();
await cnx.ExecuteBatch("PRAGMA locking_mode = EXCLUSIVE"); await cnx.ExecuteBatch("PRAGMA locking_mode = EXCLUSIVE");
await cnx.IntegrityCheck();
await cnx.ForeignKeyCheck();
foreach (var script in toExecute) { foreach (var script in toExecute) {
await cnx.ExecuteEmbeddedScript(asm, script); await cnx.ExecuteEmbeddedScript(asm, script);
} }
await cnx.IntegrityCheck(); var violations = await cnx.ForeignKeyCheck();
await cnx.ForeignKeyCheck(); if (violations.Length > 0) {
throw new Exception($"Foreign key violations ({violations.Length}):\n" + string.Join("\n", violations
.Take(50)
.Select(v => $"{v.Table} - {v.RowId} - {v.Parent} - {v.FkId}")));
}
await cnx.ExecuteBatch("VACUUM"); await cnx.ExecuteBatch("VACUUM");
await cnx.ExecuteBatch($"PRAGMA schema_version = {toVersion * 100 + VersionOffset}"); await cnx.ExecuteBatch($"PRAGMA schema_version = {toVersion * 100 + VersionOffset}");
+4 -30
View File
@@ -17,11 +17,10 @@ namespace Elwig.Helpers {
public string? Filling; public string? Filling;
public string? Limit; public string? Limit;
public bool Required; public bool Required;
public bool SyncTime;
public string? Log; public string? Log;
public string? _Log; public string? _Log;
public ScaleConfig(string id, string? type, string? model, string? cnx, string? empty, string? filling, string? limit, bool? required, bool? syncTime, string? log) { public ScaleConfig(string id, string? type, string? model, string? cnx, string? empty, string? filling, string? limit, bool? required, string? log) {
Id = id; Id = id;
Type = type; Type = type;
Model = model; Model = model;
@@ -30,7 +29,6 @@ namespace Elwig.Helpers {
Filling = filling; Filling = filling;
Limit = limit; Limit = limit;
Required = required ?? true; Required = required ?? true;
SyncTime = syncTime ?? true;
_Log = log; _Log = log;
Log = log != null ? Path.Combine(App.DataPath, log) : null; Log = log != null ? Path.Combine(App.DataPath, log) : null;
} }
@@ -39,30 +37,19 @@ namespace Elwig.Helpers {
public class Config { public class Config {
private static readonly string[] TrueValues = ["1", "true", "yes", "on"]; private static readonly string[] TrueValues = ["1", "true", "yes", "on"];
private static readonly string[] FalseValues = ["0", "false", "no", "off"];
private readonly string FileName; private readonly string FileName;
public bool Debug; public bool Debug;
public string DatabaseFile = Path.Combine(App.DataPath, "database.sqlite3"); public string DatabaseFile = App.DataPath + "database.sqlite3";
public string? DatabaseLog = null; public string? DatabaseLog = null;
public string? Branch = null; public string? Branch = null;
public WeighingMode? WeighingMode; public WeighingMode? WeighingMode;
public bool BackupAuto = true;
public string BackupPath = Path.Combine(App.DataPath, "backups");
public int BackupRetainHours = 36;
public int BackupRetainDays = 8;
public int BackupRetainWeeks = 6;
public int BackupRetainMonths = 18;
public string? UpdateUrl = null; public string? UpdateUrl = null;
public bool UpdateAuto = false; public bool UpdateAuto = false;
public string? SyncUrl = null; public string? SyncUrl = null;
public string SyncUsername = ""; public string SyncUsername = "";
public string SyncPassword = ""; public string SyncPassword = "";
public bool SyncMain = false;
public string? SmtpHost = null; public string? SmtpHost = null;
public int? SmtpPort = null; public int? SmtpPort = null;
@@ -70,10 +57,9 @@ namespace Elwig.Helpers {
public string? SmtpUsername = null; public string? SmtpUsername = null;
public string? SmtpPassword = null; public string? SmtpPassword = null;
public string? SmtpFrom = null; public string? SmtpFrom = null;
public double SmtpWait = 0; public (string Host, int Port, string Mode, string Username, string Password, string From)? Smtp =>
public (string Host, int Port, string Mode, string Username, string Password, string From, double Wait)? Smtp =>
SmtpHost == null || SmtpPort == null || SmtpMode == null || SmtpUsername == null || SmtpPassword == null || SmtpFrom == null ? SmtpHost == null || SmtpPort == null || SmtpMode == null || SmtpUsername == null || SmtpPassword == null || SmtpFrom == null ?
null : (SmtpHost, (int)SmtpPort, SmtpMode, SmtpUsername, SmtpPassword, SmtpFrom, SmtpWait); null : (SmtpHost, (int)SmtpPort, SmtpMode, SmtpUsername, SmtpPassword, SmtpFrom);
public IList<ScaleConfig> Scales; public IList<ScaleConfig> Scales;
private readonly List<ScaleConfig> ScaleList = []; private readonly List<ScaleConfig> ScaleList = [];
@@ -94,21 +80,11 @@ namespace Elwig.Helpers {
Debug = TrueValues.Contains(config["general:debug"]?.ToLower()); Debug = TrueValues.Contains(config["general:debug"]?.ToLower());
var weighing = config["general:weighing"]; var weighing = config["general:weighing"];
WeighingMode = weighing != null && Enum.TryParse<WeighingMode>(weighing, true, out var w) ? w : null; WeighingMode = weighing != null && Enum.TryParse<WeighingMode>(weighing, true, out var w) ? w : null;
BackupAuto = !FalseValues.Contains(config["backup:auto"]?.ToLower());
BackupPath = Path.Combine(Path.GetDirectoryName(DatabaseFile) ?? App.DataPath, config["backup:path"] ?? "backups");
BackupRetainHours = int.TryParse(config["backup:retain_hours"], out var hours) ? hours : 36;
BackupRetainDays = int.TryParse(config["backup:retain_days"], out var days) ? days : 8;
BackupRetainWeeks = int.TryParse(config["backup:retain_weeks"], out var weeks) ? weeks : 6;
BackupRetainMonths = int.TryParse(config["backup:retain_months"], out var months) ? months : 18;
UpdateUrl = config["update:url"]; UpdateUrl = config["update:url"];
UpdateAuto = TrueValues.Contains(config["update:auto"]?.ToLower()); UpdateAuto = TrueValues.Contains(config["update:auto"]?.ToLower());
SyncUrl = config["sync:url"]; SyncUrl = config["sync:url"];
SyncUsername = config["sync:username"] ?? ""; SyncUsername = config["sync:username"] ?? "";
SyncPassword = config["sync:password"] ?? ""; SyncPassword = config["sync:password"] ?? "";
SyncMain = TrueValues.Contains(config["sync:main"]?.ToLower());
SmtpHost = config["smtp:host"]; SmtpHost = config["smtp:host"];
SmtpPort = config["smtp:port"]?.All(char.IsAsciiDigit) == true && config["smtp:port"]?.Length > 0 ? int.Parse(config["smtp:port"]!) : null; SmtpPort = config["smtp:port"]?.All(char.IsAsciiDigit) == true && config["smtp:port"]?.Length > 0 ? int.Parse(config["smtp:port"]!) : null;
@@ -116,7 +92,6 @@ namespace Elwig.Helpers {
SmtpUsername = config["smtp:username"]; SmtpUsername = config["smtp:username"];
SmtpPassword = config["smtp:password"]; SmtpPassword = config["smtp:password"];
SmtpFrom = config["smtp:from"]; SmtpFrom = config["smtp:from"];
SmtpWait = double.TryParse(config["smtp:wait"], out var res) ? res : 0;
var scales = config.AsEnumerable().Where(i => i.Key.StartsWith("scale.")).GroupBy(i => i.Key.Split(':')[0][6..]).Select(i => i.Key).Order(); var scales = config.AsEnumerable().Where(i => i.Key.StartsWith("scale.")).GroupBy(i => i.Key.Split(':')[0][6..]).Select(i => i.Key).Order();
ScaleList.Clear(); ScaleList.Clear();
@@ -126,7 +101,6 @@ namespace Elwig.Helpers {
s, config[$"scale.{s}:type"], config[$"scale.{s}:model"], config[$"scale.{s}:connection"], s, config[$"scale.{s}:type"], config[$"scale.{s}:model"], config[$"scale.{s}:connection"],
config[$"scale.{s}:empty"], config[$"scale.{s}:filling"], config[$"scale.{s}:limit"], config[$"scale.{s}:empty"], config[$"scale.{s}:filling"], config[$"scale.{s}:limit"],
config[$"scale.{s}:required"] != null ? TrueValues.Contains(config[$"scale.{s}:required"]?.ToLower()) : null, config[$"scale.{s}:required"] != null ? TrueValues.Contains(config[$"scale.{s}:required"]?.ToLower()) : null,
config[$"scale.{s}:synctime"] != null ? !FalseValues.Contains(config[$"scale.{s}:synctime"]?.ToLower()) : null,
config[$"scale.{s}:log"] config[$"scale.{s}:log"]
)); ));
} }
+6 -6
View File
@@ -6,7 +6,7 @@ using System;
namespace Elwig.Helpers.Export { namespace Elwig.Helpers.Export {
using Row = Tuple<(string?, string?, string?, string?, string, int, string, bool, int), (string, int, string, string, string, int, string, double, double)>; using Row = Tuple<(string?, string?, string?, string?, string, int, string, int), (string, int, string, string, string, int, string, double, double)>;
public class Bki : Csv<Row> { public class Bki : Csv<Row> {
@@ -29,7 +29,7 @@ namespace Elwig.Helpers.Export {
using var cnx = await AppDbContext.ConnectAsync(); using var cnx = await AppDbContext.ConnectAsync();
using var cmd = cnx.CreateCommand(); using var cmd = cnx.CreateCommand();
cmd.CommandText = $""" cmd.CommandText = $"""
SELECT lfbis_nr, name, other_names, billing_name, address, plz, ort, vollablieferer, area, SELECT lfbis_nr, name, other_names, billing_name, address, plz, ort, area,
date, weight, type, sortid, qualid, year, hkid, kmw, oe date, weight, type, sortid, qualid, year, hkid, kmw, oe
FROM v_bki_delivery FROM v_bki_delivery
WHERE year = {year} WHERE year = {year}
@@ -38,8 +38,8 @@ namespace Elwig.Helpers.Export {
List<Row> rows = []; List<Row> rows = [];
while (await r.ReadAsync()) { while (await r.ReadAsync()) {
rows.Add(new( rows.Add(new(
(r.IsDBNull(0) ? null : r.GetString(0), r.IsDBNull(1) ? null : r.GetString(1), r.IsDBNull(2) ? null : r.GetString(2), r.IsDBNull(3) ? null : r.GetString(3), r.GetString(4), r.GetInt32(5), r.GetString(6), r.GetBoolean(7), r.GetInt32(8)), (r.IsDBNull(0) ? null : r.GetString(0), r.IsDBNull(1) ? null : r.GetString(1), r.IsDBNull(2) ? null : r.GetString(2), r.IsDBNull(3) ? null : r.GetString(3), r.GetString(4), r.GetInt32(5), r.GetString(6), r.GetInt32(7)),
(r.GetString(9), r.GetInt32(10), r.GetString(11), r.GetString(12), r.GetString(13), r.GetInt32(14), r.GetString(15), r.GetDouble(16), r.GetDouble(17)) (r.GetString(8), r.GetInt32(9), r.GetString(10), r.GetString(11), r.GetString(12), r.GetInt32(13), r.GetString(14), r.GetDouble(15), r.GetDouble(16))
)); ));
} }
@@ -52,14 +52,14 @@ namespace Elwig.Helpers.Export {
public override string FormatRow(Row row) { public override string FormatRow(Row row) {
var (member, delivery) = row; var (member, delivery) = row;
var (lfBisNr, familyName, name, billingName, address, plz, ort, vollablieferer, area) = member; var (lfBisNr, familyName, name, billingName, address, plz, ort, area) = member;
var (date, weight, type, sortid, qualid, year, hkid, kmw, oe) = delivery; var (date, weight, type, sortid, qualid, year, hkid, kmw, oe) = delivery;
var (n1, n2) = billingName == null ? (familyName, name) : Utils.SplitName(billingName, familyName); var (n1, n2) = billingName == null ? (familyName, name) : Utils.SplitName(billingName, familyName);
var (a1, a2) = Utils.SplitAddress(address); var (a1, a2) = Utils.SplitAddress(address);
var memberData = $"{lfBisNr};{n1};{n2};{a1};\t{a2};{plz};{ort}"; var memberData = $"{lfBisNr};{n1};{n2};{a1};\t{a2};{plz};{ort}";
var deliveryData = $"{string.Join(".", date.Split("-").Reverse())};{weight};TB;{(type == "W" ? "J" : "")};{(type == "R" ? "J" : "")};{sortid};;;{qualid};{year};{hkid};{kmw:0.0};{oe:0}"; var deliveryData = $"{string.Join(".", date.Split("-").Reverse())};{weight};TB;{(type == "W" ? "J" : "")};{(type == "R" ? "J" : "")};{sortid};;;{qualid};{year};{hkid};{kmw:0.0};{oe:0}";
var vollData = $"{(vollablieferer ? "J" : "N")};{(vollablieferer ? area / 10_000.0 : null):N4};{(vollablieferer ? area / 10_000.0 : null):N4};{area / 10_000.0:N4}"; var vollData = $"N;;;{area / 10_000.0}";
return $"{_clientData};{memberData};{deliveryData};{vollData}"; return $"{_clientData};{memberData};{deliveryData};{vollData}";
} }
+56 -68
View File
@@ -18,85 +18,73 @@ namespace Elwig.Helpers.Export {
} }
public static async Task ExportSqlite(string filename, bool zipFile) { public static async Task ExportSqlite(string filename, bool zipFile) {
var tmp = filename + ".tmp"; if (zipFile) {
try { File.Delete(filename);
File.Delete(tmp); using var zip = ZipFile.Open(filename, ZipArchiveMode.Create);
if (zipFile) {
using var zip = ZipFile.Open(tmp, ZipArchiveMode.Create);
var version = zip.CreateEntry("version", CompressionLevel.NoCompression); var version = zip.CreateEntry("version", CompressionLevel.NoCompression);
using (var writer = new StreamWriter(version.Open(), Utils.UTF8)) { using (var writer = new StreamWriter(version.Open(), Utils.UTF8)) {
await writer.WriteAsync("elwig:1"); await writer.WriteAsync("elwig:1");
}
var (applId, userVers, schemaVers, size) = await GetMeta();
var meta = zip.CreateEntry("meta.json", CompressionLevel.NoCompression);
using (var writer = new StreamWriter(meta.Open(), Utils.UTF8)) {
var obj = new JsonObject {
["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}",
["zwstid"] = App.ZwstId,
["device"] = Environment.MachineName,
["database"] = new JsonObject {
["application_id"] = applId,
["user_version"] = userVers,
["schema_version"] = schemaVers,
["file_size"] = size,
},
};
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
}
var db = zip.CreateEntryFromFile(App.Config.DatabaseFile, "database.sqlite3", CompressionLevel.SmallestSize);
} else {
File.Copy(App.Config.DatabaseFile, tmp);
} }
File.Move(tmp, filename, true);
} finally { var (applId, userVers, schemaVers, size) = await GetMeta();
File.Delete(tmp); var meta = zip.CreateEntry("meta.json", CompressionLevel.NoCompression);
using (var writer = new StreamWriter(meta.Open(), Utils.UTF8)) {
var obj = new JsonObject {
["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}",
["zwstid"] = App.ZwstId,
["device"] = Environment.MachineName,
["database"] = new JsonObject {
["application_id"] = applId,
["user_version"] = userVers,
["schema_version"] = schemaVers,
["file_size"] = size,
},
};
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
}
var db = zip.CreateEntryFromFile(App.Config.DatabaseFile, "database.sqlite3", CompressionLevel.SmallestSize);
} else {
File.Copy(App.Config.DatabaseFile, filename, true);
} }
} }
public static async Task ExportSql(string filename, bool zipFile) { public static async Task ExportSql(string filename, bool zipFile) {
var tmp = filename + ".tmp"; if (zipFile) {
try { File.Delete(filename);
File.Delete(tmp); using var zip = ZipFile.Open(filename, ZipArchiveMode.Create);
if (zipFile) {
using var zip = ZipFile.Open(tmp, ZipArchiveMode.Create);
var version = zip.CreateEntry("version", CompressionLevel.NoCompression); var version = zip.CreateEntry("version", CompressionLevel.NoCompression);
using (var writer = new StreamWriter(version.Open(), Utils.UTF8)) { using (var writer = new StreamWriter(version.Open(), Utils.UTF8)) {
await writer.WriteAsync("elwig:1"); await writer.WriteAsync("elwig:1");
} }
var (applId, userVers, schemaVers, size) = await GetMeta(); var (applId, userVers, schemaVers, size) = await GetMeta();
var meta = zip.CreateEntry("meta.json", CompressionLevel.NoCompression); var meta = zip.CreateEntry("meta.json", CompressionLevel.NoCompression);
using (var writer = new StreamWriter(meta.Open(), Utils.UTF8)) { using (var writer = new StreamWriter(meta.Open(), Utils.UTF8)) {
var obj = new JsonObject { var obj = new JsonObject {
["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}", ["timestamp"] = $"{DateTime.UtcNow:yyyy-MM-ddTHH:mm:ssZ}",
["zwstid"] = App.ZwstId, ["zwstid"] = App.ZwstId,
["device"] = Environment.MachineName, ["device"] = Environment.MachineName,
["database"] = new JsonObject { ["database"] = new JsonObject {
["application_id"] = applId, ["application_id"] = applId,
["user_version"] = userVers, ["user_version"] = userVers,
["schema_version"] = schemaVers, ["schema_version"] = schemaVers,
["file_size"] = size, ["file_size"] = size,
}, },
}; };
await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts)); await writer.WriteAsync(obj.ToJsonString(Utils.JsonOpts));
} }
var sql = zip.CreateEntry("database.sql", CompressionLevel.SmallestSize); var sql = zip.CreateEntry("database.sql", CompressionLevel.SmallestSize);
using (var writer = new StreamWriter(sql.Open(), Utils.UTF8)) { using (var writer = new StreamWriter(sql.Open(), Utils.UTF8)) {
await ExportSql(writer);
}
} else {
using var stream = File.OpenWrite(tmp);
using var writer = new StreamWriter(stream, Utils.UTF8);
await ExportSql(writer); await ExportSql(writer);
} }
File.Move(tmp, filename, true); } else {
} finally { using var stream = File.OpenWrite(filename);
File.Delete(tmp); using var writer = new StreamWriter(stream, Utils.UTF8);
await ExportSql(writer);
} }
} }
+15 -26
View File
@@ -10,6 +10,7 @@ using System.IO.Compression;
using System.Linq; using System.Linq;
using System.Text.Json.Nodes; using System.Text.Json.Nodes;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows;
namespace Elwig.Helpers.Export { namespace Elwig.Helpers.Export {
public static class ElwigData { public static class ElwigData {
@@ -35,16 +36,14 @@ namespace Elwig.Helpers.Export {
public static async Task Import(IEnumerable<string> filenames, ImportMode mode) { public static async Task Import(IEnumerable<string> filenames, ImportMode mode) {
try { try {
Dictionary<string, Branch> branches; Dictionary<string, Branch> branches;
Dictionary<int, AT_Kg> kgs;
Dictionary<int, int> currentDids; Dictionary<int, int> currentDids;
Dictionary<string, int> currentLsNrs; Dictionary<string, int> currentLsNrs;
Dictionary<int, List<WbRd>> currentWbRde; Dictionary<int, List<WbRd>> currentWbRde;
Dictionary<int, WbKg> currentWbKgs; Dictionary<int, AT_Kg> kgs;
List<WbGl> currentWbGls; List<WbGl> currentWbGls;
using (var ctx = new AppDbContext()) { using (var ctx = new AppDbContext()) {
branches = await ctx.FetchBranches().ToDictionaryAsync(b => b.ZwstId); branches = await ctx.FetchBranches().ToDictionaryAsync(b => b.ZwstId);
kgs = await ctx.Katastralgemeinden.ToDictionaryAsync(k => k.KgNr);
currentDids = await ctx.Deliveries currentDids = await ctx.Deliveries
.GroupBy(d => d.Year) .GroupBy(d => d.Year)
.ToDictionaryAsync(g => g.Key, g => g.Max(d => d.DId)); .ToDictionaryAsync(g => g.Key, g => g.Max(d => d.DId));
@@ -53,8 +52,8 @@ namespace Elwig.Helpers.Export {
currentWbRde = await ctx.WbRde currentWbRde = await ctx.WbRde
.GroupBy(r => r.KgNr) .GroupBy(r => r.KgNr)
.ToDictionaryAsync(g => g.Key, g => g.ToList()); .ToDictionaryAsync(g => g.Key, g => g.ToList());
currentWbKgs = await ctx.WbKgs.ToDictionaryAsync(k => k.KgNr);
currentWbGls = await ctx.WbGls.ToListAsync(); currentWbGls = await ctx.WbGls.ToListAsync();
kgs = await ctx.Katastralgemeinden.Include(k => k.WbKg).ToDictionaryAsync(k => k.KgNr);
} }
var data = new List<( var data = new List<(
@@ -123,7 +122,6 @@ namespace Elwig.Helpers.Export {
var obj = JsonNode.Parse(line)!.AsObject(); var obj = JsonNode.Parse(line)!.AsObject();
var (k, g) = obj.ToWbKg(currentWbGls); var (k, g) = obj.ToWbKg(currentWbGls);
r.WbKgs.Add(k); r.WbKgs.Add(k);
currentWbKgs[k.KgNr] = k;
if (g != null) { if (g != null) {
currentWbGls[g.GlNr] = g; currentWbGls[g.GlNr] = g;
r.WbGls.Add(g); r.WbGls.Add(g);
@@ -137,7 +135,7 @@ namespace Elwig.Helpers.Export {
string? line; string? line;
while ((line = await reader.ReadLineAsync()) != null) { while ((line = await reader.ReadLineAsync()) != null) {
var obj = JsonNode.Parse(line)!.AsObject(); var obj = JsonNode.Parse(line)!.AsObject();
var (m, b, telNrs, emailAddrs, timestamps) = obj.ToMember(kgs, currentWbKgs); var (m, b, telNrs, emailAddrs, timestamps) = obj.ToMember(kgs);
r.Members.Add(m); r.Members.Add(m);
if (b != null) r.BillingAddresses.Add(b); if (b != null) r.BillingAddresses.Add(b);
r.TelephoneNumbers.AddRange(telNrs); r.TelephoneNumbers.AddRange(telNrs);
@@ -165,7 +163,7 @@ namespace Elwig.Helpers.Export {
string? line; string? line;
while ((line = await reader.ReadLineAsync()) != null) { while ((line = await reader.ReadLineAsync()) != null) {
var obj = JsonNode.Parse(line)!.AsObject(); var obj = JsonNode.Parse(line)!.AsObject();
var (contract, areaCom, wbrd, timestamps) = obj.ToAreaCom(kgs, currentWbKgs, currentWbRde); var (contract, areaCom, wbrd, timestamps) = obj.ToAreaCom(currentWbRde);
r.Contracts.Add(contract); r.Contracts.Add(contract);
r.AreaCommitments.Add(areaCom); r.AreaCommitments.Add(areaCom);
if (wbrd != null) { if (wbrd != null) {
@@ -184,7 +182,7 @@ namespace Elwig.Helpers.Export {
string? line; string? line;
while ((line = await reader.ReadLineAsync()) != null) { while ((line = await reader.ReadLineAsync()) != null) {
var obj = JsonNode.Parse(line)!.AsObject(); var obj = JsonNode.Parse(line)!.AsObject();
var (contract, areaComs, wbrd, timestamps) = obj.ToAreaComContract(kgs, currentWbKgs, currentWbRde); var (contract, areaComs, wbrd, timestamps) = obj.ToAreaComContract(currentWbRde);
r.Contracts.Add(contract); r.Contracts.Add(contract);
r.AreaCommitments.AddRange(areaComs.Select(v => v.Item1)); r.AreaCommitments.AddRange(areaComs.Select(v => v.Item1));
if (wbrd != null) { if (wbrd != null) {
@@ -205,7 +203,7 @@ namespace Elwig.Helpers.Export {
string? line; string? line;
while ((line = await reader.ReadLineAsync()) != null) { while ((line = await reader.ReadLineAsync()) != null) {
var obj = JsonNode.Parse(line)!.AsObject(); var obj = JsonNode.Parse(line)!.AsObject();
var (d, parts, mods, rde, timestamps) = obj.ToDelivery(currentLsNrs, currentDids, kgs, currentWbKgs, currentWbRde); var (d, parts, mods, rde, timestamps) = obj.ToDelivery(currentLsNrs, currentDids, kgs, currentWbRde);
r.Deliveries.Add(d); r.Deliveries.Add(d);
r.DeliveryParts.AddRange(parts.Select(p => p.Item1)); r.DeliveryParts.AddRange(parts.Select(p => p.Item1));
r.Modifiers.AddRange(mods); r.Modifiers.AddRange(mods);
@@ -682,11 +680,11 @@ namespace Elwig.Helpers.Export {
}; };
} }
public static (Member, BillingAddr?, List<MemberTelNr>, List<MemberEmailAddr>, (DateTime CreatedAt, DateTime ModifiedAt)?) ToMember(this JsonNode json, Dictionary<int, AT_Kg> kgs, Dictionary<int, WbKg> currentWbKgs) { public static (Member, BillingAddr?, List<MemberTelNr>, List<MemberEmailAddr>, (DateTime CreatedAt, DateTime ModifiedAt)?) ToMember(this JsonNode json, Dictionary<int, AT_Kg> kgs) {
var mgnr = json["mgnr"]!.AsValue().GetValue<int>(); var mgnr = json["mgnr"]!.AsValue().GetValue<int>();
var kgnr = json["default_kgnr"]?.AsValue().GetValue<int>(); var kgnr = json["default_kgnr"]?.AsValue().GetValue<int>();
if (kgnr != null && !currentWbKgs.Values.Any(k => k.KgNr == kgnr)) { if (kgnr != null && !kgs.Values.Any(k => k.WbKg?.KgNr == kgnr)) {
throw new KeyNotFoundException($"Für KG {(kgs.TryGetValue(kgnr.Value, out var k) ? k.Name : "?")} ({kgnr:00000}) ist noch keine Großlage festgelegt!\n(Stammdaten \u2192 Herkunftshierarchie)"); throw new ArgumentException($"Für KG {(kgs.TryGetValue(kgnr.Value, out var k) ? k.Name : "?")} ({kgnr:00000}) ist noch keine Großlage festgelegt!\n(Stammdaten Herkunftshierarchie)");
} }
var createdAt = json["created_at"]?.AsValue().GetValue<string>(); var createdAt = json["created_at"]?.AsValue().GetValue<string>();
var modifiedAt = json["modified_at"]?.AsValue().GetValue<string>(); var modifiedAt = json["modified_at"]?.AsValue().GetValue<string>();
@@ -817,13 +815,10 @@ namespace Elwig.Helpers.Export {
}; };
} }
public static (AreaComContract, List<(AreaCom, (DateTime CreatedAt, DateTime ModifiedAt)?)>, WbRd?, (DateTime CreatedAt, DateTime ModifiedAt)?) ToAreaComContract(this JsonNode json, Dictionary<int, AT_Kg> kgs, Dictionary<int, WbKg> currentWbKgs, Dictionary<int, List<WbRd>> riede) { public static (AreaComContract, List<(AreaCom, (DateTime CreatedAt, DateTime ModifiedAt)?)>, WbRd?, (DateTime CreatedAt, DateTime ModifiedAt)?) ToAreaComContract(this JsonNode json, Dictionary<int, List<WbRd>> riede) {
var kgnr = json["kgnr"]!.AsValue().GetValue<int>(); var kgnr = json["kgnr"]!.AsValue().GetValue<int>();
var ried = json["ried"]?.AsValue().GetValue<string>(); var ried = json["ried"]?.AsValue().GetValue<string>();
var fbnr = json["fbnr"]!.AsValue()!.GetValue<int>(); var fbnr = json["fbnr"]!.AsValue()!.GetValue<int>();
if (!currentWbKgs.Values.Any(k => k.KgNr == kgnr)) {
throw new KeyNotFoundException($"Für KG {(kgs.TryGetValue(kgnr, out var k) ? k.Name : "?")} ({kgnr:00000}) ist noch keine Großlage festgelegt!\n(Stammdaten \u2192 Herkunftshierarchie)");
}
WbRd? rd = null; WbRd? rd = null;
bool newRd = false; bool newRd = false;
if (ried != null) { if (ried != null) {
@@ -871,12 +866,9 @@ namespace Elwig.Helpers.Export {
DateTime.ParseExact(modifiedAt, "yyyy-MM-ddTHH:mm:ssK", CultureInfo.InvariantCulture, DateTimeStyles.None))); DateTime.ParseExact(modifiedAt, "yyyy-MM-ddTHH:mm:ssK", CultureInfo.InvariantCulture, DateTimeStyles.None)));
} }
public static (AreaComContract, AreaCom, WbRd?, (DateTime CreatedAt, DateTime ModifiedAt)?) ToAreaCom(this JsonNode json, Dictionary<int, AT_Kg> kgs, Dictionary<int, WbKg> currentWbKgs, Dictionary<int, List<WbRd>> riede) { public static (AreaComContract, AreaCom, WbRd?, (DateTime CreatedAt, DateTime ModifiedAt)?) ToAreaCom(this JsonNode json, Dictionary<int, List<WbRd>> riede) {
var kgnr = json["kgnr"]!.AsValue().GetValue<int>(); var kgnr = json["kgnr"]!.AsValue().GetValue<int>();
var ried = json["ried"]?.AsValue().GetValue<string>(); var ried = json["ried"]?.AsValue().GetValue<string>();
if (!currentWbKgs.Values.Any(k => k.KgNr == kgnr)) {
throw new KeyNotFoundException($"Für KG {(kgs.TryGetValue(kgnr, out var k) ? k.Name : "?")} ({kgnr:00000}) ist noch keine Großlage festgelegt!\n(Stammdaten \u2192 Herkunftshierarchie)");
}
WbRd? rd = null; WbRd? rd = null;
bool newRd = false; bool newRd = false;
if (ried != null) { if (ried != null) {
@@ -959,13 +951,13 @@ namespace Elwig.Helpers.Export {
if (p.Unloading != null) obj["unloading"] = p.Unloading; if (p.Unloading != null) obj["unloading"] = p.Unloading;
if (p.Temperature != null) obj["temperature"] = p.Temperature; if (p.Temperature != null) obj["temperature"] = p.Temperature;
if (p.Acid != null) obj["acid"] = p.Acid; if (p.Acid != null) obj["acid"] = p.Acid;
if (p.ScaleTerminalId != null) obj["scale_terminal"] = p.ScaleTerminalId; if (p.ScaleId != null) obj["scale_id"] = p.ScaleId;
if (p.WeighingData != null) obj["weighing_data"] = JsonNode.Parse(p.WeighingData); if (p.WeighingData != null) obj["weighing_data"] = JsonNode.Parse(p.WeighingData);
if (p.WeighingReason != null) obj["weighing_reason"] = p.WeighingReason; if (p.WeighingReason != null) obj["weighing_reason"] = p.WeighingReason;
return obj; return obj;
} }
public static (Delivery, List<(DeliveryPart, (DateTime CreatedAt, DateTime ModifiedAt)?)>, List<DeliveryPartModifier>, List<WbRd>, (DateTime CreatedAt, DateTime ModifiedAt)?) ToDelivery(this JsonNode json, Dictionary<string, int> currentLsNrs, Dictionary<int, int> currentDids, Dictionary<int, AT_Kg> kgs, Dictionary<int, WbKg> currentWbKgs, Dictionary<int, List<WbRd>> riede) { public static (Delivery, List<(DeliveryPart, (DateTime CreatedAt, DateTime ModifiedAt)?)>, List<DeliveryPartModifier>, List<WbRd>, (DateTime CreatedAt, DateTime ModifiedAt)?) ToDelivery(this JsonNode json, Dictionary<string, int> currentLsNrs, Dictionary<int, int> currentDids, Dictionary<int, AT_Kg> kgs, Dictionary<int, List<WbRd>> riede) {
var year = json["year"]!.AsValue().GetValue<int>(); var year = json["year"]!.AsValue().GetValue<int>();
var lsnr = json["lsnr"]!.AsValue().GetValue<string>(); var lsnr = json["lsnr"]!.AsValue().GetValue<string>();
var did = currentLsNrs.GetValueOrDefault(lsnr, -1); var did = currentLsNrs.GetValueOrDefault(lsnr, -1);
@@ -991,9 +983,6 @@ namespace Elwig.Helpers.Export {
}, [.. json["parts"]!.AsArray().Select(p => p!.AsObject()).Select<JsonObject, (DeliveryPart, (DateTime, DateTime)?)>(p => { }, [.. json["parts"]!.AsArray().Select(p => p!.AsObject()).Select<JsonObject, (DeliveryPart, (DateTime, DateTime)?)>(p => {
var kgnr = p["kgnr"]?.AsValue().GetValue<int>(); var kgnr = p["kgnr"]?.AsValue().GetValue<int>();
var ried = p["ried"]?.AsValue().GetValue<string>(); var ried = p["ried"]?.AsValue().GetValue<string>();
if (kgnr != null && !currentWbKgs.Values.Any(k => k.KgNr == kgnr)) {
throw new KeyNotFoundException($"Für KG {(kgs.TryGetValue(kgnr.Value, out var k) ? k.Name : "?")} ({kgnr:00000}) ist noch keine Großlage festgelegt!\n(Stammdaten \u2192 Herkunftshierarchie)");
}
WbRd? rd = null; WbRd? rd = null;
if (ried != null && kgnr != null) { if (ried != null && kgnr != null) {
var rde = riede.GetValueOrDefault(kgnr.Value, []); var rde = riede.GetValueOrDefault(kgnr.Value, []);
@@ -1033,7 +1022,7 @@ namespace Elwig.Helpers.Export {
Unloading = p["unloading"]?.AsValue().GetValue<string>() ?? ((p["lesewagen"]?.AsValue().GetValue<bool>() ?? false) ? DeliveryPart.Pumped : null), Unloading = p["unloading"]?.AsValue().GetValue<string>() ?? ((p["lesewagen"]?.AsValue().GetValue<bool>() ?? false) ? DeliveryPart.Pumped : null),
Temperature = p["temperature"]?.AsValue().GetValue<double>(), Temperature = p["temperature"]?.AsValue().GetValue<double>(),
Acid = p["acid"]?.AsValue().GetValue<double>(), Acid = p["acid"]?.AsValue().GetValue<double>(),
ScaleTerminalId = p["scale_terminal"]?.AsValue().GetValue<string>() ?? p["scale_id"]?.AsValue().GetValue<string>(), ScaleId = p["scale_id"]?.AsValue().GetValue<string>(),
WeighingData = p["weighing_data"]?.AsObject().ToJsonString(Utils.JsonOpts), WeighingData = p["weighing_data"]?.AsObject().ToJsonString(Utils.JsonOpts),
WeighingReason = p["weighing_reason"]?.AsValue().GetValue<string>(), WeighingReason = p["weighing_reason"]?.AsValue().GetValue<string>(),
}, createdAt == null || modifiedAt == null ? null : }, createdAt == null || modifiedAt == null ? null :
+3 -43
View File
@@ -1,7 +1,6 @@
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.IO.Hashing; using System.IO.Hashing;
@@ -135,39 +134,11 @@ namespace Elwig.Helpers {
return await cmd.ExecuteScalarAsync(); return await cmd.ExecuteScalarAsync();
} }
public static async Task QuickCheck(this SqliteConnection cnx) { public static async Task<(string Table, long RowId, string Parent, long FkId)[]> ForeignKeyCheck(this SqliteConnection cnx) {
using var cmd = cnx.CreateCommand();
cmd.CommandText = "PRAGMA quick_check";
using var reader = await cmd.ExecuteReaderAsync();
var list = new List<string>();
while (await reader.ReadAsync()) {
list.Add(reader.GetString(0));
}
if (list.Count != 1 || list[0] != "ok") {
throw new FileFormatException($"Integrity problems ({list.Count}):\n" + string.Join("\n", list.Take(50)));
}
}
public static async Task IntegrityCheck(this SqliteConnection cnx) {
using var cmd = cnx.CreateCommand();
cmd.CommandText = "PRAGMA integrity_check";
using var reader = await cmd.ExecuteReaderAsync();
var list = new List<string>();
while (await reader.ReadAsync()) {
list.Add(reader.GetString(0));
}
if (list.Count != 1 || list[0] != "ok") {
throw new FileFormatException($"Integrity problems ({list.Count}):\n" + string.Join("\n", list.Take(50)));
}
}
public static async Task ForeignKeyCheck(this SqliteConnection cnx) {
using var cmd = cnx.CreateCommand(); using var cmd = cnx.CreateCommand();
cmd.CommandText = "PRAGMA foreign_key_check"; cmd.CommandText = "PRAGMA foreign_key_check";
using var reader = await cmd.ExecuteReaderAsync(); using var reader = await cmd.ExecuteReaderAsync();
var list = new List<(string Table, long RowId, string Parent, long FkId)>(); var list = new List<(string, long, string, long)>();
while (await reader.ReadAsync()) { while (await reader.ReadAsync()) {
var table = reader.GetString(0); var table = reader.GetString(0);
var rowid = reader.GetInt64(1); var rowid = reader.GetInt64(1);
@@ -175,11 +146,7 @@ namespace Elwig.Helpers {
var fkid = reader.GetInt64(3); var fkid = reader.GetInt64(3);
list.Add((table, rowid, parent, fkid)); list.Add((table, rowid, parent, fkid));
} }
return [.. list];
if (list.Count > 0) {
throw new InvalidDataException($"Foreign key violations ({list.Count}):\n" + string.Join("\n", list.Take(50)
.Select(v => $"{v.Table} - {v.RowId} - {v.Parent} - {v.FkId}")));
}
} }
public static IEnumerable<T> Join<T>(this IEnumerable<T> src, Func<T> separatorFactory) { public static IEnumerable<T> Join<T>(this IEnumerable<T> src, Func<T> separatorFactory) {
@@ -204,12 +171,5 @@ namespace Elwig.Helpers {
grid.Children.Add(tb); grid.Children.Add(tb);
} }
public static (int Year, int Week) GetYearAndWeek(this DateTime date) {
return (ISOWeek.GetYear(date), ISOWeek.GetWeekOfYear(date));
}
public static (int Year, int Tertial) GetYearAndTertial(this DateTime date) {
return (date.Month <= 7 ? date.Year - 1 : date.Year, date.Month == 12 || date.Month <= 3 ? 2 : date.Month <= 7 ? 3 : 1);
}
} }
} }
+20 -5
View File
@@ -1,17 +1,21 @@
using Elwig.Services; using Elwig.Services;
using Elwig.Windows; using Elwig.Windows;
using System; using System;
using System.Drawing.Printing;
using System.Threading.Tasks;
namespace Elwig.Helpers.Printing { namespace Elwig.Helpers.Printing {
public static class Pdf { public static class Pdf {
public static void Init(Action? evtHandler = null) { public static Task Init(Action? evtHandler = null) {
PdfiumNative.FPDF_InitLibrary(); PdfiumNative.FPDF_InitLibrary();
evtHandler?.Invoke(); evtHandler?.Invoke();
return Task.CompletedTask;
} }
public static void Cleanup() { public static Task Cleanup() {
PdfiumNative.FPDF_DestroyLibrary(); PdfiumNative.FPDF_DestroyLibrary();
return Task.CompletedTask;
} }
public static void Show(TempFile file, string title) { public static void Show(TempFile file, string title) {
@@ -28,13 +32,24 @@ namespace Elwig.Helpers.Printing {
}); });
} }
public static void Print(string path, int copies = 1, bool doublePaged = false) { public static async Task Print(string path, int copies = 1, bool doublePaged = false) {
await Print(path, new() {
Copies = (short)copies,
Collate = true,
Duplex = doublePaged ? Duplex.Vertical : Duplex.Simplex,
});
}
public static Task Print(string path, PrinterSettings settings) {
try { try {
var printer = new PdfPrinter(); using var printDoc = new PdfPrintDocument(path) {
printer.Print(path, copies, doublePaged); PrinterSettings = settings,
};
printDoc.Print();
} catch (Exception exc) { } catch (Exception exc) {
InteractionService.ShowException("Fehler beim Drucken", "Beim Drucken ist ein Fehler aufgetreten", exc); InteractionService.ShowException("Fehler beim Drucken", "Beim Drucken ist ein Fehler aufgetreten", exc);
} }
return Task.CompletedTask;
} }
} }
} }
+102
View File
@@ -0,0 +1,102 @@
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
namespace Elwig.Helpers.Printing {
public class PdfPrintDocument : PrintDocument {
private readonly IntPtr _handle;
private readonly int _pageCount;
private readonly double _dpi;
private int _currentPage;
public PdfPrintDocument(string path, string? password = null, double dpi = 300.0) :
base() {
_handle = PdfiumNative.FPDF_LoadDocument(path, password);
_pageCount = PdfiumNative.FPDF_GetPageCount(_handle);
_dpi = dpi;
}
protected override void Dispose(bool disposing) {
PdfiumNative.FPDF_CloseDocument(_handle);
base.Dispose(disposing);
}
protected override void OnBeginPrint(PrintEventArgs evt) {
_currentPage = (PrinterSettings.FromPage != 0) ? (PrinterSettings.FromPage - 1) : 0;
base.OnBeginPrint(evt);
}
protected override void OnPrintPage(PrintPageEventArgs evt) {
if (_currentPage < _pageCount) {
IntPtr page = PdfiumNative.FPDF_LoadPage(_handle, _currentPage);
double width = PdfiumNative.FPDF_GetPageWidth(page);
double height = PdfiumNative.FPDF_GetPageHeight(page);
int pixelWidth = (int)(width / 72.0 * _dpi);
int pixelHeight = (int)(height / 72.0 * _dpi);
IntPtr bitmap = PdfiumNative.FPDFBitmap_Create(pixelWidth, pixelHeight, 1);
PdfiumNative.FPDF_RenderPageBitmap(bitmap, page, 0, 0, pixelWidth, pixelHeight, 0, 0);
IntPtr buffer = PdfiumNative.FPDFBitmap_GetBuffer(bitmap);
int stride = PdfiumNative.FPDFBitmap_GetStride(bitmap);
using (var bmp = new Bitmap(pixelWidth, pixelHeight, stride, PixelFormat.Format32bppArgb, buffer)) {
evt.Graphics?.DrawImage(bmp, evt.PageBounds);
}
_currentPage++;
PdfiumNative.FPDFBitmap_Destroy(bitmap);
PdfiumNative.FPDF_ClosePage(page);
}
evt.HasMorePages = _currentPage < ((PrinterSettings.ToPage == 0) ? _pageCount : Math.Min(PrinterSettings.ToPage, _pageCount));
base.OnPrintPage(evt);
}
}
internal partial class PdfiumNative {
[LibraryImport("pdfium.dll")]
public static partial void FPDF_InitLibrary();
[LibraryImport("pdfium.dll")]
public static partial void FPDF_DestroyLibrary();
[LibraryImport("pdfium.dll", StringMarshalling = StringMarshalling.Utf8)]
public static partial IntPtr FPDF_LoadDocument(string filePath, string? password);
[LibraryImport("pdfium.dll")]
public static partial void FPDF_CloseDocument(IntPtr document);
[LibraryImport("pdfium.dll")]
public static partial int FPDF_GetPageCount(IntPtr document);
[LibraryImport("pdfium.dll")]
public static partial IntPtr FPDF_LoadPage(IntPtr document, int pageIndex);
[LibraryImport("pdfium.dll")]
public static partial void FPDF_ClosePage(IntPtr page);
[LibraryImport("pdfium.dll")]
public static partial double FPDF_GetPageWidth(IntPtr page);
[LibraryImport("pdfium.dll")]
public static partial double FPDF_GetPageHeight(IntPtr page);
[LibraryImport("pdfium.dll")]
public static partial IntPtr FPDFBitmap_Create(int width, int height, int alpha);
[LibraryImport("pdfium.dll")]
public static partial void FPDFBitmap_Destroy(IntPtr bitmap);
[LibraryImport("pdfium.dll")]
public static partial IntPtr FPDFBitmap_GetBuffer(IntPtr bitmap);
[LibraryImport("pdfium.dll")]
public static partial int FPDFBitmap_GetStride(IntPtr bitmap);
[LibraryImport("pdfium.dll")]
public static partial void FPDF_RenderPageBitmap(IntPtr bitmap, IntPtr page, int start_x, int start_y, int size_x, int size_y, int rotate, int flags);
}
}
-83
View File
@@ -1,83 +0,0 @@
using System;
using System.IO;
using System.Printing;
namespace Elwig.Helpers.Printing {
public class PdfPrinter {
public string PrinterName { get; init; }
public PdfPrinter(string? printerName = null) {
PrinterName = printerName ?? GetDefaultPrinterName() ?? throw new InvalidOperationException("No default Windows printer is configured.");
}
public void Print(string pdfPath, int copies = 1, bool doublePaged = false) {
if (!File.Exists(pdfPath)) throw new FileNotFoundException("PDF file not found.", pdfPath);
IntPtr document = PdfiumNative.FPDF_LoadDocument(pdfPath, null);
if (document == IntPtr.Zero) throw new InvalidOperationException("PDFium could not open the PDF.");
try {
int pageCount = PdfiumNative.FPDF_GetPageCount(document);
if (pageCount <= 0)
return;
using var printer = new Win32Printer.Printer(PrinterName);
printer.TrySetDuplex(doublePaged ? Duplexing.TwoSidedLongEdge : Duplexing.OneSided);
printer.StartDocument(Path.GetFileName(pdfPath));
bool documentStarted = true;
try {
for (int i = 0; i < copies; i++) {
for (int j = 0; j < pageCount; j++) {
PrintPage(document, printer, j);
}
}
printer.EndDocument();
documentStarted = false;
} finally {
if (documentStarted) printer.AbortDocument();
}
} finally {
PdfiumNative.FPDF_CloseDocument(document);
}
}
private static void PrintPage(IntPtr document, Win32Printer.Printer printer, int pageIndex) {
if (!PdfiumNative.FPDF_GetPageSizeByIndex(document, pageIndex, out double pageWidthPt, out double pageHeightPt)) {
throw new InvalidOperationException($"Unable to obtain PDF page {pageIndex} size.");
}
IntPtr page = PdfiumNative.FPDF_LoadPage(document, pageIndex);
if (page == IntPtr.Zero)
throw new InvalidOperationException($"Unable to load PDF page {pageIndex}.");
try {
int renderWidth = (int)Math.Round(pageWidthPt / 72.0 * printer.DpiX);
int renderHeight = (int)Math.Round(pageHeightPt / 72.0 * printer.DpiY);
int offsetX = (printer.PrintableWidth - renderWidth) / 2;
int offsetY = (printer.PrintableHeight - renderHeight) / 2;
printer.StartPage();
try {
PdfiumNative.FPDF_RenderPage(printer.Hdc, page, offsetX, offsetY, renderWidth, renderHeight, 0, PdfiumNative.FPDF_PRINTING | PdfiumNative.FPDF_ANNOT);
} finally {
printer.EndPage();
}
} finally {
PdfiumNative.FPDF_ClosePage(page);
}
}
private static string? GetDefaultPrinterName() {
using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Windows");
string? printer = key?.GetValue("Device") as string;
if (string.IsNullOrWhiteSpace(printer))
return null;
// Device has the form:
// Printer Name,winspool,PORT
int comma = printer.IndexOf(',');
return comma >= 0 ? printer[..comma] : printer;
}
}
}
-38
View File
@@ -1,38 +0,0 @@
using System;
using System.Runtime.InteropServices;
namespace Elwig.Helpers.Printing {
internal partial class PdfiumNative {
public const int FPDF_ANNOT = 0x01;
public const int FPDF_PRINTING = 0x800;
[LibraryImport("pdfium.dll")]
public static partial void FPDF_InitLibrary();
[LibraryImport("pdfium.dll")]
public static partial void FPDF_DestroyLibrary();
[LibraryImport("pdfium.dll", StringMarshalling = StringMarshalling.Utf8)]
public static partial IntPtr FPDF_LoadDocument(string filePath, string? password);
[LibraryImport("pdfium.dll")]
public static partial void FPDF_CloseDocument(IntPtr document);
[LibraryImport("pdfium.dll")]
public static partial int FPDF_GetPageCount(IntPtr document);
[LibraryImport("pdfium.dll")]
public static partial IntPtr FPDF_LoadPage(IntPtr document, int pageIndex);
[LibraryImport("pdfium.dll")]
public static partial void FPDF_ClosePage(IntPtr page);
[LibraryImport("pdfium.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool FPDF_GetPageSizeByIndex(IntPtr document, int pageIndex, out double width, out double height);
[LibraryImport("pdfium.dll")]
public static partial void FPDF_RenderPage(IntPtr hdc, IntPtr page, int startX, int startY, int sizeX, int sizeY, int rotate, int flags);
}
}
-239
View File
@@ -1,239 +0,0 @@
using System;
using System.ComponentModel;
using System.Printing;
using System.Runtime.InteropServices;
namespace Elwig.Helpers.Printing {
public partial class Win32Printer {
private const int DM_OUT_BUFFER = 2;
private const int HORZRES = 8;
private const int VERTRES = 10;
private const int LOGPIXELSX = 88;
private const int LOGPIXELSY = 90;
private const int PHYSICALWIDTH = 110;
private const int PHYSICALHEIGHT = 111;
private const int PHYSICALOFFSETX = 112;
private const int PHYSICALOFFSETY = 113;
private const int DM_DUPLEX = 0x1000;
private const short DMDUP_SIMPLEX = 1;
private const short DMDUP_VERTICAL = 2;
private const short DMDUP_HORIZONTAL = 3;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct DOCINFO {
public int cbSize;
[MarshalAs(UnmanagedType.LPWStr)]
public string? lpszDocName;
[MarshalAs(UnmanagedType.LPWStr)]
public string? lpszOutput;
[MarshalAs(UnmanagedType.LPWStr)]
public string? lpszDatatype;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct DEVMODE {
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public short dmOrientation;
public short dmPaperSize;
public short dmPaperLength;
public short dmPaperWidth;
public short dmScale;
public short dmCopies;
public short dmDefaultSource;
public short dmPrintQuality;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmFormName;
public short dmLogPixels;
public int dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
}
[DllImport("winspool.drv", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool OpenPrinter(string pPrinterName, out IntPtr phPrinter, IntPtr pDefault);
[DllImport("winspool.drv", SetLastError = true)]
private static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.drv", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern int DocumentProperties(IntPtr hwnd, IntPtr hPrinter, string pDeviceName, IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode);
[DllImport("gdi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr CreateDC(string? pDriver, string? pDevice, string? pOutput, IntPtr pInitData);
[DllImport("gdi32.dll", SetLastError = true)]
private static extern bool DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll", SetLastError = true)]
private static extern int GetDeviceCaps(IntPtr hdc, int index);
[DllImport("gdi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern int StartDoc(IntPtr hdc, ref DOCINFO lpdi);
[DllImport("gdi32.dll", SetLastError = true)]
private static extern int EndDoc(IntPtr hdc);
[DllImport("gdi32.dll", SetLastError = true)]
private static extern int AbortDoc(IntPtr hdc);
[DllImport("gdi32.dll", SetLastError = true)]
private static extern int StartPage(IntPtr hdc);
[DllImport("gdi32.dll", SetLastError = true)]
private static extern int EndPage(IntPtr hdc);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GlobalAlloc(uint uFlags, UIntPtr dwBytes);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GlobalFree(IntPtr hMem);
[DllImport("kernel32.dll")]
private static extern IntPtr GlobalLock(IntPtr hMem);
[DllImport("kernel32.dll")]
private static extern bool GlobalUnlock(IntPtr hMem);
public class Printer : IDisposable {
private readonly string _printerName;
private readonly IntPtr _printerHandle;
private readonly IntPtr _devMode;
private readonly IntPtr _hdc;
public IntPtr Hdc => _hdc;
public int PrintableWidth => GetDeviceCaps(_hdc, HORZRES);
public int PrintableHeight => GetDeviceCaps(_hdc, VERTRES);
public int DpiX => GetDeviceCaps(_hdc, LOGPIXELSX);
public int DpiY => GetDeviceCaps(_hdc, LOGPIXELSY);
public int PhysicalWidth => GetDeviceCaps(_hdc, PHYSICALWIDTH);
public int PhysicalHeight => GetDeviceCaps(_hdc, PHYSICALHEIGHT);
public int PhysicalOffsetX => GetDeviceCaps(_hdc, PHYSICALOFFSETX);
public int PhysicalOffsetY => GetDeviceCaps(_hdc, PHYSICALOFFSETY);
public Printer(string printerName) {
_printerName = printerName;
if (!OpenPrinter(_printerName, out _printerHandle, IntPtr.Zero)) {
throw new Win32Exception(Marshal.GetLastWin32Error(), $"Unable to open printer '{printerName}'.");
}
try {
_devMode = CreateDevMode();
_hdc = CreateDC(null, _printerName, null, _devMode);
if (_hdc == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error(), $"Unable to create printer DC for '{_printerName}'.");
} catch {
if (_devMode != IntPtr.Zero) Marshal.FreeHGlobal(_devMode);
ClosePrinter(_printerHandle);
throw;
}
}
public bool TrySetDuplex(Duplexing duplex) {
var devMode = Marshal.PtrToStructure<DEVMODE>(_devMode);
switch (duplex) {
case Duplexing.OneSided: devMode.dmDuplex = DMDUP_SIMPLEX; break;
case Duplexing.TwoSidedShortEdge: devMode.dmDuplex = DMDUP_HORIZONTAL; break;
case Duplexing.TwoSidedLongEdge: devMode.dmDuplex = DMDUP_VERTICAL; break;
}
if ((devMode.dmFields & DM_DUPLEX) != 0) {
Marshal.StructureToPtr(devMode, _devMode, false);
return true;
} else {
devMode.dmFields |= DM_DUPLEX;
Marshal.StructureToPtr(devMode, _devMode, false);
return false;
}
}
private IntPtr CreateDevMode() {
int size = DocumentProperties(IntPtr.Zero, _printerHandle, _printerName, IntPtr.Zero, IntPtr.Zero, 0);
if (size <= 0)
throw new Win32Exception(Marshal.GetLastWin32Error(), "DocumentProperties failed.");
IntPtr devMode = Marshal.AllocHGlobal(size);
int result = DocumentProperties(IntPtr.Zero, _printerHandle, _printerName, devMode, IntPtr.Zero, DM_OUT_BUFFER);
if (result < 0) {
Marshal.FreeHGlobal(devMode);
throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to obtain printer DEVMODE.");
}
return devMode;
}
public void StartDocument(string documentName) {
var docInfo = new DOCINFO {
cbSize = Marshal.SizeOf<DOCINFO>(),
lpszDocName = documentName,
lpszDatatype = null,
lpszOutput = null
};
if (StartDoc(_hdc, ref docInfo) <= 0)
throw new Win32Exception(Marshal.GetLastWin32Error(), "StartDoc failed.");
}
public void StartPage() {
if (Win32Printer.StartPage(_hdc) <= 0)
throw new Win32Exception(Marshal.GetLastWin32Error(), "StartPage failed.");
}
public void EndPage() {
if (Win32Printer.EndPage(_hdc) <= 0)
throw new Win32Exception(Marshal.GetLastWin32Error(), "EndPage failed.");
}
public void EndDocument() {
if (EndDoc(_hdc) <= 0)
throw new Win32Exception( Marshal.GetLastWin32Error(), "EndDoc failed.");
}
public void AbortDocument() {
AbortDoc(_hdc);
}
public void Dispose() {
if (_hdc != IntPtr.Zero)
DeleteDC(_hdc);
if (_devMode != IntPtr.Zero)
Marshal.FreeHGlobal(_devMode);
if (_printerHandle != IntPtr.Zero)
ClosePrinter(_printerHandle);
}
}
}
}
+6 -6
View File
@@ -45,6 +45,7 @@ namespace Elwig.Helpers {
public static int CurrentNextSeason => DateTime.Now.Year - (DateTime.Now.Month <= 3 ? 1 : 0); public static int CurrentNextSeason => DateTime.Now.Year - (DateTime.Now.Month <= 3 ? 1 : 0);
public static int CurrentLastSeason => DateTime.Now.Year - (DateTime.Now.Month <= 6 ? 1 : 0); public static int CurrentLastSeason => DateTime.Now.Year - (DateTime.Now.Month <= 6 ? 1 : 0);
public static int FollowingSeason => DateTime.Now.Year + (DateTime.Now.Month >= 11 ? 1 : 0); public static int FollowingSeason => DateTime.Now.Year + (DateTime.Now.Month >= 11 ? 1 : 0);
public static DateTime Today => (DateTime.Now.Hour >= 3) ? DateTime.Today : DateTime.Today.AddDays(-1);
[GeneratedRegex("^serial://([A-Za-z0-9]+):([0-9]+)(,([5-9]),([NOEMSnoems]),(0|1|1\\.5|2|))?$", RegexOptions.Compiled)] [GeneratedRegex("^serial://([A-Za-z0-9]+):([0-9]+)(,([5-9]),([NOEMSnoems]),(0|1|1\\.5|2|))?$", RegexOptions.Compiled)]
private static partial Regex GeneratedSerialRegex(); private static partial Regex GeneratedSerialRegex();
@@ -515,7 +516,7 @@ namespace Elwig.Helpers {
public static async Task<SmtpClient?> GetSmtpClient() { public static async Task<SmtpClient?> GetSmtpClient() {
if (App.Config.Smtp == null) if (App.Config.Smtp == null)
return null; return null;
var (host, port, mode, username, password, _, _) = App.Config.Smtp.Value; var (host, port, mode, username, password, _) = App.Config.Smtp.Value;
var client = new SmtpClient(); var client = new SmtpClient();
await client.ConnectAsync(host, port, mode == "starttls" ? SecureSocketOptions.StartTls : SecureSocketOptions.None); await client.ConnectAsync(host, port, mode == "starttls" ? SecureSocketOptions.StartTls : SecureSocketOptions.None);
await client.AuthenticateAsync(username, password); await client.AuthenticateAsync(username, password);
@@ -535,7 +536,6 @@ namespace Elwig.Helpers {
msg.From.Add(new MailboxAddress(App.Client.NameFull, App.Config.Smtp.Value.From)); msg.From.Add(new MailboxAddress(App.Client.NameFull, App.Config.Smtp.Value.From));
msg.To.AddRange(member.EmailAddresses.OrderBy(a => a.Nr).Select(a => new MailboxAddress(member.AdministrativeName, a.Address))); msg.To.AddRange(member.EmailAddresses.OrderBy(a => a.Nr).Select(a => new MailboxAddress(member.AdministrativeName, a.Address)));
msg.Subject = subject; msg.Subject = subject;
msg.Date = DateTime.Now;
var body = new Multipart("mixed") { var body = new Multipart("mixed") {
new TextPart("plain") { Text = text } new TextPart("plain") { Text = text }
}; };
@@ -546,10 +546,10 @@ namespace Elwig.Helpers {
msg.Body = body; msg.Body = body;
await client!.SendAsync(msg); await client!.SendAsync(msg);
await AddSentMails([( await AddSentMails([(
"email", member.MgNr, member.AdministrativeName, "email", member.MgNr, member.AdministrativeName,
member.EmailAddresses.OrderBy(a => a.Nr).Select(a => a.Address).ToArray(), member.EmailAddresses.OrderBy(a => a.Nr).Select(a => a.Address).ToArray(),
subject, docs.Select(d => d.Title).ToArray() subject, docs.Select(d => d.Title).ToArray()
)]); )]);
} catch (Exception exc) { } catch (Exception exc) {
InteractionService.ShowException(exc); InteractionService.ShowException(exc);
return false; return false;
+5 -2
View File
@@ -9,8 +9,9 @@ namespace Elwig.Helpers.Weighing {
public class AveryEventScale : Scale, IEventScale, IDisposable { public class AveryEventScale : Scale, IEventScale, IDisposable {
public string Manufacturer => "Avery"; public string Manufacturer => "Avery";
public int InternalScaleNr => 1;
public string Model { get; private set; } public string Model { get; private set; }
public string ScaleTerminalId { get; private set; } public string ScaleId { get; private set; }
public bool IsReady { get; private set; } public bool IsReady { get; private set; }
public bool HasFillingClearance { get; private set; } public bool HasFillingClearance { get; private set; }
@@ -18,11 +19,13 @@ namespace Elwig.Helpers.Weighing {
private bool IsRunning = true; private bool IsRunning = true;
private readonly Thread BackgroundThread; private readonly Thread BackgroundThread;
private readonly string Connection;
public AveryEventScale(string id, string model, string cnx, string? log = null, bool required = true) : public AveryEventScale(string id, string model, string cnx, string? log = null, bool required = true) :
base(cnx, null, null, null, log, true, !required) { base(cnx, null, null, null, log, true, !required) {
ScaleTerminalId = id; ScaleId = id;
Model = model; Model = model;
Connection = cnx;
IsReady = true; IsReady = true;
HasFillingClearance = false; HasFillingClearance = false;
Stream.WriteTimeout = -1; Stream.WriteTimeout = -1;
@@ -5,17 +5,18 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Elwig.Helpers.Weighing { namespace Elwig.Helpers.Weighing {
public class GassnerEnqScale : Scale, ICommandScale { public class GassnerScale : Scale, ICommandScale {
public string Manufacturer => "Gassner"; public string Manufacturer => "Gassner";
public int InternalScaleNr => 1;
public string Model { get; private set; } public string Model { get; private set; }
public string ScaleTerminalId { get; private set; } public string ScaleId { get; private set; }
public bool IsReady { get; private set; } public bool IsReady { get; private set; }
public bool HasFillingClearance { get; private set; } public bool HasFillingClearance { get; private set; }
public GassnerEnqScale(string id, string model, string cnx, string? empty = null, string? filling = null, int? limit = null, string? log = null) : public GassnerScale(string id, string model, string cnx, string? empty = null, string? filling = null, int? limit = null, string? log = null) :
base(cnx, empty, filling, limit, log) { base(cnx, empty, filling, limit, log) {
ScaleTerminalId = id; ScaleId = id;
Model = model; Model = model;
IsReady = true; IsReady = true;
HasFillingClearance = false; HasFillingClearance = false;
@@ -23,9 +24,10 @@ namespace Elwig.Helpers.Weighing {
Stream.ReadTimeout = 11000; Stream.ReadTimeout = 11000;
} }
protected Task SendCommand(string command) => SendCommand(Encoding.ASCII.GetBytes(command)); protected Task SendCommand(char command) => SendCommand(Convert.ToByte(command));
protected async Task SendCommand(byte[] cmd) { protected async Task SendCommand(byte command) {
byte[] cmd = [command];
await Stream.WriteAsync(cmd); await Stream.WriteAsync(cmd);
if (LogPath != null) await File.AppendAllTextAsync(LogPath, Encoding.ASCII.GetString(cmd)); if (LogPath != null) await File.AppendAllTextAsync(LogPath, Encoding.ASCII.GetString(cmd));
} }
@@ -51,15 +53,15 @@ namespace Elwig.Helpers.Weighing {
return line[1..^1]; return line[1..^1];
} }
protected async Task<WeighingResult> Weigh(int? internalScaleNr, bool incIdentNr, bool retry = true) { protected async Task<WeighingResult> Weigh(bool incIdentNr, bool retry = true) {
string record; string record;
try { try {
await SendCommand(incIdentNr ? "\x05" : "?"); await SendCommand(incIdentNr ? '\x05' : '?');
record = await ReceiveResponse(); record = await ReceiveResponse();
} catch (IOException) { } catch (IOException) {
if (!retry || Tcp == null) throw; if (!retry || Tcp == null) throw;
ReconnectTcp(); ReconnectTcp();
return await Weigh(internalScaleNr, incIdentNr, false); return await Weigh(incIdentNr, false);
} }
if (record.Length != 45) if (record.Length != 45)
throw new FormatException("Invalid response from scale: Received record has invalid size"); throw new FormatException("Invalid response from scale: Received record has invalid size");
@@ -78,7 +80,6 @@ namespace Elwig.Helpers.Weighing {
GrossWeight = int.Parse(brutto), GrossWeight = int.Parse(brutto),
TareWeight = int.Parse(tara), TareWeight = int.Parse(tara),
NetWeight = int.Parse(netto), NetWeight = int.Parse(netto),
ScaleId = scaleNr,
WeighingId = identNr, WeighingId = identNr,
FullWeighingId = identNr, FullWeighingId = identNr,
Date = DateOnly.TryParseExact(date, "yyyyMMdd", out var d) ? d : null, Date = DateOnly.TryParseExact(date, "yyyyMMdd", out var d) ? d : null,
@@ -86,12 +87,12 @@ namespace Elwig.Helpers.Weighing {
}; };
} }
public async Task<WeighingResult> Weigh(int? scaleNr = null) { public async Task<WeighingResult> Weigh() {
return await Weigh(scaleNr, true); return await Weigh(true);
} }
public async Task<WeighingResult> GetCurrentWeight(int? scaleNr = null) { public async Task<WeighingResult> GetCurrentWeight() {
return await Weigh(scaleNr, false); return await Weigh(false);
} }
public async Task Empty() { public async Task Empty() {
@@ -125,9 +126,8 @@ namespace Elwig.Helpers.Weighing {
await SetFillingClearance(false); await SetFillingClearance(false);
} }
public async Task SetDateAndTime(DateTime dateTime) { public Task SetDateAndTime(DateTime dateTime) {
await SendCommand($"C{dateTime:yyyyMMddHHmmss}\r"); throw new NotImplementedException("Für Waagen vom Typ 'Gassner' ist diese Funktion noch nicht implementiert");
await ReceiveResponse();
} }
} }
} }
+2 -2
View File
@@ -10,13 +10,13 @@ namespace Elwig.Helpers.Weighing {
/// Get the current weight on the scale without performing a weighing process /// Get the current weight on the scale without performing a weighing process
/// </summary> /// </summary>
/// <returns>Result of the weighing process (probably without a weighing id)</returns> /// <returns>Result of the weighing process (probably without a weighing id)</returns>
Task<WeighingResult> GetCurrentWeight(int? scaleNr = null); Task<WeighingResult> GetCurrentWeight();
/// <summary> /// <summary>
/// Perform a weighing process /// Perform a weighing process
/// </summary> /// </summary>
/// <returns>Result of the weighing process (including a weighing id)</returns> /// <returns>Result of the weighing process (including a weighing id)</returns>
Task<WeighingResult> Weigh(int? scaleNr = null); Task<WeighingResult> Weigh();
/// <summary> /// <summary>
/// Empty the scale container or grant clearance to do so /// Empty the scale container or grant clearance to do so
+6 -1
View File
@@ -18,7 +18,12 @@ namespace Elwig.Helpers.Weighing {
/// <summary> /// <summary>
/// Unique identificator of the scale /// Unique identificator of the scale
/// </summary> /// </summary>
string ScaleTerminalId { get; } string ScaleId { get; }
/// <summary>
/// Internal identifying number of the scale in its system
/// </summary>
int InternalScaleNr { get; }
/// <summary> /// <summary>
/// Indicates if the scale is currently processing a request or not /// Indicates if the scale is currently processing a request or not
+2 -1
View File
@@ -5,7 +5,8 @@ namespace Elwig.Helpers.Weighing {
public string Manufacturer => "NONE"; public string Manufacturer => "NONE";
public string Model => "NONE"; public string Model => "NONE";
public string ScaleTerminalId => id; public string ScaleId => id;
public int InternalScaleNr => 0;
public bool IsReady => false; public bool IsReady => false;
public bool HasFillingClearance => false; public bool HasFillingClearance => false;
public int? WeightLimit => null; public int? WeightLimit => null;
+3 -3
View File
@@ -28,10 +28,10 @@ namespace Elwig.Helpers.Weighing {
int? limit = config.Limit != null ? int.Parse(config.Limit) : null; int? limit = config.Limit != null ? int.Parse(config.Limit) : null;
if (config.Type == "SysTec-IT") { if (config.Type == "SysTec-IT") {
return new SysTecITScale(config.Id, config.Model!, config.Connection!, config.Empty, config.Filling, limit, config.Log); return new SysTecITScale(config.Id, config.Model!, config.Connection!, config.Empty, config.Filling, limit, config.Log);
} else if (config.Type == "Gassner-Enq" || config.Type == "Gassner") { } else if (config.Type == "Avery-Async") {
return new GassnerEnqScale(config.Id, config.Model!, config.Connection!, config.Empty, config.Filling, limit, config.Log);
} else if (config.Type == "Avery-Event" || config.Type == "Avery-Async") {
return new AveryEventScale(config.Id, config.Model!, config.Connection!, config.Log, config.Required); return new AveryEventScale(config.Id, config.Model!, config.Connection!, config.Log, config.Required);
} else if (config.Type == "Gassner") {
return new GassnerScale(config.Id, config.Model!, config.Connection!, config.Empty, config.Filling, limit, config.Log);
} else { } else {
throw new ArgumentException($"Invalid scale type: \"{config.Type}\""); throw new ArgumentException($"Invalid scale type: \"{config.Type}\"");
} }
+10 -10
View File
@@ -8,14 +8,15 @@ namespace Elwig.Helpers.Weighing {
public class SysTecITScale : Scale, ICommandScale { public class SysTecITScale : Scale, ICommandScale {
public string Manufacturer => "SysTec"; public string Manufacturer => "SysTec";
public int InternalScaleNr => 1;
public string Model { get; private set; } public string Model { get; private set; }
public string ScaleTerminalId { get; private set; } public string ScaleId { get; private set; }
public bool IsReady { get; private set; } public bool IsReady { get; private set; }
public bool HasFillingClearance { get; private set; } public bool HasFillingClearance { get; private set; }
public SysTecITScale(string id, string model, string cnx, string? empty = null, string? filling = null, int? limit = null, string? log = null) : public SysTecITScale(string id, string model, string cnx, string? empty = null, string? filling = null, int? limit = null, string? log = null) :
base(cnx, empty, filling, limit, log) { base(cnx, empty, filling, limit, log) {
ScaleTerminalId = id; ScaleId = id;
Model = model; Model = model;
IsReady = true; IsReady = true;
HasFillingClearance = false; HasFillingClearance = false;
@@ -73,15 +74,15 @@ namespace Elwig.Helpers.Weighing {
return line[1..^3]; return line[1..^3];
} }
protected async Task<WeighingResult> Weigh(int internalScalNr, bool incIdentNr, bool retry = true) { protected async Task<WeighingResult> Weigh(bool incIdentNr, bool retry = true) {
string record; string record;
try { try {
await SendCommand(incIdentNr ? $"RN{internalScalNr}" : $"RM{internalScalNr}"); await SendCommand(incIdentNr ? $"RN{InternalScaleNr}" : $"RM{InternalScaleNr}");
record = await ReceiveResponse(); record = await ReceiveResponse();
} catch (IOException) { } catch (IOException) {
if (!retry || Tcp == null) throw; if (!retry || Tcp == null) throw;
ReconnectTcp(); ReconnectTcp();
return await Weigh(internalScalNr, incIdentNr, false); return await Weigh(incIdentNr, false);
} }
if (record.Length != 62) if (record.Length != 62)
throw new FormatException("Invalid response from scale: Received record has invalid size"); throw new FormatException("Invalid response from scale: Received record has invalid size");
@@ -113,7 +114,6 @@ namespace Elwig.Helpers.Weighing {
GrossWeight = int.Parse(brutto), GrossWeight = int.Parse(brutto),
TareWeight = int.Parse(tara), TareWeight = int.Parse(tara),
NetWeight = int.Parse(netto), NetWeight = int.Parse(netto),
ScaleId = scaleNr,
WeighingId = identNr, WeighingId = identNr,
FullWeighingId = identNr != null ? $"{parsedDate:yyyy-MM-dd}/{identNr}" : null, FullWeighingId = identNr != null ? $"{parsedDate:yyyy-MM-dd}/{identNr}" : null,
Date = parsedDate, Date = parsedDate,
@@ -121,12 +121,12 @@ namespace Elwig.Helpers.Weighing {
}; };
} }
public async Task<WeighingResult> Weigh(int? scaleNr = 1) { public async Task<WeighingResult> Weigh() {
return await Weigh(scaleNr ?? 1, true); return await Weigh(true);
} }
public async Task<WeighingResult> GetCurrentWeight(int? scaleNr = 1) { public async Task<WeighingResult> GetCurrentWeight() {
return await Weigh(scaleNr ?? 1, false); return await Weigh(false);
} }
public async Task Empty() { public async Task Empty() {
+1 -7
View File
@@ -21,11 +21,6 @@ namespace Elwig.Helpers.Weighing {
/// </summary> /// </summary>
public int? NetWeight; public int? NetWeight;
/// <summary>
/// Reported id of the scale
/// </summary>
public string? ScaleId;
/// <summary> /// <summary>
/// Weighing id (or IdentNr) provided by the scale /// Weighing id (or IdentNr) provided by the scale
/// </summary> /// </summary>
@@ -49,12 +44,11 @@ namespace Elwig.Helpers.Weighing {
/// <returns>&lt;[GrossWeight-TaraWeight=]NetWeight/WeighingId/Date/Time&gt;</returns> /// <returns>&lt;[GrossWeight-TaraWeight=]NetWeight/WeighingId/Date/Time&gt;</returns>
public override readonly string ToString() { public override readonly string ToString() {
var w = NetWeight != null ? (GrossWeight != null && TareWeight != null ? $"{GrossWeight}-{TareWeight}=" : "") + $"{NetWeight}kg" : ""; var w = NetWeight != null ? (GrossWeight != null && TareWeight != null ? $"{GrossWeight}-{TareWeight}=" : "") + $"{NetWeight}kg" : "";
return $"<{w}/{WeighingId}/{Date:yyyy-MM-dd}/{Time:HH:mm:ss}>"; return $"<{w}/{WeighingId}/{Date:yyyy-MM-dd}/{Time:HH:mm}>";
} }
public readonly JsonObject ToJson() { public readonly JsonObject ToJson() {
var obj = new JsonObject(); var obj = new JsonObject();
if (ScaleId != null) obj["scale"] = ScaleId;
if (FullWeighingId != null) obj["id"] = FullWeighingId; if (FullWeighingId != null) obj["id"] = FullWeighingId;
if (WeighingId != null) obj["nr"] = int.Parse(WeighingId); if (WeighingId != null) obj["nr"] = int.Parse(WeighingId);
if (Date != null) obj["date"] = $"{Date:yyyy-MM-dd}"; if (Date != null) obj["date"] = $"{Date:yyyy-MM-dd}";
@@ -1,105 +0,0 @@
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Elwig.Models.Dtos {
class MemberAreaComTotalsData : DataTable<MemberAreaComTotalsRow> {
private static readonly (string, string, string?, int)[] FieldNames = [
("MgNr", "MgNr.", null, 12),
("Name1", "Name", null, 40),
("Name2", "Vorname", null, 40),
("Address", "Adresse", null, 60),
("Plz", "PLZ", null, 10),
("Locality", "Ort", null, 60),
("SortIds", "Sorte", null, 12),
("AttrIds", "Attribut", null, 16),
("Areas", "Fläche", "m²", 22),
("DeliveryObligations", "Lieferpflicht", "kg", 22),
("DeliveryRights", "Lieferrecht", "kg", 22),
];
public MemberAreaComTotalsData(IEnumerable<MemberAreaComTotalsRow> rows, int year) :
base($"Gebundene Fläche", $"Gebundene Fläche pro Mitglied {year}", rows, FieldNames) {
}
public static async Task<MemberAreaComTotalsData> ForSeason(DbSet<MemberAreaComTotalsRowSingle> table, int year) {
return new MemberAreaComTotalsData(
(await FromDbSet(table, year)).GroupBy(
r => r.MgNr,
(k, g) => new MemberAreaComTotalsRow(g)
), year);
}
private static async Task<IEnumerable<MemberAreaComTotalsRowSingle>> FromDbSet(DbSet<MemberAreaComTotalsRowSingle> table, int year) {
return await table.FromSql($"""
SELECT m.mgnr, m.name AS name_1,
COALESCE(m.prefix || ' ', '') || m.given_name ||
COALESCE(' ' || m.middle_names, '') || COALESCE(' ' || m.suffix, '') AS name_2,
p.plz, o.name AS ort, m.address,
c.bucket, c.area, c.min_kg, c.max_kg
FROM v_area_commitment_bucket_strict c
LEFT JOIN member m ON m.mgnr = c.mgnr
LEFT JOIN AT_plz_dest p ON p.id = m.postal_dest
LEFT JOIN AT_ort o ON o.okz = p.okz
WHERE c.year = {year}
ORDER BY m.mgnr, c.bucket
""").ToListAsync();
}
}
public class MemberAreaComTotalsRow {
public int MgNr;
public string Name1;
public string? Name2;
public string Address;
public int Plz;
public string Locality;
public string[] SortIds;
public string[] AttrIds;
public int[] Areas;
public int[] DeliveryObligations;
public int[] DeliveryRights;
public MemberAreaComTotalsRow(IEnumerable<MemberAreaComTotalsRowSingle> rows) {
var f = rows.First();
MgNr = f.MgNr;
Name1 = f.Name1;
Name2 = f.Name2;
Address = f.Address;
Plz = f.Plz;
Locality = f.Locality.Split(",")[0];
SortIds = [.. rows.Select(r => r.VtrgId[..2])];
AttrIds = [.. rows.Select(r => r.VtrgId[2..])];
Areas = [.. rows.Select(r => r.Area)];
DeliveryObligations = [.. rows.Select(r => r.MinKg)];
DeliveryRights = [.. rows.Select(r => r.MaxKg)];
}
}
[Keyless]
public class MemberAreaComTotalsRowSingle {
[Column("mgnr")]
public int MgNr { get; set; }
[Column("name_1")]
public required string Name1 { get; set; }
[Column("name_2")]
public string? Name2 { get; set; }
[Column("address")]
public required string Address { get; set; }
[Column("plz")]
public int Plz { get; set; }
[Column("ort")]
public required string Locality { get; set; }
[Column("bucket")]
public required string VtrgId { get; set; }
[Column("area")]
public int Area { get; set; }
[Column("min_kg")]
public int MinKg { get; set; }
[Column("max_kg")]
public int MaxKg { get; set; }
}
}
+48 -30
View File
@@ -14,49 +14,73 @@ namespace Elwig.Models.Dtos {
("Address", "Adresse", null, 60), ("Address", "Adresse", null, 60),
("Plz", "PLZ", null, 10), ("Plz", "PLZ", null, 10),
("Locality", "Ort", null, 60), ("Locality", "Ort", null, 60),
("SortId", "Sorte", null, 12), ("SortIds", "Sorte", null, 12),
("AttrId", "Attribut", null, 16), ("AttrIds", "Attribut", null, 16),
("CultId", "Bewirt.", null, 16), ("Areas", "Fläche", "m²", 22),
("GstNr", "Parzelle(n)", null, 25), ("DeliveryObligations", "Lieferpflicht", "kg", 22),
("Area", "Fläche", "", 22), ("DeliveryRights", "Lieferrecht", "kg", 22),
("MinKg", "Lieferpflicht", "kg", 22),
("MaxKg", "Lieferrecht", "kg", 22),
]; ];
public MemberAreaComsData(IEnumerable<MemberAreaComsRow> rows, int year) : public MemberAreaComsData(IEnumerable<MemberAreaComsRow> rows, int year) :
base($"Flächenbindungen", $"Flächenbindungen pro Mitglied {year}", rows, FieldNames) { base($"Flächenbindungen", $"Flächenbindungen pro Mitglied {year}", rows, FieldNames) {
} }
public static async Task<MemberAreaComsData> ForSeason(DbSet<MemberAreaComsRow> table, int year) { public static async Task<MemberAreaComsData> ForSeason(DbSet<MemberAreaComsRowSingle> table, int year) {
return new MemberAreaComsData(await FromDbSet(table, year), year); return new MemberAreaComsData(
(await FromDbSet(table, year)).GroupBy(
r => r.MgNr,
(k, g) => new MemberAreaComsRow(g)
), year);
} }
private static async Task<IEnumerable<MemberAreaComsRow>> FromDbSet(DbSet<MemberAreaComsRow> table, int year) { private static async Task<IEnumerable<MemberAreaComsRowSingle>> FromDbSet(DbSet<MemberAreaComsRowSingle> table, int year) {
return await table.FromSql($""" return await table.FromSql($"""
SELECT m.mgnr, m.name AS name_1, SELECT m.mgnr, m.name AS name_1,
COALESCE(m.prefix || ' ', '') || m.given_name || COALESCE(m.prefix || ' ', '') || m.given_name ||
COALESCE(' ' || m.middle_names, '') || COALESCE(' ' || m.suffix, '') AS name_2, COALESCE(' ' || m.middle_names, '') || COALESCE(' ' || m.suffix, '') AS name_2,
p.plz, o.name AS ort, m.address, p.plz, o.name AS ort, m.address,
t.sortid, t.attrid, c.cultid, c.bucket, c.area, c.min_kg, c.max_kg
c.gstnr, c.area, FROM v_area_commitment_bucket_strict c
CAST(ROUND(area * COALESCE(t.min_kg_per_ha, 0) / 10000.0, 0) AS INTEGER) AS min_kg,
CAST(ROUND(area * MIN(COALESCE(a.max_kg_per_ha, s.max_kg_per_ha), s.max_kg_per_ha) / 10000.0, 0) AS INTEGER) AS max_kg
FROM v_virtual_season s, area_commitment c
JOIN area_commitment_type t ON t.vtrgid = c.vtrgid
LEFT JOIN wine_attribute a ON a.attrid = t.attrid
LEFT JOIN member m ON m.mgnr = c.mgnr LEFT JOIN member m ON m.mgnr = c.mgnr
LEFT JOIN AT_plz_dest p ON p.id = m.postal_dest LEFT JOIN AT_plz_dest p ON p.id = m.postal_dest
LEFT JOIN AT_ort o ON o.okz = p.okz LEFT JOIN AT_ort o ON o.okz = p.okz
WHERE s.year = {year} AND WHERE c.year = {year}
(year_from IS NULL OR year_from <= s.year) AND ORDER BY m.mgnr, c.bucket
(year_to IS NULL OR year_to >= s.year)
ORDER BY c.mgnr, t.sortid, t.attrid, c.cultid, c.gstnr;
""").ToListAsync(); """).ToListAsync();
} }
} }
[Keyless]
public class MemberAreaComsRow { public class MemberAreaComsRow {
public int MgNr;
public string Name1;
public string? Name2;
public string Address;
public int Plz;
public string Locality;
public string[] SortIds;
public string[] AttrIds;
public int[] Areas;
public int[] DeliveryObligations;
public int[] DeliveryRights;
public MemberAreaComsRow(IEnumerable<MemberAreaComsRowSingle> rows) {
var f = rows.First();
MgNr = f.MgNr;
Name1 = f.Name1;
Name2 = f.Name2;
Address = f.Address;
Plz = f.Plz;
Locality = f.Locality.Split(",")[0];
SortIds = rows.Select(r => r.VtrgId[..2]).ToArray();
AttrIds = rows.Select(r => r.VtrgId[2..]).ToArray();
Areas = rows.Select(r => r.Area).ToArray();
DeliveryObligations = rows.Select(r => r.MinKg).ToArray();
DeliveryRights = rows.Select(r => r.MaxKg).ToArray();
}
}
[Keyless]
public class MemberAreaComsRowSingle {
[Column("mgnr")] [Column("mgnr")]
public int MgNr { get; set; } public int MgNr { get; set; }
[Column("name_1")] [Column("name_1")]
@@ -69,14 +93,8 @@ namespace Elwig.Models.Dtos {
public int Plz { get; set; } public int Plz { get; set; }
[Column("ort")] [Column("ort")]
public required string Locality { get; set; } public required string Locality { get; set; }
[Column("sortid")] [Column("bucket")]
public required string SortId { get; set; } public required string VtrgId { get; set; }
[Column("attrid")]
public string? AttrId { get; set; }
[Column("cultid")]
public string? CultId { get; set; }
[Column("gstnr")]
public required string GstNr { get; set; }
[Column("area")] [Column("area")]
public int Area { get; set; } public int Area { get; set; }
[Column("min_kg")] [Column("min_kg")]
+4 -5
View File
@@ -118,18 +118,17 @@ namespace Elwig.Models.Entities {
[Column("acid")] [Column("acid")]
public double? Acid { get; set; } public double? Acid { get; set; }
[Column("scale_terminal")] [Column("scale_id")]
public string? ScaleTerminalId { get; set; } public string? ScaleId { get; set; }
[Column("weighing_data")] [Column("weighing_data")]
public string? WeighingData { get; set; } public string? WeighingData { get; set; }
[NotMapped] [NotMapped]
public (string? ScaleId, string? Id, int? Gross, int? Tare, int? Net, DateOnly? Date, TimeOnly? Time) WeighingInfo { public (string? Id, int? Gross, int? Tare, int? Net, DateOnly? Date, TimeOnly? Time) WeighingInfo {
get { get {
try { try {
var obj = JsonNode.Parse(WeighingData!)!.AsObject(); var obj = JsonNode.Parse(WeighingData!)!.AsObject();
return ( return (
obj["scale"]?.AsValue().GetValue<string>(),
obj["id"]?.AsValue().GetValue<string>(), obj["id"]?.AsValue().GetValue<string>(),
obj["gross_weight"]?.AsValue().GetValue<int>(), obj["gross_weight"]?.AsValue().GetValue<int>(),
obj["tare_weight"]?.AsValue().GetValue<int>(), obj["tare_weight"]?.AsValue().GetValue<int>(),
@@ -138,7 +137,7 @@ namespace Elwig.Models.Entities {
TimeOnly.TryParseExact(obj["time"]?.AsValue().GetValue<string>(), ["HH:mm:ss", "HH:mm"], out var t) ? t : null TimeOnly.TryParseExact(obj["time"]?.AsValue().GetValue<string>(), ["HH:mm:ss", "HH:mm"], out var t) ? t : null
); );
} catch { } catch {
return (null, null, null, null, null, null, null); return (null, null, null, null, null, null);
} }
} }
} }
+10 -6
View File
@@ -3,11 +3,15 @@
PRAGMA writable_schema = ON; PRAGMA writable_schema = ON;
ALTER TABLE member RENAME COLUMN business_shares TO shares; ALTER TABLE member RENAME COLUMN business_shares TO shares;
ALTER TABLE member ADD COLUMN shares_red INTEGER NOT NULL DEFAULT 0 CHECK (shares_red >= 0); ALTER TABLE member ADD COLUMN shares_red INTEGER NOT NULL DEFAULT 0;
ALTER TABLE member ADD COLUMN shares_white INTEGER NOT NULL DEFAULT 0 CHECK (shares_white >= 0); ALTER TABLE member ADD COLUMN shares_white INTEGER NOT NULL DEFAULT 0;
ALTER TABLE member ADD COLUMN shares_dormant INTEGER NOT NULL DEFAULT 0 CHECK (shares_dormant >= 0); ALTER TABLE member ADD COLUMN shares_dormant INTEGER NOT NULL DEFAULT 0;
UPDATE sqlite_schema SET sql = REPLACE(sql, 'shares INTEGER NOT NULL DEFAULT 0', 'shares INTEGER NOT NULL DEFAULT 0 CHECK (shares >= 0)') UPDATE sqlite_schema SET sql = REPLACE(sql, CHAR(10) ||
') STRICT',
',' || CHAR(10) ||
' CONSTRAINT c_member_shares CHECK (shares >= 0 AND shares_red >= 0 AND shares_white >= 0 AND shares_dormant >= 0)' || CHAR(10) ||
') STRICT')
WHERE type = 'table' AND name = 'member'; WHERE type = 'table' AND name = 'member';
UPDATE client_parameter SET value = '0' WHERE param = 'ENABLE_TIME_TRIGGERS'; UPDATE client_parameter SET value = '0' WHERE param = 'ENABLE_TIME_TRIGGERS';
@@ -28,7 +32,7 @@ CREATE TABLE member_history_new (
reason TEXT NOT NULL CHECK (reason REGEXP '^[a-z_]+$'), reason TEXT NOT NULL CHECK (reason REGEXP '^[a-z_]+$'),
source TEXT NOT NULL CHECK (source REGEXP '^[a-z_]+$'), source TEXT NOT NULL CHECK (source REGEXP '^[a-z_]+$'),
shares INTEGER NOT NULL CHECK (shares > 0), shares INTEGER NOT NULL,
signed INTEGER NOT NULL CHECK (signed IN (TRUE, FALSE)) DEFAULT FALSE, signed INTEGER NOT NULL CHECK (signed IN (TRUE, FALSE)) DEFAULT FALSE,
value_per_share INTEGER DEFAULT NULL, value_per_share INTEGER DEFAULT NULL,
currency TEXT DEFAULT NULL, currency TEXT DEFAULT NULL,
@@ -45,7 +49,7 @@ CREATE TABLE member_history_new (
CONSTRAINT fk_member_history_currency FOREIGN KEY (currency) REFERENCES currency (code) CONSTRAINT fk_member_history_currency FOREIGN KEY (currency) REFERENCES currency (code)
ON UPDATE CASCADE ON UPDATE CASCADE
ON DELETE RESTRICT, ON DELETE RESTRICT,
CONSTRAINT c_member_history CHECK ((from_mgnr IS NOT NULL OR to_mgnr IS NOT NULL) AND CONSTRAINT c_member_history CHECK (shares > 0 AND (from_mgnr IS NOT NULL OR to_mgnr IS NOT NULL) AND
((from_mgnr IS NULL AND from_type IS NULL) OR (from_mgnr IS NOT NULL AND from_type IS NOT NULL)) AND ((from_mgnr IS NULL AND from_type IS NULL) OR (from_mgnr IS NOT NULL AND from_type IS NOT NULL)) AND
((to_mgnr IS NULL AND to_type IS NULL) OR (to_mgnr IS NOT NULL AND to_type IS NOT NULL))) ((to_mgnr IS NULL AND to_type IS NULL) OR (to_mgnr IS NOT NULL AND to_type IS NOT NULL)))
) STRICT; ) STRICT;
-37
View File
@@ -1,37 +0,0 @@
-- schema version 40 to 41
PRAGMA writable_schema = ON;
UPDATE sqlite_schema SET sql = REPLACE(sql, 'scale_id ', 'scale_terminal')
WHERE type = 'table' AND name = 'delivery_part';
DROP VIEW v_bki_delivery;
DROP VIEW v_bki_member;
CREATE VIEW v_bki_member AS
SELECT s.year, m.mgnr, m.lfbis_nr, m.name,
(COALESCE(m.prefix || ' ', '') || m.given_name || COALESCE(' ' || m.middle_names, '') || COALESCE(' ' || m.suffix, '')) AS other_names,
a.name AS billing_name, COALESCE(a.address, m.address) AS address,
COALESCE(a.country, m.country) AS country, COALESCE(a.postal_dest, m.postal_dest) AS postal_dest,
m.volllieferant AS vollablieferer,
SUM(COALESCE(IIF((c.year_from IS NULL OR c.year_from <= s.year) AND (c.year_to IS NULL OR c.year_to >= s.year), c.area, NULL), 0)) AS area
FROM season s, member m
LEFT JOIN member_billing_address a ON a.mgnr = m.mgnr
LEFT JOIN area_commitment c ON c.mgnr = m.mgnr
GROUP BY s.year, m.mgnr;
CREATE VIEW v_bki_delivery AS
SELECT m.lfbis_nr, m.name, m.other_names, m.billing_name,
m.address, plz.plz, IIF(INSTR(o.name, ',') = 0, o.name, SUBSTR(o.name, 1, INSTR(o.name, ',') - 1)) AS ort,
d.date, d.weight, v.type, v.sortid, d.qualid, d.year, d.hkid, d.kmw, d.oe,
m.vollablieferer, m.area
FROM v_delivery d
JOIN v_bki_member m ON (m.year, m.mgnr) = (d.year, d.mgnr)
JOIN postal_dest pd ON (pd.country, pd.id) = (m.country, m.postal_dest)
LEFT JOIN AT_plz_dest ap ON (ap.country, ap.id) = (pd.country, pd.id)
LEFT JOIN AT_plz plz ON plz.plz = ap.plz
LEFT JOIN AT_ort o ON o.okz = ap.okz
JOIN wine_variety v ON v.sortid = d.sortid
ORDER BY d.date, d.time;
PRAGMA writable_schema = OFF;
-133
View File
@@ -1,133 +0,0 @@
using Elwig.Helpers;
using Elwig.Helpers.Export;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Elwig.Services {
public static class BackupService {
public static bool IsAnyBackupUpToDate {
get {
var lastDbWrite = File.GetLastWriteTime(App.Config.DatabaseFile);
lastDbWrite += new TimeSpan(0, 0, -1);
return Directory.GetFiles(App.Config.BackupPath, "????-??-??_??-??-??.*.zip")
.Any(n => DateTime.ParseExact(Path.GetFileName(n)[..19], "yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture, DateTimeStyles.None) >= lastDbWrite);
}
}
public static async Task TryDatabaseBackup() {
if (IsAnyBackupUpToDate) return;
await BackupDatabase();
PruneBackups();
}
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);
}
public static void PruneBackups() {
var retain = new HashSet<string>();
var backups = Directory.GetFiles(App.Config.BackupPath, "????-??-??_??-??-??.*.zip")
.Select(n => (FileName: n, Timestamp: DateTime.ParseExact(Path.GetFileName(n)[..19], "yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture, DateTimeStyles.None)))
.OrderByDescending(t => t.Timestamp).ToArray();
DateTime now;
// retain hourly backups
now = DateTime.Now;
for (int i = 0; i < App.Config.BackupRetainHours; i++, now = now.AddHours(-1)) {
foreach (var b in backups) {
if (b.Timestamp.Date == now.Date && b.Timestamp.Hour == now.Hour) {
retain.Add(b.FileName);
break;
}
}
}
// retain daily backups
now = DateTime.Now;
for (int i = 0; i < App.Config.BackupRetainDays; i++, now = now.AddDays(-1)) {
foreach (var b in backups) {
if (b.Timestamp.Date == now.Date) {
retain.Add(b.FileName);
break;
}
}
}
// retain weekly backups
now = DateTime.Now;
for (int i = 0; i < App.Config.BackupRetainWeeks; i++, now = now.AddDays(-7)) {
foreach (var b in backups) {
if (b.Timestamp.GetYearAndWeek() == now.GetYearAndWeek()) {
retain.Add(b.FileName);
break;
}
}
}
// retain monthly backups
now = DateTime.Now;
for (int i = 0; i < App.Config.BackupRetainMonths; i++, now = now.AddMonths(-1)) {
foreach (var b in backups) {
if (b.Timestamp.Year == now.Year && b.Timestamp.Month == now.Month) {
retain.Add(b.FileName);
break;
}
}
}
// retain tertial backups
now = new DateTime(DateTime.Now.Year + 1, 3, 1);
for (int i = 0; i < 600; i++, now = now.AddMonths(-4)) {
foreach (var b in backups) {
if (b.Timestamp.GetYearAndTertial() == now.GetYearAndTertial()) {
retain.Add(b.FileName);
break;
}
}
}
// delete non-retained files
foreach (var b in backups) {
if (retain.Contains(b.FileName)) continue;
try {
File.Delete(b.FileName);
} catch { }
}
// delete temp files
foreach (var f in Directory.GetFiles(App.Config.BackupPath, "*.tmp")) {
try {
File.Delete(f);
} catch { }
}
}
public static async Task RestoreDatabase() {
try {
var d = new OpenFileDialog() {
Title = "Datenbank wiederherstellen - Elwig",
DefaultDirectory = App.Config.BackupPath,
InitialDirectory = App.Config.BackupPath,
DefaultExt = "sql.zip",
Filter = "SQLite-Datenbank (*.sqlite3, *.sqlite3.zip, *.sql, *.sql.zip)|*.sqlite3;*.sqlite3.zip;*.sql;*.sql.zip",
};
if (d.ShowDialog() == true) {
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);
}
} catch (Exception exc) {
InteractionService.ShowException(exc);
}
Mouse.OverrideCursor = null;
}
}
}
+1 -2
View File
@@ -45,8 +45,7 @@ namespace Elwig.Services {
deliveryAncmtQuery = deliveryAncmtQuery.Where(a => a.Year == s.Year && a.DsNr == s.DsNr); deliveryAncmtQuery = deliveryAncmtQuery.Where(a => a.Year == s.Year && a.DsNr == s.DsNr);
filterNames.Add($"{s.Date:dd.MM.yyyy} {s.Branch.Name} {s.Description}"); filterNames.Add($"{s.Date:dd.MM.yyyy} {s.Branch.Name} {s.Description}");
} else { } else {
var today = DateTime.Today; deliveryAncmtQuery = deliveryAncmtQuery.Where(a => a.Year == vm.FilterSeason && (!vm.FilterOnlyUpcoming || a.Schedule.DateString.CompareTo(Utils.Today.ToString("yyyy-MM-dd")) >= 0));
deliveryAncmtQuery = deliveryAncmtQuery.Where(a => a.Year == vm.FilterSeason && (!vm.FilterOnlyUpcoming || a.Schedule.DateString.CompareTo(today.ToString("yyyy-MM-dd")) >= 0));
filterNames.Add($"{vm.FilterSeason}"); filterNames.Add($"{vm.FilterSeason}");
} }
+2 -3
View File
@@ -49,9 +49,8 @@ namespace Elwig.Services {
filterNames.Add($"{vm.FilterSeason}"); filterNames.Add($"{vm.FilterSeason}");
} }
if (vm.FilterOnlyUpcoming) { if (vm.FilterOnlyUpcoming) {
var today = DateTime.Today; deliveryScheduleQuery = deliveryScheduleQuery.Where(s => s.DateString.CompareTo(Utils.Today.ToString("yyyy-MM-dd")) >= 0);
deliveryScheduleQuery = deliveryScheduleQuery.Where(s => s.DateString.CompareTo(today.ToString("yyyy-MM-dd")) >= 0); filterNames.Add($"ab {Utils.Today:dd.MM.yyyy}");
filterNames.Add($"ab {today:dd.MM.yyyy}");
} }
var filterVar = new List<string>(); var filterVar = new List<string>();
+14 -50
View File
@@ -67,50 +67,11 @@ namespace Elwig.Services {
vm.IsGebunden = p.IsGebunden; vm.IsGebunden = p.IsGebunden;
vm.Unloading = p.Unloading; vm.Unloading = p.Unloading;
vm.ScaleTerminalId = p.ScaleTerminalId; vm.ScaleId = p.ScaleId;
vm.WeighingData = p.WeighingData; vm.WeighingData = p.WeighingData;
vm.ManualWeighingReason = p.WeighingReason; vm.ManualWeighingReason = p.WeighingReason;
} }
public static (DateTime From, DateTime To)? GetFilterToday(DateTime today, IEnumerable<DateTime> timestamps) {
var filtered = timestamps.Where(t => t >= today.AddDays(-1) && t < today.AddDays(1)).Order().ToArray();
if (filtered.Length == 0) return null;
var latest = filtered.Last();
var since = filtered.Cast<DateTime>().Reverse().Aggregate(latest, (s, c) => s.Subtract(c).TotalHours <= 6 ? c : s);
latest += new TimeSpan(0, 1, -latest.Minute, -latest.Second, -latest.Millisecond, -latest.Microsecond);
since += new TimeSpan(0, 0, -since.Minute, -since.Second, -since.Millisecond, -since.Microsecond);
if (since.Subtract(today) <= new TimeSpan(-6, 0, 0) && latest.Subtract(today) < new TimeSpan(0, 0, 0))
return null;
return (since, latest);
}
private static async Task<(Expression<Func<Delivery, bool>>, string)> GetFilterToday(AppDbContext ctx) {
var today = DateTime.Today;
var timestamps = (await ctx.Deliveries
.Where(d => d.DateString.CompareTo(today.AddDays(-1).ToString("yyyy-MM-dd")) >= 0)
.OrderBy(d => d.DateString).ThenBy(d => d.TimeString)
.Select(d => d.DateString + " " + d.TimeString)
.ToListAsync())
.Select(s => DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt) ? (DateTime?)dt : null)
.Where(t => t.HasValue)
.Cast<DateTime>()
.ToArray();
var res = GetFilterToday(today, timestamps);
if (!res.HasValue) {
return (_ => false, today.ToString("dd.MM.yyyy"));
} else {
var from = res.Value.From;
var to = res.Value.To;
return (d => (d.DateString == from.ToString("yyyy-MM-dd") && (d.TimeString == null || d.TimeString.CompareTo(from.ToString("HH:mm:ss")) >= 0)) ||
(d.DateString.CompareTo(from.ToString("yyyy-MM-dd")) > 0),
from.Date == to.Date ? from.ToString("dd.MM.yyyy") : $"{from:dd.MM.yyyy \\a\\b HH:mm} / {to:dd.MM.yyyy \\b\\i\\s HH:mm}");
}
}
public static async Task<(List<string>, IQueryable<Delivery>, IQueryable<DeliveryPart>, Predicate<DeliveryPart>, List<string>)> GetFilters(this DeliveryAdminViewModel vm, AppDbContext ctx) { public static async Task<(List<string>, IQueryable<Delivery>, IQueryable<DeliveryPart>, Predicate<DeliveryPart>, List<string>)> GetFilters(this DeliveryAdminViewModel vm, AppDbContext ctx) {
List<string> filterNames = []; List<string> filterNames = [];
IQueryable<Delivery> deliveryQuery = ctx.Deliveries; IQueryable<Delivery> deliveryQuery = ctx.Deliveries;
@@ -123,9 +84,10 @@ namespace Elwig.Services {
filterNames.Add(vm.FilterMember.AdministrativeName); filterNames.Add(vm.FilterMember.AdministrativeName);
} }
if (vm.FilterTodayOnly) { if (vm.FilterTodayOnly) {
var (pred, name) = await GetFilterToday(ctx); deliveryQuery = deliveryQuery
deliveryQuery = deliveryQuery.Where(pred); .Where(d => (d.DateString == Utils.Today.ToString("yyyy-MM-dd") && (d.TimeString == null || d.TimeString.CompareTo("03:00:00") > 0)) ||
filterNames.Add(name); (d.DateString == Utils.Today.AddDays(1).ToString("yyyy-MM-dd") && (d.TimeString == null || d.TimeString.CompareTo("03:00:00") <= 0)));
filterNames.Add(Utils.Today.ToString("dd.MM.yyyy"));
} else if (!vm.FilterAllSeasons) { } else if (!vm.FilterAllSeasons) {
deliveryQuery = deliveryQuery.Where(d => d.Year == vm.FilterSeason); deliveryQuery = deliveryQuery.Where(d => d.Year == vm.FilterSeason);
filterNames.Add($"{vm.FilterSeason}"); filterNames.Add($"{vm.FilterSeason}");
@@ -553,7 +515,7 @@ namespace Elwig.Services {
Weight = vm.Weight!.Value, Weight = vm.Weight!.Value,
IsManualWeighing = vm.IsManualWeighing, IsManualWeighing = vm.IsManualWeighing,
ScaleTerminalId = vm.ScaleTerminalId, ScaleId = vm.ScaleId,
WeighingData = vm.WeighingData, WeighingData = vm.WeighingData,
WeighingReason = vm.ManualWeighingReason, WeighingReason = vm.ManualWeighingReason,
}; };
@@ -768,9 +730,10 @@ namespace Elwig.Services {
query = q; query = q;
filterNames.AddRange(f); filterNames.AddRange(f);
} else if (subject == ExportSubject.FromToday) { } else if (subject == ExportSubject.FromToday) {
var (pred, name) = await GetFilterToday(ctx); var date = $"{Utils.Today:yyyy-MM-dd}";
query = ctx.Deliveries.Where(pred).SelectMany(d => d.Parts); query = ctx.DeliveryParts
filterNames.Add(name); .Where(p => p.Delivery.DateString == date);
filterNames.Add($"{Utils.Today:dd.MM.yyyy}");
} else if (subject == ExportSubject.FromSeasonAndBranch) { } else if (subject == ExportSubject.FromSeasonAndBranch) {
query = ctx.DeliveryParts query = ctx.DeliveryParts
.Where(p => p.Year == Utils.CurrentLastSeason && p.Delivery.ZwstId == App.ZwstId); .Where(p => p.Year == Utils.CurrentLastSeason && p.Delivery.ZwstId == App.ZwstId);
@@ -842,9 +805,10 @@ namespace Elwig.Services {
query = q; query = q;
filterNames.AddRange(f); filterNames.AddRange(f);
} else if (subject == ExportSubject.FromToday) { } else if (subject == ExportSubject.FromToday) {
var (pred, name) = await GetFilterToday(ctx); var date = $"{Utils.Today:yyyy-MM-dd}";
query = ctx.Deliveries.Where(pred).SelectMany(d => d.Parts); query = ctx.DeliveryParts
filterNames.Add(name); .Where(p => p.Delivery.DateString == date);
filterNames.Add($"{Utils.Today:dd.MM.yyyy}");
} else { } else {
throw new ArgumentException("Invalid value for ExportSubject"); throw new ArgumentException("Invalid value for ExportSubject");
} }
@@ -3,7 +3,6 @@ using Elwig.Models;
using Elwig.Models.Entities; using Elwig.Models.Entities;
using Elwig.ViewModels; using Elwig.ViewModels;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -12,7 +11,7 @@ namespace Elwig.Services {
public static async Task InitInputs(this MemberBusinessSharesViewModel vm) { public static async Task InitInputs(this MemberBusinessSharesViewModel vm) {
using var ctx = new AppDbContext(); using var ctx = new AppDbContext();
vm.DateNoticeString = $"{DateTime.Today:dd.MM.yyyy}"; vm.DateNoticeString = $"{Utils.Today:dd.MM.yyyy}";
vm.ValuePerShare = (await ctx.Seasons.OrderBy(s => s.Year).LastOrDefaultAsync())?.BusinessShareValue; vm.ValuePerShare = (await ctx.Seasons.OrderBy(s => s.Year).LastOrDefaultAsync())?.BusinessShareValue;
} }
+2 -11
View File
@@ -214,7 +214,7 @@ namespace Elwig.Services {
]; ];
} }
public static async Task Download(string url, string username, string password, bool confirmImports) { public static async Task Download(string url, string username, string password) {
try { try {
var import = await GetFilesToImport(url, username, password); var import = await GetFilesToImport(url, username, password);
var paths = new List<string>(); var paths = new List<string>();
@@ -226,7 +226,7 @@ namespace Elwig.Services {
paths.Add(filename); paths.Add(filename);
} }
} }
await ElwigData.Import(paths, confirmImports ? ElwigData.ImportMode.Interactively : ElwigData.ImportMode.FromBranches); await ElwigData.Import(paths, ElwigData.ImportMode.FromBranches);
} catch (HttpRequestException exc) { } catch (HttpRequestException exc) {
InteractionService.ShowException("Daten herunterladen", "Eventuell Internetverbindung prüfen!", exc); InteractionService.ShowException("Daten herunterladen", "Eventuell Internetverbindung prüfen!", exc);
} catch (TaskCanceledException exc) { } catch (TaskCanceledException exc) {
@@ -264,14 +264,5 @@ namespace Elwig.Services {
return false; return false;
} }
} }
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);
} catch {
return false;
}
}
} }
} }
+1 -1
View File
@@ -25,7 +25,7 @@ namespace Elwig.ViewModels {
[ObservableProperty] [ObservableProperty]
private string? _manualWeighingReason; private string? _manualWeighingReason;
[ObservableProperty] [ObservableProperty]
private string? _scaleTerminalId; private string? _scaleId;
[ObservableProperty] [ObservableProperty]
private string? _weighingData; private string? _weighingData;
+17 -17
View File
@@ -47,26 +47,26 @@ namespace Elwig.Windows {
if (!_actChanged || _actList == null || _acts == null || _actIds == null) if (!_actChanged || _actList == null || _acts == null || _actIds == null)
return; return;
// delete foreach (var (vtrgid, _) in _acts.Where(a => a.Value == null)) {
var delete = _acts.Where(a => a.Value == null).Select(a => a.Key).ToList(); ctx.Remove(ctx.AreaCommitmentTypes.Find(vtrgid)!);
await ctx.AreaCommitmentTypes.Where(v => delete.Contains(v.VtrgId)).ExecuteDeleteAsync(); }
foreach (var (attr, old) in _actIds) {
// update attr.VtrgId = old;
ctx.UpdateRange(_actList }
.Where(_actIds.ContainsKey) foreach (var (old, vtrgid) in _acts.Where(a => a.Value != null)) {
.Select(t => { ctx.Update(ctx.AreaCommitmentTypes.Find(old)!);
t.VtrgId = _actIds[t]; }
ctx.Entry(t).State = EntityState.Added;
return t;
}));
await ctx.SaveChangesAsync(); await ctx.SaveChangesAsync();
foreach (var (old, vtrgid) in _acts.Where(a => a.Value != null && a.Key != a.Value)) {
foreach (var (old, vtrgid) in _acts.Where(a => a.Value != null)) {
await ctx.Database.ExecuteSqlAsync($"UPDATE area_commitment_type SET vtrgid = {vtrgid} WHERE vtrgid = {old}"); await ctx.Database.ExecuteSqlAsync($"UPDATE area_commitment_type SET vtrgid = {vtrgid} WHERE vtrgid = {old}");
} }
await ctx.SaveChangesAsync();
// insert foreach (var type in _actList.Where(a => !_actIds.ContainsKey(a))) {
ctx.AddRange(_actList if (type.VtrgId == null) continue;
.Where(t => !_actIds.ContainsKey(t) && t.VtrgId != null)); ctx.Add(type);
}
await ctx.SaveChangesAsync(); await ctx.SaveChangesAsync();
} }
@@ -125,7 +125,7 @@ namespace Elwig.Windows {
var id = AreaCommitmentTypeIdInput.Text; var id = AreaCommitmentTypeIdInput.Text;
if (old != null) _acts[old] = id; if (old != null) _acts[old] = id;
attr.VtrgId = id; attr.VtrgId = id;
attr.SortId = v?.SortId ?? ""; attr.SortId = v?.SortId;
attr.AttrId = a?.AttrId; attr.AttrId = a?.AttrId;
attr.MinKgPerHa = AreaCommitmentTypeMinKgPerHaInput.Text.Length > 0 ? int.Parse(AreaCommitmentTypeMinKgPerHaInput.Text) : null; attr.MinKgPerHa = AreaCommitmentTypeMinKgPerHaInput.Text.Length > 0 ? int.Parse(AreaCommitmentTypeMinKgPerHaInput.Text) : null;
attr.PenaltyPerKg = AreaCommitmentTypePenaltyPerKgInput.Text.Length > 0 ? decimal.Parse(AreaCommitmentTypePenaltyPerKgInput.Text) : null; attr.PenaltyPerKg = AreaCommitmentTypePenaltyPerKgInput.Text.Length > 0 ? decimal.Parse(AreaCommitmentTypePenaltyPerKgInput.Text) : null;
+12 -13
View File
@@ -41,26 +41,25 @@ namespace Elwig.Windows {
if (!_branchChanged || _branchList == null || _branches == null || _branchIds == null) if (!_branchChanged || _branchList == null || _branches == null || _branchIds == null)
return; return;
// delete
var deleteZwstIds = _branches.Where(b => b.Value == null).Select(b => b.Key).ToList(); var deleteZwstIds = _branches.Where(b => b.Value == null).Select(b => b.Key).ToList();
await ctx.Branches.Where(b => deleteZwstIds.Contains(b.ZwstId)).ExecuteDeleteAsync(); await ctx.Branches.Where(b => deleteZwstIds.Contains(b.ZwstId)).ExecuteDeleteAsync();
// update foreach (var (branch, old) in _branchIds) {
ctx.UpdateRange(_branchList branch.ZwstId = old;
.Where(_branchIds.ContainsKey) }
.Select(b => { foreach (var (old, zwstid) in _branches.Where(b => b.Value != null)) {
b.ZwstId = _branchIds[b]; ctx.Update(ctx.Branches.Find(old)!);
ctx.Entry(b).State = EntityState.Added; }
return b;
}));
await ctx.SaveChangesAsync(); await ctx.SaveChangesAsync();
foreach (var (old, zwstid) in _branches.Where(b => b.Value != null && b.Key != b.Value)) {
foreach (var (old, zwstid) in _branches.Where(b => b.Value != null)) {
await ctx.Database.ExecuteSqlAsync($"UPDATE branch SET zwstid = {zwstid} WHERE zwstid = {old}"); await ctx.Database.ExecuteSqlAsync($"UPDATE branch SET zwstid = {zwstid} WHERE zwstid = {old}");
} }
// insert foreach (var branch in _branchList.Where(b => !_branchIds.ContainsKey(b))) {
ctx.AddRange(_branchList if (branch.ZwstId == null) continue;
.Where(b => !_branchIds.ContainsKey(b) && b.ZwstId != null)); ctx.Add(branch);
}
await ctx.SaveChangesAsync(); await ctx.SaveChangesAsync();
} }
+16 -16
View File
@@ -48,30 +48,30 @@ namespace Elwig.Windows {
if (!_modChanged || _modList == null || _mods == null || _modIds == null) if (!_modChanged || _modList == null || _mods == null || _modIds == null)
return; return;
var year = (SeasonList.SelectedItem as Season)?.Year;
int i = 0; int i = 0;
foreach (var mod in _modList) mod.Ordering = ++i; foreach (var mod in _modList) mod.Ordering = ++i;
// delete var year = (SeasonList.SelectedItem as Season)?.Year;
var deleteModIds = _mods.Where(b => b.Value == null).Select(b => b.Key).ToList(); foreach (var (modid, _) in _mods.Where(m => m.Value == null)) {
await ctx.Modifiers.Where(b => b.Year == year && deleteModIds.Contains(b.ModId)).ExecuteDeleteAsync(); ctx.Remove(ctx.Modifiers.Find(year, modid)!);
}
// update foreach (var (mod, old) in _modIds) {
ctx.UpdateRange(_modList mod.ModId = old;
.Where(_modIds.ContainsKey) }
.Select(m => { foreach (var (old, modid) in _mods.Where(m => m.Value != null)) {
m.ModId = _modIds[m]; ctx.Update(ctx.Modifiers.Find(year, old)!);
ctx.Entry(m).State = EntityState.Added; }
return m;
}));
await ctx.SaveChangesAsync(); await ctx.SaveChangesAsync();
foreach (var (old, modid) in _mods.Where(m => m.Value != null)) { foreach (var (old, modid) in _mods.Where(m => m.Value != null)) {
await ctx.Database.ExecuteSqlAsync($"UPDATE modifier SET modid = {modid} WHERE (year, modid) = ({year}, {old})"); await ctx.Database.ExecuteSqlAsync($"UPDATE modifier SET modid = {modid} WHERE (year, modid) = ({year}, {old})");
} }
await ctx.SaveChangesAsync();
// insert foreach (var mod in _modList.Where(m => !_modIds.ContainsKey(m))) {
ctx.AddRange(_modList if (mod.ModId == null) continue;
.Where(m => !_modIds.ContainsKey(m) && m.ModId != null)); await ctx.AddAsync(mod);
}
await ctx.SaveChangesAsync(); await ctx.SaveChangesAsync();
} }
+12 -14
View File
@@ -41,28 +41,26 @@ namespace Elwig.Windows {
if (!_attrChanged || _attrList == null || _attrs == null || _attrIds == null) if (!_attrChanged || _attrList == null || _attrs == null || _attrIds == null)
return; return;
// delete
var deleteAttrIds = _attrs.Where(a => a.Value == null).Select(a => a.Key).ToList(); var deleteAttrIds = _attrs.Where(a => a.Value == null).Select(a => a.Key).ToList();
await ctx.WineAttributes.Where(a => deleteAttrIds.Contains(a.AttrId)).ExecuteDeleteAsync(); await ctx.WineAttributes.Where(a => deleteAttrIds.Contains(a.AttrId)).ExecuteDeleteAsync();
foreach (var (attr, old) in _attrIds) {
// update attr.AttrId = old;
ctx.UpdateRange(_attrList }
.Where(_attrIds.ContainsKey) foreach (var (old, attrid) in _attrs.Where(a => a.Value != null)) {
.Select(a => { ctx.Update(ctx.WineAttributes.Find(old)!);
a.AttrId = _attrIds[a]; }
ctx.Entry(a).State = EntityState.Added;
return a;
}));
await ctx.SaveChangesAsync(); await ctx.SaveChangesAsync();
foreach (var (old, attrid) in _attrs.Where(a => a.Value != null)) { foreach (var (old, attrid) in _attrs.Where(a => a.Value != null)) {
await ctx.Database.ExecuteSqlAsync($"UPDATE wine_attribute SET attrid = {attrid} WHERE attrid = {old}"); await ctx.Database.ExecuteSqlAsync($"UPDATE wine_attribute SET attrid = {attrid} WHERE attrid = {old}");
await ctx.Database.ExecuteSqlAsync($"UPDATE area_commitment_type SET vtrgid = (sortid || COALESCE(attrid, '') || COALESCE(disc, '')) WHERE attrid = {attrid}"); await ctx.Database.ExecuteSqlAsync($"UPDATE area_commitment_type SET vtrgid = (sortid || COALESCE(attrid, '') || COALESCE(disc, '')) WHERE attrid = {attrid}");
await ctx.Database.ExecuteSqlAsync($"UPDATE payment_variant SET data = REPLACE(REPLACE(data, {$"/{old}\""}, {$"/{attrid}\""}), {$"/{old}-"}, {$"/{attrid}-"})"); await ctx.Database.ExecuteSqlRawAsync($"UPDATE payment_variant SET data = REPLACE(REPLACE(data, '/{old}\"', '/{attrid}\"'), '/{old}-', '/{attrid}-')");
} }
// insert foreach (var attr in _attrList.Where(a => !_attrIds.ContainsKey(a))) {
ctx.AddRange(_attrList if (attr.AttrId == null) continue;
.Where(a => !_attrIds.ContainsKey(a) && a.AttrId != null)); ctx.Add(attr);
}
await ctx.SaveChangesAsync(); await ctx.SaveChangesAsync();
} }
+12 -14
View File
@@ -41,27 +41,25 @@ namespace Elwig.Windows {
if (!_cultChanged || _cultList == null || _cults == null || _cultIds == null) if (!_cultChanged || _cultList == null || _cults == null || _cultIds == null)
return; return;
// delete
var deleteCultIds = _cults.Where(c => c.Value == null).Select(c => c.Key).ToList(); var deleteCultIds = _cults.Where(c => c.Value == null).Select(c => c.Key).ToList();
await ctx.WineCultivations.Where(c => deleteCultIds.Contains(c.CultId)).ExecuteDeleteAsync(); await ctx.WineCultivations.Where(c => deleteCultIds.Contains(c.CultId)).ExecuteDeleteAsync();
foreach (var (cult, old) in _cultIds) {
// update cult.CultId = old;
ctx.UpdateRange(_cultList }
.Where(_cultIds.ContainsKey) foreach (var (old, cultid) in _cults.Where(c => c.Value != null)) {
.Select(c => { ctx.Update(ctx.WineCultivations.Find(old)!);
c.CultId = _cultIds[c]; }
ctx.Entry(c).State = EntityState.Added;
return c;
}));
await ctx.SaveChangesAsync(); await ctx.SaveChangesAsync();
foreach (var (old, cultid) in _cults.Where(c => c.Value != null)) { foreach (var (old, cultid) in _cults.Where(c => c.Value != null)) {
await ctx.Database.ExecuteSqlAsync($"UPDATE wine_cultivation SET cultid = {cultid} WHERE cultid = {old}"); await ctx.Database.ExecuteSqlAsync($"UPDATE wine_cultivation SET cultid = {cultid} WHERE cultid = {old}");
await ctx.Database.ExecuteSqlAsync($"UPDATE payment_variant SET data = REPLACE(data, {$"-{old}\""}, {$"-{cultid}\""})"); await ctx.Database.ExecuteSqlRawAsync($"UPDATE payment_variant SET data = REPLACE(data, '-{old}\"', '-{cultid}\"')");
} }
// insert foreach (var cult in _cultList.Where(c => !_cultIds.ContainsKey(c))) {
ctx.AddRange(_cultList if (cult.CultId == null) continue;
.Where(c => !_cultIds.ContainsKey(c) && c.CultId != null)); ctx.Add(cult);
}
await ctx.SaveChangesAsync(); await ctx.SaveChangesAsync();
} }
+18 -15
View File
@@ -12,6 +12,8 @@ using System.Windows.Input;
namespace Elwig.Windows { namespace Elwig.Windows {
public partial class BaseDataWindow : AdministrationWindow { public partial class BaseDataWindow : AdministrationWindow {
protected AppDbContext? EditContext;
public BaseDataWindow() { public BaseDataWindow() {
InitializeComponent(); InitializeComponent();
RequiredInputs = [ RequiredInputs = [
@@ -187,30 +189,31 @@ namespace Elwig.Windows {
} }
private async Task InitEditing() { private async Task InitEditing() {
using var ctx = new AppDbContext(); EditContext = new AppDbContext();
await BranchesInitEditing(ctx); await BranchesInitEditing(EditContext);
await WineAttributesInitEditing(ctx); await WineAttributesInitEditing(EditContext);
await WineCultivationsInitEditing(ctx); await WineCultivationsInitEditing(EditContext);
await AreaCommitmentTypesInitEditing(ctx); await AreaCommitmentTypesInitEditing(EditContext);
await SeasonsInitEditing(ctx); await SeasonsInitEditing(EditContext);
await ModifiersInitEditing(ctx); await ModifiersInitEditing(EditContext);
} }
private async Task Save() { private async Task Save() {
await UpdateClientParameters(App.Client); await UpdateClientParameters(App.Client);
await UpdateParameters(Utils.CurrentLastSeason); await UpdateParameters(Utils.CurrentLastSeason);
using var ctx = new AppDbContext(); using var tx = await EditContext!.Database.BeginTransactionAsync();
using var tx = await ctx.Database.BeginTransactionAsync(); await BranchesSave(EditContext!);
await BranchesSave(ctx); await WineAttributesSave(EditContext!);
await WineAttributesSave(ctx); await WineCultivationsSave(EditContext!);
await WineCultivationsSave(ctx); await AreaCommitmentTypesSave(EditContext!);
await AreaCommitmentTypesSave(ctx); await SeasonsSave(EditContext!);
await SeasonsSave(ctx); await ModifiersSave(EditContext!);
await ModifiersSave(ctx);
await tx.CommitAsync(); await tx.CommitAsync();
} }
private async Task FinishEditing() { private async Task FinishEditing() {
EditContext?.Dispose();
EditContext = null;
using var ctx = new AppDbContext(); using var ctx = new AppDbContext();
await BranchesFinishEditing(ctx); await BranchesFinishEditing(ctx);
await WineAttributesFinishEditing(ctx); await WineAttributesFinishEditing(ctx);
+12 -12
View File
@@ -85,10 +85,10 @@ namespace Elwig.Windows {
if (n < 3) WeighingCButton.Visibility = Visibility.Hidden; if (n < 3) WeighingCButton.Visibility = Visibility.Hidden;
if (n < 4) WeighingDButton.Visibility = Visibility.Hidden; if (n < 4) WeighingDButton.Visibility = Visibility.Hidden;
if (n == 1) WeighingAButton.Content = "Wiegen"; if (n == 1) WeighingAButton.Content = "Wiegen";
if (n > 1) WeighingAButton.Content = $"Wiegen {App.CommandScales[0].ScaleTerminalId}"; if (n > 1) WeighingAButton.Content = $"Wiegen {App.CommandScales[0].ScaleId}";
if (n >= 2) WeighingBButton.Content = $"Wiegen {App.CommandScales[1].ScaleTerminalId}"; if (n >= 2) WeighingBButton.Content = $"Wiegen {App.CommandScales[1].ScaleId}";
if (n >= 3) WeighingCButton.Content = $"Wiegen {App.CommandScales[2].ScaleTerminalId}"; if (n >= 3) WeighingCButton.Content = $"Wiegen {App.CommandScales[2].ScaleId}";
if (n >= 4) WeighingDButton.Content = $"Wiegen {App.CommandScales[3].ScaleTerminalId}"; if (n >= 4) WeighingDButton.Content = $"Wiegen {App.CommandScales[3].ScaleId}";
WeighingManualButton.Margin = new Thickness(10, 10 + n * 32, 10, 10); WeighingManualButton.Margin = new Thickness(10, 10 + n * 32, 10, 10);
foreach (var s in App.EventScales) { foreach (var s in App.EventScales) {
s.WeighingEvent += Scale_Weighing; s.WeighingEvent += Scale_Weighing;
@@ -139,7 +139,7 @@ namespace Elwig.Windows {
if (await ctx.FetchSeasons(Utils.CurrentYear).SingleOrDefaultAsync() == null) { if (await ctx.FetchSeasons(Utils.CurrentYear).SingleOrDefaultAsync() == null) {
InteractionService.ShowWarning("Saison noch nicht erstellt", InteractionService.ShowWarning("Saison noch nicht erstellt",
"Die Saison für das aktuelle Jahr wurde noch nicht erstellt. Neue Lieferungen können nicht abgespeichert werden.\n\n" + "Die Saison für das aktuelle Jahr wurde noch nicht erstellt. Neue Lieferungen können nicht abgespeichert werden.\n\n" +
"(Stammdaten \u2192 Saisons \u2192 Neu anlegen...)"); "(Stammdaten -> Saisons -> Neu anlegen...)");
} }
} }
} }
@@ -366,7 +366,7 @@ namespace Elwig.Windows {
private void InitialInputs() { private void InitialInputs() {
ViewModel.LastScaleError = null; ViewModel.LastScaleError = null;
ViewModel.WeighingData = null; ViewModel.WeighingData = null;
ViewModel.ScaleTerminalId = null; ViewModel.ScaleId = null;
ViewModel.ManualWeighingReason = null; ViewModel.ManualWeighingReason = null;
ClearOriginalValues(); ClearOriginalValues();
@@ -651,13 +651,13 @@ namespace Elwig.Windows {
private void OnWeighingResult(IScale scale, WeighingResult res) { private void OnWeighingResult(IScale scale, WeighingResult res) {
if ((res.NetWeight ?? 0) > 0 && res.FullWeighingId != null) { if ((res.NetWeight ?? 0) > 0 && res.FullWeighingId != null) {
ViewModel.Weight = res.NetWeight; ViewModel.Weight = res.NetWeight;
ViewModel.ScaleTerminalId = scale.ScaleTerminalId; ViewModel.ScaleId = scale.ScaleId;
ViewModel.WeighingData = res.ToJson().ToJsonString(); ViewModel.WeighingData = res.ToJson().ToJsonString();
ViewModel.ManualWeighingReason = null; ViewModel.ManualWeighingReason = null;
ManualWeighingInput.IsChecked = false; ManualWeighingInput.IsChecked = false;
} else { } else {
ViewModel.Weight = null; ViewModel.Weight = null;
ViewModel.ScaleTerminalId = null; ViewModel.ScaleId = null;
ViewModel.WeighingData = null; ViewModel.WeighingData = null;
} }
ViewModel.LastScaleError = null; ViewModel.LastScaleError = null;
@@ -685,7 +685,7 @@ namespace Elwig.Windows {
private async void TodayOnlyInput_Changed(object sender, RoutedEventArgs evt) { private async void TodayOnlyInput_Changed(object sender, RoutedEventArgs evt) {
if (!HasContextLoaded) return; if (!HasContextLoaded) return;
if (TodayOnlyInput.IsChecked == true && AllSeasonsInput.IsChecked == false) { if (TodayOnlyInput.IsChecked == true && AllSeasonsInput.IsChecked == false) {
ViewModel.FilterSeason = DateTime.Today.Year; ViewModel.FilterSeason = Utils.Today.Year;
ViewModel.FilterTodayOnly = true; ViewModel.FilterTodayOnly = true;
} }
await RefreshList(); await RefreshList();
@@ -771,7 +771,7 @@ namespace Elwig.Windows {
} }
private void EmptyScale() { private void EmptyScale() {
var scale = App.Scales.Where(s => s.ScaleTerminalId == ViewModel.ScaleTerminalId).FirstOrDefault(); var scale = App.Scales.Where(s => s.ScaleId == ViewModel.ScaleId).FirstOrDefault();
if (scale is not ICommandScale cs) return; if (scale is not ICommandScale cs) return;
cs.Empty(); cs.Empty();
} }
@@ -953,7 +953,7 @@ namespace Elwig.Windows {
ViewModel.Weight = res?.Item1; ViewModel.Weight = res?.Item1;
ManualWeighingInput.IsChecked = true; ManualWeighingInput.IsChecked = true;
ViewModel.ManualWeighingReason = res?.Item2; ViewModel.ManualWeighingReason = res?.Item2;
ViewModel.ScaleTerminalId = null; ViewModel.ScaleId = null;
ViewModel.WeighingData = null; ViewModel.WeighingData = null;
} }
@@ -1379,7 +1379,7 @@ namespace Elwig.Windows {
var kl = mod.Where(m => m.Name.StartsWith("Klasse ")).Select(m => m.ModId).LastOrDefault("_")[0]; var kl = mod.Where(m => m.Name.StartsWith("Klasse ")).Select(m => m.ModId).LastOrDefault("_")[0];
if (ViewModel.IsUnloadingPumped && (kl == 'A' || kl == '_')) { if (ViewModel.IsUnloadingPumped && (kl == 'A' || kl == '_')) {
kl = 'B'; kl = 'B';
} else if (ViewModel.IsUnloadingDumper && (kl == 'B' || kl == '_')) { } else if (ViewModel.IsUnloadingDumper && kl == '_') {
kl = 'A'; kl = 'A';
} else { } else {
kl = '_'; kl = '_';
@@ -91,9 +91,8 @@ namespace Elwig.Windows {
.ToListAsync(); .ToListAsync();
list.ForEach(v => v.Schedule.AnnouncedWeightOverride = v.AnnouncedWeight); list.ForEach(v => v.Schedule.AnnouncedWeightOverride = v.AnnouncedWeight);
var deliverySchedules = list.Select(v => v.Schedule).ToList(); var deliverySchedules = list.Select(v => v.Schedule).ToList();
var today = DateTime.Today;
ControlUtils.RenewItemsSource(DeliveryScheduleList, deliverySchedules ControlUtils.RenewItemsSource(DeliveryScheduleList, deliverySchedules
.Where(s => !ViewModel.FilterOnlyUpcoming || s.DateString.CompareTo(today.ToString("yyyy-MM-dd")) >= 0) .Where(s => !ViewModel.FilterOnlyUpcoming || s.DateString.CompareTo(Utils.Today.ToString("yyyy-MM-dd")) >= 0)
.ToList(), DeliveryScheduleList_SelectionChanged, ViewModel.FilterFromAllSchedules ? ControlUtils.RenewSourceDefault.None : ControlUtils.RenewSourceDefault.First); .ToList(), DeliveryScheduleList_SelectionChanged, ViewModel.FilterFromAllSchedules ? ControlUtils.RenewSourceDefault.None : ControlUtils.RenewSourceDefault.First);
ControlUtils.RenewItemsSource(DeliveryScheduleInput, deliverySchedules, DeliveryScheduleInput_SelectionChanged); ControlUtils.RenewItemsSource(DeliveryScheduleInput, deliverySchedules, DeliveryScheduleInput_SelectionChanged);
} }
+3 -6
View File
@@ -108,7 +108,7 @@ namespace Elwig.Windows {
public MailWindow(int? year = null) { public MailWindow(int? year = null) {
InitializeComponent(); InitializeComponent();
using (var ctx = new AppDbContext()) { using (var ctx = new AppDbContext()) {
Year = year ?? ctx.Seasons.OrderByDescending(s => s.Year).FirstOrDefault()?.Year ?? DateTime.Today.Year; Year = year ?? ctx.Seasons.OrderByDescending(s => s.Year).FirstOrDefault()?.Year ?? Utils.Today.Year;
Title = $"Rundschreiben - Lese {Year} - Elwig"; Title = $"Rundschreiben - Lese {Year} - Elwig";
} }
@@ -150,7 +150,7 @@ namespace Elwig.Windows {
PostalSender1.Text = App.Client.Sender1; PostalSender1.Text = App.Client.Sender1;
PostalSender2.Text = App.Client.Sender2; PostalSender2.Text = App.Client.Sender2;
PostalLocation.Text = App.BranchLocation; PostalLocation.Text = App.BranchLocation;
PostalDate.Text = $"{DateTime.Today:dd.MM.yyyy}"; PostalDate.Text = $"{Utils.Today:dd.MM.yyyy}";
EmailSubjectInput.Text = App.Client.TextEmailSubject ?? "Rundschreiben"; EmailSubjectInput.Text = App.Client.TextEmailSubject ?? "Rundschreiben";
EmailBodyInput.Text = App.Client.TextEmailBody ?? "Sehr geehrtes Mitglied,\n\nim Anhang finden Sie das aktuelle Rundschreiben.\n\nIhre Winzergenossenschaft\n"; EmailBodyInput.Text = App.Client.TextEmailBody ?? "Sehr geehrtes Mitglied,\n\nim Anhang finden Sie das aktuelle Rundschreiben.\n\nIhre Winzergenossenschaft\n";
} }
@@ -438,7 +438,7 @@ namespace Elwig.Windows {
private void Date_LostFocus(object sender, RoutedEventArgs evt) { private void Date_LostFocus(object sender, RoutedEventArgs evt) {
var res = Validator.CheckDate((TextBox)sender, true); var res = Validator.CheckDate((TextBox)sender, true);
if (!res.IsValid) ((TextBox)sender).Text = $"{DateTime.Today:dd.MM.yyyy}"; if (!res.IsValid) ((TextBox)sender).Text = $"{Utils.Today:dd.MM.yyyy}";
} }
private async Task UpdateRecipients(AppDbContext ctx) { private async Task UpdateRecipients(AppDbContext ctx) {
@@ -937,7 +937,6 @@ namespace Elwig.Windows {
Mouse.OverrideCursor = Cursors.Wait; Mouse.OverrideCursor = Cursors.Wait;
var subject = EmailSubjectInput.Text; var subject = EmailSubjectInput.Text;
var text = EmailBodyInput.Text; var text = EmailBodyInput.Text;
var date = DateTime.Now;
await Task.Run(async () => { await Task.Run(async () => {
await Utils.AddSentMailBody(subject, text, EmailDocuments.Count); await Utils.AddSentMailBody(subject, text, EmailDocuments.Count);
foreach (var (m, docs) in EmailDocuments) { foreach (var (m, docs) in EmailDocuments) {
@@ -945,7 +944,6 @@ namespace Elwig.Windows {
msg.From.Add(new MailboxAddress(App.Client.NameFull, App.Config.Smtp.Value.From)); msg.From.Add(new MailboxAddress(App.Client.NameFull, App.Config.Smtp.Value.From));
msg.To.AddRange(m.EmailAddresses.OrderBy(a => a.Nr).Select(a => new MailboxAddress(m.AdministrativeName, a.Address))); msg.To.AddRange(m.EmailAddresses.OrderBy(a => a.Nr).Select(a => new MailboxAddress(m.AdministrativeName, a.Address)));
msg.Subject = subject; msg.Subject = subject;
msg.Date = date;
var body = new Multipart("mixed") { var body = new Multipart("mixed") {
new TextPart("plain") { Text = text } new TextPart("plain") { Text = text }
}; };
@@ -960,7 +958,6 @@ namespace Elwig.Windows {
m.EmailAddresses.OrderBy(a => a.Nr).Select(a => a.Address).ToArray(), m.EmailAddresses.OrderBy(a => a.Nr).Select(a => a.Address).ToArray(),
subject, docs.Select(d => d.Title).ToArray() subject, docs.Select(d => d.Title).ToArray()
)]); )]);
await Task.Delay((int)(App.Config.SmtpWait * 1000));
} }
}); });
+29 -39
View File
@@ -50,27 +50,22 @@ namespace Elwig.Windows {
_syncTimer.Start(); _syncTimer.Start();
} }
private async void Window_Closing(object sender, CancelEventArgs evt) { private void Window_Closing(object sender, CancelEventArgs evt) {
evt.Cancel = !App.ForceShutdown;
if (App.NumWindows > 1 && !App.ForceShutdown) { if (App.NumWindows > 1 && !App.ForceShutdown) {
foreach (var w in Application.Current.Windows.Cast<Window>().Where(w => ((w as AdministrationWindow)?.IsEditing ?? false) || ((w as AdministrationWindow)?.IsCreating ?? false))) { foreach (var w in App.Current.Windows.Cast<Window>().Where(w => ((w as AdministrationWindow)?.IsEditing ?? false) || ((w as AdministrationWindow)?.IsCreating ?? false))) {
try { try {
w.Close(); w.Close();
} catch { } } catch { }
} }
Thread.Sleep(100); Thread.Sleep(100);
if (App.NumWindows > 1 && !Application.Current.Windows.Cast<Window>().Any(w => ((w as AdministrationWindow)?.IsEditing ?? false) || ((w as AdministrationWindow)?.IsCreating ?? false))) { if (App.NumWindows > 1 && !App.Current.Windows.Cast<Window>().Any(w => ((w as AdministrationWindow)?.IsEditing ?? false) || ((w as AdministrationWindow)?.IsCreating ?? false))) {
if (!InteractionService.AskConfirmation("Elwig beenden", "Es sind noch weitere Fenster geöffnet.\nSollen alle Fenster geschlossen werden?")) { if (!InteractionService.AskConfirmation("Elwig beenden", "Es sind noch weitere Fenster geöffnet.\nSollen alle Fenster geschlossen werden?")) {
return; evt.Cancel = true;
} else {
Application.Current.Shutdown();
} }
App.ForceShutdown = true;
} }
} }
Mouse.OverrideCursor = Cursors.AppStarting;
await (Application.Current as App)!.OnClosing();
Application.Current.Shutdown();
} }
private void Menu_Help_About_Click(object sender, RoutedEventArgs evt) { private void Menu_Help_About_Click(object sender, RoutedEventArgs evt) {
@@ -167,7 +162,7 @@ namespace Elwig.Windows {
private async void Menu_Database_Backup_Click(object sender, RoutedEventArgs evt) { private async void Menu_Database_Backup_Click(object sender, RoutedEventArgs evt) {
try { try {
var filename = InteractionService.SaveFile("Datenbank-Sicherung", $"database_{DateTime.Today:yyyy-MM-dd}", "sql.zip"); var filename = InteractionService.SaveFile("Datenbank-Sicherung", $"database_{Utils.Today:yyyy-MM-dd}", "sql.zip");
if (filename != null) { if (filename != null) {
if (!filename.EndsWith(".sql.zip")) filename += ".sql.zip"; if (!filename.EndsWith(".sql.zip")) filename += ".sql.zip";
Mouse.OverrideCursor = Cursors.Wait; Mouse.OverrideCursor = Cursors.Wait;
@@ -182,7 +177,22 @@ namespace Elwig.Windows {
} }
private async void Menu_Database_Restore_Click(object sender, RoutedEventArgs evt) { private async void Menu_Database_Restore_Click(object sender, RoutedEventArgs evt) {
await BackupService.RestoreDatabase(); try {
var d = new OpenFileDialog() {
Title = "Datenbank wiederherstellen - Elwig",
DefaultExt = "sql.zip",
Filter = "SQLite-Datenbank (*.sqlite3, *.sqlite3.zip, *.sql, *.sql.zip)|*.sqlite3;*.sqlite3.zip;*.sql;*.sql.zip",
};
if (d.ShowDialog() == true) {
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);
}
} catch (Exception exc) {
InteractionService.ShowException(exc);
}
Mouse.OverrideCursor = null;
} }
private async void SyncButton_Click(object sender, RoutedEventArgs evt) { private async void SyncButton_Click(object sender, RoutedEventArgs evt) {
@@ -190,13 +200,8 @@ namespace Elwig.Windows {
return; return;
Mouse.OverrideCursor = Cursors.Wait; Mouse.OverrideCursor = Cursors.Wait;
await Task.Run(async () => { await Task.Run(async () => {
if (App.Config.SyncMain) { await SyncService.Download(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword);
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);
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);
await SyncService.UploadBranchDeliveries(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword);
}
}); });
Mouse.OverrideCursor = null; Mouse.OverrideCursor = null;
} }
@@ -206,7 +211,7 @@ namespace Elwig.Windows {
return; return;
Mouse.OverrideCursor = Cursors.Wait; Mouse.OverrideCursor = Cursors.Wait;
await Task.Run(async () => { await Task.Run(async () => {
await SyncService.Download(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, App.Config.SyncMain); await SyncService.Download(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword);
}); });
Mouse.OverrideCursor = null; Mouse.OverrideCursor = null;
} }
@@ -224,10 +229,6 @@ namespace Elwig.Windows {
private async void Menu_Sync_UploadModified_Click(object sender, RoutedEventArgs evt) { private async void Menu_Sync_UploadModified_Click(object sender, RoutedEventArgs evt) {
if (App.Config.SyncUrl == null) if (App.Config.SyncUrl == null)
return; return;
if (!App.Config.SyncMain) {
InteractionService.ShowInformation("Mitglieder und Lieferungen hochladen", "Hochladen nicht möglich: Dieses Gerät ist nicht das Hauptgerät!");
return;
}
Mouse.OverrideCursor = Cursors.Wait; Mouse.OverrideCursor = Cursors.Wait;
await Task.Run(async () => { await Task.Run(async () => {
await SyncService.UploadModified(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword); await SyncService.UploadModified(App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword);
@@ -295,11 +296,6 @@ namespace Elwig.Windows {
if (App.Config.SyncUrl == null) if (App.Config.SyncUrl == null)
return; return;
if (!App.Config.SyncMain) {
InteractionService.ShowInformation("Datenbank hochladen", "Hochladen nicht möglich: Dieses Gerät ist nicht das Hauptgerät!");
return;
}
if (!InteractionService.AskContinue("Datenbank hochladen", "Sind Sie wirklich sicher, dass Sie die Datenbank dieses\nGerätes hochladen möchten? Das sollte nur vom Hauptgerät aus passieren!")) if (!InteractionService.AskContinue("Datenbank hochladen", "Sind Sie wirklich sicher, dass Sie die Datenbank dieses\nGerätes hochladen möchten? Das sollte nur vom Hauptgerät aus passieren!"))
return; return;
@@ -371,11 +367,7 @@ namespace Elwig.Windows {
await Task.Delay(delay); await Task.Delay(delay);
var ch = false; var ch = false;
using (var ctx = new AppDbContext()) { using (var ctx = new AppDbContext()) {
if (App.Config.SyncMain) { ch = await SyncService.ChangesAvailable(ctx, App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword);
ch = await SyncService.ChangesAvailable(ctx, App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword);
} else {
ch = await SyncService.ChangesAvailable(ctx, App.Config.SyncUrl, App.Config.SyncUsername, App.Config.SyncPassword, default);
}
} }
await App.MainDispatcher.BeginInvoke(() => { await App.MainDispatcher.BeginInvoke(() => {
if (ch) { if (ch) {
@@ -528,11 +520,9 @@ namespace Elwig.Windows {
App.HintContextChange(); App.HintContextChange();
using var ctx = new AppDbContext(); using var ctx = new AppDbContext();
var tbl1 = await MemberAreaComTotalsData.ForSeason(ctx.MemberAreaComTotalsRows, year); var tbl = await MemberAreaComsData.ForSeason(ctx.MemberAreaComsRows, year);
var tbl2 = await MemberAreaComsData.ForSeason(ctx.MemberAreaComsRows, year);
using var ods = new OdsFile(filename); using var ods = new OdsFile(filename);
await ods.AddTable(tbl1); await ods.AddTable(tbl);
await ods.AddTable(tbl2);
} catch (Exception exc) { } catch (Exception exc) {
InteractionService.ShowException(exc); InteractionService.ShowException(exc);
} }
+4 -16
View File
@@ -706,24 +706,12 @@
</TextBlock.ToolTip> </TextBlock.ToolTip>
</TextBlock> </TextBlock>
<Button x:Name="DeliveryButton" IsEnabled="{Binding IsMemberSelected}" <Button x:Name="DeliveryButton" Content="Lieferungen" IsEnabled="{Binding IsMemberSelected}"
Click="DeliveryButton_Click" Click="DeliveryButton_Click"
HorizontalAlignment="Right" Margin="10,00,10,37" Width="160" VerticalAlignment="Bottom" Grid.ColumnSpan="3" HorizontalContentAlignment="Stretch"> HorizontalAlignment="Right" Margin="10,00,10,37" Width="150" VerticalAlignment="Bottom" Grid.ColumnSpan="3"/>
<Grid> <Button x:Name="AreaCommitmentButton" Content="Flächenbindungen" IsEnabled="{Binding IsMemberSelected}"
<TextBlock Margin="0,0,10,0" TextAlignment="Center">Lieferungen</TextBlock>
<TextBlock FontFamily="Segoe MDL2 Assets" FontSize="16" Text="&#xE8A7;"
TextAlignment="Left" HorizontalAlignment="Right" Padding="0,1.5,0,0" Margin="0,0,0,0"/>
</Grid>
</Button>
<Button x:Name="AreaCommitmentButton" IsEnabled="{Binding IsMemberSelected}"
Click="AreaCommitmentButton_Click" Click="AreaCommitmentButton_Click"
HorizontalAlignment="Right" Margin="10,10,10,5" Width="160" VerticalAlignment="Bottom" Grid.ColumnSpan="3" HorizontalContentAlignment="Stretch"> HorizontalAlignment="Right" Margin="10,10,10,5" Width="150" VerticalAlignment="Bottom" Grid.ColumnSpan="3"/>
<Grid>
<TextBlock Margin="0,0,15,0" TextAlignment="Center">Flächenbindungen</TextBlock>
<TextBlock FontFamily="Segoe MDL2 Assets" FontSize="16" Text="&#xE8A7;"
TextAlignment="Left" HorizontalAlignment="Right" Padding="0,1.5,0,0" Margin="0,0,0,0"/>
</Grid>
</Button>
</Grid> </Grid>
</GroupBox> </GroupBox>
</Grid> </Grid>
@@ -198,7 +198,7 @@ namespace Elwig.Windows {
int mgnr; int mgnr;
try { try {
mgnr = await ViewModel.UpdateMemberHistory(ViewModel.SelectedHistoryEntry?.HistNr, IsEditing || ViewModel.DateNotice >= DateOnly.FromDateTime(DateTime.Today).AddDays(-14)); mgnr = await ViewModel.UpdateMemberHistory(ViewModel.SelectedHistoryEntry?.HistNr, IsEditing || ViewModel.DateNotice >= DateOnly.FromDateTime(Utils.Today).AddDays(-14));
App.HintContextChange(); App.HintContextChange();
} catch (Exception exc) { } catch (Exception exc) {
InteractionService.ShowDbException("Geschäftsanteilbewegung aktualisieren", exc); InteractionService.ShowDbException("Geschäftsanteilbewegung aktualisieren", exc);
+11 -28
View File
@@ -7,7 +7,7 @@
xmlns:local="clr-namespace:Elwig.Windows" xmlns:local="clr-namespace:Elwig.Windows"
xmlns:vm="clr-namespace:Elwig.ViewModels" xmlns:vm="clr-namespace:Elwig.ViewModels"
xmlns:ctrl="clr-namespace:Elwig.Controls" xmlns:ctrl="clr-namespace:Elwig.Controls"
Title="Auszahlungsvarianten - Elwig" Height="480" Width="850" MinHeight="430" MinWidth="850"> Title="Auszahlungsvarianten - Elwig" Height="480" Width="850" MinHeight="400" MinWidth="850">
<Window.DataContext> <Window.DataContext>
<vm:PaymentVariantsViewModel/> <vm:PaymentVariantsViewModel/>
</Window.DataContext> </Window.DataContext>
@@ -195,10 +195,11 @@
Content="Benutzerdefinierte Zu-/Abschläge pro Mitglied" Content="Benutzerdefinierte Zu-/Abschläge pro Mitglied"
Margin="110,175,10,10" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="110,175,10,10" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top"
Checked="ConsiderCustomInput_Changed" Unchecked="ConsiderCustomInput_Changed"/> Checked="ConsiderCustomInput_Changed" Unchecked="ConsiderCustomInput_Changed"/>
<Label Content="&#xF0AE;" FontFamily="Segoe MDL2 Assets" FontSize="16" Grid.Row="0" Grid.Column="1" Margin="108,195,10,10"/>
<Grid Grid.Column="0" Grid.ColumnSpan="2" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="50,200,10,10"> <Grid Grid.Column="0" Grid.ColumnSpan="2" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="50,200,10,10">
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
<ColumnDefinition Width="130"/> <ColumnDefinition Width="110"/>
<ColumnDefinition Width="27"/> <ColumnDefinition Width="27"/>
<ColumnDefinition Width="110"/> <ColumnDefinition Width="110"/>
<ColumnDefinition Width="27"/> <ColumnDefinition Width="27"/>
@@ -206,7 +207,7 @@
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition Height="27"/> <RowDefinition Height="27"/>
<RowDefinition Height="37"/> <RowDefinition Height="5"/>
<RowDefinition Height="27"/> <RowDefinition Height="27"/>
<RowDefinition Height="5"/> <RowDefinition Height="5"/>
<RowDefinition Height="27"/> <RowDefinition Height="27"/>
@@ -226,23 +227,11 @@
</Grid.Resources> </Grid.Resources>
<Button x:Name="EditButton" IsEnabled="{Binding IsPaymentVariantSelected}" <Button x:Name="EditButton" IsEnabled="{Binding IsPaymentVariantSelected}"
Grid.Column="0" Grid.Row="2" HorizontalContentAlignment="Stretch" Content="{Binding EditText}" Grid.Column="0" Grid.Row="2"
Click="EditButton_Click"> Click="EditButton_Click"/>
<Grid>
<TextBlock Margin="0,0,13,0" TextAlignment="Center" Text="{Binding EditText}"/>
<TextBlock FontFamily="Segoe MDL2 Assets" FontSize="16" Text="&#xE8A7;"
TextAlignment="Left" HorizontalAlignment="Right" Padding="0,1.5,0,0" Margin="0,0,5,0"/>
</Grid>
</Button>
<Label Content="&#xF0AF;" FontFamily="Segoe MDL2 Assets" FontSize="16" Grid.Row="2" Grid.Column="1"/> <Label Content="&#xF0AF;" FontFamily="Segoe MDL2 Assets" FontSize="16" Grid.Row="2" Grid.Column="1"/>
<Button x:Name="ModifierButton" Grid.Column="0" Grid.Row="4" HorizontalContentAlignment="Stretch" <Button x:Name="ModifierButton" Content="Zu-/Abschläge" Grid.Column="0" Grid.Row="4"
Click="ModifierButton_Click"> Click="ModifierButton_Click"/>
<Grid>
<TextBlock Margin="0,0,15,0" TextAlignment="Center">Zu-/Abschläge</TextBlock>
<TextBlock FontFamily="Segoe MDL2 Assets" FontSize="16" Text="&#xE8A7;"
TextAlignment="Left" HorizontalAlignment="Right" Padding="0,1.5,0,0" Margin="0,0,5,0"/>
</Grid>
</Button>
<Label Content="&#xF0AF;" FontFamily="Segoe MDL2 Assets" FontSize="16" Grid.Row="4" Grid.Column="1" RenderTransformOrigin="0.5,0.5" > <Label Content="&#xF0AF;" FontFamily="Segoe MDL2 Assets" FontSize="16" Grid.Row="4" Grid.Column="1" RenderTransformOrigin="0.5,0.5" >
<Label.RenderTransform> <Label.RenderTransform>
<TransformGroup> <TransformGroup>
@@ -255,14 +244,8 @@
Content="Berechnen" Grid.Column="2" Grid.Row="2" Content="Berechnen" Grid.Column="2" Grid.Row="2"
Click="CalculateButton_Click"/> Click="CalculateButton_Click"/>
<Label Content="{Binding Arrow}" FontFamily="Segoe MDL2 Assets" FontSize="16" Grid.Row="2" Grid.Column="3"/> <Label Content="{Binding Arrow}" FontFamily="Segoe MDL2 Assets" FontSize="16" Grid.Row="2" Grid.Column="3"/>
<Button x:Name="PaymentAdjustmentButton" Grid.Column="2" Grid.Row="4" HorizontalContentAlignment="Stretch" <Button x:Name="PaymentAdjustmentButton" Content="Anpassen" Grid.Column="2" Grid.Row="4"
Click="PaymentAdjustmentButton_Click"> Click="PaymentAdjustmentButton_Click"/>
<Grid>
<TextBlock Margin="0,0,13,0" TextAlignment="Center">Anpassen</TextBlock>
<TextBlock FontFamily="Segoe MDL2 Assets" FontSize="16" Text="&#xE8A7;"
TextAlignment="Left" HorizontalAlignment="Right" Padding="0,1.5,0,0" Margin="0,0,5,0"/>
</Grid>
</Button>
<Label Content="{Binding Arrow}" FontFamily="Segoe MDL2 Assets" FontSize="16" Grid.Row="4" Grid.Column="3" RenderTransformOrigin="0.5,0.5" > <Label Content="{Binding Arrow}" FontFamily="Segoe MDL2 Assets" FontSize="16" Grid.Row="4" Grid.Column="3" RenderTransformOrigin="0.5,0.5" >
<Label.RenderTransform> <Label.RenderTransform>
<TransformGroup> <TransformGroup>
@@ -278,7 +261,7 @@
Content="Freigeben" Grid.Column="4" Grid.Row="2" Content="Freigeben" Grid.Column="4" Grid.Row="2"
Click="RevertButton_Click"/> Click="RevertButton_Click"/>
<Button x:Name="SaveButton" IsEnabled="{Binding SaveIsEnabled}" <Button x:Name="SaveButton" IsEnabled="{Binding SaveIsEnabled}"
Content="Speichern" Grid.Column="2" Grid.Row="0" Content="Speichern" Grid.Column="4" Grid.Row="0"
Click="SaveButton_Click"/> Click="SaveButton_Click"/>
</Grid> </Grid>
+1 -14
View File
@@ -5,7 +5,6 @@ using Elwig.Services;
using Elwig.ViewModels; using Elwig.ViewModels;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -240,27 +239,15 @@ namespace Elwig.Windows {
private async void SaveButton_Click(object sender, RoutedEventArgs evt) { private async void SaveButton_Click(object sender, RoutedEventArgs evt) {
if (PaymentVariantList.SelectedItem is not PaymentVar v || ViewModel.BillingData == null) if (PaymentVariantList.SelectedItem is not PaymentVar v || ViewModel.BillingData == null)
return; return;
Mouse.OverrideCursor = Cursors.Wait; Mouse.OverrideCursor = Cursors.Wait;
try { try {
await ViewModel.UpdatePaymentVariant(v.Year, v.AvNr); await ViewModel.UpdatePaymentVariant(v.Year, v.AvNr);
App.HintContextChange();
} catch (Exception exc) { } catch (Exception exc) {
await ForceContextReload(); await ForceContextReload();
InteractionService.ShowDbException("Auszahlungsvariante aktualisieren", exc); InteractionService.ShowDbException("Auszahlungsvariante aktualisieren", exc);
} }
try {
await Task.Run(async () => {
var b = await BillingVariant.Create(v.Year, v.AvNr);
await b.Calculate(false);
});
} catch (KeyNotFoundException exc) {
InteractionService.ShowInformation("Noch nicht alle Preise festgelegt", exc.Message);
} catch (Exception exc) {
InteractionService.ShowException("Berechnungsfehler", exc);
}
App.HintContextChange();
Mouse.OverrideCursor = null; Mouse.OverrideCursor = null;
await EnsureContextRenewed(); await EnsureContextRenewed();
CommentInput_TextChanged(null, null); CommentInput_TextChanged(null, null);
DateInput_TextChanged(null, null); DateInput_TextChanged(null, null);
+8 -1
View File
@@ -16,7 +16,14 @@
<dependency> <dependency>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" /> <assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly> </dependentAssembly>
</dependency> </dependency>
</assembly> </assembly>
-1
View File
@@ -13,6 +13,5 @@ Data and configuration folder
C:\ProgramData\Elwig\ C:\ProgramData\Elwig\
- config.ini : main configuration file - config.ini : main configuration file
- database.sqlite3 : stores all data - database.sqlite3 : stores all data
- backups\ : (automatic) backups of the database
- imported.txt : list of all imported *.elwig.zip files to not automatically import them again - imported.txt : list of all imported *.elwig.zip files to not automatically import them again
- mails\ : sent/outgoing email log - mails\ : sent/outgoing email log
-12
View File
@@ -3,7 +3,6 @@
; Only needed, if more than one branch is stored in database ; Only needed, if more than one branch is stored in database
;branch = Zweigstelle ;branch = Zweigstelle
;debug = true ;debug = true
;weighing = gross ; gross/net/box
[database] [database]
; Relative or absolute path to database file ; Relative or absolute path to database file
@@ -11,14 +10,6 @@ file = database.sqlite3
; Enables database logging ; Enables database logging
;log = db.log ;log = db.log
[backup]
;auto = false
;path = backups
;retain_hours = 36
;retain_days = 8
;retain_weeks = 6
;retain_months = 18
[update] [update]
url = https://elwig.at/files/elwig/latest url = https://elwig.at/files/elwig/latest
auto = true auto = true
@@ -35,7 +26,6 @@ auto = true
;username = "" ;username = ""
;password = "" ;password = ""
;from = mail@wg.at ;from = mail@wg.at
;wait = 0.5
;[scale.1] ;[scale.1]
;type = SysTec-IT ;type = SysTec-IT
@@ -47,8 +37,6 @@ auto = true
;limit = 3500 ;limit = 3500
; Enables scale logging ; Enables scale logging
;log = waage.log ;log = waage.log
; Opt-out of auto time synchronization at startup
;synctime = false
;[scale.B] ;[scale.B]
;type = Avery-Async ;type = Avery-Async
+2 -2
View File
@@ -13,7 +13,7 @@ About
**Product:** Elwig **Product:** Elwig
**Description:** Electronic Management for Vintners' Cooperatives **Description:** Electronic Management for Vintners' Cooperatives
**Type:** ERP system **Type:** ERP system
**Version:** 1.1.2.1 ([Changelog](./CHANGELOG.md)) **Version:** 1.0.5.6 ([Changelog](./CHANGELOG.md))
**License:** [GNU General Public License 3.0 (GPLv3)](./LICENSE) **License:** [GNU General Public License 3.0 (GPLv3)](./LICENSE)
**Website:** https://elwig.at/ **Website:** https://elwig.at/
**Source code:** https://git.necronda.net/winzer/elwig **Source code:** https://git.necronda.net/winzer/elwig
@@ -33,7 +33,7 @@ Packaging: [WiX Toolset](https://www.firegiant.com/wixtoolset/)
**Produkt:** Elwig **Produkt:** Elwig
**Beschreibung:** Elektronische Winzergenossenschaftsverwaltung **Beschreibung:** Elektronische Winzergenossenschaftsverwaltung
**Typ:** Warenwirtschaftssystem (ERP-System) **Typ:** Warenwirtschaftssystem (ERP-System)
**Version:** 1.1.2.1 ([Änderungsprotokoll](./CHANGELOG.md)) **Version:** 1.0.5.6 ([Änderungsprotokoll](./CHANGELOG.md))
**Lizenz:** [GNU General Public License 3.0 (GPLv3)](./LICENSE) **Lizenz:** [GNU General Public License 3.0 (GPLv3)](./LICENSE)
**Website:** https://elwig.at/ **Website:** https://elwig.at/
**Quellcode:** https://git.necronda.net/winzer/elwig **Quellcode:** https://git.necronda.net/winzer/elwig
+1 -1
View File
@@ -53,7 +53,7 @@ namespace Tests.E2ETests {
Session.App.FindElement(By.Name("Rundschreiben")).Click(); Session.App.FindElement(By.Name("Rundschreiben")).Click();
Thread.Sleep(Utils.WINDOW_OPEN_SLEEP); Thread.Sleep(Utils.WINDOW_OPEN_SLEEP);
var window = Session.CreateWindowDriver("MailWindow"); var window = Session.CreateWindowDriver("MailWindow");
Assert.That(window.Title, Is.EqualTo($"Rundschreiben - Lese {DateTime.Today.Year} - Elwig")); Assert.That(window.Title, Is.EqualTo($"Rundschreiben - Lese {Elwig.Helpers.Utils.Today.Year} - Elwig"));
window.Close(); window.Close();
}); });
} }
+2 -2
View File
@@ -45,7 +45,7 @@ INSERT INTO delivery (mgnr, year, did, date, time, zwstid, lnr) VALUES
(101, 2020, 1, '2020-10-01', NULL, 'X', 1), (101, 2020, 1, '2020-10-01', NULL, 'X', 1),
(101, 2020, 2, '2020-10-01', NULL, 'X', 2), (101, 2020, 2, '2020-10-01', NULL, 'X', 2),
(101, 2020, 3, '2020-10-01', NULL, 'X', 3); (101, 2020, 3, '2020-10-01', NULL, 'X', 3);
INSERT INTO delivery_part (year, did, dpnr, sortid, attrid, cultid, weight, kmw, qualid, hkid, kgnr, net_weight, manual_weighing, spl_check, scale_terminal, weighing_data, weighing_reason) VALUES INSERT INTO delivery_part (year, did, dpnr, sortid, attrid, cultid, weight, kmw, qualid, hkid, kgnr, net_weight, manual_weighing, spl_check, scale_id, weighing_data, weighing_reason) VALUES
(2020, 1, 1, 'GV', 'K', NULL, 4000, 17, 'KAB', 'WLNO', 06109, TRUE, FALSE, FALSE, NULL, NULL, NULL), (2020, 1, 1, 'GV', 'K', NULL, 4000, 17, 'KAB', 'WLNO', 06109, TRUE, FALSE, FALSE, NULL, NULL, NULL),
(2020, 1, 2, 'GV', NULL, NULL, 4000, 16, 'QUW', 'WLNO', 06109, TRUE, FALSE, FALSE, NULL, NULL, NULL), (2020, 1, 2, 'GV', NULL, NULL, 4000, 16, 'QUW', 'WLNO', 06109, TRUE, FALSE, FALSE, NULL, NULL, NULL),
(2020, 2, 1, 'GV', NULL, 'B', 4000, 15, 'QUW', 'WLNO', 06109, TRUE, FALSE, FALSE, NULL, NULL, NULL), (2020, 2, 1, 'GV', NULL, 'B', 4000, 15, 'QUW', 'WLNO', 06109, TRUE, FALSE, FALSE, NULL, NULL, NULL),
@@ -60,7 +60,7 @@ INSERT INTO delivery (mgnr, year, did, date, time, zwstid, lnr) VALUES
(101, 2021, 1, '2021-10-01', NULL, 'X', 1), (101, 2021, 1, '2021-10-01', NULL, 'X', 1),
(101, 2021, 2, '2021-10-01', NULL, 'X', 2), (101, 2021, 2, '2021-10-01', NULL, 'X', 2),
(101, 2021, 3, '2021-10-01', NULL, 'X', 3); (101, 2021, 3, '2021-10-01', NULL, 'X', 3);
INSERT INTO delivery_part (year, did, dpnr, sortid, attrid, cultid, weight, kmw, qualid, hkid, kgnr, gebunden, net_weight, manual_weighing, spl_check, scale_terminal, weighing_data, weighing_reason) VALUES INSERT INTO delivery_part (year, did, dpnr, sortid, attrid, cultid, weight, kmw, qualid, hkid, kgnr, gebunden, net_weight, manual_weighing, spl_check, scale_id, weighing_data, weighing_reason) VALUES
(2021, 1, 1, 'GV', 'K', NULL, 4000, 17, 'KAB', 'WLNO', 06109, TRUE, TRUE, FALSE, FALSE, NULL, NULL, NULL), (2021, 1, 1, 'GV', 'K', NULL, 4000, 17, 'KAB', 'WLNO', 06109, TRUE, TRUE, FALSE, FALSE, NULL, NULL, NULL),
(2021, 1, 2, 'GV', NULL, NULL, 4000, 16, 'QUW', 'WLNO', 06109, FALSE, TRUE, FALSE, FALSE, NULL, NULL, NULL), (2021, 1, 2, 'GV', NULL, NULL, 4000, 16, 'QUW', 'WLNO', 06109, FALSE, TRUE, FALSE, FALSE, NULL, NULL, NULL),
(2021, 2, 1, 'GV', NULL, 'B', 4000, 15, 'QUW', 'WLNO', 06109, TRUE, TRUE, FALSE, FALSE, NULL, NULL, NULL), (2021, 2, 1, 'GV', NULL, 'B', 4000, 15, 'QUW', 'WLNO', 06109, TRUE, TRUE, FALSE, FALSE, NULL, NULL, NULL),
+1 -1
View File
@@ -39,7 +39,7 @@ INSERT INTO delivery (mgnr, year, did, date, time, zwstid, lnr) VALUES
(104, 2020, 11, '2020-10-03', '14:39:22', 'X', 2), (104, 2020, 11, '2020-10-03', '14:39:22', 'X', 2),
(104, 2020, 12, '2020-10-03', '15:15:41', 'X', 3); (104, 2020, 12, '2020-10-03', '15:15:41', 'X', 3);
INSERT INTO delivery_part (year, did, dpnr, sortid, attrid, cultid, weight, kmw, qualid, hkid, kgnr, net_weight, manual_weighing, spl_check, scale_terminal, weighing_data, weighing_reason) VALUES INSERT INTO delivery_part (year, did, dpnr, sortid, attrid, cultid, weight, kmw, qualid, hkid, kgnr, net_weight, manual_weighing, spl_check, scale_id, weighing_data, weighing_reason) VALUES
(2020, 1, 1, 'GV', NULL, NULL, 3219, 15.0, 'QUW', 'WLNO', 06109, TRUE, FALSE, FALSE, '1', '{"id":"321","nr":321,"gross_weight":3219,"tare_weight":0,"net_weight":3219,"date":"2020-10-01","time":"09:02:46"}', NULL), (2020, 1, 1, 'GV', NULL, NULL, 3219, 15.0, 'QUW', 'WLNO', 06109, TRUE, FALSE, FALSE, '1', '{"id":"321","nr":321,"gross_weight":3219,"tare_weight":0,"net_weight":3219,"date":"2020-10-01","time":"09:02:46"}', NULL),
(2020, 2, 1, 'GV', 'K', NULL, 2987, 17.5, 'KAB', 'WLNO', 06109, TRUE, FALSE, FALSE, NULL, NULL, NULL), (2020, 2, 1, 'GV', 'K', NULL, 2987, 17.5, 'KAB', 'WLNO', 06109, TRUE, FALSE, FALSE, NULL, NULL, NULL),
(2020, 2, 2, 'GV', 'K', NULL, 1873, 17.7, 'KAB', 'WLNO', 06109, TRUE, FALSE, FALSE, NULL, NULL, NULL), (2020, 2, 2, 'GV', 'K', NULL, 1873, 17.7, 'KAB', 'WLNO', 06109, TRUE, FALSE, FALSE, NULL, NULL, NULL),
+1 -1
View File
@@ -76,7 +76,7 @@ INSERT INTO delivery (mgnr, year, did, date, time, zwstid, lnr) VALUES
(101, 2023, 18, '2023-10-10', NULL, 'X', 2), (101, 2023, 18, '2023-10-10', NULL, 'X', 2),
(101, 2023, 19, '2023-10-10', NULL, 'X', 3); (101, 2023, 19, '2023-10-10', NULL, 'X', 3);
INSERT INTO delivery_part (year, did, dpnr, sortid, attrid, cultid, weight, kmw, qualid, hkid, kgnr, net_weight, manual_weighing, spl_check, scale_terminal, weighing_data, weighing_reason) VALUES INSERT INTO delivery_part (year, did, dpnr, sortid, attrid, cultid, weight, kmw, qualid, hkid, kgnr, net_weight, manual_weighing, spl_check, scale_id, weighing_data, weighing_reason) VALUES
(2021, 1, 1, 'GV', NULL, NULL, 3500, 15.0, 'QUW', 'WLNO', 15224, TRUE, FALSE, FALSE, NULL, NULL, NULL), (2021, 1, 1, 'GV', NULL, NULL, 3500, 15.0, 'QUW', 'WLNO', 15224, TRUE, FALSE, FALSE, NULL, NULL, NULL),
(2021, 2, 1, 'GV', NULL, NULL, 4000, 17.0, 'KAB', 'WLNO', 15224, TRUE, FALSE, FALSE, NULL, NULL, NULL), (2021, 2, 1, 'GV', NULL, NULL, 4000, 17.0, 'KAB', 'WLNO', 15224, TRUE, FALSE, FALSE, NULL, NULL, NULL),
(2021, 2, 2, 'GV', NULL, NULL, 4000, 16.0, 'QUW', 'WLNO', 15224, TRUE, FALSE, FALSE, NULL, NULL, NULL), (2021, 2, 2, 'GV', NULL, NULL, 4000, 16.0, 'QUW', 'WLNO', 15224, TRUE, FALSE, FALSE, NULL, NULL, NULL),
+2 -2
View File
@@ -19,11 +19,11 @@
</Target> </Target>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.9.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.7.0" />
<PackageReference Include="Appium.WebDriver" Version="4.4.5" /> <PackageReference Include="Appium.WebDriver" Version="4.4.5" />
<PackageReference Include="NReco.PdfRenderer" Version="1.6.0" /> <PackageReference Include="NReco.PdfRenderer" Version="1.6.0" />
<PackageReference Include="NUnit" Version="4.6.1" /> <PackageReference Include="NUnit" Version="4.6.1" />
<PackageReference Include="NUnit3TestAdapter" Version="6.3.0" /> <PackageReference Include="NUnit3TestAdapter" Version="6.2.0" />
<PackageReference Include="NUnit.Analyzers" Version="4.14.0"> <PackageReference Include="NUnit.Analyzers" Version="4.14.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -16,7 +16,7 @@ namespace Tests.UnitTests.DocumentTests {
""")); """));
Assert.That(text, Contains.Substring("0123463")); // Betriebsnummer Assert.That(text, Contains.Substring("0123463")); // Betriebsnummer
Assert.That(text, Contains.Substring("pauschaliert")); Assert.That(text, Contains.Substring("pauschaliert"));
Assert.That(text, Contains.Substring($"Wolkersdorf, am {DateTime.Today:dd.MM.yyyy}")); Assert.That(text, Contains.Substring($"Wolkersdorf, am {Elwig.Helpers.Utils.Today:dd.MM.yyyy}"));
Assert.That(text, Contains.Substring("Traubengutschrift Max Mustermann Probevariante")); Assert.That(text, Contains.Substring("Traubengutschrift Max Mustermann Probevariante"));
Assert.That(text, Contains.Substring("AT81 1234 5678 9012 3457")); Assert.That(text, Contains.Substring("AT81 1234 5678 9012 3457"));
Assert.That(text, Contains.Substring(""" Assert.That(text, Contains.Substring("""
@@ -21,7 +21,7 @@ namespace Tests.UnitTests.DocumentTests {
""")); """));
Assert.That(text, Contains.Substring("0123463")); // Betriebsnummer Assert.That(text, Contains.Substring("0123463")); // Betriebsnummer
Assert.That(text, Contains.Substring("pauschaliert")); Assert.That(text, Contains.Substring("pauschaliert"));
Assert.That(text, Contains.Substring($"Wolkersdorf, am {DateTime.Today:dd.MM.yyyy}")); Assert.That(text, Contains.Substring($"Wolkersdorf, am {Elwig.Helpers.Utils.Today:dd.MM.yyyy}"));
Assert.That(text, Contains.Substring("Anlieferungsbestätigung 2020")); Assert.That(text, Contains.Substring("Anlieferungsbestätigung 2020"));
Assert.That(text, Contains.Substring(""" Assert.That(text, Contains.Substring("""
20201001X001 1 Grüner Veltliner QUW 73 15,0 ungeb.: 3 219 3 219 20201001X001 1 Grüner Veltliner QUW 73 15,0 ungeb.: 3 219 3 219
@@ -23,7 +23,7 @@ namespace Tests.UnitTests.DocumentTests {
1 Grüner Veltliner Qualitätswein 73 15,0 3 219 1 Grüner Veltliner Qualitätswein 73 15,0 3 219
Herkunft: Österreich / Weinland / Niederösterreich Herkunft: Österreich / Weinland / Niederösterreich
/ Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf / Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf
Waage/Terminal: ?/1, ID: 321 09:02, 01.10.2020 Waage: 1, ID: 321 09:02, 01.10.2020
Brutto: 3 219 kg Tara: 0 kg Netto: 3 219 kg gerebelt gewogen Brutto: 3 219 kg Tara: 0 kg Netto: 3 219 kg gerebelt gewogen
""")); """));
}); });
@@ -49,13 +49,13 @@ namespace Tests.UnitTests.DocumentTests {
1 Grüner Veltliner Qualitätswein 82 16,7 4 002 1 Grüner Veltliner Qualitätswein 82 16,7 4 002
Herkunft: Österreich / Weinland / Niederösterreich Herkunft: Österreich / Weinland / Niederösterreich
/ Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf / Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf
Waage/Terminal: ?/?, ID: ? (gerebelt gewogen) Waage: ?, ID: ? (gerebelt gewogen)
""")); """));
Assert.That(text, Contains.Substring(""" Assert.That(text, Contains.Substring("""
2 Grüner Veltliner Qualitätswein 75 15,3 481 2 Grüner Veltliner Qualitätswein 75 15,3 481
Herkunft: Österreich / Weinland / Niederösterreich Herkunft: Österreich / Weinland / Niederösterreich
/ Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf / Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf
Waage/Terminal: ?/?, ID: ? (gerebelt gewogen) Waage: ?, ID: ? (gerebelt gewogen)
""")); """));
Assert.That(text, Contains.Substring("Gesamt: 81 16,5 4 483")); Assert.That(text, Contains.Substring("Gesamt: 81 16,5 4 483"));
}); });
@@ -80,19 +80,19 @@ namespace Tests.UnitTests.DocumentTests {
1 Grüner Veltliner Wein 75 15,4 2 561 1 Grüner Veltliner Wein 75 15,4 2 561
Herkunft: Österreich Herkunft: Österreich
/ Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf / Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf
Waage/Terminal: ?/?, ID: ? (gerebelt gewogen) Waage: ?, ID: ? (gerebelt gewogen)
""")); """));
Assert.That(text, Contains.Substring(""" Assert.That(text, Contains.Substring("""
2 Grüner Veltliner Kabinett Wein 87 17,6 3 129 2 Grüner Veltliner Kabinett Wein 87 17,6 3 129
Herkunft: Österreich Herkunft: Österreich
/ Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf / Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf
Waage/Terminal: ?/?, ID: ? (gerebelt gewogen) Waage: ?, ID: ? (gerebelt gewogen)
""")); """));
Assert.That(text, Contains.Substring(""" Assert.That(text, Contains.Substring("""
3 Grüner Veltliner Wein 79 16,1 1 280 3 Grüner Veltliner Wein 79 16,1 1 280
Herkunft: Österreich Herkunft: Österreich
/ Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf / Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf
Waage/Terminal: ?/?, ID: ? (gerebelt gewogen) Waage: ?, ID: ? (gerebelt gewogen)
""")); """));
Assert.That(text, Contains.Substring("Gesamt: 81 16,5 6 970")); Assert.That(text, Contains.Substring("Gesamt: 81 16,5 6 970"));
}); });
@@ -118,14 +118,14 @@ namespace Tests.UnitTests.DocumentTests {
Bewirtschaftung: Bio (AT-BIO-302) Bewirtschaftung: Bio (AT-BIO-302)
Herkunft: Österreich Herkunft: Österreich
/ Wolkersdorfer Hochleithen / Wolkersdorf im Weinviertel / KG Wolkersdorf / Wolkersdorfer Hochleithen / Wolkersdorf im Weinviertel / KG Wolkersdorf
Waage/Terminal: ?/?, ID: ? (gerebelt gewogen) Waage: ?, ID: ? (gerebelt gewogen)
""")); """));
Assert.That(text, Contains.Substring(""" Assert.That(text, Contains.Substring("""
2 Grüner Veltliner Qualitätswein 75 15,4 2 134 2 Grüner Veltliner Qualitätswein 75 15,4 2 134
Bewirtschaftung: Bio (AT-BIO-302) Bewirtschaftung: Bio (AT-BIO-302)
Herkunft: Österreich / Weinland / Niederösterreich Herkunft: Österreich / Weinland / Niederösterreich
/ Wolkersdorfer Hochleithen / Wolkersdorf im Weinviertel / KG Wolkersdorf / Wolkersdorfer Hochleithen / Wolkersdorf im Weinviertel / KG Wolkersdorf
Waage/Terminal: ?/?, ID: ? (gerebelt gewogen) Waage: ?, ID: ? (gerebelt gewogen)
""")); """));
Assert.That(text, Contains.Substring("Gesamt: 78 15,9 5 332")); Assert.That(text, Contains.Substring("Gesamt: 78 15,9 5 332"));
}); });
@@ -152,12 +152,12 @@ namespace Tests.UnitTests.DocumentTests {
Herkunft: Österreich / Weinland / Niederösterreich Herkunft: Österreich / Weinland / Niederösterreich
/ Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf / Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf
Zu-/Abschläge: Geschädigte Trauben 10,00 % Zu-/Abschläge: Geschädigte Trauben 10,00 %
Waage/Terminal: ?/?, ID: ? (gerebelt gewogen) Waage: ?, ID: ? (gerebelt gewogen)
2 Grüner Veltliner Kabinett Kabinett 87 17,7 1 873 2 Grüner Veltliner Kabinett Kabinett 87 17,7 1 873
Herkunft: Österreich / Weinland / Niederösterreich Herkunft: Österreich / Weinland / Niederösterreich
/ Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf / Matzner Hügel / Hohenruppersdorf / KG Hohenruppersdorf
Zu-/Abschläge: Keine Voranmeldung 0,1000 /kg Zu-/Abschläge: Keine Voranmeldung 0,1000 /kg
Waage/Terminal: ?/?, ID: ? (gerebelt gewogen) Waage: ?, ID: ? (gerebelt gewogen)
Gesamt: 87 17,6 4 860 Gesamt: 87 17,6 4 860
""")); """));
} }
+4 -4
View File
@@ -24,13 +24,13 @@ namespace Tests.UnitTests.DocumentTests {
} }
[OneTimeSetUp] [OneTimeSetUp]
public void SetupPrinting() { public async Task SetupPrinting() {
Pdf.Init(); await Pdf.Init();
} }
[OneTimeTearDown] [OneTimeTearDown]
public void TeardownPrinting() { public async Task TeardownPrinting() {
Pdf.Cleanup(); await Pdf.Cleanup();
} }
} }
} }
@@ -842,151 +842,5 @@ namespace Tests.UnitTests.ServiceTests {
Assert.That(await ctx.Deliveries.FindAsync(2022, 2), Is.Null); Assert.That(await ctx.Deliveries.FindAsync(2022, 2), Is.Null);
} }
} }
private static readonly DateTime[] DeliveryDates = [
new(2020, 10, 1, 17, 45, 0),
new(2020, 10, 1, 18, 30, 0),
new(2020, 10, 2, 8, 34, 0),
new(2020, 10, 2, 9, 45, 0),
new(2020, 10, 2, 10, 19, 0),
new(2020, 10, 2, 11, 22, 0),
new(2020, 10, 2, 13, 39, 0),
new(2020, 10, 2, 14, 2, 0),
new(2020, 10, 2, 15, 55, 0),
new(2020, 10, 2, 16, 28, 0),
new(2020, 10, 2, 17, 13, 0),
new(2020, 10, 2, 18, 10, 0),
new(2020, 10, 3, 8, 13, 0),
new(2020, 10, 3, 9, 39, 0),
new(2020, 10, 3, 10, 20, 0),
new(2020, 10, 3, 11, 46, 0),
new(2020, 10, 3, 13, 56, 0),
new(2020, 10, 3, 14, 4, 0),
new(2020, 10, 3, 15, 33, 0),
new(2020, 10, 3, 16, 23, 0),
new(2020, 10, 3, 17, 18, 0),
new(2020, 10, 3, 18, 19, 0),
new(2020, 10, 3, 19, 10, 0),
new(2020, 10, 3, 20, 25, 0),
new(2020, 10, 4, 5, 57, 0),
new(2020, 10, 4, 6, 13, 0),
new(2020, 10, 4, 7, 42, 0),
new(2020, 10, 4, 8, 34, 0),
new(2020, 10, 4, 9, 45, 0),
new(2020, 10, 4, 10, 19, 0),
new(2020, 10, 4, 11, 22, 0),
new(2020, 10, 4, 13, 39, 0),
new(2020, 10, 4, 14, 2, 0),
new(2020, 10, 4, 15, 55, 0),
new(2020, 10, 4, 16, 28, 0),
new(2020, 10, 4, 17, 13, 0),
new(2020, 10, 4, 18, 10, 0),
new(2020, 10, 5, 5, 57, 0),
new(2020, 10, 5, 6, 13, 0),
new(2020, 10, 5, 7, 42, 0),
new(2020, 10, 5, 8, 34, 0),
new(2020, 10, 5, 9, 45, 0),
new(2020, 10, 5, 10, 19, 0),
new(2020, 10, 5, 11, 22, 0),
new(2020, 10, 5, 13, 39, 0),
new(2020, 10, 5, 14, 2, 0),
new(2020, 10, 5, 15, 55, 0),
new(2020, 10, 5, 16, 28, 0),
new(2020, 10, 5, 17, 13, 0),
new(2020, 10, 5, 18, 10, 0),
new(2020, 10, 5, 19, 10, 0),
new(2020, 10, 5, 20, 25, 0),
new(2020, 10, 6, 16, 23, 0),
new(2020, 10, 6, 22, 24, 0),
new(2020, 10, 6, 23, 45, 0),
new(2020, 10, 7, 0, 32, 0),
new(2020, 10, 7, 1, 12, 0),
new(2020, 10, 7, 2, 16, 0),
new(2020, 10, 7, 3, 24, 0),
new(2020, 10, 7, 4, 9, 0),
new(2020, 10, 7, 5, 57, 0),
new(2020, 10, 7, 6, 41, 0),
new(2020, 10, 7, 7, 10, 0),
new(2020, 10, 7, 17, 23, 0),
new(2020, 10, 7, 18, 16, 0),
new(2020, 10, 7, 19, 39, 0),
new(2020, 10, 7, 20, 31, 0),
new(2020, 10, 7, 21, 23, 0),
new(2020, 10, 7, 22, 24, 0),
new(2020, 10, 7, 23, 45, 0),
new(2020, 10, 8, 0, 32, 0),
new(2020, 10, 8, 1, 12, 0),
new(2020, 10, 8, 2, 16, 0),
new(2020, 10, 8, 3, 24, 0),
new(2020, 10, 8, 4, 9, 0),
new(2020, 10, 8, 5, 57, 0),
new(2020, 10, 8, 6, 41, 0),
new(2020, 10, 8, 7, 10, 0),
new(2020, 10, 9, 7, 53, 0),
new(2020, 10, 9, 12, 36, 0),
new(2020, 10, 9, 16, 26, 0),
new(2020, 10, 9, 20, 19, 0),
];
[Test]
public void Test_GetFilterToday_01_Empty() {
Assert.That(DeliveryService.GetFilterToday(new(2020, 10, 10), DeliveryDates),
Is.Null);
}
[Test]
public void Test_GetFilterToday_02_Normal() {
Assert.That(DeliveryService.GetFilterToday(new(2020, 10, 2), DeliveryDates),
Is.EqualTo((new DateTime(2020, 10, 2, 8, 0, 0), new DateTime(2020, 10, 2, 19, 0, 0))));
}
[Test]
public void Test_GetFilterToday_03_Overtime() {
Assert.That(DeliveryService.GetFilterToday(new(2020, 10, 3), DeliveryDates),
Is.EqualTo((new DateTime(2020, 10, 3, 8, 0, 0), new DateTime(2020, 10, 3, 21, 0, 0))));
}
[Test]
public void Test_GetFilterToday_04_EarlyStart() {
Assert.That(DeliveryService.GetFilterToday(new(2020, 10, 4), DeliveryDates),
Is.EqualTo((new DateTime(2020, 10, 4, 5, 0, 0), new DateTime(2020, 10, 4, 19, 0, 0))));
}
[Test]
public void Test_GetFilterToday_05_EarlyStartAndOvertime() {
Assert.That(DeliveryService.GetFilterToday(new(2020, 10, 5), DeliveryDates),
Is.EqualTo((new DateTime(2020, 10, 5, 5, 0, 0), new DateTime(2020, 10, 5, 21, 0, 0))));
}
[Test]
public void Test_GetFilterToday_06_NightShift() {
using (Assert.EnterMultipleScope()) {
Assert.That(DeliveryService.GetFilterToday(new(2020, 10, 6), DeliveryDates),
Is.EqualTo((new DateTime(2020, 10, 6, 22, 0, 0), new DateTime(2020, 10, 7, 0, 0, 0))));
Assert.That(DeliveryService.GetFilterToday(new(2020, 10, 7), DeliveryDates.Where(d => d <= new DateTime(2020, 10, 7, 12, 0, 0))),
Is.EqualTo((new DateTime(2020, 10, 6, 22, 0, 0), new DateTime(2020, 10, 7, 8, 0, 0))));
Assert.That(DeliveryService.GetFilterToday(new(2020, 10, 7), DeliveryDates.Where(d => d <= new DateTime(2020, 10, 7, 12, 0, 0)).Append(new(2020, 10, 7, 15, 10, 0))),
Is.EqualTo((new DateTime(2020, 10, 7, 15, 0, 0), new DateTime(2020, 10, 7, 16, 0, 0))));
}
}
[Test]
public void Test_GetFilterToday_07_EarlyStartNightShift() {
using (Assert.EnterMultipleScope()) {
Assert.That(DeliveryService.GetFilterToday(new(2020, 10, 7), DeliveryDates),
Is.EqualTo((new DateTime(2020, 10, 7, 17, 0, 0), new DateTime(2020, 10, 8, 0, 0, 0))));
Assert.That(DeliveryService.GetFilterToday(new(2020, 10, 8), DeliveryDates),
Is.EqualTo((new DateTime(2020, 10, 7, 17, 0, 0), new DateTime(2020, 10, 8, 8, 0, 0))));
Assert.That(DeliveryService.GetFilterToday(new(2020, 10, 8), DeliveryDates.Append(new(2020, 10, 8, 15, 10, 0))),
Is.EqualTo((new DateTime(2020, 10, 8, 15, 0, 0), new DateTime(2020, 10, 8, 16, 0, 0))));
}
}
} }
} }
@@ -31,19 +31,16 @@ namespace Tests.UnitTests.WeighingTests {
Mock.Weight = 1235; Mock.Weight = 1235;
Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1235, TareWeight = 0, NetWeight = 1235, GrossWeight = 1235, TareWeight = 0, NetWeight = 1235,
ScaleId = "1",
Date = new DateOnly(2020, 10, 17), Time = new TimeOnly(14, 23), Date = new DateOnly(2020, 10, 17), Time = new TimeOnly(14, 23),
})); }));
Mock.Weight = 1240; Mock.Weight = 1240;
Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1240, TareWeight = 0, NetWeight = 1240, GrossWeight = 1240, TareWeight = 0, NetWeight = 1240,
ScaleId = "1",
Date = new DateOnly(2020, 10, 17), Time = new TimeOnly(14, 23), Date = new DateOnly(2020, 10, 17), Time = new TimeOnly(14, 23),
})); }));
Mock.Weight = 1245; Mock.Weight = 1245;
Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1245, TareWeight = 0, NetWeight = 1245, GrossWeight = 1245, TareWeight = 0, NetWeight = 1245,
ScaleId = "1",
Date = new DateOnly(2020, 10, 17), Time = new TimeOnly(14, 23), Date = new DateOnly(2020, 10, 17), Time = new TimeOnly(14, 23),
})); }));
} }
@@ -53,19 +50,19 @@ namespace Tests.UnitTests.WeighingTests {
Mock.Weight = 1235; Mock.Weight = 1235;
Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 1235, TareWeight = 0, NetWeight = 1235, GrossWeight = 1235, TareWeight = 0, NetWeight = 1235,
ScaleId = "1", WeighingId = "1", FullWeighingId = $"2020-10-17/1", WeighingId = "1", FullWeighingId = $"2020-10-17/1",
Date = new DateOnly(2020, 10, 17), Time = new TimeOnly(14, 23), Date = new DateOnly(2020, 10, 17), Time = new TimeOnly(14, 23),
})); }));
Mock.Weight = 3335; Mock.Weight = 3335;
Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 3335, TareWeight = 0, NetWeight = 3335, GrossWeight = 3335, TareWeight = 0, NetWeight = 3335,
ScaleId = "1", WeighingId = "2", FullWeighingId = $"2020-10-17/2", WeighingId = "2", FullWeighingId = $"2020-10-17/2",
Date = new DateOnly(2020, 10, 17), Time = new TimeOnly(14, 23), Date = new DateOnly(2020, 10, 17), Time = new TimeOnly(14, 23),
})); }));
Mock.Weight = 6420; Mock.Weight = 6420;
Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 6420, TareWeight = 0, NetWeight = 6420, GrossWeight = 6420, TareWeight = 0, NetWeight = 6420,
ScaleId = "1", WeighingId = "3", FullWeighingId = $"2020-10-17/3", WeighingId = "3", FullWeighingId = $"2020-10-17/3",
Date = new DateOnly(2020, 10, 17), Time = new TimeOnly(14, 23), Date = new DateOnly(2020, 10, 17), Time = new TimeOnly(14, 23),
})); }));
} }
@@ -5,7 +5,7 @@ namespace Tests.UnitTests.WeighingTests {
public class ScaleTestHaugsdorfDMA02 { public class ScaleTestHaugsdorfDMA02 {
private MockScale Mock; private MockScale Mock;
private GassnerEnqScale Scale; private GassnerScale Scale;
[OneTimeSetUp] [OneTimeSetUp]
public void SetupScale() { public void SetupScale() {
@@ -32,23 +32,29 @@ namespace Tests.UnitTests.WeighingTests {
Mock.Weight = 1234; Mock.Weight = 1234;
Mock.Tare = 0; Mock.Tare = 0;
Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1234, TareWeight = 0, NetWeight = 1234, GrossWeight = 1234,
ScaleId = "1", TareWeight = 0,
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), NetWeight = 1234,
Date = new DateOnly(2020, 10, 15),
Time = new TimeOnly(12, 34),
})); }));
Mock.Weight = 1235; Mock.Weight = 1235;
Mock.Tare = 46; Mock.Tare = 46;
Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1281, TareWeight = 46, NetWeight = 1235, GrossWeight = 1281,
ScaleId = "1", TareWeight = 46,
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), NetWeight = 1235,
Date = new DateOnly(2020, 10, 15),
Time = new TimeOnly(12, 34),
})); }));
Mock.Weight = 1236; Mock.Weight = 1236;
Mock.Tare = 92; Mock.Tare = 92;
Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1328, TareWeight = 92, NetWeight = 1236, GrossWeight = 1328,
ScaleId = "1", TareWeight = 92,
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), NetWeight = 1236,
Date = new DateOnly(2020, 10, 15),
Time = new TimeOnly(12, 34),
})); }));
} }
@@ -57,23 +63,35 @@ namespace Tests.UnitTests.WeighingTests {
Mock.Weight = 1234; Mock.Weight = 1234;
Mock.Tare = 92; Mock.Tare = 92;
Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 1326, TareWeight = 92, NetWeight = 1234, GrossWeight = 1326,
ScaleId = "1", WeighingId = "1", FullWeighingId = "1", TareWeight = 92,
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), NetWeight = 1234,
WeighingId = "1",
FullWeighingId = "1",
Date = new DateOnly(2020, 10, 15),
Time = new TimeOnly(12, 34),
})); }));
Mock.Weight = 3333; Mock.Weight = 3333;
Mock.Tare = 41; Mock.Tare = 41;
Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 3374, TareWeight = 41, NetWeight = 3333, GrossWeight = 3374,
ScaleId = "1", WeighingId = "2", FullWeighingId = "2", TareWeight = 41,
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), NetWeight = 3333,
WeighingId = "2",
FullWeighingId = "2",
Date = new DateOnly(2020, 10, 15),
Time = new TimeOnly(12, 34),
})); }));
Mock.Weight = 4321; Mock.Weight = 4321;
Mock.Tare = 0; Mock.Tare = 0;
Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 4321, TareWeight = 0, NetWeight = 4321, GrossWeight = 4321,
ScaleId = "1", WeighingId = "3", FullWeighingId = "3", TareWeight = 0,
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), NetWeight = 4321,
WeighingId = "3",
FullWeighingId = "3",
Date = new DateOnly(2020, 10, 15),
Time = new TimeOnly(12, 34),
})); }));
} }
@@ -31,19 +31,16 @@ namespace Tests.UnitTests.WeighingTests {
Mock.Weight = 1234; Mock.Weight = 1234;
Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1234, TareWeight = 0, NetWeight = 1234, GrossWeight = 1234, TareWeight = 0, NetWeight = 1234,
ScaleId = "1",
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34),
})); }));
Mock.Weight = 1235; Mock.Weight = 1235;
Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1235, TareWeight = 0, NetWeight = 1235, GrossWeight = 1235, TareWeight = 0, NetWeight = 1235,
ScaleId = "1",
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34),
})); }));
Mock.Weight = 1236; Mock.Weight = 1236;
Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1236, TareWeight = 0, NetWeight = 1236, GrossWeight = 1236, TareWeight = 0, NetWeight = 1236,
ScaleId = "1",
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34),
})); }));
} }
@@ -53,19 +50,19 @@ namespace Tests.UnitTests.WeighingTests {
Mock.Weight = 1234; Mock.Weight = 1234;
Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 1234, TareWeight = 0, NetWeight = 1234, GrossWeight = 1234, TareWeight = 0, NetWeight = 1234,
ScaleId = "1", WeighingId = "1", FullWeighingId = $"2020-10-15/1", WeighingId = "1", FullWeighingId = $"2020-10-15/1",
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34),
})); }));
Mock.Weight = 3333; Mock.Weight = 3333;
Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 3333, TareWeight = 0, NetWeight = 3333, GrossWeight = 3333, TareWeight = 0, NetWeight = 3333,
ScaleId = "1", WeighingId = "2", FullWeighingId = $"2020-10-15/2", WeighingId = "2", FullWeighingId = $"2020-10-15/2",
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34),
})); }));
Mock.Weight = 4321; Mock.Weight = 4321;
Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 4321, TareWeight = 0, NetWeight = 4321, GrossWeight = 4321, TareWeight = 0, NetWeight = 4321,
ScaleId = "1", WeighingId = "3", FullWeighingId = $"2020-10-15/3", WeighingId = "3", FullWeighingId = $"2020-10-15/3",
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34),
})); }));
} }
@@ -5,7 +5,7 @@ namespace Tests.UnitTests.WeighingTests {
public class ScaleTestSitzendorfDMA03Baby { public class ScaleTestSitzendorfDMA03Baby {
private MockScale Mock; private MockScale Mock;
private GassnerEnqScale Scale; private GassnerScale Scale;
[OneTimeSetUp] [OneTimeSetUp]
public void SetupScale() { public void SetupScale() {
@@ -32,23 +32,29 @@ namespace Tests.UnitTests.WeighingTests {
Mock.Weight = 1234; Mock.Weight = 1234;
Mock.Tare = 0; Mock.Tare = 0;
Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1234, TareWeight = 0, NetWeight = 1234, GrossWeight = 1234,
ScaleId = "1", TareWeight = 0,
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), NetWeight = 1234,
Date = new DateOnly(2020, 10, 15),
Time = new TimeOnly(12, 34),
})); }));
Mock.Weight = 1235; Mock.Weight = 1235;
Mock.Tare = 46; Mock.Tare = 46;
Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1281, TareWeight = 46, NetWeight = 1235, GrossWeight = 1281,
ScaleId = "1", TareWeight = 46,
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), NetWeight = 1235,
Date = new DateOnly(2020, 10, 15),
Time = new TimeOnly(12, 34),
})); }));
Mock.Weight = 1236; Mock.Weight = 1236;
Mock.Tare = 92; Mock.Tare = 92;
Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1328, TareWeight = 92, NetWeight = 1236, GrossWeight = 1328,
ScaleId = "1", TareWeight = 92,
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), NetWeight = 1236,
Date = new DateOnly(2020, 10, 15),
Time = new TimeOnly(12, 34),
})); }));
} }
@@ -57,23 +63,35 @@ namespace Tests.UnitTests.WeighingTests {
Mock.Weight = 1234; Mock.Weight = 1234;
Mock.Tare = 92; Mock.Tare = 92;
Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 1326, TareWeight = 92, NetWeight = 1234, GrossWeight = 1326,
ScaleId = "1", WeighingId = "1", FullWeighingId = "1", TareWeight = 92,
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), NetWeight = 1234,
WeighingId = "1",
FullWeighingId = "1",
Date = new DateOnly(2020, 10, 15),
Time = new TimeOnly(12, 34),
})); }));
Mock.Weight = 3333; Mock.Weight = 3333;
Mock.Tare = 41; Mock.Tare = 41;
Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 3374, TareWeight = 41, NetWeight = 3333, GrossWeight = 3374,
ScaleId = "1", WeighingId = "2", FullWeighingId = "2", TareWeight = 41,
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), NetWeight = 3333,
WeighingId = "2",
FullWeighingId = "2",
Date = new DateOnly(2020, 10, 15),
Time = new TimeOnly(12, 34),
})); }));
Mock.Weight = 4321; Mock.Weight = 4321;
Mock.Tare = 0; Mock.Tare = 0;
Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await Scale!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 4321, TareWeight = 0, NetWeight = 4321, GrossWeight = 4321,
ScaleId = "1", WeighingId = "3", FullWeighingId = "3", TareWeight = 0,
Date = new DateOnly(2020, 10, 15), Time = new TimeOnly(12, 34), NetWeight = 4321,
WeighingId = "3",
FullWeighingId = "3",
Date = new DateOnly(2020, 10, 15),
Time = new TimeOnly(12, 34),
})); }));
} }
@@ -40,25 +40,21 @@ namespace Tests.UnitTests.WeighingTests {
MockA.Weight = 1234; MockA.Weight = 1234;
Assert.That(await ScaleA!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await ScaleA!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1234, TareWeight = 0, NetWeight = 1234, GrossWeight = 1234, TareWeight = 0, NetWeight = 1234,
ScaleId = "1",
Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47), Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47),
})); }));
MockB.Weight = 3456; MockB.Weight = 3456;
Assert.That(await ScaleB!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await ScaleB!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 3456, TareWeight = 0, NetWeight = 3456, GrossWeight = 3456, TareWeight = 0, NetWeight = 3456,
ScaleId = "1",
Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47), Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47),
})); }));
MockA.Weight = 1236; MockA.Weight = 1236;
Assert.That(await ScaleA!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await ScaleA!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 1236, TareWeight = 0, NetWeight = 1236, GrossWeight = 1236, TareWeight = 0, NetWeight = 1236,
ScaleId = "1",
Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47), Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47),
})); }));
MockB.Weight = 3457; MockB.Weight = 3457;
Assert.That(await ScaleB!.GetCurrentWeight(), Is.EqualTo(new WeighingResult { Assert.That(await ScaleB!.GetCurrentWeight(), Is.EqualTo(new WeighingResult {
GrossWeight = 3457, TareWeight = 0, NetWeight = 3457, GrossWeight = 3457, TareWeight = 0, NetWeight = 3457,
ScaleId = "1",
Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47), Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47),
})); }));
} }
@@ -68,25 +64,25 @@ namespace Tests.UnitTests.WeighingTests {
MockA.Weight = 1234; MockA.Weight = 1234;
Assert.That(await ScaleA!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await ScaleA!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 1234, TareWeight = 0, NetWeight = 1234, GrossWeight = 1234, TareWeight = 0, NetWeight = 1234,
ScaleId = "1", WeighingId = "1", FullWeighingId = $"2020-10-08/1", WeighingId = "1", FullWeighingId = $"2020-10-08/1",
Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47), Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47),
})); }));
MockB.Weight = 3456; MockB.Weight = 3456;
Assert.That(await ScaleB!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await ScaleB!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 3456, TareWeight = 0, NetWeight = 3456, GrossWeight = 3456, TareWeight = 0, NetWeight = 3456,
ScaleId = "1", WeighingId = "1", FullWeighingId = $"2020-10-08/1", WeighingId = "1", FullWeighingId = $"2020-10-08/1",
Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47), Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47),
})); }));
MockA.Weight = 4321; MockA.Weight = 4321;
Assert.That(await ScaleA!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await ScaleA!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 4321, TareWeight = 0, NetWeight = 4321, GrossWeight = 4321, TareWeight = 0, NetWeight = 4321,
ScaleId = "1", WeighingId = "2", FullWeighingId = $"2020-10-08/2", WeighingId = "2", FullWeighingId = $"2020-10-08/2",
Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47), Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47),
})); }));
MockB.Weight = 3333; MockB.Weight = 3333;
Assert.That(await ScaleB!.Weigh(), Is.EqualTo(new WeighingResult { Assert.That(await ScaleB!.Weigh(), Is.EqualTo(new WeighingResult {
GrossWeight = 3333, TareWeight = 0, NetWeight = 3333, GrossWeight = 3333, TareWeight = 0, NetWeight = 3333,
ScaleId = "1", WeighingId = "2", FullWeighingId = $"2020-10-08/2", WeighingId = "2", FullWeighingId = $"2020-10-08/2",
Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47), Date = new DateOnly(2020, 10, 8), Time = new TimeOnly(8, 47),
})); }));
} }
+1 -1
View File
@@ -1 +1 @@
curl --fail -s -L "https://elwig.at/files/create.sql?v=41" -u "elwig:ganzGeheim123!" -o "Resources\Sql\Create.sql" curl --fail -s -L "https://elwig.at/files/create.sql?v=40" -u "elwig:ganzGeheim123!" -o "Resources\Sql\Create.sql"