From 83d1c28b29ecf4072c6163cbebe6a480b277ca07 Mon Sep 17 00:00:00 2001 From: Stefan Date: Fri, 10 Jul 2026 21:03:55 +0200 Subject: [PATCH] Refactor code structure and remove redundant sections for improved readability and maintainability --- Fuchs.Tests/FdsInvoiceDataBlocksTests.cs | 52 +++++++ Fuchs.Tests/InvoiceDraftCalculatorTests.cs | 73 ++++++++++ Fuchs.Tests/InvoiceDraftServiceTests.cs | 124 ++++++++++++++++ .../IntranetController.Requests.cs | 25 +++- Fuchs/Docs/Concepts/live-draft-editing.md | 19 ++- Fuchs/Services/InvoiceDraftEditService.cs | 137 ++++++++++++++---- Fuchs/Services/InvoiceService.cs | 58 +++++++- Fuchs/code/FdsInvoiceData.cs | 33 ++++- Fuchs/code/FuchsPdf.cs | 87 ++++++++--- Fuchs/code/InvoiceDraftCalculator.cs | 25 ++++ Fuchs/js/intranet/modules/fis.inv_shared.js | 39 ++++- Fuchs/js/intranet/oci_sortable.js | 12 +- Fuchs/wwwroot/web/fis.inv.de.js | 39 ++++- Fuchs/wwwroot/web/fis.inv.de.min.js | 2 +- Fuchs/wwwroot/web/fis.js | 12 +- Fuchs/wwwroot/web/fis.min.js | 4 +- Fuchs/wwwroot/web/fis.req.de.js | 39 ++++- Fuchs/wwwroot/web/fis.req.de.min.js | 2 +- 18 files changed, 696 insertions(+), 86 deletions(-) create mode 100644 Fuchs.Tests/FdsInvoiceDataBlocksTests.cs diff --git a/Fuchs.Tests/FdsInvoiceDataBlocksTests.cs b/Fuchs.Tests/FdsInvoiceDataBlocksTests.cs new file mode 100644 index 0000000..0af1bc9 --- /dev/null +++ b/Fuchs.Tests/FdsInvoiceDataBlocksTests.cs @@ -0,0 +1,52 @@ +using System.Linq; +using Fuchs.intranet; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Fuchs.Tests; + +/// +/// Verifies the block projection that feeds the PDF item table: each service-request +/// group exposes its heading (the section title the editor shows) and its line items, +/// so the PDF can print a heading row per block and the flat item list still works. +/// +public class FdsInvoiceDataBlocksTests +{ + private static FdsInvoiceData FromReq(string reqJson) => + new(JObject.Parse(@"{'admin':{'type':'r'},'new':{},'sms':{},'req':" + reqJson + "}")); + + [Fact] + public void InvoiceBlocks_ExposesHeadingFromTextThenNme_AndItems() + { + var inv = FromReq(@"[ + {'Id':'1','text':'Sektion A','items':[{'id':'a','type':'material','title':'X','price_net':10,'total_net':10}]}, + {'Id':'2','nme':'Sektion B','items':[{'id':'b','type':'material','title':'Y','price_net':20,'total_net':20}]} + ]"); + + var blocks = inv.InvoiceBlocks; + + Assert.Equal(2, blocks.Count); + Assert.Equal("Sektion A", blocks[0].Heading); + Assert.Equal("Sektion B", blocks[1].Heading); // falls back to nme + Assert.Single(blocks[0].Items); + Assert.Equal("X", blocks[0].Items[0]["title"]); + } + + [Fact] + public void InvoiceBlocks_MissingHeading_IsEmpty() + { + var inv = FromReq(@"[{'Id':'1','items':[{'id':'a','type':'material','total_net':5}]}]"); + Assert.Equal("", Assert.Single(inv.InvoiceBlocks).Heading); + } + + [Fact] + public void InvoiceItems_StillFlattensAcrossBlocks() + { + var inv = FromReq(@"[ + {'Id':'1','text':'A','items':[{'id':'a','type':'material','total_net':10}]}, + {'Id':'2','text':'B','items':[{'id':'b','type':'material','total_net':20},{'id':'c','type':'material','total_net':30}]} + ]"); + + Assert.Equal(new[] { "a", "b", "c" }, inv.InvoiceItems.Select(i => i["id"]!.ToString()).ToArray()); + } +} diff --git a/Fuchs.Tests/InvoiceDraftCalculatorTests.cs b/Fuchs.Tests/InvoiceDraftCalculatorTests.cs index 51e4e6a..f70dae9 100644 --- a/Fuchs.Tests/InvoiceDraftCalculatorTests.cs +++ b/Fuchs.Tests/InvoiceDraftCalculatorTests.cs @@ -136,4 +136,77 @@ public class InvoiceDraftCalculatorTests InvoiceDraftCalculator.Validate(s); Assert.Contains(s.ValidationMessages, m => m.Field == "total" && m.Severity == "warning"); } + + // ── RecomputePositions ──────────────────────────────────────────────────── + private static string Pos(InvoiceDraftSession s, int block, int line) => + ((JObject)((JArray)((JObject)s.Req[block])["itm"]!)[line])["p"]!.ToString(); + + [Fact] + public void RecomputePositions_NumbersPricedLinesContinuouslyAcrossBlocks() + { + var s = SessionWith(@"[ + { 'Id':'10','itm':[ {'id':'a','typ':'material','vt':1}, {'id':'b','typ':'service','vt':2} ] }, + { 'Id':'11','itm':[ {'id':'c','typ':'material','vt':3} ] } + ]"); + + InvoiceDraftCalculator.RecomputePositions(s); + + Assert.Equal("1", Pos(s, 0, 0)); + Assert.Equal("2", Pos(s, 0, 1)); + Assert.Equal("3", Pos(s, 1, 0)); // continuous, not restarting per block + } + + [Fact] + public void RecomputePositions_SkipsHeadingAndFreeTextLines() + { + var s = SessionWith(@"[ + { 'Id':'10','itm':[ + {'id':'t','typ':'Title','vt':0}, + {'id':'a','typ':'material','vt':1}, + {'id':'x','typ':'Text','vt':0}, + {'id':'b','typ':'material','vt':2} ] } + ]"); + + InvoiceDraftCalculator.RecomputePositions(s); + + Assert.Equal("", Pos(s, 0, 0)); // title carries no number + Assert.Equal("1", Pos(s, 0, 1)); + Assert.Equal("", Pos(s, 0, 2)); // free text carries no number + Assert.Equal("2", Pos(s, 0, 3)); + } + + [Fact] + public void RecomputePositions_NumbersSetHeaderLikeAnyItem() + { + // A set header is numbered just like the editor numbers it — only text/title lines are skipped. + var s = SessionWith(@"[ + { 'Id':'10','itm':[ + {'id':'h','typ':'set','vt':1000}, + {'id':'a','typ':'material','vt':600}, + {'id':'b','typ':'material','vt':400} ] } + ]"); + + InvoiceDraftCalculator.RecomputePositions(s); + + Assert.Equal("1", Pos(s, 0, 0)); // set header keeps position 1 (matches the editor) + Assert.Equal("2", Pos(s, 0, 1)); + Assert.Equal("3", Pos(s, 0, 2)); + } + + [Fact] + public void RecomputePositions_AfterBlockOrderChange_RenumbersToNewSequence() + { + var s = SessionWith(@"[ + { 'Id':'10','itm':[ {'id':'a','typ':'material','vt':1} ] }, + { 'Id':'11','itm':[ {'id':'b','typ':'material','vt':2} ] } + ]"); + // Simulate a section reorder: swap the two blocks. + var b0 = s.Req[0]; var b1 = s.Req[1]; + s.Req = new JArray(b1.DeepClone(), b0.DeepClone()); + + InvoiceDraftCalculator.RecomputePositions(s); + + Assert.Equal("1", Pos(s, 0, 0)); // formerly block 11's item is now position 1 + Assert.Equal("2", Pos(s, 1, 0)); + } } diff --git a/Fuchs.Tests/InvoiceDraftServiceTests.cs b/Fuchs.Tests/InvoiceDraftServiceTests.cs index ebb99b5..4b646c3 100644 --- a/Fuchs.Tests/InvoiceDraftServiceTests.cs +++ b/Fuchs.Tests/InvoiceDraftServiceTests.cs @@ -352,4 +352,128 @@ public class InvoiceDraftServiceTests Assert.Null(svc.Get(s.Token)); Assert.False(svc.Close(s.Token)); } + + // ── HTML sanitisation (values must never reach the DB/PDF wrapped in tags) ─ + [Theory] + [InlineData("provisionperiod", "provisionperiod")] + [InlineData("title", "invoicetitle")] + [InlineData("email", "invoiceemail")] + public void ApplyPatch_ScalarField_StripsHtmlWrapper(string target, string newKey) + { + var (svc, _, _) = NewService(); + var s = svc.OpenFromPayload(Payload(), "user1"); + + var s2 = svc.ApplyPatch(s.Token, new InvoiceDraftDelta { Target = target, Value = JToken.FromObject("

18.06.2026

") }); + + Assert.Equal("18.06.2026", s2!.New[newKey]!.Value()); // no

tags stored + Assert.Equal("18.06.2026", Assert.Single(s2.History).NewValue); + } + + [Fact] + public void ApplyPatch_Address_MultilineHtml_KeepsLineBreaks() + { + var (svc, _, _) = NewService(); + var s = svc.OpenFromPayload(Payload(), "user1"); + + var s2 = svc.ApplyPatch(s.Token, new InvoiceDraftDelta + { + Target = "address", + Value = JToken.FromObject("

Firma AG

Weg 1
5080 Laufenburg

") + }); + + Assert.Equal("Firma AG\nWeg 1\n5080 Laufenburg", s2!.New["invoiceaddress"]!.Value()); + } + + [Fact] + public void ApplyPatch_ScalarField_DecodesEntities() + { + var (svc, _, _) = NewService(); + var s = svc.OpenFromPayload(Payload(), "user1"); + + var s2 = svc.ApplyPatch(s.Token, new InvoiceDraftDelta { Target = "title", Value = JToken.FromObject("Tom & Jerry") }); + + Assert.Equal("Tom & Jerry", s2!.New["invoicetitle"]!.Value()); + } + + [Fact] + public void ApplyPatch_ProvisionLocation_SanitisesAndMirrorsLoc() + { + var (svc, _, _) = NewService(); + var s = svc.OpenFromPayload(Payload(), "user1"); + + var s2 = svc.ApplyPatch(s.Token, new InvoiceDraftDelta { Target = "provisionlocation", Value = JToken.FromObject("

Baustelle 7

") }); + + Assert.Equal("Baustelle 7", s2!.New["provisionlocation"]!.Value()); + Assert.Equal("Baustelle 7", s2.New["loc"]!.Value()); + } + + // ── Change history records the changed field, not the whole block JSON ───── + [Fact] + public void ApplyPatch_BlockReplace_HistoryNewValueIsSectionText_NotJson() + { + var (svc, _, _) = NewService(); + var s = svc.OpenFromPayload(Payload(), "user1"); + + var newBlock = JObject.Parse(@"{'Id':'1','text':'

Neue Überschrift

', + 'itm':[{'id':'900','typ':'material','vt':100,'vv':19,'vat':'19%'}], + 'items':[{'id':'900','type':'material','total_net':100,'vat':'19%'}]}"); + var s2 = svc.ApplyPatch(s.Token, new InvoiceDraftDelta { Target = "block.replace", Ref = "1", Value = newBlock }); + + var h = Assert.Single(s2!.History); + Assert.Equal("Neue Überschrift", h.NewValue); // the heading, sanitised — never the block JSON + Assert.DoesNotContain("{", h.NewValue); + Assert.Equal("Auftrag", h.OldValue); + // and the cached block text is stored clean too + Assert.Equal("Neue Überschrift", ((JObject)s2.Req[0])["text"]!.Value()); + } + + // ── Section reorder ─────────────────────────────────────────────────────── + private static JObject TwoBlockPayload() => JObject.Parse(@"{ + 'admin':{'p13b':false,'type':'r'}, + 'new':{'invoiceemail':'a@b.de','invoiceaddress':'Weg 1'}, + 'req':[ + {'Id':'1','text':'A','itm':[{'id':'900','typ':'material','vt':100,'vv':19,'vat':'19%'}],'items':[{'id':'900','type':'material','total_net':100,'vat':'19%'}]}, + {'Id':'2','text':'B','itm':[{'id':'950','typ':'material','vt':30,'vv':5.7,'vat':'19%'}],'items':[{'id':'950','type':'material','total_net':30,'vat':'19%'}]} + ]}"); + + [Fact] + public void ApplyPatch_BlockOrder_ReordersReqAndRenumbersPositions() + { + var (svc, _, _) = NewService(); + var s = svc.OpenFromPayload(TwoBlockPayload(), "user1"); + Assert.Equal(new[] { "1", "2" }, s.Req.Select(b => b["Id"]!.Value()).ToArray()); + + var s2 = svc.ApplyPatch(s.Token, new InvoiceDraftDelta { Target = "block.order", Value = JArray.Parse("['2','1']") }); + + Assert.Equal(new[] { "2", "1" }, s2!.Req.Select(b => b["Id"]!.Value()).ToArray()); + Assert.Equal("1", ((JObject)((JArray)((JObject)s2.Req[0])["itm"]!)[0])["p"]!.ToString()); // block 2's item now position 1 + Assert.Equal(130m, s2.Sums.TotalNet); // totals unaffected by reorder + var h = Assert.Single(s2.History); + Assert.Equal("1,2", h.OldValue); + Assert.Equal("2,1", h.NewValue); + } + + [Fact] + public void ApplyPatch_BlockOrder_UnchangedSequence_IsNoOp() + { + var (svc, _, _) = NewService(); + var s = svc.OpenFromPayload(TwoBlockPayload(), "user1"); + + var s2 = svc.ApplyPatch(s.Token, new InvoiceDraftDelta { Target = "block.order", Value = JArray.Parse("['1','2']") }); + + Assert.Equal(0, s2!.Version); // no-op: no version bump, no history + Assert.Empty(s2.History); + } + + [Fact] + public void ApplyPatch_BlockOrder_UnknownIds_KeepMentionedFirstThenRest() + { + var (svc, _, _) = NewService(); + var s = svc.OpenFromPayload(TwoBlockPayload(), "user1"); + + // Only name block 2; block 1 is unmentioned and must be kept (appended after). + var s2 = svc.ApplyPatch(s.Token, new InvoiceDraftDelta { Target = "block.order", Value = JArray.Parse("['2','ghost']") }); + + Assert.Equal(new[] { "2", "1" }, s2!.Req.Select(b => b["Id"]!.Value()).ToArray()); + } } diff --git a/Fuchs/Controllers/IntranetController.Requests.cs b/Fuchs/Controllers/IntranetController.Requests.cs index 1d1af0b..8a90277 100644 --- a/Fuchs/Controllers/IntranetController.Requests.cs +++ b/Fuchs/Controllers/IntranetController.Requests.cs @@ -369,6 +369,21 @@ public partial class IntranetController return await InvoiceIssueResult("Die Rechnung konnte aufgrund eines Fehlers nicht erstellt werden."); } + /// + /// Serves the PDF inline (browser shows it) while advertising the real download filename — + /// both a quoted ASCII form and RFC 5987 filename* for spaces/non-ASCII. Works around + /// the OCORE FileContentResult helper, whose classic-MVC ExecuteResult(ControllerContext) + /// never runs under ASP.NET Core, so the filename was dropped and downloads used the "idoc" + /// endpoint segment. + /// + private void SetInlinePdfFilename(string filename) + { + string safe = (filename ?? "").Replace("\"", "").Replace("\r", " ").Replace("\n", " ").Trim(); + if (safe.Length == 0) return; + Response.Headers["Content-Disposition"] = + $"inline; filename=\"{safe}\"; filename*=UTF-8''{Uri.EscapeDataString(safe)}"; + } + private async Task HandleRequestIdoc(string fn, string id, string code) { if (!HasForm("id") || string.IsNullOrEmpty(Form("id"))) { _logger.LogWarning("HandleRequestIdoc: missing/empty form field 'id', user={User}", UserAccountID); return StatusCode(404); } @@ -381,9 +396,13 @@ public partial class IntranetController byte[]? ct = Form("create", "0") != "1" ? await _invoices.GetInvoiceFileAsync(fdInv, fdInv.IsDraft, _mfr) is { Length: > 0 } f1 ? f1 : await _invoices.StoreInvoiceDocumentFileAsync(fdInv, fdInv.IsDraft, UserAccountID, DbSec) : _pdf.DocToPdfBytes(_invoices.GenerateInvoicePdf(fdInv, fdInv.IsDraft)); - return ct != null - ? await FileContentResultAsync(ct, "application/pdf", filename, inline: true) - : await InvoiceIssueResult("Die Rechnungs-PDF konnte aufgrund eines Fehlers nicht erstellt werden.", fdInv.Id); + if (ct == null) + return await InvoiceIssueResult("Die Rechnungs-PDF konnte aufgrund eines Fehlers nicht erstellt werden.", fdInv.Id); + // Serve inline for the in-browser viewer, but carry the real DocumentName so the browser's + // "download" uses "Rechnung R2026-0121.pdf" instead of the "idoc" endpoint segment. (The + // OCORE FileContentResult helper drops the filename under ASP.NET Core, so set it here.) + SetInlinePdfFilename(filename); + return File(ct, "application/pdf"); } var imgcol = await _pdf.DocToImageCollectionAsync(_invoices.GenerateInvoicePdf(fdInv, fdInv.IsDraft)); return await JSONAsync(new { id = fdInv.Id, img = imgcol.ImgB64Array, total = imgcol.TotalPages }); diff --git a/Fuchs/Docs/Concepts/live-draft-editing.md b/Fuchs/Docs/Concepts/live-draft-editing.md index 0555f0d..b3e4cf1 100644 --- a/Fuchs/Docs/Concepts/live-draft-editing.md +++ b/Fuchs/Docs/Concepts/live-draft-editing.md @@ -51,9 +51,22 @@ Expiry: Server (timer) --SignalR draftExpiring{token,secondsLeft}--> warn "bit `Sums`, `ValidationMessages`, `History`, `Version`, `Token`, `InvId`, `LastAccessUtc`. - **Calculation** (`InvoiceDraftCalculator`, static/pure) ports the former client math: `RecomputeItem` (quantity × price × VAT, the `quantChange` port), `RecomputeTotals` - (the `invSumUpdate`/`csms` aggregation + §13b reverse-charge), and `Validate` - (email/address/items/VAT-rate/negative-total checks). Being pure, it is exhaustively - unit-tested. + (the `invSumUpdate`/`csms` aggregation + §13b reverse-charge), `RecomputePositions` + (numbers every line except heading/free-text lines continuously across the whole invoice — + mirroring the editor's `invSumUpdate`, so the editor and the PDF show identical `Pos.` numbers, + including after a reorder), + and `Validate` (email/address/items/VAT-rate/negative-total checks). Being pure, it is + exhaustively unit-tested. +- **Sanitisation & reorder.** Scalar text deltas (`title`/`email`/`address`/`provisionperiod`/ + `provisionlocation`) and the section heading (`block.replace`) are stripped of the editor's + TinyMCE HTML (`

`, `
`) to plain text in `ApplyDelta` (`HtmlToPlain`) — the backend + is the single source of truth, so no HTML reaches the DB, the PDF or a reloaded draft. Section + drags post a `block.order` delta (`["id",…]`) that reorders `Req`; positions are then + renumbered and pushed back via the view state (`applyState`/`applyPositions`). The change + history records the **changed field** (e.g. the new heading text), never the whole block JSON. + The PDF (`FuchsPdf`) renders a heading row per block (`FdsInvoiceData.InvoiceBlocks`) and shows + every position's price (set members are priced like standalone lines; only `setonly` collapses + them), so the PDF preview mirrors the online editor. - **Orchestration** (`InvoiceDraftEditService`, scoped) opens sessions (from a fresh payload or by reloading a DB draft via `fds__getInvoice`, reshaped like `BuildInvoiceRequestList`), applies deltas (`ApplyDelta`), builds the view-state DTO, diff --git a/Fuchs/Services/InvoiceDraftEditService.cs b/Fuchs/Services/InvoiceDraftEditService.cs index 0bce450..323b824 100644 --- a/Fuchs/Services/InvoiceDraftEditService.cs +++ b/Fuchs/Services/InvoiceDraftEditService.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Text.RegularExpressions; using Fuchs.intranet; using Microsoft.Extensions.Logging; using MigraDoc.DocumentObjectModel; @@ -59,8 +60,8 @@ public sealed class InvoiceDraftEditService : IInvoiceDraftService var session = _cache.Get(token); if (session == null) return null; - string oldValue = ""; - bool mutated = ApplyDelta(session, delta, ref oldValue); + string oldValue = "", newValue = ""; + bool mutated = ApplyDelta(session, delta, ref oldValue, ref newValue); if (!mutated) { _logger.LogDebug("Draft {Token}: no-op patch target={Target} ref={Ref}", token, delta.Target, delta.Ref); @@ -75,71 +76,89 @@ public sealed class InvoiceDraftEditService : IInvoiceDraftService Target = delta.Target, Ref = delta.Ref, OldValue = oldValue, - NewValue = delta.ValueString, + NewValue = newValue, Version = session.Version }); _cache.Set(session); return session; } - /// Applies one delta to the payload; returns whether anything changed and captures the prior value. - private static bool ApplyDelta(InvoiceDraftSession s, InvoiceDraftDelta d, ref string oldValue) + /// + /// Applies one delta to the payload; returns whether anything changed and captures the prior + /// and new value for the change history. Scalar text fields and the section heading are + /// sanitised from the editor's HTML (TinyMCE wraps inline edits in <p>…</p>) + /// to plain text here — the backend is the single source of truth (ADR 0006), so no HTML ever + /// reaches the DB, the PDF or a reloaded draft, regardless of which UI path produced it. + /// + private static bool ApplyDelta(InvoiceDraftSession s, InvoiceDraftDelta d, ref string oldValue, ref string newValue) { switch (d.Target) { - case "email": return SetNew(s, "invoiceemail", d, ref oldValue); - case "address": return SetNew(s, "invoiceaddress", d, ref oldValue); - case "title": return SetNew(s, "invoicetitle", d, ref oldValue); - case "provisionperiod": return SetNew(s, "provisionperiod", d, ref oldValue); + case "email": return SetNewText(s, "invoiceemail", d, ref oldValue, ref newValue); + case "address": return SetNewText(s, "invoiceaddress", d, ref oldValue, ref newValue); + case "title": return SetNewText(s, "invoicetitle", d, ref oldValue, ref newValue); + case "provisionperiod": return SetNewText(s, "provisionperiod", d, ref oldValue, ref newValue); case "provisionlocation": oldValue = Str(s.New["provisionlocation"]); - s.New["provisionlocation"] = d.ValueString; - s.New["loc"] = d.ValueString; // editor mirrors both + newValue = HtmlToPlain(d.ValueString); + s.New["provisionlocation"] = newValue; + s.New["loc"] = newValue; // editor mirrors both return true; - case "contact": return SetContact(s, d, ref oldValue); - case "setmode": return SetAdmin(s, "setmode", d, ref oldValue); + case "contact": return SetContact(s, d, ref oldValue, ref newValue); + case "setmode": return SetAdmin(s, "setmode", d, ref oldValue, ref newValue); case "p13b": oldValue = Str(s.Admin["p13b"]); - s.Admin["p13b"] = d.Value != null && d.Value.Type != JTokenType.Null + bool p13b = d.Value != null && d.Value.Type != JTokenType.Null ? AsBool(d.Value) : !AsBool(s.Admin["p13b"]); // toggle when no explicit value + s.Admin["p13b"] = p13b; + newValue = p13b ? "§13b" : ""; return true; - case "block.replace": return ReplaceBlock(s, d, ref oldValue); - case "block.remove": return RemoveBlock(s, d, ref oldValue); + case "block.replace": return ReplaceBlock(s, d, ref oldValue, ref newValue); + case "block.remove": return RemoveBlock(s, d, ref oldValue, ref newValue); + case "block.order": return ReorderBlocks(s, d, ref oldValue, ref newValue); default: return false; } } - private static bool SetNew(InvoiceDraftSession s, string key, InvoiceDraftDelta d, ref string oldValue) + private static bool SetNewText(InvoiceDraftSession s, string key, InvoiceDraftDelta d, ref string oldValue, ref string newValue) { oldValue = Str(s.New[key]); - s.New[key] = d.ValueString; + newValue = HtmlToPlain(d.ValueString); + s.New[key] = newValue; return true; } - private static bool SetAdmin(InvoiceDraftSession s, string key, InvoiceDraftDelta d, ref string oldValue) + private static bool SetAdmin(InvoiceDraftSession s, string key, InvoiceDraftDelta d, ref string oldValue, ref string newValue) { oldValue = Str(s.Admin[key]); - s.Admin[key] = d.ValueString; + newValue = d.ValueString; + s.Admin[key] = newValue; return true; } - private static bool SetContact(InvoiceDraftSession s, InvoiceDraftDelta d, ref string oldValue) + private static bool SetContact(InvoiceDraftSession s, InvoiceDraftDelta d, ref string oldValue, ref string newValue) { - oldValue = Str(s.New["CustomValues"]); - JObject cvo = TryParseObject(oldValue); + JObject prev = TryParseObject(Str(s.New["CustomValues"])); + oldValue = ContactLabel(Str(prev["contactName"]), Str(prev["contactEmail"])); + JObject cvo = (JObject)prev.DeepClone(); if (d.Value is JObject vo) { cvo["contactName"] = vo["name"] ?? vo["contactName"] ?? ""; cvo["contactEmail"] = vo["email"] ?? vo["contactEmail"] ?? ""; } s.New["CustomValues"] = cvo.ToString(Newtonsoft.Json.Formatting.None); + newValue = ContactLabel(Str(cvo["contactName"]), Str(cvo["contactEmail"])); return true; } + private static string ContactLabel(string name, string email) => + string.IsNullOrEmpty(name) ? email : string.IsNullOrEmpty(email) ? name : $"{name} <{email}>"; + /// Replaces (or inserts) a whole block — the editor re-emits an edited block's line arrays as one delta. - private static bool ReplaceBlock(InvoiceDraftSession s, InvoiceDraftDelta d, ref string oldValue) + private static bool ReplaceBlock(InvoiceDraftSession s, InvoiceDraftDelta d, ref string oldValue, ref string newValue) { if (d.Value is not JObject nb) return false; + SanitizeBlockText(nb); string bid = !string.IsNullOrEmpty(d.Ref) ? d.Ref : Str(nb["Id"]); var existing = FindBlock(s, bid); if (existing != null) @@ -152,18 +171,58 @@ public sealed class InvoiceDraftEditService : IInvoiceDraftService oldValue = ""; s.Req.Add(nb); } + newValue = Str(nb["text"]); // the section heading — never the whole block JSON return true; } - private static bool RemoveBlock(InvoiceDraftSession s, InvoiceDraftDelta d, ref string oldValue) + private static bool RemoveBlock(InvoiceDraftSession s, InvoiceDraftDelta d, ref string oldValue, ref string newValue) { var block = FindBlock(s, d.Ref); if (block == null) return false; oldValue = Str(block["text"]); + newValue = ""; block.Remove(); return true; } + /// + /// Reorders the service-request blocks to the id sequence the editor posts after a section + /// drag (Value = ["id",…]). Named ids move into the given order; any not named are kept + /// in their current relative order at the end. Totals are unaffected; item position numbers + /// are renumbered by and pushed back to the browser via the view state. + /// + private static bool ReorderBlocks(InvoiceDraftSession s, InvoiceDraftDelta d, ref string oldValue, ref string newValue) + { + if (d.Value is not JArray order) return false; + var current = s.Req.OfType().ToList(); + oldValue = string.Join(",", current.Select(b => Str(b["Id"]))); + + var byId = current.ToDictionary(b => Str(b["Id"]), b => b); + var ordered = new List(); + var seen = new HashSet(); + foreach (var idTok in order) + { + string id = Str(idTok); + if (byId.TryGetValue(id, out var blk) && seen.Add(id)) ordered.Add(blk); + } + foreach (var b in current) // append blocks the order list didn't mention, in place + if (seen.Add(Str(b["Id"]))) ordered.Add(b); + + newValue = string.Join(",", ordered.Select(b => Str(b["Id"]))); + if (oldValue == newValue) return false; // no-op reorder + + s.Req.Clear(); + foreach (var b in ordered) s.Req.Add(b); + return true; + } + + /// Strips the editor's HTML from a block's heading (text/nme) before it is cached. + private static void SanitizeBlockText(JObject block) + { + if (block["text"] != null) block["text"] = HtmlToPlain(Str(block["text"])); + if (block["nme"] != null) block["nme"] = HtmlToPlain(Str(block["nme"])); + } + // ── View state / history ──────────────────────────────────────────────── public object BuildState(InvoiceDraftSession session) { @@ -230,6 +289,7 @@ public sealed class InvoiceDraftEditService : IInvoiceDraftService private static void Refresh(InvoiceDraftSession session) { InvoiceDraftCalculator.RecomputeTotals(session); + InvoiceDraftCalculator.RecomputePositions(session); InvoiceDraftCalculator.Validate(session); } @@ -349,4 +409,31 @@ public sealed class InvoiceDraftEditService : IInvoiceDraftService } return new JObject(); } + + /// + /// Converts the editor's HTML (TinyMCE-wrapped inline edits, e.g. <p>18.06.2026</p>) + /// to plain text: line-break-producing tags become newlines, remaining tags are stripped and + /// entities decoded. Multi-line fields (address, Leistungsort) keep their line breaks — the PDF + /// splits those on \n/<br> — while single-line fields collapse to one line. + /// Blank lines are removed so a stray <p></p> never becomes an empty row. + /// + internal static string HtmlToPlain(string? raw) + { + if (string.IsNullOrEmpty(raw)) return ""; + if (raw.IndexOf('<') < 0 && raw.IndexOf('&') < 0) return raw.Trim(); + + // Turn line-break / block-close tags into newlines before stripping the rest. + string s = Regex.Replace(raw, @"<\s*br\s*/?\s*>", "\n", RegexOptions.IgnoreCase); + s = Regex.Replace(s, @"", "\n", RegexOptions.IgnoreCase); + + var doc = new HtmlAgilityPack.HtmlDocument(); + doc.LoadHtml(s); + string text = System.Net.WebUtility.HtmlDecode(doc.DocumentNode.InnerText); + + var lines = text.Replace("\r\n", "\n").Replace('\r', '\n') + .Split('\n') + .Select(l => l.Trim()) + .Where(l => l.Length > 0); + return string.Join("\n", lines).Trim(); + } } diff --git a/Fuchs/Services/InvoiceService.cs b/Fuchs/Services/InvoiceService.cs index 593be5c..a4890e4 100644 --- a/Fuchs/Services/InvoiceService.cs +++ b/Fuchs/Services/InvoiceService.cs @@ -63,10 +63,64 @@ public class InvoiceService : IInvoiceService inv.InvoiceRegistration = new GenericObjectDictionary(dset.Table("inv").FirstRow.toObjectDictionary()); inv.IsDraft = inv.InvoiceRegistration.getItem("IsFinal", false) is not true; - _logger.LogDebug("LoadInvoiceAsync loaded id={Id} draft={Draft}", inv.Id, inv.IsDraft); + // Reconstruct the service-request blocks + line items so the PDF renders the positions. + // Without this the reloaded/finalized invoice showed an empty item table (only the header + // + totals came from InvoiceRegistration), i.e. it did not match the cached preview. + inv.Req = BuildPdfRequestBlocks(dset); + _logger.LogDebug("LoadInvoiceAsync loaded id={Id} draft={Draft} blocks={Blocks}", inv.Id, inv.IsDraft, inv.Req?.Count ?? 0); return inv; } + /// + /// Rebuilds the invoice's service-request groups and line items from the persisted + /// req/itm tables (fds__getInvoice) into the exact block shape the PDF + /// consumes ( → item contract + /// type/title/desc/qty/price_net/total_net). Item order follows the persisted + /// SortOrder, so a reordered draft renders in its saved order — making the finalized + /// PDF and the re-downloaded (idoc) document identical to the cached preview. + /// + private static List> BuildPdfRequestBlocks(SQLDataSet dset) + { + var blocks = new List>(); + if (!dset.Contains("req")) return blocks; + + var reqTable = dset.Tables("req"); + string reqSort = reqTable.Columns.Contains("order") ? "order" : ""; + foreach (DataRow rq in reqTable.Select("", reqSort)) + { + var rdic = rq.toObjectDictionary(); + var items = new List>(); + if (dset.Contains("itm")) + { + var itmTable = dset.Tables("itm"); + string itmSort = itmTable.Columns.Contains("order") ? "order" : ""; + foreach (DataRow it in itmTable.Select($"[InvRqId] = '{rdic.nz("Id")}'", itmSort)) + { + var d = it.toObjectDictionary(); + // The persisted "Text" holds the item's rendered HTML (the editor's co.t); it is + // the full title+description, so it maps to the contract's desc (title stays empty). + items.Add(new Dictionary + { + ["id"] = d.nz("mfr__item"), + ["type"] = d.nz("Type"), + ["title"] = "", + ["desc"] = d.nz("Text"), + ["qty"] = d.nz("Quantity"), + ["price_net"] = d.no("value", 0), + ["total_net"] = d.no("value_total", 0) + }); + } + } + blocks.Add(new Dictionary + { + ["Id"] = rdic.nz("mfr__servicerequest"), + ["text"] = System.Net.WebUtility.HtmlDecode(rdic.nz("title")), + ["items"] = items + }); + } + return blocks; + } + public async Task RegisterInvoiceAsync(FdsInvoiceData invoice, bool change, string invId, string userAccountId, DatabaseSecurity dbSec) { @@ -212,7 +266,7 @@ public class InvoiceService : IInvoiceService var reg = invoice.InvoiceRegistration; var tb = new FuchsPdf.FdsTextBlocks { - AdminRef = reg?.getString("Id") ?? "", + AdminRef = (reg?.getString("InvoiceId") ?? "").ne(reg?.getString("Id") ?? ""), Address = reg?.getString("SendToAddress") is { Length: > 0 } sa ? sa.Replace("
", "\n").Replace("
", "\n").Split('\n').Select(t => t.Trim()).ToArray() : Array.Empty(), diff --git a/Fuchs/code/FdsInvoiceData.cs b/Fuchs/code/FdsInvoiceData.cs index bf4bb14..1b99afb 100644 --- a/Fuchs/code/FdsInvoiceData.cs +++ b/Fuchs/code/FdsInvoiceData.cs @@ -19,7 +19,7 @@ public class FdsInvoiceData public GenericObjectDictionary? Admin { get; private set; } public GenericObjectDictionary? NewValues { get; private set; } public GenericObjectDictionary? Sms { get; private set; } - public List>? Req { get; private set; } + public List>? Req { get; internal set; } public GenericObjectDictionary? InvoiceRegistration { get; internal set; } public bool IsDraft { get; internal set; } = true; @@ -46,9 +46,25 @@ public class FdsInvoiceData get { var result = new List>(); + foreach (var block in InvoiceBlocks) result.AddRange(block.Items); + return result; + } + } + + /// + /// The service-request groups as they should render on the invoice: each block carries its + /// heading (the section title the editor shows) and its line items. The PDF renders a heading + /// row per block followed by that block's items, so the online editor and the PDF stay in sync. + /// + public List InvoiceBlocks + { + get + { + var result = new List(); if (Req == null) return result; foreach (var req in Req) { + var items = new List>(); if (req.TryGetValue("items", out var itmsObj)) { IEnumerable>? itms = @@ -56,8 +72,12 @@ public class FdsInvoiceData ?? (itmsObj is JArray ja ? ja.ToObject>>() : null); - if (itms != null) result.AddRange(itms); + if (itms != null) items.AddRange(itms); } + string heading = ""; + if (req.TryGetValue("text", out var th) && th != null) heading = th.ToString() ?? ""; + if (heading.Length == 0 && req.TryGetValue("nme", out var nh) && nh != null) heading = nh.ToString() ?? ""; + result.Add(new InvoiceBlock { Heading = heading, Items = items }); } return result; } @@ -196,3 +216,12 @@ public class FdsInvoiceData return double.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out var d) ? d : 0; } } + +/// A service-request group as it renders on the invoice: a heading plus its line items. +public sealed class InvoiceBlock +{ + /// The section heading (editor's text/nme); empty when the group has none. + public string Heading { get; init; } = ""; + /// The group's line items (the editor's items contract). + public List> Items { get; init; } = new(); +} diff --git a/Fuchs/code/FuchsPdf.cs b/Fuchs/code/FuchsPdf.cs index d8b7f66..dab23eb 100644 --- a/Fuchs/code/FuchsPdf.cs +++ b/Fuchs/code/FuchsPdf.cs @@ -137,6 +137,30 @@ public static class FuchsPdf public static string TranslatePaymentTerm(string pt) => pt.Replace("wd", " Werktagen").Replace("d", " Tagen").Replace("wk", " Wochen").ne("10 Tagen"); + /// + /// Maps one editor item-contract entry to a display line, mirroring the online editor: the + /// item's own price/total is shown, a set header is emphasised, and free-text/heading lines + /// (type text/title) show neither a price nor a position number. This is the flat + /// (non-collapsing) rendering used for every set mode except the explicit setonly. + /// + private static InvoiceSetLine MapItemToLine(Dictionary i) + { + string type = i.nz("type", "").ToLowerInvariant(); + bool isText = type is "text" or "title"; + ParseDec(i.no("price_net", 0), out decimal price); + ParseDec(i.no("total_net", 0), out decimal total); + return new InvoiceSetLine + { + Title = i.nz("title", ""), + Desc = i.nz("desc", ""), + Qty = i.nz("qty", ""), + PriceNet = price, + TotalNet = total, + ShowPrice = !isText, + IsSetHeader = type == "set" + }; + } + /// /// Parses a numeric value coming from JSON deserialization (long/double), SQL /// (decimal), or an already-invariant numeric string. Numeric CLR types are @@ -593,30 +617,49 @@ public static class FuchsPdf hRow.Cells[i].Format.Alignment = i >= 2 ? ParagraphAlignment.Right : ParagraphAlignment.Left; } - // Data rows — resolved through the set-display mode (see InvoiceSetPricing). - // For invoices without sets this passes items through unchanged; for sets it - // emits set header + members per the chosen mode, blanking price cells where - // a line should show no price. Totals come from the registration balance, so - // the mode is purely presentational. + // Data rows — grouped by service-request block (see FdsInvoiceData.InvoiceBlocks). + // Per the product decision the PDF must mirror the online editor exactly: each section + // prints its heading, every position shows its own price, and positions are numbered the + // same way the editor numbers them (every line except free-text/heading lines, including a + // set header). Set-display collapsing is honoured only for the explicit SetOnly mode; every + // other mode renders the items flat, so nothing is silently blanked or renumbered. var setMode = InvoiceSetPricing.ModeFromInvoiceOptions(inv.InvoiceRegistration?.getString("InvoiceOptions")); - int pos = 1; - foreach (var line in InvoiceSetPricing.Build(inv.InvoiceItems, setMode)) + int pos = 0; + foreach (var block in inv.InvoiceBlocks) { - var row = tbl.AddRow(); - row.HeightRule = RowHeightRule.Auto; - row.Cells[0].AddParagraph(pos.ToString()).Style = "TblCell_Base"; - var titleCell = row.Cells[1].AddParagraph(); - titleCell.Style = "TblCell_RTitle"; - if (line.IsSetHeader) titleCell.AddFormattedText(line.Title, TextFormat.Bold); - else titleCell.AddText(line.Title); - if (!string.IsNullOrEmpty(line.Desc)) row.Cells[1].AddHtml($"
{line.Desc}
"); - row.Cells[2].AddParagraph(line.Qty).Style = "TblCell_Base"; - row.Cells[3].AddParagraph(line.ShowPrice ? Currency(line.PriceNet) : "").Style = "TblCell_Base"; - row.Cells[4].AddParagraph(line.ShowPrice ? Currency(line.TotalNet) : "").Style = "TblCell_RSum"; - row.Cells[2].Format.Alignment = ParagraphAlignment.Right; - row.Cells[3].Format.Alignment = ParagraphAlignment.Right; - row.Cells[4].Format.Alignment = ParagraphAlignment.Right; - pos++; + if (!string.IsNullOrWhiteSpace(block.Heading)) + { + var hr = tbl.AddRow(); + hr.HeightRule = RowHeightRule.Auto; + hr.Cells[1].MergeRight = 3; // span Bezeichnung … Gesamtpreis + hr.Cells[1].AddParagraph().WithStyle("TblCell_RTitle").AddFormattedText(block.Heading, TextFormat.Bold); + } + + var lines = setMode == SetDisplayMode.SetOnly && InvoiceSetPricing.ContainsSets(block.Items) + ? InvoiceSetPricing.Build(block.Items, SetDisplayMode.SetOnly) // only this mode collapses members + : block.Items.Select(MapItemToLine).ToList(); // flat: faithful mirror of the editor + + foreach (var line in lines) + { + bool numbered = line.IsSetHeader || line.ShowPrice; // free-text/heading lines carry no number + var row = tbl.AddRow(); + row.HeightRule = RowHeightRule.Auto; + row.Cells[0].AddParagraph(numbered ? (++pos).ToString() : "").Style = "TblCell_Base"; + if (!string.IsNullOrEmpty(line.Title)) // skip the empty paragraph that added a blank line before free text + { + var titleCell = row.Cells[1].AddParagraph(); + titleCell.Style = "TblCell_RTitle"; + if (line.IsSetHeader) titleCell.AddFormattedText(line.Title, TextFormat.Bold); + else titleCell.AddText(line.Title); + } + if (!string.IsNullOrEmpty(line.Desc)) row.Cells[1].AddHtml($"
{line.Desc}
"); + row.Cells[2].AddParagraph(line.Qty).Style = "TblCell_Base"; + row.Cells[3].AddParagraph(line.ShowPrice ? Currency(line.PriceNet) : "").Style = "TblCell_Base"; + row.Cells[4].AddParagraph(line.ShowPrice ? Currency(line.TotalNet) : "").Style = "TblCell_RSum"; + row.Cells[2].Format.Alignment = ParagraphAlignment.Right; + row.Cells[3].Format.Alignment = ParagraphAlignment.Right; + row.Cells[4].Format.Alignment = ParagraphAlignment.Right; + } } // Totals diff --git a/Fuchs/code/InvoiceDraftCalculator.cs b/Fuchs/code/InvoiceDraftCalculator.cs index dd09c9e..357928b 100644 --- a/Fuchs/code/InvoiceDraftCalculator.cs +++ b/Fuchs/code/InvoiceDraftCalculator.cs @@ -68,6 +68,31 @@ public static class InvoiceDraftCalculator session.Sums = sums; } + /// + /// Renumbers the visible line positions authoritatively (the port of the client-side + /// numbering in invSumUpdate): priced lines are numbered sequentially across the whole + /// invoice — matching the PDF's Pos. column — while heading/free-text lines + /// (typ = "text"/"title") carry no number. The result is written onto each line's + /// p field so it flows back to the browser (via the view state) and into the PDF; this + /// keeps the online editor and the PDF preview showing the same position numbers, including + /// after a reorder. + /// + public static void RecomputePositions(InvoiceDraftSession session) + { + int pos = 0; + foreach (var blockTok in session.Req) + { + if (blockTok is not JObject block || block["itm"] is not JArray lines) continue; + foreach (var lineTok in lines) + { + if (lineTok is not JObject co) continue; + string typ = Str(co["typ"]).Trim().ToLowerInvariant(); + bool numbered = typ is not ("text" or "title"); // only headings/free-text carry no number (mirrors invSumUpdate) + co["p"] = numbered ? (JToken)(++pos) : (JToken)""; + } + } + } + /// /// Refreshes the draft's plausibility / consistency findings. "error" severity marks /// issues that should block a clean finalise; "warning" is advisory. Kept in German, diff --git a/Fuchs/js/intranet/modules/fis.inv_shared.js b/Fuchs/js/intranet/modules/fis.inv_shared.js index 41c3edd..e6c393a 100644 --- a/Fuchs/js/intranet/modules/fis.inv_shared.js +++ b/Fuchs/js/intranet/modules/fis.inv_shared.js @@ -130,7 +130,7 @@ $inv.d = { let l = $inv.d.layout(); l.aC('freeze'); $ocms.postXT({ url: $ocms.url('inv/dopen'), data: { payload: JSON.stringify(payload) }, success: (r) => { - $inv.d.tbl().data('dtoken', r.token).data('dver', r.version).data('dhashes', $inv.d.hashes()); + $inv.d.tbl().data('dtoken', r.token).data('dver', r.version).data('dhashes', $inv.d.hashes()).data('dorder', $inv.d.order()); $fis.draft.bind(r.token, { onReady: () => $inv.d.refresh(), onExpiring: (s) => $inv.d.warnExpiry(s), @@ -155,6 +155,17 @@ $inv.d = { tbl.data('dver', state.version).data('serverSums', state.sums); $inv.d.footer(tbl, state.sums || {}, state.admin || {}); $inv.d.validation(state.validation || []); + $inv.d.applyPositions(tbl, state.req || []); + }, + /* Push the server's authoritative position numbers back onto the rendered rows so the online + editor and the PDF preview always agree (the server numbers priced lines continuously; the + browser must not keep its own numbering). Only the position cell is touched — no re-render. */ + applyPositions: function (tbl, req) { + (req || []).forEach((b) => (b && b.itm || []).forEach((co) => { + if (!co || (co.id || '') === '') { return; } + let cell = tbl.find('#itm' + co.id + ' td.keep').first(); + if (cell.length) { cell.text(co.p != null ? co.p : ''); } + })); }, /* Send one change to the server; the draftReady signal and this success both refresh. */ sync: function (delta) { @@ -166,16 +177,23 @@ $inv.d = { error: (xhr) => { $inv.d.layout().rC('freeze'); if (xhr && xhr.status === 410) { $inv.d.closed('expired'); } } }); }, + /* The current section id sequence (used to detect a reorder that changes no block content). */ + order: function () { return (($inv.d.tbl().data('bai')) || []).map((b) => (b.Id || '').toString()); }, /* Diff the freshly-rebuilt blocks against the last-synced state and send only the - changed/removed blocks as granular block.replace / block.remove deltas. */ + changed/removed blocks as granular block.replace / block.remove deltas. A pure section + reorder (same blocks, new sequence) changes no block hash, so it is sent separately as a + block.order delta; the server reorders the cache, renumbers positions and pushes them back. */ syncChanged: function (tbl) { if (($inv.d.token()) === '') { return; } let bai = tbl.data('bai') || [], prev = tbl.data('dhashes') || {}, next = {}, changed = [], removed = []; $.each(bai, (i, b) => { let id = (b.Id || '').toString(), h = JSON.stringify(b); next[id] = h; if (prev[id] !== h) { changed.push(b); } }); $.each(prev, (id) => { if (next[id] === undefined) { removed.push(id); } }); - tbl.data('dhashes', next); + let order = $inv.d.order(), prevOrder = tbl.data('dorder') || []; + tbl.data('dhashes', next).data('dorder', order); changed.forEach((b) => $inv.d.sync({ Target: 'block.replace', Ref: (b.Id || '').toString(), Value: b })); removed.forEach((id) => $inv.d.sync({ Target: 'block.remove', Ref: id })); + let sameSet = prevOrder.length === order.length && prevOrder.slice().sort().join(',') === order.slice().sort().join(','); + if (sameSet && prevOrder.join(',') !== order.join(',')) { $inv.d.sync({ Target: 'block.order', Value: order }); } }, /* Map an inline recipient field to its delta target and send it. */ syncField: function (nme, val) { @@ -672,9 +690,12 @@ $inv.cSt = function (data) { }; $inv.eHtml = function (ev) { let t = $(this), frmct = ev.data instanceof jQuery ? ev.data : ev.data.t; - /* invoiceemail must stay plain text — using the TinyMCE/html editor here used to wrap the - address in

tags, which then got posted and persisted verbatim into SendToEmail. */ - let isPlainText = ev.data.nme === 'invoiceemail'; + /* Single-line fields must stay plain text — the TinyMCE/html editor wraps the value in

+ tags, which used to get posted and persisted verbatim (e.g.

18.06.2026

in the + Leistungsdatum). The backend sanitises HTML too (single source of truth, ADR 0006), but + keeping these plain here avoids the UI briefly holding the wrapped value. Multi-line fields + (invoiceaddress, loc) stay HTML-capable and are normalised to newlines server-side. */ + let isPlainText = ['invoiceemail', 'provisionperiod', 'invoicetitle'].includes(ev.data.nme); let flds = isPlainText ? [{ name: 'txt', label: 'Text', type: 'text', value: frmct.text() }] : [{ name: 'txt', label: 'Text', type: 'html', value: frmct.html(), tinymce: true, attr: { style: 'height: 300px' } }]; @@ -777,7 +798,11 @@ $inv.eRw = function(row, dta, flds) { }, typedvalues: true }); }; -$inv.bdysort = (i, e) => { $(e).Sortable({ dragItem: false, dragHandleClass: 'ico', parentident: 'tr', swapdone: (p1, p2, i1, i2) => { $inv.t_fds_inv(); } }) } +/* Reorder items via drag. The DOM swap happens inside the Sortable during the drag; we commit + the new order once, reliably, on drop (onend) — that recomputes positions/totals and pushes the + changed block(s) to the backend session (t_fds_inv -> syncChanged). Committing on drop (rather + than on every mid-drag hover-swap) avoids rebuilding the row that is currently being dragged. */ +$inv.bdysort = (i, e) => { $(e).Sortable({ dragItem: false, dragHandleClass: 'ico', parentident: 'tr', onend: () => { $inv.t_fds_inv(); } }) } $inv.rrw = function () { let rw = $(this), dta = rw.data(), co = {}, ph = rw.is('.placeholder'), hn = rw.is('.hidenote'); let oHtml = (e) => $$.d().append(e).html(); diff --git a/Fuchs/js/intranet/oci_sortable.js b/Fuchs/js/intranet/oci_sortable.js index 9458116..0ee2dbd 100644 --- a/Fuchs/js/intranet/oci_sortable.js +++ b/Fuchs/js/intranet/oci_sortable.js @@ -63,7 +63,8 @@ if (!Element.prototype.closest) { this._dragging = false; this._dragHandleClass = this._options.dragHandleClass || ''; this._parentident = this._options.parentident || ''; - this._swapdone = typeof this._options.swapdone === "function" ? this._options._swapdone : null; + this._swapdone = typeof this._options.swapdone === "function" ? this._options.swapdone : null; + this._onend = typeof this._options.onend === "function" ? this._options.onend : null; this._container.setAttribute("data-is-sortable", 1); this._container.classList.add("sortable"); @@ -213,10 +214,17 @@ if (!Element.prototype.closest) { } }, - // on item release/drop + // on item release/drop _onRelease: function (e) { + // Was THIS list mid-drag? (mouseup fires on every instance's window listener.) + var wasDragging = this._dragging === true && this._clickItem !== null; this._dragging = false; this._trashDragItem(); + // Fire a single "drag finished" callback so callers can commit the new order once, + // reliably, on drop — rather than relying on the per-hover _swapdone during the drag. + if (wasDragging && typeof this._onend === 'function') { + this._onend(); + } }, // on item drag/move diff --git a/Fuchs/wwwroot/web/fis.inv.de.js b/Fuchs/wwwroot/web/fis.inv.de.js index 3119d48..7c45e3a 100644 --- a/Fuchs/wwwroot/web/fis.inv.de.js +++ b/Fuchs/wwwroot/web/fis.inv.de.js @@ -677,7 +677,7 @@ $inv.d = { let l = $inv.d.layout(); l.aC('freeze'); $ocms.postXT({ url: $ocms.url('inv/dopen'), data: { payload: JSON.stringify(payload) }, success: (r) => { - $inv.d.tbl().data('dtoken', r.token).data('dver', r.version).data('dhashes', $inv.d.hashes()); + $inv.d.tbl().data('dtoken', r.token).data('dver', r.version).data('dhashes', $inv.d.hashes()).data('dorder', $inv.d.order()); $fis.draft.bind(r.token, { onReady: () => $inv.d.refresh(), onExpiring: (s) => $inv.d.warnExpiry(s), @@ -702,6 +702,17 @@ $inv.d = { tbl.data('dver', state.version).data('serverSums', state.sums); $inv.d.footer(tbl, state.sums || {}, state.admin || {}); $inv.d.validation(state.validation || []); + $inv.d.applyPositions(tbl, state.req || []); + }, + /* Push the server's authoritative position numbers back onto the rendered rows so the online + editor and the PDF preview always agree (the server numbers priced lines continuously; the + browser must not keep its own numbering). Only the position cell is touched — no re-render. */ + applyPositions: function (tbl, req) { + (req || []).forEach((b) => (b && b.itm || []).forEach((co) => { + if (!co || (co.id || '') === '') { return; } + let cell = tbl.find('#itm' + co.id + ' td.keep').first(); + if (cell.length) { cell.text(co.p != null ? co.p : ''); } + })); }, /* Send one change to the server; the draftReady signal and this success both refresh. */ sync: function (delta) { @@ -713,16 +724,23 @@ $inv.d = { error: (xhr) => { $inv.d.layout().rC('freeze'); if (xhr && xhr.status === 410) { $inv.d.closed('expired'); } } }); }, + /* The current section id sequence (used to detect a reorder that changes no block content). */ + order: function () { return (($inv.d.tbl().data('bai')) || []).map((b) => (b.Id || '').toString()); }, /* Diff the freshly-rebuilt blocks against the last-synced state and send only the - changed/removed blocks as granular block.replace / block.remove deltas. */ + changed/removed blocks as granular block.replace / block.remove deltas. A pure section + reorder (same blocks, new sequence) changes no block hash, so it is sent separately as a + block.order delta; the server reorders the cache, renumbers positions and pushes them back. */ syncChanged: function (tbl) { if (($inv.d.token()) === '') { return; } let bai = tbl.data('bai') || [], prev = tbl.data('dhashes') || {}, next = {}, changed = [], removed = []; $.each(bai, (i, b) => { let id = (b.Id || '').toString(), h = JSON.stringify(b); next[id] = h; if (prev[id] !== h) { changed.push(b); } }); $.each(prev, (id) => { if (next[id] === undefined) { removed.push(id); } }); - tbl.data('dhashes', next); + let order = $inv.d.order(), prevOrder = tbl.data('dorder') || []; + tbl.data('dhashes', next).data('dorder', order); changed.forEach((b) => $inv.d.sync({ Target: 'block.replace', Ref: (b.Id || '').toString(), Value: b })); removed.forEach((id) => $inv.d.sync({ Target: 'block.remove', Ref: id })); + let sameSet = prevOrder.length === order.length && prevOrder.slice().sort().join(',') === order.slice().sort().join(','); + if (sameSet && prevOrder.join(',') !== order.join(',')) { $inv.d.sync({ Target: 'block.order', Value: order }); } }, /* Map an inline recipient field to its delta target and send it. */ syncField: function (nme, val) { @@ -1219,9 +1237,12 @@ $inv.cSt = function (data) { }; $inv.eHtml = function (ev) { let t = $(this), frmct = ev.data instanceof jQuery ? ev.data : ev.data.t; - /* invoiceemail must stay plain text — using the TinyMCE/html editor here used to wrap the - address in

tags, which then got posted and persisted verbatim into SendToEmail. */ - let isPlainText = ev.data.nme === 'invoiceemail'; + /* Single-line fields must stay plain text — the TinyMCE/html editor wraps the value in

+ tags, which used to get posted and persisted verbatim (e.g.

18.06.2026

in the + Leistungsdatum). The backend sanitises HTML too (single source of truth, ADR 0006), but + keeping these plain here avoids the UI briefly holding the wrapped value. Multi-line fields + (invoiceaddress, loc) stay HTML-capable and are normalised to newlines server-side. */ + let isPlainText = ['invoiceemail', 'provisionperiod', 'invoicetitle'].includes(ev.data.nme); let flds = isPlainText ? [{ name: 'txt', label: 'Text', type: 'text', value: frmct.text() }] : [{ name: 'txt', label: 'Text', type: 'html', value: frmct.html(), tinymce: true, attr: { style: 'height: 300px' } }]; @@ -1324,7 +1345,11 @@ $inv.eRw = function(row, dta, flds) { }, typedvalues: true }); }; -$inv.bdysort = (i, e) => { $(e).Sortable({ dragItem: false, dragHandleClass: 'ico', parentident: 'tr', swapdone: (p1, p2, i1, i2) => { $inv.t_fds_inv(); } }) } +/* Reorder items via drag. The DOM swap happens inside the Sortable during the drag; we commit + the new order once, reliably, on drop (onend) — that recomputes positions/totals and pushes the + changed block(s) to the backend session (t_fds_inv -> syncChanged). Committing on drop (rather + than on every mid-drag hover-swap) avoids rebuilding the row that is currently being dragged. */ +$inv.bdysort = (i, e) => { $(e).Sortable({ dragItem: false, dragHandleClass: 'ico', parentident: 'tr', onend: () => { $inv.t_fds_inv(); } }) } $inv.rrw = function () { let rw = $(this), dta = rw.data(), co = {}, ph = rw.is('.placeholder'), hn = rw.is('.hidenote'); let oHtml = (e) => $$.d().append(e).html(); diff --git a/Fuchs/wwwroot/web/fis.inv.de.min.js b/Fuchs/wwwroot/web/fis.inv.de.min.js index d29d27c..dbceaf4 100644 --- a/Fuchs/wwwroot/web/fis.inv.de.min.js +++ b/Fuchs/wwwroot/web/fis.inv.de.min.js @@ -1 +1 @@ -let $rct={mdl:"Aufträge",or:"offene Aufträge",orr:"offene Aufträge (4 W)",rn:"Auftragsnummer",iov:{all:"Auftragsübersicht (alle)","":"Auftragsübersicht"},wk:"Woche",nd:"Keine Daten gefunden.",h:"Uhr",rq1:"Auftragsdaten werden von MFR abgerufen.\nDer Vorgang kann bis zu 90Sek dauern.",rq2:"Auftragsdaten werden geladen",rq1f:"Die Auftragsdaten von MFR konnten nicht oder nicht schnell genug abgerufen werde.\nMöchten Sie mit den bestehenden Daten trotzdem weitermachen?",note1:"Im Bruttobetrag sind {0} Lohnkosten enthalten (netto {1}). Die darin enthaltene Umsatzsteuer beträgt {2}.",note2:"Bitte beachten Sie, nach §14 Abs. 1 Umsatzsteuergesetz ist diese Rechnung ein Zahlungsbeleg oder eine andere beweiskräftige Unterlage für 2 Jahre nach Ablauf des Kalenderjahres der Ausstellung dieser Rechnung aufzubewahren, soweit nicht aufgrund anderer gesetzlicher Regelungen andere ggf.längere Aufbewahrungsfristen gelten.",note3:"Privathaushalten erstattet das Finanzamt bis zu {0} des Arbeitslohns mit der nächsten Steuererklärung.",note4:"Für bereits erbrachte Arbeiten, Dienstleistungen, Materiallieferungen und getätigte Bestellvorgänge zum oben genannten Bauvorhaben, die sich aus dem mit Ihnen geschlossenen Vertrag ergeben, stellen wir Ihnen vertragsgemäß unsere Akontozahlung in Rechnung. Eine Endabrechnung erhalten Sie als Schlussrechnung nach Abschluss des gesamten Bauvorhabens. Das Ausführungsdatum entnehmen Sie bitte dem Schlusstext dieser Rechnung. Wir danken Ihnen herzlich für das entgegengebrachte Vertrauen und bitten Sie um kurzfristigen Ausgleich der Akontorechnung.",note13b:"Gem. §13b Umsatzsteuergesetz unterliegen Sie der Steuerschuldnerschaft des Leistungsempfängers zur Umsatzsteuer aus dieser Rechnung mit einem Steuersatz von 19%.",crI:"Rechnung erstellen",crII:"Abschlagsrechnung erstellen",dII:"Für eine Abschlagsrechnung darf nur ein Auftrag gewählt werden.",dnS:"Für eine Rechnung muss mindestens ein Auftrag gewählt werden.",inv:"Rechnung",invs:"Rechnungen",req:"Auftrag",provP:"Leistungszeitraum",provD:"Leistungsdatum",cP:"Position ändern",iRb:"Zeile darunter einfügen",dR:"Zeile löschen",sV:"USt festlegen",cD:"Löschen?",mR:"Zeile verschieben",svcPart:"Service-Anteil",vat:"Umsatzsteuer",combP:"Positionen zusammenfassen",iSum:"Zwischensumme",dtRel:"Freigegeben am: ",dtCr:"Erstellt am: ",rqV:"USt des Auftrags?",cthd:"wirklich aus-/einblenden ?",cst:{style:"currency",currency:"EUR"},sts:{IsWorkDone:"Arbeiten erledigt",Closed:"Auftrag geschlossen",SubcontractorPendingConfirmation:"Warten auf Bestätigung (Unterauftrag)",Scheduled:"Geplant",OfferIsRejected:"Angebot abgelehnt",OfferIsSend:"Offen (Angebot versandt)",CollaborationWaitingConfirmation:"Warten auf Bestätigung (Zusammenarbeit)",Released:"Freigegeben",OfferIsConfirmed:"Bestätigt",InProgress:"In Bearbeitung",ReadyForScheduling:"Zur Planung",Created:"Erstellt",Rejected:"Abgebrochen",Invoiced:"Rechnung gestellt","-":"-"},invHR:["Pos.","Menge","Artikelbezeichnung","VK","Summe"],frm:{invoiceaddress:"Adresse",loc:"Leistungsort / Lieferadresse",invoiceemail:"Email"}},$rcol={req:new fields_definition("Auftrag","Aufträge",[{name:"tags",label:"",type:"string",dfnc:function(e,t){""!==(e||"")&&($(this).aC("tags"),e.split(",").forEach((e=>{""!==e&&$(this).append($$.sc("tag "+e.replace(" ","_").replace("/","_").toLowerCase(),e))})))}},{name:"DateOfCreation",label:"Datum",type:"date",title:function(e){$(this).attr("title",$rct.dtCr+fdt(e.DateOfCreation).ne("-")+" \n"+$rct.dtRel+fdt(e.DateReleased).ne("-"))}},{name:"CustomerName",label:"Kunde (Firma)",type:"string"},{name:"Name",label:"Auftragsname",type:"string"},{name:"ExternalId",label:"Auftragsnummer",type:"string"},{name:"ParentExtenalId",label:"PAuftrag",type:"string"},{name:"InvoiceId",label:"RNummer",type:"string",dfnc:function(e,t){$(this).rwText(e," ").find("span").each((function(){$(this).aC("cla").click({id:$(this).text()},$inv.jdbn)}))}},{name:"State",label:"Status",type:"string"},{name:"WorkDoneAt",label:"Erledigt am",type:"date"},{name:"Description",label:"Beschreibung",type:"html"}]),itm:new fields_definition("Auftragsposition","Auftragspositionen",[{name:"NameOrNumber",label:"Bezeichnung",type:"string"},{name:"Type",label:"Typ",type:"select",required:!0,value:"Text",url:[{value:"Text",label:"Text"},{value:"Equipment",label:"Ausrüstung"},{value:"Material",label:"Material"},{value:"Service",label:"Arbeitsleistung"}],change:function(e){$req.quantChange.call(this,e)}},{name:"quantityhours",label:"Anzahl / Menge",type:"number",precision:"0.01",value:1,change:function(e){$inv.quantChange.call(this,e)}},{name:"UnitString",label:"Einheit",type:"select",url:["LFDM","Stck","Std.","QM","AW","Pauschal"],change:function(e){$inv.quantChange.call(this,e)}},{name:"net",label:"EinzelPreis netto",type:"number",precision:"0.01",value:0,change:function(e){$inv.quantChange.call(this,e)}},{name:"net_val",label:"GesamtPreis netto",type:"number",precision:"0.01",value:0},{name:"vat_val",label:"GesamtPreis USt",type:"number",precision:"0.01",value:0},{name:"svcnet_val",label:"Arbeitslohn netto",type:"number",precision:"0.01",value:0},{name:"svcvat_val",label:"Arbeitslohn USt",type:"number",precision:"0.01",value:0},{name:"net_pos",label:"Netto",type:"string"},{name:"bo_pos",label:"Brutto",type:"string"},{name:"vat",label:"USt",type:"string",value:"19,0%",change:function(e){$inv.quantChange.call(this,e)}},{name:"Note",label:"Details",type:"html",tinymce:!0}])},$ict={mdl:"Rechnungen",iov:{all:"Rechnungen (alle)","":"Rechnungen (nur fertige)","#d":"Rechnungen (nur Entwürfe)","#u":"Rechnungen (nur unbezahlt)","#r":"Rechnungen (nur angemahnt)","#a":"Rechnungen (nur Akonto)","#c":"Rechnungen (nur Storno)","#ru":"Rechnungen (nur angemahnt + unbez.)"},uba:", gesamter Zeitraum)",req:"Auftrag",inv:"Rechnung",rem:"Mahnung",in:"Rechnungsnummer",cc:"Kunde",wk:"Woche",nd:"Keine Daten gefunden.",dl:"Herunterladen",ed:"Bearbeiten",ced:"Bearbeitung fortsetzen",sItm:"Einzelheiten anzeigen",sPay:"Zahlungen anzeigen",cdI:"Entwurf der Rechnung löschen?",rel:"Neu Laden",relm:"Bitte laden Sie Liste manuell neu, um die Änderungen zu sehen.",dsp:"Rechnung anzeigen",storno:"Storno-Rechnung erstellen",credit:"Gutschrift erstellen",remd:"Mahnung erstellen",remdt:"Mahnung erstellen zur Rechnung {0}",remlst:"Mahnungen anzeigen",remdsp:"Mahnung anzeigen",remres:"Mahnung erneut senden",remresc:"Mahnung {0} wirklich erneut senden?",remresr:"Mahnung {0} wurde erfolgreich versandt.",setpyd:"Bezahlt markieren",cpyd:"Rechnung wirklich als bezahlt markieren?",setupd:"Bezahlt-Markierung aufheben",cupd:"Bezahlt-Markierung wirklich aufheben?",ivE:"Die Email-Adresse ist vermutlich nicht gültig.",ivEc:"\nMöchten Sie fortfahren?",pna:"Diese Seite ist in der Vorschau nicht verfügbar",tpe:"Die Anzahl von {0} Seiten wird aktuell nicht unterstützt",eis:"Der Rechnungsentwurf konnte nicht gespeichert werden.",iss:"Zwischenstand speichern.",p13b:"USt -> §13b",setm:"Set-Preisanzeige",setmo:{setprice:"Set mit Preis – Positionen ohne Preis",itemprices:"Positionen mit Preis – Set als Überschrift",setonly:"Nur Set mit Preis – Positionen ausgeblendet"},ctp:"Ansprechpartner festlegen",mfr:"Von MFR neu abrufen",rq1:"Auftragsdaten werden von MFR abgerufen.\nDer Vorgang kann bis zu 90Sek dauern.",rq2:"Auftragsdaten werden geladen",iq1:"Rechnungsdaten werden von MFR abgerufen.\nDer Vorgang kann bis zu 90Sek dauern.",iq2:"Rechnungsdaten werden geladen",sis:"Rechnung als versandt markieren",srs:"Mahnung als versandt markieren",sisc:"Rechnung wirklich als versandt markieren?",srsc:"Mahnung wirklich als versandt markieren?",iSt:{dft:"Entwurf",uns:"nicht versandt",pyd:"bezahlt",cc:"storniert",op:"offen",due:"fällig",ovd:"überfällig",rem:"angemahnt"},rSt:["","Überfällig","2. Mahnung","3. Stufe"],pSt:{a:"Vollst.",p:"Teilz."},ivT:{i:"AbschlagsR.",f:"SchlussR",r:"Rechnung",c:"StornoR."},rovlh:"Übersicht der bisherigen Mahnungen",rovl:["Betreff","Betrag","Betrag gezahlt","fertiggestellt am"],remHR:["Rechnung","vom","Rechnungsbetrag","bereits bezahlt","noch offen"],remt:{f:["Sehr geehrte Damen und Herren,","ein Mahnschreiben sollte kurz, freundlich und erfolgreich sein. Kurz ist es, freundlich sowieso; ob es auch erfolgreich ist, hängt von Ihnen ab."],m:["Sehr geehrte Damen und Herren,","nun müssen wir Sie noch einmal anschreiben.","Wahrscheinlich haben Sie triftige Gründe dafür, warum Sie die Zahlung unserer Forderung nicht vornehmen und auch nicht auf unsere Mahnung reagieren. Sollten wir darüber nicht einmal sprechen?","Bitte nehmen Sie umgehend in dieser Sache mit uns Kontakt auf."],l:["Sehr geehrte Damen und Herren,",'Eine DRITTE MAHNUNG zu erhalten bereitet Ihnen bestimmt ebenso wenig Freude wie uns, sie zu verschicken. Leider haben wir auf unsere zweite Mahnung noch keine Antwort von Ihnen erhalten.", "Wir bitten Sie, den offenen Betrag innerhalb der nächsten 7 Werktage nach Erhalt dieses Schreibens zu begleichen. Nach Ablauf dieser Frist erfolgt keine weitere Mahnung mehr.',"Sollte die Forderung bis dahin nicht beglichen sein, eröffnen wir das gerichtliche Mahnverfahren. Sollten Sie die Rechnung inzwischen beglichen haben, so betrachten Sie bitte dieses Schreiben als gegenstandslos."]},remt2:{f:["Wir bitten Sie, den noch offenen Rechnungsbetrag innerhalb einer Woche auf unser Konto zu überweisen.","Sollten Sie den Betrag bereits überwiesen haben, so bitten wir Sie, diese Zahlungserinnerung als gegenstandslos zu betrachten."],m:["Um Ihnen zusätzliche Kosten für weitere Mahnungen zu ersparen, bitten wir Sie nunmehr um die Überweisung des noch zu zahlenden Gesamtbetrages inklusive der ggf. bereits fälligen Mahnzinsen und Mahngebühren innerhalb von einer Woche."],l:[]},payi:{account:"Konto",name:"Zahler",text:"Verw.Zweck",InvoiceID:"Rechnung",amount:"Betrag",date:"Datum",manual:"Typ"}},$invcol={datev:new fields_definition("Rechnung","Rechnungen",[{name:"Umsatz (ohne Soll/Haben-Kz)",label:"Umsatz (ohne Soll/Haben-Kz)",type:"string"},{name:"vf",label:"vf",type:"string"},{name:"Soll/Haben-Kennzeichen",label:"Soll/Haben-Kennzeichen",type:"string"},{name:"Konto",label:"Konto",type:"string"},{name:"Gegenkonto",label:"Gegenkonto",type:"string"},{name:"BU-Schlüssel",label:"BU-Schlüssel",type:"string"},{name:"Belegdatum",label:"Belegdatum",type:"string"},{name:"Belegfeld 1",label:"Belegfeld 1",type:"string"},{name:"Belegfeld 2",label:"Belegfeld 2",type:"string"},{name:"Buchungstext",label:"Buchungstext",type:"string"}]),inv:new fields_definition("Rechnung","Rechnungen",[{name:"invstatus",label:"Status",type:"select",url:$ict.iSt},{name:"balance",label:"Umsatz",type:"string",dtype:"currency"},{name:"CustomerName",label:"Kunde",type:"string"},{name:"InvoiceId",label:"RNummer",type:"string"},{name:"InvoiceType",label:"Typ",type:"select",url:$ict.ivT},{name:"request",label:"Auftrag",type:"string",dtype:"num"},{name:"vat",label:"MwSt",type:"string",dtype:"num"},{name:"deb_cred",label:"Soll/Haben",type:"string"},{name:"customer",label:"Konto",type:"string",dtype:"num"},{name:"contra_account",label:"Gegenkonto",type:"string",dtype:"num"},{name:"Belegdatum",label:"Belegdatum",type:"date"},{name:"reminderstatus",label:"MahnStatus",type:"select",url:$ict.rSt},{name:"reminder",label:"# Mahnungen",type:"integer"},{name:"Buchungstext",label:"Buchungstext",type:"string"},{name:"Payment",label:"Zahlung",type:"string"}]),rem:new fields_definition("Zahlungserinnerung","Zahlungserinnerung",[{name:"amount",label:"Rechnungsbetrag",type:"number",precision:"0.01",value:1},{name:"amount_payed",label:"bereits bezahlt",type:"number",precision:"0.01",value:1}]),rem2:new fields_definition("Zahlungserinnerung","Zahlungserinnerung",[{name:"DocumentName",label:"Name",type:"string"},{name:"subject",label:"Betreff",type:"string"},{name:"DateSent",label:"Versanddatum",type:"date"},{name:"status",label:"Status",type:"string"},{name:"amount_open",label:"offener Betrag",type:"number",precision:"0.01"},{name:"InvoiceId",label:"RNummer",type:"string"}]),rid:new fields_definition("Zahlungserinnerung","Zahlungserinnerung",[{name:"type",label:"Typ",type:"select",url:[["f","einfache Zahlungserinnerung"],["m","Mahnung"],["l","letzte Mahnung"]],required:!0},{name:"level",label:"Stufe",type:"select",url:[["1","Stufe 1"],["2","Stufe 2"],["3","Stufe 3"],["4","Stufe 4"],["5","Stufe 5"],["6","Stufe 6"]],required:!0}]),ctp:new fields_definition("Ansprechpartner","Ansprechpartner",[{name:"name",label:"Name",type:"string"},{name:"email",label:"Email",type:"string"}])},gi=(e,t)=>$$.sc("glyphicon glyphicon-"+e).aC(t),$inv={init2:function(e,t){e=e||"inv",t=t||{},$ocms.getScript([],(function(){$inv.init3(e,t)}))},init3:async function(e,t){$fis.cf(!0);let n=$fis.lf(!0);$("#topbar").ocmsmenu([]),$("#activemodule").text($ict.mdl);let i=[(async()=>{await $fis.getAuth("fds_inv")>0&&($inv.prepLst(""),n.aC("fix"))})(),new Promise(((e,t)=>{$fis.prepAuth(["fds_reminder"])}))];await Promise.all(i)},prepLst:function(e){let t=new Date,n=$fis.lf(!0).ldng(1),i=new Date("2021-01-01");$fis.frm_list().IN((function(){}));let a=[];$.each($ict.iov,((e,t)=>{a.push({lbl:t,fnc:()=>{$inv.prepLst(e),n.aC("fix")}})})),$fis.lfm().ocmsmenu([{lbl:"Filter",itm:a}]);$$.i({placeholder:$ict.in}).appendTo($$.dc("mth ivn",n)).enterKey((function(e){let t=$(this),n=t.val()||"";e.stopPropagation(),t.parent().siblings().rC("selected"),n.length>3&&(t.parent().aC("selected"),$inv.renderinv("i:"+n,"s","all"),t.val(""))})),$$.i({placeholder:$ict.cc}).appendTo($$.dc("mth ivc",n)).enterKey((function(e){let t=$(this),n=t.val()||"";e.stopPropagation(),t.parent().siblings().rC("selected"),n.length>=3&&(t.parent().aC("selected"),$inv.renderinv("c:"+n,"s","all"),t.val(""))}));"#"===e.substr(0,1)&&$$.dc("mth extra",n).text($ict.iov[e].replace(")",$ict.uba)).click((function(t){let n=$(this);if(t.stopPropagation(),n.siblings().rC("selected"),!0===n.is(".selected")){n.toggleClass("selected");let t=fdt(new Date,"yy-MM-dd");$inv.renderinv(t,"a",e)}n.aC("selected")})),n.append("
");let r=$$.dc("mthl",n),l=t.getFullYear(),s=t.getMonth()+1;for(let t=i.getFullYear();t<=l;t++){let n=$$.dc("yr").prependTo(r).text($ict.iov[e]+" - "+t.toString()).toggleClass("selected",t===l);n.click({yr:t},(function(e){e.stopPropagation(),n.siblings().rC("selected"),n.aC("selected")}));let a=$$.dc("mfrm",n);for(let n=0;n<(t!==l?12:s);n++){i=new Date(t,n,1);let r=$$.dc("mth").prependTo(a).text($ict.iov[e]+" - "+fdt(i,"MMM yyyy"));if(r.click({yr:t,mt:n},(function(t){if(t.stopPropagation(),r.siblings().rC("selected"),!0===r.is(".selected")){r.toggleClass("selected");let n=fdt(new Date(t.data.yr,t.data.mt,1),"yy-MM-dd");$inv.renderinv(n,"m",e)}r.aC("selected")})),""===e){$$.dc("mthdl",r).append(gi("compressed","ico")).click({yr:t,mt:n},(function(e){e.stopPropagation();let t=fdt(new Date(e.data.yr,e.data.mt,1),"yy-MM-dd");$inv.downloadzip(t,"m")}))}let l=getMonday(i),s=new Date(i);s.setMonth(s.getMonth()+1),s.setDate(0),s=getMonday(s);let d=$$.dc("wfrm",r);for(;l<=s;){let t=$$.dc("wk",d).text(($ict.wk||"W")+" "+fdt(l,"dd.MM.yy"));t.click({rd:new Date(l)},(function(n){n.stopPropagation();let i=fdt(n.data.rd,"yy-MM-dd");$inv.renderinv(i,"w",e),r.siblings().rC("selected").find(".wk").rC("selected"),r.aC("selected").find(".wk").rC("selected"),t.aC("selected")})),$$.dc("wkdl",t).append(gi("compressed","ico")).click({rd:new Date(l)},(function(e){e.stopPropagation();let t=fdt(e.data.rd,"yy-MM-dd");$inv.downloadzip(t,"w")})),l.setDate(l.getDate()+7)}}}n.ldng(0)},rerenderinv:function(){let e=$("#contentframe .invfrm:first");if(e.length>0){let t=e.data("sets")||{};t.mode&&$inv.renderinv(t.tgt,t.mode,t.includes)}},renderinv:function(e,t,n){let i=$fis.frm_list(!0,!0).ldng(1),a=$$.dc("invfrm",i).aC("md"+t).data("sets",$.extend({},{tgt:e,mode:t,includes:n})),r=$fis.lf();$ocms.postXT({url:$ocms.url("inv/invl"),data:{mode:t,tgt:e,includes:n},success:i=>{r.rC("fix").aC("hd"),$$.dc("ovhd",a).text(i.admin.title);let l=$$.tblset({},a),s=$invcol.inv,d=$$.tr(l.hd);$$.th(d);$.each(s.fields||[],((e,t)=>{$$.th(d).text(t.label),"vat"===t.name&&$$.th(d)})),$.each(i.invoices||[],((d,c)=>{let o=$$.tr(l.bdy);o.click((function(){r.rC("fix").aC("hd"),o.toggleClass("selected").siblings().rC("selected").find("td.av").rC("av"),o.find("td.av").rC("av"),!0===o.is(".selected")?$inv.iMn(c):$inv.eM()}));let u=$$.td(o,{class:"raux"});c.hasFile?($$.dc("idl ilbtn",u,{title:$ict.dl+"\n"+c.DocumentName}).append(gi("save-file","ico")).click({id:c.Id},$inv.downloadinv),$$.dc("idl ilbtn",u,{title:$ict.dsp+"\n"+c.DocumentName}).append(gi("eye-open","ico")).click({id:c.Id,typ:"inv"},$inv.jdisp)):!1===c.isFinal&&!0===$fis.isAuth("fds_inv",2)&&$$.dc("idl ilbtn",u,{title:$ict.ed}).append(gi("edit","ico")).click({id:c.Id},$inv.doContInv),$$.dc("iitm ilbtn",u,{title:$ict.sItm}).append(gi("list","ico")).click({id:c.Id},$inv.showitm),$$.dc("iitm ilbtn",u,{title:$ict.sPay}).append(gi("euro","ico")).click({id:c.Id},$inv.showpay),$.each(s.fields||[],((r,l)=>{let s,d,u=$$.td(o).aC(l.dtype);switch("select"===(l.type||"")?u.text((l.url||{})[c[l.name]]||""):u.text(c[l.name]),l.name||""){case"vat":s=$$.sel().appendTo($$.td(o,{class:"vsel"})),d=(i.admin.ust_options||"19,0%;16,0%;0,0%").split(";"),$.each(d,((e,t)=>{$$.opt(t,t).appendTo(s)})),s.click((function(e){e.stopPropagation()})).val(c[l.name]).change().change({frm:a,tgt:e,mode:t,id:c.Id,td:u,includes:n},$inv.setvat),u.toggleClass("hl",c[l.name].substr(0,2)!==d[0].substr(0,2)).click((function(e){e.stopPropagation(),$(this).toggleClass("av")}));break;case"balance":u.aC("sh_"+(c.SollHaben||"").toLowerCase());break;case"invstatus":case"reminderstatus":u.aC(("invstatus"===l.name?"is_":"rs_")+c[l.name])}}))}))},complete:()=>{i.ldng(0)}})},setvat:function(e){let t=$(this),n=e.data||{};$ocms.postXT({url:$ocms.url("inv/setvat"),data:{id:n.id,val:t.val()},success:e=>{n.td.rC("av"),$inv.renderinv(n.tgt,n.mode,n.includes)}})},downloadzip:function(e,t){$(this).empty();window.open($ocms.url("inv/datevzip?mode="+t+"&tgt="+encodeURIComponent(e)),"_blank")},showitm:function(e){let t=$(this).closest("tr");e.stopPropagation(),!1!==t.is(".selected")&&$ocms.postXT({url:$ocms.url("inv/rqi"),data:{id:e.data.id},success:e=>{let t=$$.dc("rfrm");(e.requests||[]).length<1?t.text($ict.nd):$.each(e.requests||[],(function(e,n){let i=$$.dc("srq",t);$$.dc("nme",i).text(n.name);let a=$$.tblset({class:"if"},i);$.each(n.items||[],((e,t)=>{let n=$$.tr({id:"itm"+t.Id}).appendTo(a.bdy);$$.td(n).text(t.NameOrNumber),$$.td(n).text(t.Type),$$.td(n).aC("currency").text(t.net_pos),$$.td(n).aC("currency").text(t.bo_pos),$$.td(n).aC("num").text(t.vat)}))})),$ocms.dlg(t,{width:1e3})}})},showpay:function(e){let t=$(this).closest("tr");e.stopPropagation(),!1!==t.is(".selected")&&$ocms.postXT({url:$ocms.url("inv/pyi"),data:{id:e.data.id},success:e=>{let t=$$.dc("rfrm");if((e.payments||[]).length<1)t.text($ict.nd);else{let n=$$.tblset({class:"if"},t),i=$$.tr(n.hd);$.each(["date","account","name","text","InvoiceID","amount","manual"],((e,t)=>{$$.th(i,$ict.payi[t])})),$.each(e.payments,((e,t)=>{let i=$$.tr({id:"itm"+t.banking_uid}).appendTo(n.bdy);$$.td(i).aC("date").text(t.date),$$.td(i).text(t.account),$$.td(i).text(t.name),$$.td(i).text(t.text),$$.td(i).text(t.InvoiceID),$$.td(i).aC("currency").text(t.amount),$$.td(i).text(t.manual)}))}$ocms.dlg(t,{width:1e3,title:"Übersicht der Zahlungen"})}})},downloadinv:function(e){let t=$(this).closest("tr");e.stopPropagation(),!1!==t.is(".selected")&&window.open($ocms.url("inv/rdoc?id="+e.data.id),"_blank")},doContInv:function(e){let t=$(this).closest("tr");e.stopPropagation(),!1!==t.is(".selected")&&$inv.cntInv({id:e.data.id})}},$$inv={init2:$inv.init2,auth:{}};export default $$inv;$inv.cInv=function(e){let t=$(this).closest("tr");e.stopPropagation(),!1!==t.is(".selected")&&!1!==$fis.isAuth("fds_inv",2)&&$inv.cInv2({id:e.data.id})},$inv.rMn=e=>{let t=[{lbl:$ict.req,itm:[]}];return!0===bool(e,!1)&&!0===$fis.isAuth("fds_inv",2)&&Array.prototype.push.apply(t[0].itm,[{lbl:$rct.crI,fnc:$inv.ccInv,data:{typ:"r"}},{lbl:$rct.crII,fnc:$inv.ccInv,data:{typ:"i"}}]),t.push({lbl:$ict.rel,fnc:$inv.rReload}),$("#topbar").ocmsmenu(t)},$inv.iMnr=e=>{let t=booln(e.isFinal,!0),n=e.Id,i=booln(e.fds,!1),a=[{glyph:"glyphicon-menu-left",fnc:()=>{$fis.frm_edit().remove()}},{lbl:$ict.inv,itm:[]},{lbl:$ict.rem,itm:[]}];return!1===t&&!0===$fis.isAuth("fds_inv",2)?a[1].itm.push({lbl:$ict.ced,fnc:$inv.clCntInv}):!0===$fis.isAuth("fds_inv",1)&&a[1].itm.push({lbl:$ict.dsp,fnc:()=>$inv.disp(n,"inv")}),!0===i&&!0===t&&!0===$fis.isAuth("fds_inv",2)&&(a[1].itm.push({lbl:$ict.storno,fnc:()=>$inv.storno(n,i)}),a[1].itm.push({lbl:$ict.credit,fnc:()=>$inv.credit(n,i)})),!0===t&&!0===$fis.isAuth("fds_reminder",2)&&(a[2].itm.push({lbl:$ict.remd,fnc:()=>$inv.ccRem(n,e.InvoiceId)}),a[2].itm.push({lbl:$ict.remlst,fnc:()=>$inv.dspRem(n)})),!0===t&&!0===$fis.isAuth("fds_reminder",2)&&!1===booln(e.IsSent,!1)&&a[2].itm.push({lbl:$ict.srs,fnc:()=>$inv.srs(n)}),a.push({lbl:$ict.rel,fnc:$inv.rReload}),$("#topbar").ocmsmenu(a)},$inv.iMn=e=>{let t=booln(e.isFinal,!0),n=e.Id,i=booln(e.fds,!1),a=[{glyph:"glyphicon-menu-left",fnc:()=>{$fis.frm_edit().remove()}},{lbl:$ict.inv,itm:[]},{lbl:$ict.rem,itm:[]}];return!1===t&&!0===$fis.isAuth("fds_inv",2)?a[1].itm.push({lbl:$ict.ced,fnc:()=>{$inv.cntInv({id:n})}}):!0===$fis.isAuth("fds_inv",1)&&a[1].itm.push({lbl:$ict.dsp,fnc:()=>$inv.disp(n,"inv")}),!0===$fis.isAuth("fds_inv",2)&&(a[1].itm.push({lbl:$ict.storno,fnc:()=>$inv.storno(n,i)}),a[1].itm.push({lbl:$ict.credit,fnc:()=>$inv.credit(n,i)})),!0===t&&!1===booln(e.IsPayed,!1)?(!0===$fis.isAuth("fds_reminder",2)&&a[2].itm.push({lbl:$ict.remd,fnc:()=>$inv.ccRem(n,e.InvoiceId)}),!0===$fis.isAuth("fds_inv",2)&&a[1].itm.push({lbl:$ict.setpyd,fnc:()=>$inv.setPyd(n)})):!0===t&&!0===booln(e.IsPayed,!1)&&"m"===(e.PaymentStatus||"")&&!0===$fis.isAuth("fds_inv",2)&&a[1].itm.push({lbl:$ict.setupd,fnc:()=>$inv.setUpd(n)}),!0===$fis.isAuth("fds_reminder",2)&&a[2].itm.push({lbl:$ict.remlst,fnc:()=>$inv.dspRem(n)}),!0===t&&!0===$fis.isAuth("fds_inv",2)&&!1===booln(e.IsSent,!1)&&a[1].itm.push({lbl:$ict.sis,fnc:()=>$inv.sis(n)}),!1===i&&a[1].itm.push({lbl:$ict.mfr,fnc:()=>$inv.mfrrel(n)}),$("#topbar").ocmsmenu(a)},$inv.eM=(e,t,n)=>{let i=[];return!0!==booln(e,!1)&&!0!==booln(t,!1)||i.push({glyph:"glyphicon-menu-left",fnc:()=>{$fis.lf(!0),$fis.frm_edit().remove()}}),!0===(n||"").split(",").includes("iss")&&i.push({lbl:$ict.iss,fnc:$inv.ssave}),!0===(n||"").split(",").includes("ctp")&&i.push({lbl:$ict.ctp,fnc:$inv.sctp}),!0===(n||"").split(",").includes("p13b")&&i.push({lbl:$ict.p13b,fnc:$inv.sp13b}),!0===(n||"").split(",").includes("setm")&&i.push({lbl:$ict.setm,fnc:$inv.ssetmode}),!0===(n||"").split(",").includes("iss")&&(i.push({lbl:"Änderungshistorie",fnc:()=>$inv.d.history()}),i.push({lbl:"Änderungen verwerfen",fnc:()=>$inv.d.discard()})),!0===booln(e,!1)&&i.push({lbl:$ict.rel,fnc:$inv.rReload}),$("#topbar").ocmsmenu(i)},$inv.d={tbl:()=>$("div.invoice_layout table.invi"),layout:()=>$("div.invoice_layout"),token:function(){return $inv.d.tbl().data("dtoken")||""},hashes:function(){let e=$inv.d.tbl().data("bai")||[],t={};return $.each(e,((e,n)=>{t[(n.Id||"").toString()]=JSON.stringify(n)})),t},seed:function(e){let t=$inv.d.layout();t.aC("freeze"),$ocms.postXT({url:$ocms.url("inv/dopen"),data:{payload:JSON.stringify(e)},success:e=>{$inv.d.tbl().data("dtoken",e.token).data("dver",e.version).data("dhashes",$inv.d.hashes()),$fis.draft.bind(e.token,{onReady:()=>$inv.d.refresh(),onExpiring:e=>$inv.d.warnExpiry(e),onClosed:e=>$inv.d.closed(e)}),$inv.d.refresh()},error:()=>{t.rC("freeze")},complete:()=>{$inv.d.tbl().removeData("dseeding")}})},refresh:function(e){let t=$inv.d.token();""!==t&&$ocms.postXT({url:$ocms.url("inv/dstate"),data:{token:t},success:t=>{$inv.d.applyState(t),"function"==typeof e&&e(t)},error:e=>{e&&410===e.status&&$inv.d.closed("expired")},complete:()=>{$inv.d.layout().rC("freeze")}})},applyState:function(e){let t=$inv.d.tbl();t.length<1||(t.data("dver",e.version).data("serverSums",e.sums),$inv.d.footer(t,e.sums||{},e.admin||{}),$inv.d.validation(e.validation||[]))},sync:function(e){let t=$inv.d.token();""!==t&&($inv.d.layout().aC("freeze"),$ocms.postXT({url:$ocms.url("inv/dpatch"),data:{token:t,delta:JSON.stringify(e)},success:()=>{$inv.d.refresh()},error:e=>{$inv.d.layout().rC("freeze"),e&&410===e.status&&$inv.d.closed("expired")}}))},syncChanged:function(e){if(""===$inv.d.token())return;let t=e.data("bai")||[],n=e.data("dhashes")||{},i={},a=[],r=[];$.each(t,((e,t)=>{let r=(t.Id||"").toString(),l=JSON.stringify(t);i[r]=l,n[r]!==l&&a.push(t)})),$.each(n,(e=>{void 0===i[e]&&r.push(e)})),e.data("dhashes",i),a.forEach((e=>$inv.d.sync({Target:"block.replace",Ref:(e.Id||"").toString(),Value:e}))),r.forEach((e=>$inv.d.sync({Target:"block.remove",Ref:e})))},syncField:function(e,t){if(""===$inv.d.token())return;let n={invoicetitle:"title",invoiceaddress:"address",invoiceemail:"email",loc:"provisionlocation",provisionlocation:"provisionlocation",provisionperiod:"provisionperiod"}[e];n&&$inv.d.sync({Target:n,Value:t})},footer:function(e,t,n){let i=e.children("tfoot").empty();e.nextAll(".fnote").remove();let a=bool(n.p13b,!1),r=(e,t,n)=>$$.tdc("currency",$$.tr(i,{class:n||"tsum"}).append([$$.tdc("aux"),$$.td({colspan:4}).text(e)]),fnum(t,$rct.cst)),l=t=>$$.dc("fnote").insertAfter(e).rwText(t);r("Netto",t.total_net||0),!1===a&&$.each(t.vat||{},((e,t)=>r($rct.vat+" "+e+"%",t,"tvat"))),r("Summe",t.total_gross||0);let s=n.type||"";"i"===s?(l($rct.note2),l($rct.note4)):"c"===s?l($rct.note2):(l(string($rct.note3,[fnum(((t.service_net||0)+(t.service_vat||0))*(n.tax_servicerefund||0),$rct.cst)])).aC("ntax"),l($rct.note2),l(string($rct.note1,[fnum((t.service_net||0)+(t.service_vat||0),$rct.cst),fnum(t.service_net||0,$rct.cst),fnum(t.service_vat||0,$rct.cst)]))),!0===a&&l($rct.note13b)},validation:function(e){let t=$("div.invoice_layout");if(t.length<1)return;let n=t.children(".dvalidation");n.length<1&&(n=$$.dc("dvalidation"),t.prepend(n)),n.empty().tC("hidden",(e||[]).length<1),$.each(e||[],((e,t)=>$$.dc("dvmsg",n).aC(t.severity).text(t.message)))},preview:function(){let e=$inv.d.token();if(""===e)return;let t=$inv.d.layout(),n=($inv.d.tbl().data("new")||{}).invoiceemail||"";!1===$fis.ValidateEmail(n)&&!1===bool(confirm($ict.ivE+$ict.ivEc),!1)||(t.aC("freeze"),$ocms.postXT({url:$ocms.url("inv/dpreview"),data:{token:e},success:n=>{t.rC("freeze");let i=$$.dc("imagecollection pdfpreview"),a=Math.round(.88*vh()),r=n.total;r>10&&$$.dc("note warn",i).text($ict.tpe),$.each(n.img||[],((e,t)=>{$$.dc("pdfp",i).append($$.img(t).css("max-height",(a-rpx(6)).toString()+"px"))}));for(let e=(n.img||[]).length+1;e<=r;e++)$$.dc("pdfp ph",i).append($$.dc("note",$ict.pna));$ocms.dlg(i,{size:[a,Math.round(.88*vw())],zindex:50,form:!1,button:$rct.crI,confirm:function(n){let i=$(this);t.aC("freeze"),$ocms.postXT({url:$ocms.url("inv/dsave"),data:{token:e},success:e=>{$ocms.postXT({url:$ocms.url("req/sconf"),data:{id:e.invid},success:t=>{i.trigger("modal_close"),!0===t.hasFile&&window.open($ocms.url("req/idoc")+"?id="+e.invid,"_blank"),$inv.d.close(),$ocms.init("req"),$inv.rReload()},error:()=>{alert($t.f1),i.trigger("modal_close")},complete:()=>{t.rC("freeze")}})},error:()=>{t.rC("freeze"),alert($ict.eis)}})},cancel:function(e){confirm($ict.cdI)&&($inv.d.close(),$inv.rReload())}})},error:()=>{t.rC("freeze"),alert($ict.eis)}}))},save:function(){let e=$inv.d.token();if(""===e)return;let t=$inv.d.layout();t.aC("freeze"),$ocms.postXT({url:$ocms.url("inv/dsave"),data:{token:e},success:e=>{$inv.d.tbl().data("invid",e.invid)},error:()=>{alert($ict.eis)},complete:()=>{t.rC("freeze")}})},history:function(){let e=$inv.d.token();""!==e&&$ocms.postXT({url:$ocms.url("inv/dhistory"),data:{token:e},success:e=>{let t=$$.dc("dhist");if((e.history||[]).length<1)$$.dc("note",t).text("Noch keine Änderungen erfasst.");else{let n=$$.tblset({class:"invtbl fullwidth"},t);$$.tr(n.hd).append([$$.th().text("Zeit"),$$.th().text("Feld"),$$.th().text("Alt"),$$.th().text("Neu")]),$.each(e.history,((e,t)=>$$.tr(n.bdy).append([$$.tdc("keep",fdt(t.timestamp)),$$.td().text(t.target),$$.td().text(t.oldValue),$$.td().text(t.newValue)])))}$ocms.dlg(t,{width:800,form:!1})}})},discard:function(){let e=$inv.d.tbl().data("invid")||"";""!==e?!1!==confirm("Alle Änderungen verwerfen und den zuletzt gespeicherten Stand neu laden?")&&($inv.d.close(),$inv.cntInv({id:e})):alert("Es wurde noch kein Zwischenstand gespeichert, der wiederhergestellt werden könnte.")},warnExpiry:function(e){let t=Math.max(1,Math.round((e||0)/60));$fis.notifications.push({severity:"info",title:"Entwurf läuft ab",message:"Der Rechnungsentwurf läuft in etwa "+t+" Minute(n) ab. Bitte zwischenspeichern, sonst gehen die Änderungen verloren."})},closed:function(e){let t=$inv.d.token();$inv.d.tbl().removeData("dtoken"),""!==t&&$fis.draft.release(t),$fis.frm_edit().remove(),$fis.lf(!0),$fis.notifications.push({severity:"error",title:"Entwurf geschlossen",message:"expired"===e?"Der Rechnungsentwurf ist wegen Inaktivität abgelaufen. Nicht gespeicherte Änderungen sind verloren.":"Der Rechnungsentwurf wurde geschlossen."});try{$inv.rReload()}catch(e){}},close:function(){let e=$inv.d.token();""!==e&&($ocms.postXT({url:$ocms.url("inv/dclose"),data:{token:e}}),$fis.draft.release(e)),$inv.d.tbl().removeData("dtoken")}},$inv.cInv2=function(e){let t=$$.dc("rfrm").ldng(1),n=$ocms.dlg(t,{width:1e3});n&&n.ft.rwText($rct.rq1);let i=()=>{$ocms.postXT({url:$ocms.url("req/get"),timeout:60,data:{id:e.id,mode:"r"},success:t=>{t.admin=t.admin||{};let n=$fis.lf(!0).aC("fix").rC("hd");if($fis.frm_edit().IN(),$inv.eM(!0,!0),(t.requests||[]).length<1)n.aC("fix").text($rct.nd);else{$$.dc("lh",n,$rct.mdl);let i=$$.d(),a=$$.ul({class:"rql"}).data({search:e.id,parent:t.admin.parent}).appendTo(n),r={},l=$rcol.req.lbl();$.each(t.requests||[],(function(e,t){let n=$$.li({class:"cli rli"}).data($.extend({},t)).appendTo(a),s=$$.dc("lihd",n).addClass(t.state);!0===booln(t.open,!1)&&s.append($$.sc("cbox").click((()=>{n.tC("checked"),i.find("li").rC("checked"),!0===n.is(".checked")?$inv.rMn(t.open):$inv.eM(!0)}))),s.append([$$.sc("eid",t.ExternalId),$$.sc("nme",t.Name)]),$$.dc("lidt",n).append([$$.dc("rqs").append([$$.s(l.State+": "),$$.s($rct.sts[t.State||"-"])]),$$.dc("ivn").append([$$.s(l.InvoiceId+": "),$$.s(t.InvoiceId||"- -")]),$$.dc("wda").append([$$.s(l.WorkDoneAt+": "),$$.s(fdt(t.WorkDoneAt,"dd.MM.yyyy"))])]),r[t.Id]=n})),(t.inv||[]).length>0&&($$.dc("lh",n,$rct.invs),i=$$.ul({class:"ivl"}).appendTo(n),$.each(t.inv||[],((e,t)=>{let n=$$.li({class:"cli ili"}).data($.extend({},t)).appendTo(i),r=$$.dc("lihd",n).addClass(t.invstatus);!1===booln(t.isFinal,!0)?r.append($$.sc("cbox").click((()=>{""!==(t.Id||"")&&(n.tC("checked").siblings().rC("checked"),a.find("li").rC("checked"),!0===n.is(".checked")?$inv.iMnr(t):$inv.eM(!0))}))):["","dft"].indexOf(t.invstatus)<0&&r.append($$.sc("dli").click((function(){$inv.disp(t.Id,"inv")}))),r.append($$.sc("nme",t.DocumentName||t.Id)),$$.dc("lidt",n).append([$$.dc("wda").append([$$.s(fdt(t.DateCreated,"dd.MM.yyyy"))]),$$.d().text($ict.iSt[t.invstatus]||t.invstatus)])})))}},complete:()=>{n&&n.c.trigger("modal_close")}})};$ocms.postXT({url:$ocms.url("req/pget"),timeout:90,data:{id:e.id},success:e=>{n&&n.ft.rwText($rct.rq2),i()},error:()=>{confirm($rct.rq1f)?(n&&n.ft.rwText($rct.rq2),i()):n&&n.c.trigger("modal_close")}})},$inv.ccInv=function(e){let t=(e.data||{}).typ||"r",n=$fis.lf(),i=n.children("ul.rql"),a=i.data("parent"),r=[];if(i.find("li.rli.checked").each((function(){r.push($(this).data("Id"))})),r.length<1)return void alert($rct.dnS);if("i"===t&&r.length>1)return void alert($rct.dII);let l=$fis.frm_edit(),s=$$.dc("invoice_layout",l).append($$.dc("btn sprev").click($inv.sprev)),d=$fis.cf().width()>s.width()+n.width()+20;n.tC("fix",d).tC("hd",!d),$inv.eM(!1,!0);let c=$$.dc("rfrm").ldng(1),o=$ocms.dlg(c,{width:1e3});o.ft.rwText($rct.rq2),$ocms.postXT({url:$ocms.url("req/iget"),timeout:60,data:{id:a,mode:"ful",typ:t,sel:r.join(",")},success:e=>{let t=$$.dc("srq",s),n=$$.tblset({class:"invi"},t);n.bdy.remove(),n.ft=$$[0]("tfoot"),e.admin=e.admin||{},e.admin.p13b=bool(e.admin.p13b||"",!0===((e.inv||{}).InvoiceOptions||"").split(",").includes("§13b")),n.tbl.data($.extend({new:{},sms:{},itm:{}},{admin:e.admin,companies:e.companies,locations:e.locations}));let i=$$.tr(n.hd).aC("shd").append([$$.th().aC("aux")]);$rct.invHR.forEach((e=>$$.th(i,e))),n.tbl.on("fds.inv",$inv.invSumUpdate),$.each(e.requests||[],(function(t,i){if(0!==(i.Id||0)){let t=$inv.worknotes(i);i.text="i"===e.admin.type?$rct.req+jine([i.ExternalId,i.Name],": ").eine(" ",""):jine([jine([fdt(i.WorkDoneAt,"dd.MM.yy"),i.ExternalId]," - "+$rct.req+" "),t.ne(i.Name)],": \n");let a=$$.tbody(n.tbl).data($.extend({},i));$inv.rendersrq.call(a)}}));let a=$$.tr($$.tbody(n.tbl),{class:"placeholder"}).data({net_val:0,vat_val:0,svcnet_val:0,svcvat_val:0,net:0});$inv.rrw.call(a),n.ft.appendTo(n.tbl);let r,l,d=e.admin||{},c=(e,t,i,a,r)=>{let l=$$.dc("inpfrm",s).aC(e).append("string"==typeof a?$$.dc("ahd",a):a>0?$$.dc("ahd",$rct.frm[i]):null),d=$$.dc("content",l).rwText(t);$$.dc("axf",l).append($$.dc("ibtn edit").data("dialog",$rct.frm[i]).append(gi("pencil")).click($.extend({t:d,nme:i,change:e=>{n.tbl.data("new")[i]=e}},r),$inv.eHtml)),n.tbl.data("new")[i]=t};c("tfrm",d.invoicetitle,"invoicetitle",0,null),c("adrfrm",d.invoiceaddress,"invoiceaddress",0,null),c("locfrm","","loc",1,{list:deepCopy(e.locations),lbl:"ref",property:"address"}),c("emailfrm",d.invoiceemail,"invoiceemail",0,null),$$.dc("sndfrm",s).append($$.dc("content").text(d.sender)),d.provisionend&&(l=d.provisionstart?$rct.provP:$rct.provD,r=d.provisionstart?fdt(d.provisionstart,"dd.MM.yyyy")+" - "+fdt(d.provisionend,"dd.MM.yyyy"):fdt(d.provisionend,"dd.MM.yyyy")),c("admfrm",r,"provisionperiod",l,1),n.tbl.data("new").CustomValues=d.CustomValues||"",$$.dc("inpfrm ctpfrm",s).text(jObj(d.CustomValues,"contactName")),n.tbl.children("tbody").each($inv.bdysort),n.tbl.trigger("fds.inv"),$inv.eM(!1,!0,"iss,p13b,setm,ctp")},complete:()=>{o.c.trigger("modal_close")}})},$inv.ccStInv=function(e){let t=e.data||{},n=$fis.lf(),i=t.id,a=$$.dc("invoice_layout",$fis.frm_edit()).append($$.dc("btn sprev").click($inv.sprev)),r=$fis.cf().width()>a.width()+n.width()+20;n.tC("fix",r).tC("hd",!r),$inv.eM(!1,!0);let l=$$.dc("rfrm").ldng(1),s=$ocms.dlg(l,{width:1e3});s.ft.rwText($ict.iq1),$ocms.postXT({url:$ocms.url("inv/pget"),timeout:90,data:{id:t.id},success:e=>{s&&s.ft.rwText($ict.iq2),$ocms.postXT({url:$ocms.url("inv/icget"),timeout:60,data:{id:i},success:e=>{let t=$$.dc("srq",a),n=$$.tblset({class:"invi"},t);n.bdy.remove(),n.ft=$$[0]("tfoot"),e.admin=e.admin||{},e.admin.p13b=bool(e.admin.p13b||"",!0===((e.inv||{}).InvoiceOptions||"").split(",").includes("§13b")),n.tbl.data($.extend({new:{},sms:{},itm:{}},{admin:e.admin,companies:e.companies,locations:e.locations}));let i=$$.tr(n.hd).aC("shd").append([$$.th().aC("aux")]);$rct.invHR.forEach((e=>$$.th(i,e))),n.tbl.on("fds.inv",$inv.invSumUpdate),$.each(e.requests||[],(function(t,i){if(0!==(i.Id||0)){let t=$inv.worknotes(i);i.text="i"===e.admin.type?$rct.req+jine([i.ExternalId,i.Name],": ").eine(" ",""):jine([fdt(i.WorkDoneAt,"dd.MM.yy")+t.ne(i.Name)],": ");let a=$$.tbody(n.tbl).data($.extend({},i));$inv.rendersrq.call(a)}}));let r=$$.tr($$.tbody(n.tbl),{class:"placeholder"}).data({net_val:0,vat_val:0,svcnet_val:0,svcvat_val:0,net:0});$inv.rrw.call(r),n.ft.appendTo(n.tbl);let l,s,d=e.admin||{},c=(e,t,i,r,l)=>{let s=$$.dc("inpfrm",a).aC(e).append("string"==typeof r?$$.dc("ahd",r):r>0?$$.dc("ahd",$rct.frm[i]):null),d=$$.dc("content",s).rwText(t);$$.dc("axf",s).append($$.dc("ibtn edit").data("dialog",$rct.frm[i]).append(gi("pencil")).click($.extend({t:d,nme:i,change:e=>{n.tbl.data("new")[i]=e}},l),$inv.eHtml)),n.tbl.data("new")[i]=t};c("tfrm",d.invoicetitle,"invoicetitle",0,null),c("adrfrm",d.invoiceaddress,"invoiceaddress",0,null),c("locfrm",d.provisionlocation,"loc",1,{list:deepCopy(e.locations),lbl:"ref",property:"address"}),c("emailfrm",d.invoiceemail,"invoiceemail",0,null),$$.dc("sndfrm",a).append($$.dc("content").text(d.sender)),d.provisionend&&(s=d.provisionstart?$rct.provP:$rct.provD,l=d.provisionstart?fdt(d.provisionstart,"dd.MM.yyyy")+" - "+fdt(d.provisionend,"dd.MM.yyyy"):fdt(d.provisionend,"dd.MM.yyyy")),c("admfrm",l,"provisionperiod",s,1),n.tbl.data("new").CustomValues=d.CustomValues||"",$$.dc("inpfrm ctpfrm",a).text(jObj(d.CustomValues,"contactName")),n.tbl.children("tbody").each($inv.bdysort),n.tbl.trigger("fds.inv")},complete:()=>{s.c.trigger("modal_close")}})},error:()=>{s&&s.c.trigger("modal_close")}})},$inv.clCntInv=function(e){let t=$fis.lf(!1),n=[];t.find("li.ili.checked").each((function(){n.push($(this).data("Id"))})),1===n.length&&$inv.cntInv({id:n[0]})},$inv.cntInv=function(e){e=e||{};$fis.lf(!1).rC("fix").aC("hd");let t=$$.dc("invoice_layout",$fis.frm_edit()).append($$.dc("btn sprev").click($inv.sedit));$inv.eM(!1,!0);let n=$$.dc("rfrm").ldng(1),i=$ocms.dlg(n,{width:1e3});i.ft.rwText($rct.rq2),$ocms.postXT({url:$ocms.url("inv/get"),timeout:60,data:{id:e.id},success:e=>{e.admin=e.admin||{};let n=e.inv||{},i=$$.dc("srq",t),a=$$.tblset({class:"invi"},i);a.bdy.remove(),a.ft=$$[0]("tfoot"),a.tbl.data($.extend({invid:n.Id,new:{},sms:{},itm:{},bai:[]},e));let r=$$.tr(a.hd).aC("shd").append([$$.th().aC("aux")]);$rct.invHR.forEach((e=>$$.th(r,e))),a.tbl.on("fds.inv",$inv.invSumUpdate),$.each(e.req||[],(function(e,t){let n=$$.tbody(a.tbl).data($.extend({},t));$inv.rendersrq.call(n)}));let l=$$.tr($$.tbody(a.tbl),{class:"placeholder"}).data({net_val:0,vat_val:0,svcnet_val:0,svcvat_val:0,net:0});$inv.rrw.call(l),a.ft.appendTo(a.tbl);let s=(e,n,i,r,l)=>{let s=$$.dc("inpfrm",t).aC(e).append("string"==typeof r?$$.dc("ahd",r):r>0?$$.dc("ahd",$rct.frm[i]):null),d=$$.dc("content",s).rwText(n);$$.dc("axf",s).append($$.dc("ibtn edit").data("dialog",$rct.frm[i]).append(gi("pencil")).click($.extend({t:d,nme:i,change:e=>{a.tbl.data("new")[i]=e}},l),$inv.eHtml)),a.tbl.data("new")[i]=n};s("tfrm",n.InvoiceTitle,"invoicetitle",0,null),s("adrfrm",n.SendToAddress,"invoiceaddress",0,null),s("locfrm",n.ProvisionLocation,"loc",1,null),s("emailfrm",n.SendToEmail,"invoiceemail",0,null),$$.dc("sndfrm",t).append($$.dc("content").text(e.admin.sender)),s("admfrm",n.ProvisionPeriod,"provisionperiod",!0===(n.ProvisionPeriod||"").includes("-")?$rct.provP:$rct.provD,1),a.tbl.data("new").CustomValues=n.CustomValues||"",$$.dc("inpfrm ctpfrm",t).text(jObj(n.CustomValues,"contactName")),a.tbl.children("tbody").each($inv.bdysort),a.tbl.trigger("fds.inv"),$inv.eM(!1,!0,"iss,p13b,setm,ctp")},complete:()=>{i.c.trigger("modal_close")}})},$inv.cSt=function(e){e=e||{};let t=$fis.lf(),n=$$.dc("invoice_layout",$fis.frm_edit()).append($$.dc("btn sprev").click($inv.sedit)),i=$fis.cf().width()>n.width()+t.width()+20;t.tC("fix",i).tC("hd",!i),$inv.eM(!1,!0);let a=$$.dc("rfrm").ldng(1),r=$ocms.dlg(a,{width:1e3});r.ft.rwText($ict.iq1),$ocms.postXT({url:$ocms.url("inv/pget"),data:{id:e.id},success:t=>{r&&r.ft.rwText($ict.iq2),$ocms.postXT({url:$ocms.url("inv/storno"),data:{id:e.id,mode:e.mode},success:e=>{e.admin=e.admin||{},e.admin.p13b=bool(e.admin.p13b||"",!0===((e.inv||{}).InvoiceOptions||"").split(",").includes("§13b"));let t=e.inv||{},i=$$.dc("srq",n),a=$$.tblset({class:"invi"},i);a.bdy.remove(),a.ft=$$[0]("tfoot"),a.tbl.data($.extend({invid:t.Id,new:{},sms:{},itm:{},bai:[]},e));let r=$$.tr(a.hd).aC("shd").append([$$.th().aC("aux")]);$rct.invHR.forEach((e=>$$.th(r,e))),a.tbl.on("fds.inv",$inv.invSumUpdate),$.each(e.req||[],(function(e,t){let n=$$.tbody(a.tbl).data($.extend({},t));$inv.rendersrq.call(n)}));let l=$$.tr($$.tbody(a.tbl),{class:"placeholder"}).data({net_val:0,vat_val:0,svcnet_val:0,svcvat_val:0,net:0});$inv.rrw.call(l),a.ft.appendTo(a.tbl);let s=(e,t,i,r,l)=>{let s=$$.dc("inpfrm",n).aC(e).append("string"==typeof r?$$.dc("ahd",r):r>0?$$.dc("ahd",$rct.frm[i]):null),d=$$.dc("content",s).rwText(t);$$.dc("axf",s).append($$.dc("ibtn edit").data("dialog",$rct.frm[i]).append(gi("pencil")).click($.extend({t:d,nme:i,change:e=>{a.tbl.data("new")[i]=e}},l),$inv.eHtml)),a.tbl.data("new")[i]=t};s("tfrm",t.InvoiceTitle,"invoicetitle",0,null),s("adrfrm",t.SendToAddress,"invoiceaddress",0,null),s("locfrm",t.ProvisionLocation,"loc",1,null),s("emailfrm",t.SendToEmail,"invoiceemail",0,null),$$.dc("sndfrm",n).append($$.dc("content").text(e.admin.sender)),s("admfrm",t.ProvisionPeriod,"provisionperiod",!0===(t.ProvisionPeriod||"").includes("-")?$rct.provP:$rct.provD,1),a.tbl.data("new").CustomValues=t.CustomValues||"",$$.dc("inpfrm ctpfrm",n).text(jObj(t.CustomValues,"contactName")),a.tbl.children("tbody").each($inv.bdysort),a.tbl.trigger("fds.inv")},complete:()=>{r.c.trigger("modal_close")}})},error:()=>{r&&r.c.trigger("modal_close")}})},$inv.eHtml=function(e){let t=$(this),n=e.data instanceof jQuery?e.data:e.data.t,i="invoiceemail"===e.data.nme,a=i?[{name:"txt",label:"Text",type:"text",value:n.text()}]:[{name:"txt",label:"Text",type:"html",value:n.html(),tinymce:!0,attr:{style:"height: 300px"}}],r=e.data.change||null,l={title:t.data("dialog")||"",success:function(t){i?n.text(t.txt||""):n.html(t.txt),"function"==typeof r&&r(t.txt),$inv.d.syncField(e.data.nme,i?t.txt||"":t.txt)},tinymce:{valid_elements:"br",hidemenu:!0,hidetoolbar:!0}};if(Array.isArray(e.data.list)){let t=$$.dc("lstfrm");$.each(e.data.list,((n,i)=>{let a=$$.dc("li",t).append(""!==(e.data.lbl||"")?$$.dc("lbl").rwText(i[e.data.lbl]):null);$$.dc("adr",a).rwText(i[e.data.property]).data("val",i[e.data.property]).click((function(){let e=$(this),t=e.closest(".modal-body").find(':input[name="txt"]');t.is(".tinymce")?tinymce.get(t.attr("id")).setContent($$.s().rwText(e.data("val")).html()):"TEXTAREA"===t.prop("tagName")?t.val(e.data("val")).change():t.rwText(e.data("val"))}))})),l.addcontent=t}$ocms.dlgform(a,l)},$inv.setVat=function(e){$(this);let t=e.data,n=prompt($rct.rqV);n&&(n=parseFloat(n.replace("%","")),n>1&&(n*=.01),!1===isNaN(n)&&(t.siblings(".itm").each((function(){let e=$(this).data();e.vat=fnum(n,{style:"percent"}).replace(" ",""),(e.net_val||0)>0&&(e.vat_val=e.net_val*n),(e.svcnet_val||0)>0&&(e.svcvat_val=e.svcnet_val*n)})),$inv.t_fds_inv()))},$inv.inRow=function(e){let t=$(this),n=e.data,i={},a=$rcol.itm.clone(["SortOrder","NameOrNumber","Type","quantityhours","UnitString","net","svcnet_val","svcvat_val","net_val","vat_val","vat","Note"]),r="N"+(65536*(1+Math.random())||0).toString(16).substr(6),l=$$.tr({id:"itm_"+r.toString(),class:"itm"});$ocms.dlgform(a,{title:t.data("dialog")||"",success:function(e){l.data($.extend({Id:r},i,e)),$inv.rrw.call(l),l.insertAfter(n),$inv.t_fds_inv()},typedvalues:!0})},$inv.eRow=function(e){let t=$(this),n=e.data,i=n.data()||{},a=["SortOrder","NameOrNumber","Type","quantityhours","UnitString","net","svcnet_val","svcvat_val","net_val","vat_val","vat","Note"];i.id||""!==(i.Type||"")||a.unshift("Type");let r=$rcol.itm.clone(a).applyValues(i);r.set("Type","hidden","type"),$inv.eRw.call(t,n,i,r)},$inv.eRw=function(e,t,n){let i=$(this);$ocms.dlgform(n,{title:i.data("dialog")||"",success:function(n){let i={};""===(t.Id||"")&&(i.Id="N"+(65536*(1+Math.random())||0).toString(16).substr(6),e.attr("id","itm_"+i.Id.toString())),i.quantity=((n.quantityhours||"").toString()+" "+(n.UnitString||"").toString()).trimEnd(),e.data($.extend({},t,n,i)),console.debug("eRw success %o",e.data()),$inv.rrw.call(e),$inv.t_fds_inv()},typedvalues:!0})},$inv.bdysort=(e,t)=>{$(t).Sortable({dragItem:!1,dragHandleClass:"ico",parentident:"tr",swapdone:(e,t,n,i)=>{$inv.t_fds_inv()}})},$inv.rrw=function(){let e=$(this),t=e.data(),n={},i=e.is(".placeholder"),a=e.is(".hidenote"),r=e=>$$.d().append(e).html(),l=[$$.dc("ibtn insb",{title:$rct.iRb}).append(gi("indent-left")).click(e,$inv.inRow)];!1===i&&(l.unshift($$.dc("ibtn edit",{title:$rct.cP}).append(gi("pencil")).click(e,$inv.eRow)),l.push($$.dc("ibtn del",{title:$rct.dR}).append(gi("trash")).click((function(t){confirm($rct.cD)&&(e.remove(),$inv.t_fds_inv())}))));let s=$$.dc("axf").append(l);!0===i?n={id:"",typ:"placeholder"}:!0===e.is(".itm.osum")?n={invrqid:t.InvRqId,id:"osum"+e.index(),typ:"osum",p:"",q:null,t:r(t.tbl.tbl),tt:null,v:null,vt:t.net_val,vs:t.svcnet_val,vat:t.vat,vv:t.vat_val,vsv:t.svcvat_val,det:!1}:(n={invrqid:t.InvRqId,id:t.Id||"",typ:t.Type||"other",p:"",q:null,t:"",tt:null,v:null,vt:t.net_val,vs:t.svcnet_val,vat:t.vat,vv:t.vat_val,vsv:t.svcvat_val,det:""!==(t.Note||"")&&!1===a},$$.dc("ibtn ico move",s,{title:$rct.mR}),n.p=t.position||t.SortOrder||"",""===n.id?n.t="":["Text","Title"].includes(n.typ)&&0===(t.net_val||0)?n.t=t.htmltext||("#"!==(t.NameOrNumber||"").substr(0,1)?r($$[0]("p").text(t.NameOrNumber)):"")+(t.Note||""):(n.tt=n.det?"":$$.s(t.Note||"").text(),n.q=t.quantity||fnum(t.quantityhours)+" "+(t.UnitString||""),n.t=t.htmltext||(n.det?r($$.s(t.NameOrNumber||""))+r($$.dc("desc").html(t.Note)):r($$.s(t.NameOrNumber||""))),n.v=t.net,n.vt=t.net_val)),""!==(t.Note||"")&&$$.dc("ibtn add",s).append(gi("object-align-left")).click((function(t){$inv.rrw.call(e.tC("hidenote"))}));let d=[$$.tdc("aux").append(s),$$.tdc("keep").text(n.p)];""===n.id?d.push($$.td(e,{colspan:4}).append(n.t)):(Array.prototype.push.apply(d,n.q?[$$.tdc("keep").text(n.q)]:[]),Array.prototype.push.apply(d,[$$.tdc("txt",{colspan:n.q?1:2,title:n.tt}).append(n.t),$$.tdc("currency").text(fnum(n.v,$rct.cst)),$$.tdc("currency inetval").text(fnum(n.vt,$rct.cst)).attr("title",$rct.svcPart+": "+fnum(n.vs,$rct.cst))])),e.empty().attr("class",i?"placeholder":"itm").aC(n.Typ).tC("hidenote",a).append(d),t.co=n},$inv.invSumUpdate=function(){let e=$(this),t=e.children("tfoot").empty(),n=bool((e.data().admin||{}).p13b||"",!1);e.nextAll(".fnote").remove();let i={ttn:0,ttb:0,ttvat:0,tscn:0,tscvat:0,vat:{},itmnet:{}},a=[],r=(e,n,i)=>$$.tdc("currency",$$.tr(t,{class:i||"tsum"}).append([$$.tdc("aux"),$$.td({colspan:4}).text(e)]),fnum(n,$rct.cst)),l=t=>$$.dc("fnote").insertAfter(e).rwText(t),s=e.children("tbody");s.each(((e,t)=>{let n=$(t),r=n.data()||{},l=[],s=[],d=null,c=0,o=n.find("tr.itm"),u=0;n.tC("empty",o.length<1),o.each(((e,t)=>{let n=$(t).data()||{};!function(e,t,n){t.tscn+=e.svcnet_val||0,t.tscvat+=e.svcvat_val||0,t.ttn+=e.net_val||0,t.ttvat+=e.vat_val||0,t.ttb+=(e.net_val||0)+(e.vat_val||0),""!==(e.vat||"")&&(t.vat[e.vat]=(t.vat[e.vat]||0)+(e.vat_val||0))}(n,i,r.Id),c+=n.net_val||0,l.push(n.co);let a=$inv.itemToContract(n);"set"===a.type&&""!==a.id?d=a.id:null!==d&&""!==(a.id||"")&&(a.setId=d),s.push(a),(void 0===n.SortOrder||null===n.SortOrder?-1:n.SortOrder)>-1&&(!1===["text","title"].includes((n.Type||"other").toLowerCase())&&u++,n.SortOrder=0,n.position=u,$inv.rrw.call(t))})),n.find("tr.isum > td.isumval").text(fnum(c,$rct.cst)),a.push({Id:r.Id,nme:r.Name,text:r.text,itm:l,items:s,netval:c})}));let d=e.find("tbody:not(.empty)").length;s.find("tr.isum").tC("hidden",d<2),r("Netto",i.ttn),!1===n?$.each(i.vat,((e,t)=>{r($rct.vat+" "+e,t,"tvat")})):i.ttb=i.ttn,r("Summe",i.ttb);let c=e.data().admin.type;"i"===c?(l($rct.note2),l($rct.note4)):"c"===c?l($rct.note2):(l(string($rct.note3,[fnum((i.tscn+i.tscvat)*(e.data().admin.tax_servicerefund||0),$rct.cst)])).aC("ntax"),l($rct.note2),l(string($rct.note1,[fnum(i.tscn+i.tscvat,$rct.cst),fnum(i.tscn,$rct.cst),fnum(i.tscvat,$rct.cst)]))),!0===n&&l($rct.note13b),e.data("sms",i),e.data("bai",a),""===(e.data("dtoken")||"")&&!1===bool(e.data("dseeding"),!1)&&null!=(e.data("admin")||{}).type&&(e.data("dseeding",!0),$inv.d.seed($.extend($inv.invcPayload(e.data()),{invid:e.data("invid")||""})))},$inv.worknotes=function(e){let t="";return e.steps.forEach(((e,n)=>{let i;try{i=JSON.parse(e.Data||{}).fields||[]}catch(e){console.debug(e),i=[]}!0!==Array.isArray(i||"")&&(i="object"==typeof i&&!0===Array.isArray(i.field||"")?i.field:[]),i.forEach(((e,n)=>{"Ausgeführte Arbeiten"===e.name&&(t=e.result||"")}))})),t},$inv.rendersrq=function(){let e=$(this).empty(),t=e.is(".onesum"),n=e.data(),i=$$.tr(e,{id:"srq"+n.Id}).aC("title nosort"),a=($rcol.itm.lbl(),$$.dc("axf").appendTo($$.tdc("aux",i)));$$.dc("ibtn osum",a,{title:$rct.combP}).append(gi("euro")).click((function(t){e.tC("onesum"),$inv.rendersrq.call(e),$inv.t_fds_inv()})),$$.dc("ibtn setvat",a,{title:$rct.sV}).append(gi("gbp")).click(i,$inv.setVat),$$.dc("ibtn insb",a,{title:$rct.iRb}).append(gi("indent-left")).click(i,$inv.inRow);let r,l=$$.sc("text",n.text),s=($$.td(i,{colspan:t?4:5}).append(l),["net_val","vat_val","svcnet_val","svcvat_val","net"]);if($$.dc("ibtn edit",a).data("dialog",$rcol.req.lbl().Name).append(gi("pencil")).click({t:l,change:e=>{n.text=e,$inv.t_fds_inv()}},$inv.eHtml),t&&($$.tdc("currency isumval",i),r={Id:n.Id.toString()+"_osum",net_val:0,vat_val:0,svcnet_val:0,svcvat_val:0,net:0},r.tbl=$$.tblset({class:"stbl"})),$.each(n.items||[],((n,i)=>{let a,l={Id:i.Id,net_val:i.net_val||0,vat_val:i.vat_val||0,svcnet_val:0,svcvat_val:0,net:i.net||0,Note:i.Note||""};if("service"===i.Type.toLowerCase())l.svcnet_val=i.net_val||0,l.svcvat_val=i.vat_val||0;t?(a=$$.tr(r.tbl.bdy,{id:"itm"+i.Id,class:"sitm"}).aC(i.Type),"Text"===i.Type||"Title"===i.Type?$$.td(a,{colspan:2}).html(i.htmltext||i.Note):($$.tdc("keep",a).text(i.quantity||((i.quantityhours||0)>0?fnum(i.quantityhours)+(i.UnitString||"").eine(" ",""):"")),i.htmltext?$$.tdc("txt",a).html(i.htmltext):$$.tdc("txt",a).text(i.NameOrNumber).attr("title",i.Note)),$.each(s,((e,t)=>{r[t]+=l[t]})),a.data(l)):($.extend(l,i),a=$$.tr(e,{id:"itm"+i.Id,class:"itm"}),a.data(l),$inv.rrw.call(a))})),t){let t=$$.tr(e,{id:"itmsq"+n.Id,class:"itm osum"}).data(r);$inv.rrw.call(t)}else{let t=$$.tr(e).aC("isum nosort");$$.tdc("aux",t),$$.td(t,{colspan:4}).text($rct.iSum),$$.tdc("currency isumval",t)}},$inv.t_fds_inv=()=>{let e=$("div.invoice_layout table.invi");e.trigger("fds.inv"),""!==(e.data("dtoken")||"")&&$inv.d.syncChanged(e)},$inv.sedit=()=>{$inv.sprev(!0)},$inv.jdisp=function(e){e.stopPropagation(),e.data.id&&$inv.disp(e.data.id,e.data.typ||"")},$inv.disp=(e,t)=>{let n="";switch(t){case"inv":n="inv/rdoc";break;case"rem":n="rem/rdoc"}""!==n&&$ocms.postXT({url:$ocms.url(n),data:{id:e||"",typ:"img"},success:e=>{let t=$$.dc("imagecollection pdfpreview"),n=Math.round(.88*vh());e.id;$.each(e.img||[],(function(e,i){$$.dc("pdfp",t).append($$.img(i).css("max-height",(n-rpx(6)).toString()+"px"))})),$ocms.dlg(t,{size:[n,Math.round(.88*vw())],zindex_min:50,form:!1,exclusive:!1})}})},$inv.jdbn=function(e){$ocms.postXT({url:$ocms.url("inv/rdocn"),data:{name:e.data.id||"",typ:"img"},success:e=>{let t=$$.dc("imagecollection pdfpreview"),n=Math.round(.88*vh());e.id;$.each(e.img||[],(function(e,i){$$.dc("pdfp",t).append($$.img(i).css("max-height",(n-rpx(6)).toString()+"px"))})),$ocms.dlg(t,{size:[n,Math.round(.88*vw())],zindex:50,form:!1})}})},$inv.sp13b=()=>{var e=$("div.invoice_layout").find("table.invi"),t=e.data();t.admin.p13b=!0,!1===(t.inv.InvoiceOptions||"").split(",").includes("§13b")&&(t.inv.InvoiceOptions+=",§13b"),e.trigger("fds.inv"),$inv.d.sync({Target:"p13b",Value:t.admin.p13b})},$inv.itemToContract=function(e){let t=((e=e||{}).Type||"").toString().toLowerCase(),n={id:(e.Id||"").toString(),type:t,title:"",desc:"",qty:"",price_net:"",total_net:e.net_val||0,vat:e.vat||""};var i;return e.co&&"osum"===e.co.typ?(n.desc=e.co.t||"",n.total_net=e.net_val||0):["text","title"].includes(t)&&0===(e.net_val||0)?(n.desc=e.htmltext||("#"!==(e.NameOrNumber||"").substr(0,1)?(i=$$[0]("p").text(e.NameOrNumber||""),$$.d().append(i).html()):"")+(e.Note||""),n.total_net=""):(e.htmltext?n.desc=e.htmltext:(n.title=e.NameOrNumber||"",n.desc=e.Note||""),n.qty=e.quantity||(0!==(e.quantityhours||0)?fnum(e.quantityhours)+(e.UnitString?" "+e.UnitString:""):""),n.price_net=e.net||0,n.total_net=e.net_val||0),n},$inv.ssetmode=()=>{let e=$("div.invoice_layout").find("table.invi").data();e.admin=e.admin||{};let t,n=e.admin.setmode||"setprice",i=e=>$$.dc("btn",$ict.setmo[e]).tC("selected",n===e).click((()=>{t.c.trigger("modal_close"),$inv.setSetmode(e)})),a=$$.dc("choicefrm").append([i("setprice"),i("itemprices"),i("setonly")]);t=$ocms.dlg(a,{width:800})},$inv.setSetmode=e=>{let t=$("div.invoice_layout").find("table.invi").data();t.admin=t.admin||{},t.admin.setmode=e,t.inv=t.inv||{};let n=(t.inv.InvoiceOptions||"").split(",").filter((e=>""!==e&&0!==e.indexOf("setmode:")));e&&"setprice"!==e&&n.push("setmode:"+e),t.inv.InvoiceOptions=n.join(","),$inv.d.sync({Target:"setmode",Value:e})},$inv.sctp=()=>{let e=$invcol.ctp;$ocms.dlgform(e,{title:$ict.ctp,success:function(e){var t=$("div.invoice_layout"),n=t.find("table.invi").data();let i={};void 0!==n.new&&"{"===(n.new.CustomValues||"").substr(0,1)&&(i=JSON.parse(n.inv.CustomValues)),i.contactName=e.name,i.contactEmail=e.email,n.new.CustomValues=JSON.stringify(i),t.find(".ctpfrm").text(ne(e.name,e.email)),$inv.d.sync({Target:"contact",Value:{name:e.name,email:e.email}})},typedvalues:!0})},$inv.invcPayload=function(e){let t=(e=e||{}).sms||{},n=$.extend({},e.new),i=$.extend({},e.admin);return n.total_net=t.ttn||0,n.total_gross=t.ttb||0,n.title=null!=n.invoicetitle?n.invoicetitle:n.title||"",n.provisionlocation=null!=n.loc?n.loc:n.provisionlocation||"",n.paymentterm=null!=i.paymentterms?i.paymentterms:n.paymentterm||"",i.customerid=null!=i.customerid?i.customerid:i.CustomerId,{admin:i,req:e.bai,sms:e.sms,new:n}},$inv.ssave=()=>{$inv.d.save()},$inv.sprev=e=>{$inv.d.preview()},$inv.rReload=()=>{try{let e=$("#listframe ul.rql:first").data();$inv.cInv2({id:e.search})}catch(e){}},$inv.quantChange=function(e){let t=$(this).closest("form"),n={},i=e=>parseFloat(e.toString().replace("%","").replace(",",".")),a=e=>e.toFixed(2);t.find(":input").each(((e,t)=>{n[$(t).attr("name")]=$(t)}));let r=parseInt(n.quantityhours.val()||"0"),l=i(n.net.val()||"0"),s=.01*i(n.vat.val());r>0&&l>0&&(n.net_val.val(a(r*l)),n.vat_val.val(a(r*l*s)),["Service"].includes(n.Type.val())&&(n.svcnet_val.val(a(r*l)),n.svcvat_val.val(a(r*l*s))))},$inv.storno=function(e,t){let n,i=$$.dc("choicefrm").append([$$.dc("btn","Storno ohne Details").click({id:e,mode:"simple"},(e=>{n.c.trigger("modal_close"),$inv.cSt(e.data)})),$$.dc("btn","Storno mit neuer Rechnung").click({id:e},(e=>{n.c.trigger("modal_close"),$inv.ccStInv(e)})),$$.dc("btn","Storno mit best. Rechnung").tC("inactive",!1===bool(t,!1)).click({id:e,mode:"copy"},(e=>{!0===bool(t,!1)&&(n.c.trigger("modal_close"),$inv.cSt(e.data))}))]);n=$ocms.dlg(i,{width:1e3})},$inv.credit=function(e,t){let n,i=$$.dc("choicefrm").append([$$.dc("btn","Gutschrift").click({id:e,mode:"credit"},(e=>{n.c.trigger("modal_close"),$inv.cSt(e.data)}))]);n=$ocms.dlg(i,{width:1e3})},$inv.setPyd=function(e){confirm($ict.cpyd)&&$ocms.postXT({url:$ocms.url("inv/setpyd"),timeout:60,data:{id:e},success:e=>{alert($ict.relm)},error:()=>{alert($t.f1)}})},$inv.setUpd=function(e){confirm($ict.cupd)&&$ocms.postXT({url:$ocms.url("inv/setupd"),timeout:60,data:{id:e},success:e=>{alert($ict.relm)},error:()=>{alert($t.f1)}})},$inv.resendRem=function(e){e.stopPropagation(),e.data.id&&confirm(string($ict.remresc,[e.data.name]))&&$ocms.postXT({url:$ocms.url("rem/resend"),timeout:60,data:{id:e.data.id},success:t=>{alert(string($ict.remresr,[e.data.name]))},error:()=>{alert($t.f1)}})},$inv.dspRem=function(e){let t=$$.dc("rfrm").ldng(1),n=$ocms.dlg(t,{width:1e3});n.ft.rwText($rct.rq2),$ocms.postXT({url:$ocms.url("inv/getrem"),timeout:60,data:{id:e,drafts:!1},success:e=>{n.ft.empty();let i=$$.tblset({class:"invtbl"},t.empty()),a=$invcol.rem2,r=$$.tr(i.hd);$$.th(r);$.each(a.fields||[],((e,t)=>{$$.th(r).text(t.label)}));let l=!1;$.each(e,((e,t)=>{l=!l;let n=$$.tr(i.bdy).tC("alt",l),r=$$.td(n);n.click((function(){n.tC("selected").siblings().rC("selected")})),!0===bool(t.hasFile,!1)&&($$.dc("idl ilbtn",r,{title:$ict.dl+"\n"+t.DocumentName}).append(gi("save-file","ico")).click({id:t.Id},$inv.downloadrem),$$.dc("idl ilbtn",r,{title:$ict.remdsp+"\n"+t.DocumentName}).append(gi("eye-open","ico")).click({id:t.Id,typ:"rem"},$inv.jdisp),$$.dc("idl ilbtn",r,{title:$ict.remres+"\n"+t.DocumentName}).append(gi("refresh","ico")).click({id:t.Id,typ:"rem",name:t.DocumentName},$inv.resendRem)),$.each(a.fields||[],((e,i)=>{let a=$$.td(n).aC(i.dtype),r=t[i.name];if("function"==typeof i.dfnc)i.dfnc.call(a,r,t);else switch(i.type||""){case"date":a.text(fdt(t[i.name],"dd.MM.yy"));break;case"datetime":a.text(fdt(t[i.name]));break;case"html":a.append($$.dc("ctw").html(r)),a.append($$.dc("ttip").html(r));break;default:a.text(t[i.name])}if("InvoiceId"===(i.name||""))a.aC("keep");switch(typeof i.title){case"function":i.title.call(a,t);break;case"string":a.attr("title",cs.title)}}))}))},error:()=>{t.empty(),n.ft.rwText($t.f1)},complete:()=>{t.ldng(0)}})},$inv.ccRem=function(e,t){$(this);$ocms.postXT({url:$ocms.url("rem/lrem"),timeout:60,data:{id:e},success:n=>{let i=$invcol.rid.clone();i.applyValues(n.ov);let a=$$.dc("ac"),r=$$.tblset({class:"fullgrid fullwidth"},a);if((n.lst||[]).length>0){$$.d({style:"margin: 1.5rem 0 1rem 0;font-size: 110%;text-decoration: underline;"}).prependTo(a).text($ict.rovlh);let e=$$.tr(r.hd);$ict.rovl.forEach(((t,n)=>$$.th(e,t))),$.each(n.lst,((e,t)=>{$$.tr(r.bdy).append([$$.tdc("keep",t.subject),$$.tdc("currency",fnum(t.amount,$rct.cst)),$$.tdc("currency",fnum(t.amount_payed,$rct.cst)),$$.tdc("keep",fdt(t.DateFinalized,"dd.MM.yy"))])}))}else $$.td($$.tr(r.bdy),$ict.nd);$ocms.dlgform(i,{addcontent:a,title:string($ict.remdt,[t||"?"]),success:function(t){$inv.ccRem_s2(e,t)},typedvalues:!0})}})},$inv.rRemRw=function(e){let t=$(this),n=e.rm||{};t.empty().data({invoiceid:n.invoiceid,invoicedate:n.invoicedate,amount:n.amount,amount_payed:n.amount_payed});let i=$$.dc("axf").append($$.dc("ibtn edit",{title:$rct.cP}).append(gi("pencil")).click(t,$inv.eRowR));t.append([$$.tdc("aux").append(i),$$.tdc("keep",n.invoiceid),$$.tdc("keep",fdt(n.invoicedate,"dd.MM.yy")),$$.tdc("currency",fnum(n.amount,$rct.cst)),$$.tdc("currency",fnum(n.amount_payed,$rct.cst)),$$.tdc("currency",fnum(n.amount-n.amount_payed,$rct.cst))])},$inv.eRowR=function(e){let t=$(this),n=e.data,i=n.data()||{},a=$invcol.rem.clone().applyValues(i);$ocms.dlgform(a,{title:t.data("dialog")||"",success:function(e){let i=t.closest("table"),a=i.data();$.extend(a.rm,e),i.data(a),$inv.rRemRw.call(n,a)},typedvalues:!0})},$inv.ccRem_s2=function(e,t){$fis.lf(!1).rC("fix").aC("hd");let n=$$.dc("invoice_layout",$fis.frm_edit()).append($$.dc("btn sprev").click($inv.rprev));$inv.eM(!1,!0);$$.dc("rfrm").ldng(1);$ocms.postXT({url:$ocms.url("rem/get"),timeout:60,data:$.extend({id:e},t),success:e=>{let t=e.rm||{},i=$$.dc("srq",n);$ict.remt[t.type].forEach((e=>$$[0]("p").rwText(e).appendTo(i)));let a=$$.tblset({class:"invi"},i);a.ft=$$[0]("tfoot"),a.tbl.data($.extend({invid:t.invid,new:{}},e));let r=$$.tr(a.hd).aC("shd").append([$$.th().aC("aux")]);$ict.remHR.forEach((e=>$$.th(r,e))),$inv.rRemRw.call($$.tr(a.bdy),a.tbl.data()),a.ft.appendTo(a.tbl),$ict.remt2[t.type].forEach((e=>$$[0]("p").rwText(e).appendTo(i)));let l=(e,t,i,r,l)=>{let s=$$.dc("inpfrm",n).aC(e).append("string"==typeof r?$$.dc("ahd",r):r>0?$$.dc("ahd",$rct.frm[i]):null),d=$$.dc("content",s).rwText(t);$$.dc("axf",s).append($$.dc("ibtn edit").data("dialog",$rct.frm[i]).append(gi("pencil")).click($.extend({t:d,nme:i,change:e=>{a.tbl.data("new")[i]=e}},l),$inv.eHtml)),a.tbl.data("new")[i]=t};l("tfrm",t.subject,"subject",0,null),l("adrfrm",t.invoiceaddress,"invoiceaddress",0,null),l("emailfrm",t.invoiceemail,"invoiceemail",0,null),$$.dc("sndfrm",n).append($$.dc("content").text(t.sender)),a.tbl.children("tbody").each($inv.bdysort),a.tbl.trigger("fds.inv")},complete:()=>{}})},$inv.rprev=()=>{var e=$("div.invoice_layout"),t=e.find("table.invi"),n=t.data();$.extend(n.new,t.find("tbody > tr:first").data()),e.aC("freeze"),!1!==$fis.ValidateEmail(n.new.invoiceemail||"")||!1!==bool(confirm($ict.ivE+$ict.ivEc),!1)?$ocms.postXT({url:$ocms.url("rem/prep"),data:{remc:JSON.stringify({rem:n.rm,new:n.new}),id:n.invid||""},success:t=>{e.rC("freeze");let n=$$.dc("imagecollection pdfpreview"),i=Math.round(.88*vh()),a=t.id;$.each(t.img||[],(function(e,t){$$.dc("pdfp",n).append($$.img(t).css("max-height",(i-rpx(6)).toString()+"px"))})),$ocms.dlg(n,{size:[i,Math.round(.88*vw())],zindex:50,form:!1,button:$ict.remd,confirm:function(e){let t=$(this);$ocms.postXT({url:$ocms.url("rem/conf"),data:{id:a},success:()=>{t.trigger("modal_close"),window.open($ocms.url("rem/idoc")+"?id="+a,"_blank"),$ocms.init("req"),$inv.rReload()},error:()=>{alert($t.f1),t.trigger("modal_close")}})},cancel:function(e){$(this);confirm($ict.cdI)&&$ocms.postXT({url:$ocms.url("rem/del"),data:{id:a}}),$inv.rReload()}})}}):e.rC("freeze")},$inv.sis=e=>{confirm($ict.sisc)&&$ocms.postXT({url:$ocms.url("inv/sis"),data:{id:e||""},success:e=>{}})},$inv.srs=e=>{confirm($ict.srsc)&&$ocms.postXT({url:$ocms.url("rem/srs"),data:{id:e||""},success:e=>{}})},$inv.mfrrel=e=>{$("#contentframe").ldng(),$ocms.postXT({url:$ocms.url("inv/mfrrel"),data:{id:e||""},success:e=>{$inv.rerenderinv()},complete:()=>{$("#contentframe").ldng(0)}})}; \ No newline at end of file +let $rct={mdl:"Aufträge",or:"offene Aufträge",orr:"offene Aufträge (4 W)",rn:"Auftragsnummer",iov:{all:"Auftragsübersicht (alle)","":"Auftragsübersicht"},wk:"Woche",nd:"Keine Daten gefunden.",h:"Uhr",rq1:"Auftragsdaten werden von MFR abgerufen.\nDer Vorgang kann bis zu 90Sek dauern.",rq2:"Auftragsdaten werden geladen",rq1f:"Die Auftragsdaten von MFR konnten nicht oder nicht schnell genug abgerufen werde.\nMöchten Sie mit den bestehenden Daten trotzdem weitermachen?",note1:"Im Bruttobetrag sind {0} Lohnkosten enthalten (netto {1}). Die darin enthaltene Umsatzsteuer beträgt {2}.",note2:"Bitte beachten Sie, nach §14 Abs. 1 Umsatzsteuergesetz ist diese Rechnung ein Zahlungsbeleg oder eine andere beweiskräftige Unterlage für 2 Jahre nach Ablauf des Kalenderjahres der Ausstellung dieser Rechnung aufzubewahren, soweit nicht aufgrund anderer gesetzlicher Regelungen andere ggf.längere Aufbewahrungsfristen gelten.",note3:"Privathaushalten erstattet das Finanzamt bis zu {0} des Arbeitslohns mit der nächsten Steuererklärung.",note4:"Für bereits erbrachte Arbeiten, Dienstleistungen, Materiallieferungen und getätigte Bestellvorgänge zum oben genannten Bauvorhaben, die sich aus dem mit Ihnen geschlossenen Vertrag ergeben, stellen wir Ihnen vertragsgemäß unsere Akontozahlung in Rechnung. Eine Endabrechnung erhalten Sie als Schlussrechnung nach Abschluss des gesamten Bauvorhabens. Das Ausführungsdatum entnehmen Sie bitte dem Schlusstext dieser Rechnung. Wir danken Ihnen herzlich für das entgegengebrachte Vertrauen und bitten Sie um kurzfristigen Ausgleich der Akontorechnung.",note13b:"Gem. §13b Umsatzsteuergesetz unterliegen Sie der Steuerschuldnerschaft des Leistungsempfängers zur Umsatzsteuer aus dieser Rechnung mit einem Steuersatz von 19%.",crI:"Rechnung erstellen",crII:"Abschlagsrechnung erstellen",dII:"Für eine Abschlagsrechnung darf nur ein Auftrag gewählt werden.",dnS:"Für eine Rechnung muss mindestens ein Auftrag gewählt werden.",inv:"Rechnung",invs:"Rechnungen",req:"Auftrag",provP:"Leistungszeitraum",provD:"Leistungsdatum",cP:"Position ändern",iRb:"Zeile darunter einfügen",dR:"Zeile löschen",sV:"USt festlegen",cD:"Löschen?",mR:"Zeile verschieben",svcPart:"Service-Anteil",vat:"Umsatzsteuer",combP:"Positionen zusammenfassen",iSum:"Zwischensumme",dtRel:"Freigegeben am: ",dtCr:"Erstellt am: ",rqV:"USt des Auftrags?",cthd:"wirklich aus-/einblenden ?",cst:{style:"currency",currency:"EUR"},sts:{IsWorkDone:"Arbeiten erledigt",Closed:"Auftrag geschlossen",SubcontractorPendingConfirmation:"Warten auf Bestätigung (Unterauftrag)",Scheduled:"Geplant",OfferIsRejected:"Angebot abgelehnt",OfferIsSend:"Offen (Angebot versandt)",CollaborationWaitingConfirmation:"Warten auf Bestätigung (Zusammenarbeit)",Released:"Freigegeben",OfferIsConfirmed:"Bestätigt",InProgress:"In Bearbeitung",ReadyForScheduling:"Zur Planung",Created:"Erstellt",Rejected:"Abgebrochen",Invoiced:"Rechnung gestellt","-":"-"},invHR:["Pos.","Menge","Artikelbezeichnung","VK","Summe"],frm:{invoiceaddress:"Adresse",loc:"Leistungsort / Lieferadresse",invoiceemail:"Email"}},$rcol={req:new fields_definition("Auftrag","Aufträge",[{name:"tags",label:"",type:"string",dfnc:function(e,t){""!==(e||"")&&($(this).aC("tags"),e.split(",").forEach((e=>{""!==e&&$(this).append($$.sc("tag "+e.replace(" ","_").replace("/","_").toLowerCase(),e))})))}},{name:"DateOfCreation",label:"Datum",type:"date",title:function(e){$(this).attr("title",$rct.dtCr+fdt(e.DateOfCreation).ne("-")+" \n"+$rct.dtRel+fdt(e.DateReleased).ne("-"))}},{name:"CustomerName",label:"Kunde (Firma)",type:"string"},{name:"Name",label:"Auftragsname",type:"string"},{name:"ExternalId",label:"Auftragsnummer",type:"string"},{name:"ParentExtenalId",label:"PAuftrag",type:"string"},{name:"InvoiceId",label:"RNummer",type:"string",dfnc:function(e,t){$(this).rwText(e," ").find("span").each((function(){$(this).aC("cla").click({id:$(this).text()},$inv.jdbn)}))}},{name:"State",label:"Status",type:"string"},{name:"WorkDoneAt",label:"Erledigt am",type:"date"},{name:"Description",label:"Beschreibung",type:"html"}]),itm:new fields_definition("Auftragsposition","Auftragspositionen",[{name:"NameOrNumber",label:"Bezeichnung",type:"string"},{name:"Type",label:"Typ",type:"select",required:!0,value:"Text",url:[{value:"Text",label:"Text"},{value:"Equipment",label:"Ausrüstung"},{value:"Material",label:"Material"},{value:"Service",label:"Arbeitsleistung"}],change:function(e){$req.quantChange.call(this,e)}},{name:"quantityhours",label:"Anzahl / Menge",type:"number",precision:"0.01",value:1,change:function(e){$inv.quantChange.call(this,e)}},{name:"UnitString",label:"Einheit",type:"select",url:["LFDM","Stck","Std.","QM","AW","Pauschal"],change:function(e){$inv.quantChange.call(this,e)}},{name:"net",label:"EinzelPreis netto",type:"number",precision:"0.01",value:0,change:function(e){$inv.quantChange.call(this,e)}},{name:"net_val",label:"GesamtPreis netto",type:"number",precision:"0.01",value:0},{name:"vat_val",label:"GesamtPreis USt",type:"number",precision:"0.01",value:0},{name:"svcnet_val",label:"Arbeitslohn netto",type:"number",precision:"0.01",value:0},{name:"svcvat_val",label:"Arbeitslohn USt",type:"number",precision:"0.01",value:0},{name:"net_pos",label:"Netto",type:"string"},{name:"bo_pos",label:"Brutto",type:"string"},{name:"vat",label:"USt",type:"string",value:"19,0%",change:function(e){$inv.quantChange.call(this,e)}},{name:"Note",label:"Details",type:"html",tinymce:!0}])},$ict={mdl:"Rechnungen",iov:{all:"Rechnungen (alle)","":"Rechnungen (nur fertige)","#d":"Rechnungen (nur Entwürfe)","#u":"Rechnungen (nur unbezahlt)","#r":"Rechnungen (nur angemahnt)","#a":"Rechnungen (nur Akonto)","#c":"Rechnungen (nur Storno)","#ru":"Rechnungen (nur angemahnt + unbez.)"},uba:", gesamter Zeitraum)",req:"Auftrag",inv:"Rechnung",rem:"Mahnung",in:"Rechnungsnummer",cc:"Kunde",wk:"Woche",nd:"Keine Daten gefunden.",dl:"Herunterladen",ed:"Bearbeiten",ced:"Bearbeitung fortsetzen",sItm:"Einzelheiten anzeigen",sPay:"Zahlungen anzeigen",cdI:"Entwurf der Rechnung löschen?",rel:"Neu Laden",relm:"Bitte laden Sie Liste manuell neu, um die Änderungen zu sehen.",dsp:"Rechnung anzeigen",storno:"Storno-Rechnung erstellen",credit:"Gutschrift erstellen",remd:"Mahnung erstellen",remdt:"Mahnung erstellen zur Rechnung {0}",remlst:"Mahnungen anzeigen",remdsp:"Mahnung anzeigen",remres:"Mahnung erneut senden",remresc:"Mahnung {0} wirklich erneut senden?",remresr:"Mahnung {0} wurde erfolgreich versandt.",setpyd:"Bezahlt markieren",cpyd:"Rechnung wirklich als bezahlt markieren?",setupd:"Bezahlt-Markierung aufheben",cupd:"Bezahlt-Markierung wirklich aufheben?",ivE:"Die Email-Adresse ist vermutlich nicht gültig.",ivEc:"\nMöchten Sie fortfahren?",pna:"Diese Seite ist in der Vorschau nicht verfügbar",tpe:"Die Anzahl von {0} Seiten wird aktuell nicht unterstützt",eis:"Der Rechnungsentwurf konnte nicht gespeichert werden.",iss:"Zwischenstand speichern.",p13b:"USt -> §13b",setm:"Set-Preisanzeige",setmo:{setprice:"Set mit Preis – Positionen ohne Preis",itemprices:"Positionen mit Preis – Set als Überschrift",setonly:"Nur Set mit Preis – Positionen ausgeblendet"},ctp:"Ansprechpartner festlegen",mfr:"Von MFR neu abrufen",rq1:"Auftragsdaten werden von MFR abgerufen.\nDer Vorgang kann bis zu 90Sek dauern.",rq2:"Auftragsdaten werden geladen",iq1:"Rechnungsdaten werden von MFR abgerufen.\nDer Vorgang kann bis zu 90Sek dauern.",iq2:"Rechnungsdaten werden geladen",sis:"Rechnung als versandt markieren",srs:"Mahnung als versandt markieren",sisc:"Rechnung wirklich als versandt markieren?",srsc:"Mahnung wirklich als versandt markieren?",iSt:{dft:"Entwurf",uns:"nicht versandt",pyd:"bezahlt",cc:"storniert",op:"offen",due:"fällig",ovd:"überfällig",rem:"angemahnt"},rSt:["","Überfällig","2. Mahnung","3. Stufe"],pSt:{a:"Vollst.",p:"Teilz."},ivT:{i:"AbschlagsR.",f:"SchlussR",r:"Rechnung",c:"StornoR."},rovlh:"Übersicht der bisherigen Mahnungen",rovl:["Betreff","Betrag","Betrag gezahlt","fertiggestellt am"],remHR:["Rechnung","vom","Rechnungsbetrag","bereits bezahlt","noch offen"],remt:{f:["Sehr geehrte Damen und Herren,","ein Mahnschreiben sollte kurz, freundlich und erfolgreich sein. Kurz ist es, freundlich sowieso; ob es auch erfolgreich ist, hängt von Ihnen ab."],m:["Sehr geehrte Damen und Herren,","nun müssen wir Sie noch einmal anschreiben.","Wahrscheinlich haben Sie triftige Gründe dafür, warum Sie die Zahlung unserer Forderung nicht vornehmen und auch nicht auf unsere Mahnung reagieren. Sollten wir darüber nicht einmal sprechen?","Bitte nehmen Sie umgehend in dieser Sache mit uns Kontakt auf."],l:["Sehr geehrte Damen und Herren,",'Eine DRITTE MAHNUNG zu erhalten bereitet Ihnen bestimmt ebenso wenig Freude wie uns, sie zu verschicken. Leider haben wir auf unsere zweite Mahnung noch keine Antwort von Ihnen erhalten.", "Wir bitten Sie, den offenen Betrag innerhalb der nächsten 7 Werktage nach Erhalt dieses Schreibens zu begleichen. Nach Ablauf dieser Frist erfolgt keine weitere Mahnung mehr.',"Sollte die Forderung bis dahin nicht beglichen sein, eröffnen wir das gerichtliche Mahnverfahren. Sollten Sie die Rechnung inzwischen beglichen haben, so betrachten Sie bitte dieses Schreiben als gegenstandslos."]},remt2:{f:["Wir bitten Sie, den noch offenen Rechnungsbetrag innerhalb einer Woche auf unser Konto zu überweisen.","Sollten Sie den Betrag bereits überwiesen haben, so bitten wir Sie, diese Zahlungserinnerung als gegenstandslos zu betrachten."],m:["Um Ihnen zusätzliche Kosten für weitere Mahnungen zu ersparen, bitten wir Sie nunmehr um die Überweisung des noch zu zahlenden Gesamtbetrages inklusive der ggf. bereits fälligen Mahnzinsen und Mahngebühren innerhalb von einer Woche."],l:[]},payi:{account:"Konto",name:"Zahler",text:"Verw.Zweck",InvoiceID:"Rechnung",amount:"Betrag",date:"Datum",manual:"Typ"}},$invcol={datev:new fields_definition("Rechnung","Rechnungen",[{name:"Umsatz (ohne Soll/Haben-Kz)",label:"Umsatz (ohne Soll/Haben-Kz)",type:"string"},{name:"vf",label:"vf",type:"string"},{name:"Soll/Haben-Kennzeichen",label:"Soll/Haben-Kennzeichen",type:"string"},{name:"Konto",label:"Konto",type:"string"},{name:"Gegenkonto",label:"Gegenkonto",type:"string"},{name:"BU-Schlüssel",label:"BU-Schlüssel",type:"string"},{name:"Belegdatum",label:"Belegdatum",type:"string"},{name:"Belegfeld 1",label:"Belegfeld 1",type:"string"},{name:"Belegfeld 2",label:"Belegfeld 2",type:"string"},{name:"Buchungstext",label:"Buchungstext",type:"string"}]),inv:new fields_definition("Rechnung","Rechnungen",[{name:"invstatus",label:"Status",type:"select",url:$ict.iSt},{name:"balance",label:"Umsatz",type:"string",dtype:"currency"},{name:"CustomerName",label:"Kunde",type:"string"},{name:"InvoiceId",label:"RNummer",type:"string"},{name:"InvoiceType",label:"Typ",type:"select",url:$ict.ivT},{name:"request",label:"Auftrag",type:"string",dtype:"num"},{name:"vat",label:"MwSt",type:"string",dtype:"num"},{name:"deb_cred",label:"Soll/Haben",type:"string"},{name:"customer",label:"Konto",type:"string",dtype:"num"},{name:"contra_account",label:"Gegenkonto",type:"string",dtype:"num"},{name:"Belegdatum",label:"Belegdatum",type:"date"},{name:"reminderstatus",label:"MahnStatus",type:"select",url:$ict.rSt},{name:"reminder",label:"# Mahnungen",type:"integer"},{name:"Buchungstext",label:"Buchungstext",type:"string"},{name:"Payment",label:"Zahlung",type:"string"}]),rem:new fields_definition("Zahlungserinnerung","Zahlungserinnerung",[{name:"amount",label:"Rechnungsbetrag",type:"number",precision:"0.01",value:1},{name:"amount_payed",label:"bereits bezahlt",type:"number",precision:"0.01",value:1}]),rem2:new fields_definition("Zahlungserinnerung","Zahlungserinnerung",[{name:"DocumentName",label:"Name",type:"string"},{name:"subject",label:"Betreff",type:"string"},{name:"DateSent",label:"Versanddatum",type:"date"},{name:"status",label:"Status",type:"string"},{name:"amount_open",label:"offener Betrag",type:"number",precision:"0.01"},{name:"InvoiceId",label:"RNummer",type:"string"}]),rid:new fields_definition("Zahlungserinnerung","Zahlungserinnerung",[{name:"type",label:"Typ",type:"select",url:[["f","einfache Zahlungserinnerung"],["m","Mahnung"],["l","letzte Mahnung"]],required:!0},{name:"level",label:"Stufe",type:"select",url:[["1","Stufe 1"],["2","Stufe 2"],["3","Stufe 3"],["4","Stufe 4"],["5","Stufe 5"],["6","Stufe 6"]],required:!0}]),ctp:new fields_definition("Ansprechpartner","Ansprechpartner",[{name:"name",label:"Name",type:"string"},{name:"email",label:"Email",type:"string"}])},gi=(e,t)=>$$.sc("glyphicon glyphicon-"+e).aC(t),$inv={init2:function(e,t){e=e||"inv",t=t||{},$ocms.getScript([],(function(){$inv.init3(e,t)}))},init3:async function(e,t){$fis.cf(!0);let n=$fis.lf(!0);$("#topbar").ocmsmenu([]),$("#activemodule").text($ict.mdl);let i=[(async()=>{await $fis.getAuth("fds_inv")>0&&($inv.prepLst(""),n.aC("fix"))})(),new Promise(((e,t)=>{$fis.prepAuth(["fds_reminder"])}))];await Promise.all(i)},prepLst:function(e){let t=new Date,n=$fis.lf(!0).ldng(1),i=new Date("2021-01-01");$fis.frm_list().IN((function(){}));let a=[];$.each($ict.iov,((e,t)=>{a.push({lbl:t,fnc:()=>{$inv.prepLst(e),n.aC("fix")}})})),$fis.lfm().ocmsmenu([{lbl:"Filter",itm:a}]);$$.i({placeholder:$ict.in}).appendTo($$.dc("mth ivn",n)).enterKey((function(e){let t=$(this),n=t.val()||"";e.stopPropagation(),t.parent().siblings().rC("selected"),n.length>3&&(t.parent().aC("selected"),$inv.renderinv("i:"+n,"s","all"),t.val(""))})),$$.i({placeholder:$ict.cc}).appendTo($$.dc("mth ivc",n)).enterKey((function(e){let t=$(this),n=t.val()||"";e.stopPropagation(),t.parent().siblings().rC("selected"),n.length>=3&&(t.parent().aC("selected"),$inv.renderinv("c:"+n,"s","all"),t.val(""))}));"#"===e.substr(0,1)&&$$.dc("mth extra",n).text($ict.iov[e].replace(")",$ict.uba)).click((function(t){let n=$(this);if(t.stopPropagation(),n.siblings().rC("selected"),!0===n.is(".selected")){n.toggleClass("selected");let t=fdt(new Date,"yy-MM-dd");$inv.renderinv(t,"a",e)}n.aC("selected")})),n.append("
");let r=$$.dc("mthl",n),l=t.getFullYear(),s=t.getMonth()+1;for(let t=i.getFullYear();t<=l;t++){let n=$$.dc("yr").prependTo(r).text($ict.iov[e]+" - "+t.toString()).toggleClass("selected",t===l);n.click({yr:t},(function(e){e.stopPropagation(),n.siblings().rC("selected"),n.aC("selected")}));let a=$$.dc("mfrm",n);for(let n=0;n<(t!==l?12:s);n++){i=new Date(t,n,1);let r=$$.dc("mth").prependTo(a).text($ict.iov[e]+" - "+fdt(i,"MMM yyyy"));if(r.click({yr:t,mt:n},(function(t){if(t.stopPropagation(),r.siblings().rC("selected"),!0===r.is(".selected")){r.toggleClass("selected");let n=fdt(new Date(t.data.yr,t.data.mt,1),"yy-MM-dd");$inv.renderinv(n,"m",e)}r.aC("selected")})),""===e){$$.dc("mthdl",r).append(gi("compressed","ico")).click({yr:t,mt:n},(function(e){e.stopPropagation();let t=fdt(new Date(e.data.yr,e.data.mt,1),"yy-MM-dd");$inv.downloadzip(t,"m")}))}let l=getMonday(i),s=new Date(i);s.setMonth(s.getMonth()+1),s.setDate(0),s=getMonday(s);let d=$$.dc("wfrm",r);for(;l<=s;){let t=$$.dc("wk",d).text(($ict.wk||"W")+" "+fdt(l,"dd.MM.yy"));t.click({rd:new Date(l)},(function(n){n.stopPropagation();let i=fdt(n.data.rd,"yy-MM-dd");$inv.renderinv(i,"w",e),r.siblings().rC("selected").find(".wk").rC("selected"),r.aC("selected").find(".wk").rC("selected"),t.aC("selected")})),$$.dc("wkdl",t).append(gi("compressed","ico")).click({rd:new Date(l)},(function(e){e.stopPropagation();let t=fdt(e.data.rd,"yy-MM-dd");$inv.downloadzip(t,"w")})),l.setDate(l.getDate()+7)}}}n.ldng(0)},rerenderinv:function(){let e=$("#contentframe .invfrm:first");if(e.length>0){let t=e.data("sets")||{};t.mode&&$inv.renderinv(t.tgt,t.mode,t.includes)}},renderinv:function(e,t,n){let i=$fis.frm_list(!0,!0).ldng(1),a=$$.dc("invfrm",i).aC("md"+t).data("sets",$.extend({},{tgt:e,mode:t,includes:n})),r=$fis.lf();$ocms.postXT({url:$ocms.url("inv/invl"),data:{mode:t,tgt:e,includes:n},success:i=>{r.rC("fix").aC("hd"),$$.dc("ovhd",a).text(i.admin.title);let l=$$.tblset({},a),s=$invcol.inv,d=$$.tr(l.hd);$$.th(d);$.each(s.fields||[],((e,t)=>{$$.th(d).text(t.label),"vat"===t.name&&$$.th(d)})),$.each(i.invoices||[],((d,c)=>{let o=$$.tr(l.bdy);o.click((function(){r.rC("fix").aC("hd"),o.toggleClass("selected").siblings().rC("selected").find("td.av").rC("av"),o.find("td.av").rC("av"),!0===o.is(".selected")?$inv.iMn(c):$inv.eM()}));let u=$$.td(o,{class:"raux"});c.hasFile?($$.dc("idl ilbtn",u,{title:$ict.dl+"\n"+c.DocumentName}).append(gi("save-file","ico")).click({id:c.Id},$inv.downloadinv),$$.dc("idl ilbtn",u,{title:$ict.dsp+"\n"+c.DocumentName}).append(gi("eye-open","ico")).click({id:c.Id,typ:"inv"},$inv.jdisp)):!1===c.isFinal&&!0===$fis.isAuth("fds_inv",2)&&$$.dc("idl ilbtn",u,{title:$ict.ed}).append(gi("edit","ico")).click({id:c.Id},$inv.doContInv),$$.dc("iitm ilbtn",u,{title:$ict.sItm}).append(gi("list","ico")).click({id:c.Id},$inv.showitm),$$.dc("iitm ilbtn",u,{title:$ict.sPay}).append(gi("euro","ico")).click({id:c.Id},$inv.showpay),$.each(s.fields||[],((r,l)=>{let s,d,u=$$.td(o).aC(l.dtype);switch("select"===(l.type||"")?u.text((l.url||{})[c[l.name]]||""):u.text(c[l.name]),l.name||""){case"vat":s=$$.sel().appendTo($$.td(o,{class:"vsel"})),d=(i.admin.ust_options||"19,0%;16,0%;0,0%").split(";"),$.each(d,((e,t)=>{$$.opt(t,t).appendTo(s)})),s.click((function(e){e.stopPropagation()})).val(c[l.name]).change().change({frm:a,tgt:e,mode:t,id:c.Id,td:u,includes:n},$inv.setvat),u.toggleClass("hl",c[l.name].substr(0,2)!==d[0].substr(0,2)).click((function(e){e.stopPropagation(),$(this).toggleClass("av")}));break;case"balance":u.aC("sh_"+(c.SollHaben||"").toLowerCase());break;case"invstatus":case"reminderstatus":u.aC(("invstatus"===l.name?"is_":"rs_")+c[l.name])}}))}))},complete:()=>{i.ldng(0)}})},setvat:function(e){let t=$(this),n=e.data||{};$ocms.postXT({url:$ocms.url("inv/setvat"),data:{id:n.id,val:t.val()},success:e=>{n.td.rC("av"),$inv.renderinv(n.tgt,n.mode,n.includes)}})},downloadzip:function(e,t){$(this).empty();window.open($ocms.url("inv/datevzip?mode="+t+"&tgt="+encodeURIComponent(e)),"_blank")},showitm:function(e){let t=$(this).closest("tr");e.stopPropagation(),!1!==t.is(".selected")&&$ocms.postXT({url:$ocms.url("inv/rqi"),data:{id:e.data.id},success:e=>{let t=$$.dc("rfrm");(e.requests||[]).length<1?t.text($ict.nd):$.each(e.requests||[],(function(e,n){let i=$$.dc("srq",t);$$.dc("nme",i).text(n.name);let a=$$.tblset({class:"if"},i);$.each(n.items||[],((e,t)=>{let n=$$.tr({id:"itm"+t.Id}).appendTo(a.bdy);$$.td(n).text(t.NameOrNumber),$$.td(n).text(t.Type),$$.td(n).aC("currency").text(t.net_pos),$$.td(n).aC("currency").text(t.bo_pos),$$.td(n).aC("num").text(t.vat)}))})),$ocms.dlg(t,{width:1e3})}})},showpay:function(e){let t=$(this).closest("tr");e.stopPropagation(),!1!==t.is(".selected")&&$ocms.postXT({url:$ocms.url("inv/pyi"),data:{id:e.data.id},success:e=>{let t=$$.dc("rfrm");if((e.payments||[]).length<1)t.text($ict.nd);else{let n=$$.tblset({class:"if"},t),i=$$.tr(n.hd);$.each(["date","account","name","text","InvoiceID","amount","manual"],((e,t)=>{$$.th(i,$ict.payi[t])})),$.each(e.payments,((e,t)=>{let i=$$.tr({id:"itm"+t.banking_uid}).appendTo(n.bdy);$$.td(i).aC("date").text(t.date),$$.td(i).text(t.account),$$.td(i).text(t.name),$$.td(i).text(t.text),$$.td(i).text(t.InvoiceID),$$.td(i).aC("currency").text(t.amount),$$.td(i).text(t.manual)}))}$ocms.dlg(t,{width:1e3,title:"Übersicht der Zahlungen"})}})},downloadinv:function(e){let t=$(this).closest("tr");e.stopPropagation(),!1!==t.is(".selected")&&window.open($ocms.url("inv/rdoc?id="+e.data.id),"_blank")},doContInv:function(e){let t=$(this).closest("tr");e.stopPropagation(),!1!==t.is(".selected")&&$inv.cntInv({id:e.data.id})}},$$inv={init2:$inv.init2,auth:{}};export default $$inv;$inv.cInv=function(e){let t=$(this).closest("tr");e.stopPropagation(),!1!==t.is(".selected")&&!1!==$fis.isAuth("fds_inv",2)&&$inv.cInv2({id:e.data.id})},$inv.rMn=e=>{let t=[{lbl:$ict.req,itm:[]}];return!0===bool(e,!1)&&!0===$fis.isAuth("fds_inv",2)&&Array.prototype.push.apply(t[0].itm,[{lbl:$rct.crI,fnc:$inv.ccInv,data:{typ:"r"}},{lbl:$rct.crII,fnc:$inv.ccInv,data:{typ:"i"}}]),t.push({lbl:$ict.rel,fnc:$inv.rReload}),$("#topbar").ocmsmenu(t)},$inv.iMnr=e=>{let t=booln(e.isFinal,!0),n=e.Id,i=booln(e.fds,!1),a=[{glyph:"glyphicon-menu-left",fnc:()=>{$fis.frm_edit().remove()}},{lbl:$ict.inv,itm:[]},{lbl:$ict.rem,itm:[]}];return!1===t&&!0===$fis.isAuth("fds_inv",2)?a[1].itm.push({lbl:$ict.ced,fnc:$inv.clCntInv}):!0===$fis.isAuth("fds_inv",1)&&a[1].itm.push({lbl:$ict.dsp,fnc:()=>$inv.disp(n,"inv")}),!0===i&&!0===t&&!0===$fis.isAuth("fds_inv",2)&&(a[1].itm.push({lbl:$ict.storno,fnc:()=>$inv.storno(n,i)}),a[1].itm.push({lbl:$ict.credit,fnc:()=>$inv.credit(n,i)})),!0===t&&!0===$fis.isAuth("fds_reminder",2)&&(a[2].itm.push({lbl:$ict.remd,fnc:()=>$inv.ccRem(n,e.InvoiceId)}),a[2].itm.push({lbl:$ict.remlst,fnc:()=>$inv.dspRem(n)})),!0===t&&!0===$fis.isAuth("fds_reminder",2)&&!1===booln(e.IsSent,!1)&&a[2].itm.push({lbl:$ict.srs,fnc:()=>$inv.srs(n)}),a.push({lbl:$ict.rel,fnc:$inv.rReload}),$("#topbar").ocmsmenu(a)},$inv.iMn=e=>{let t=booln(e.isFinal,!0),n=e.Id,i=booln(e.fds,!1),a=[{glyph:"glyphicon-menu-left",fnc:()=>{$fis.frm_edit().remove()}},{lbl:$ict.inv,itm:[]},{lbl:$ict.rem,itm:[]}];return!1===t&&!0===$fis.isAuth("fds_inv",2)?a[1].itm.push({lbl:$ict.ced,fnc:()=>{$inv.cntInv({id:n})}}):!0===$fis.isAuth("fds_inv",1)&&a[1].itm.push({lbl:$ict.dsp,fnc:()=>$inv.disp(n,"inv")}),!0===$fis.isAuth("fds_inv",2)&&(a[1].itm.push({lbl:$ict.storno,fnc:()=>$inv.storno(n,i)}),a[1].itm.push({lbl:$ict.credit,fnc:()=>$inv.credit(n,i)})),!0===t&&!1===booln(e.IsPayed,!1)?(!0===$fis.isAuth("fds_reminder",2)&&a[2].itm.push({lbl:$ict.remd,fnc:()=>$inv.ccRem(n,e.InvoiceId)}),!0===$fis.isAuth("fds_inv",2)&&a[1].itm.push({lbl:$ict.setpyd,fnc:()=>$inv.setPyd(n)})):!0===t&&!0===booln(e.IsPayed,!1)&&"m"===(e.PaymentStatus||"")&&!0===$fis.isAuth("fds_inv",2)&&a[1].itm.push({lbl:$ict.setupd,fnc:()=>$inv.setUpd(n)}),!0===$fis.isAuth("fds_reminder",2)&&a[2].itm.push({lbl:$ict.remlst,fnc:()=>$inv.dspRem(n)}),!0===t&&!0===$fis.isAuth("fds_inv",2)&&!1===booln(e.IsSent,!1)&&a[1].itm.push({lbl:$ict.sis,fnc:()=>$inv.sis(n)}),!1===i&&a[1].itm.push({lbl:$ict.mfr,fnc:()=>$inv.mfrrel(n)}),$("#topbar").ocmsmenu(a)},$inv.eM=(e,t,n)=>{let i=[];return!0!==booln(e,!1)&&!0!==booln(t,!1)||i.push({glyph:"glyphicon-menu-left",fnc:()=>{$fis.lf(!0),$fis.frm_edit().remove()}}),!0===(n||"").split(",").includes("iss")&&i.push({lbl:$ict.iss,fnc:$inv.ssave}),!0===(n||"").split(",").includes("ctp")&&i.push({lbl:$ict.ctp,fnc:$inv.sctp}),!0===(n||"").split(",").includes("p13b")&&i.push({lbl:$ict.p13b,fnc:$inv.sp13b}),!0===(n||"").split(",").includes("setm")&&i.push({lbl:$ict.setm,fnc:$inv.ssetmode}),!0===(n||"").split(",").includes("iss")&&(i.push({lbl:"Änderungshistorie",fnc:()=>$inv.d.history()}),i.push({lbl:"Änderungen verwerfen",fnc:()=>$inv.d.discard()})),!0===booln(e,!1)&&i.push({lbl:$ict.rel,fnc:$inv.rReload}),$("#topbar").ocmsmenu(i)},$inv.d={tbl:()=>$("div.invoice_layout table.invi"),layout:()=>$("div.invoice_layout"),token:function(){return $inv.d.tbl().data("dtoken")||""},hashes:function(){let e=$inv.d.tbl().data("bai")||[],t={};return $.each(e,((e,n)=>{t[(n.Id||"").toString()]=JSON.stringify(n)})),t},seed:function(e){let t=$inv.d.layout();t.aC("freeze"),$ocms.postXT({url:$ocms.url("inv/dopen"),data:{payload:JSON.stringify(e)},success:e=>{$inv.d.tbl().data("dtoken",e.token).data("dver",e.version).data("dhashes",$inv.d.hashes()).data("dorder",$inv.d.order()),$fis.draft.bind(e.token,{onReady:()=>$inv.d.refresh(),onExpiring:e=>$inv.d.warnExpiry(e),onClosed:e=>$inv.d.closed(e)}),$inv.d.refresh()},error:()=>{t.rC("freeze")},complete:()=>{$inv.d.tbl().removeData("dseeding")}})},refresh:function(e){let t=$inv.d.token();""!==t&&$ocms.postXT({url:$ocms.url("inv/dstate"),data:{token:t},success:t=>{$inv.d.applyState(t),"function"==typeof e&&e(t)},error:e=>{e&&410===e.status&&$inv.d.closed("expired")},complete:()=>{$inv.d.layout().rC("freeze")}})},applyState:function(e){let t=$inv.d.tbl();t.length<1||(t.data("dver",e.version).data("serverSums",e.sums),$inv.d.footer(t,e.sums||{},e.admin||{}),$inv.d.validation(e.validation||[]),$inv.d.applyPositions(t,e.req||[]))},applyPositions:function(e,t){(t||[]).forEach((t=>(t&&t.itm||[]).forEach((t=>{if(!t||""===(t.id||""))return;let n=e.find("#itm"+t.id+" td.keep").first();n.length&&n.text(null!=t.p?t.p:"")}))))},sync:function(e){let t=$inv.d.token();""!==t&&($inv.d.layout().aC("freeze"),$ocms.postXT({url:$ocms.url("inv/dpatch"),data:{token:t,delta:JSON.stringify(e)},success:()=>{$inv.d.refresh()},error:e=>{$inv.d.layout().rC("freeze"),e&&410===e.status&&$inv.d.closed("expired")}}))},order:function(){return($inv.d.tbl().data("bai")||[]).map((e=>(e.Id||"").toString()))},syncChanged:function(e){if(""===$inv.d.token())return;let t=e.data("bai")||[],n=e.data("dhashes")||{},i={},a=[],r=[];$.each(t,((e,t)=>{let r=(t.Id||"").toString(),l=JSON.stringify(t);i[r]=l,n[r]!==l&&a.push(t)})),$.each(n,(e=>{void 0===i[e]&&r.push(e)}));let l=$inv.d.order(),s=e.data("dorder")||[];e.data("dhashes",i).data("dorder",l),a.forEach((e=>$inv.d.sync({Target:"block.replace",Ref:(e.Id||"").toString(),Value:e}))),r.forEach((e=>$inv.d.sync({Target:"block.remove",Ref:e}))),s.length===l.length&&s.slice().sort().join(",")===l.slice().sort().join(",")&&s.join(",")!==l.join(",")&&$inv.d.sync({Target:"block.order",Value:l})},syncField:function(e,t){if(""===$inv.d.token())return;let n={invoicetitle:"title",invoiceaddress:"address",invoiceemail:"email",loc:"provisionlocation",provisionlocation:"provisionlocation",provisionperiod:"provisionperiod"}[e];n&&$inv.d.sync({Target:n,Value:t})},footer:function(e,t,n){let i=e.children("tfoot").empty();e.nextAll(".fnote").remove();let a=bool(n.p13b,!1),r=(e,t,n)=>$$.tdc("currency",$$.tr(i,{class:n||"tsum"}).append([$$.tdc("aux"),$$.td({colspan:4}).text(e)]),fnum(t,$rct.cst)),l=t=>$$.dc("fnote").insertAfter(e).rwText(t);r("Netto",t.total_net||0),!1===a&&$.each(t.vat||{},((e,t)=>r($rct.vat+" "+e+"%",t,"tvat"))),r("Summe",t.total_gross||0);let s=n.type||"";"i"===s?(l($rct.note2),l($rct.note4)):"c"===s?l($rct.note2):(l(string($rct.note3,[fnum(((t.service_net||0)+(t.service_vat||0))*(n.tax_servicerefund||0),$rct.cst)])).aC("ntax"),l($rct.note2),l(string($rct.note1,[fnum((t.service_net||0)+(t.service_vat||0),$rct.cst),fnum(t.service_net||0,$rct.cst),fnum(t.service_vat||0,$rct.cst)]))),!0===a&&l($rct.note13b)},validation:function(e){let t=$("div.invoice_layout");if(t.length<1)return;let n=t.children(".dvalidation");n.length<1&&(n=$$.dc("dvalidation"),t.prepend(n)),n.empty().tC("hidden",(e||[]).length<1),$.each(e||[],((e,t)=>$$.dc("dvmsg",n).aC(t.severity).text(t.message)))},preview:function(){let e=$inv.d.token();if(""===e)return;let t=$inv.d.layout(),n=($inv.d.tbl().data("new")||{}).invoiceemail||"";!1===$fis.ValidateEmail(n)&&!1===bool(confirm($ict.ivE+$ict.ivEc),!1)||(t.aC("freeze"),$ocms.postXT({url:$ocms.url("inv/dpreview"),data:{token:e},success:n=>{t.rC("freeze");let i=$$.dc("imagecollection pdfpreview"),a=Math.round(.88*vh()),r=n.total;r>10&&$$.dc("note warn",i).text($ict.tpe),$.each(n.img||[],((e,t)=>{$$.dc("pdfp",i).append($$.img(t).css("max-height",(a-rpx(6)).toString()+"px"))}));for(let e=(n.img||[]).length+1;e<=r;e++)$$.dc("pdfp ph",i).append($$.dc("note",$ict.pna));$ocms.dlg(i,{size:[a,Math.round(.88*vw())],zindex:50,form:!1,button:$rct.crI,confirm:function(n){let i=$(this);t.aC("freeze"),$ocms.postXT({url:$ocms.url("inv/dsave"),data:{token:e},success:e=>{$ocms.postXT({url:$ocms.url("req/sconf"),data:{id:e.invid},success:t=>{i.trigger("modal_close"),!0===t.hasFile&&window.open($ocms.url("req/idoc")+"?id="+e.invid,"_blank"),$inv.d.close(),$ocms.init("req"),$inv.rReload()},error:()=>{alert($t.f1),i.trigger("modal_close")},complete:()=>{t.rC("freeze")}})},error:()=>{t.rC("freeze"),alert($ict.eis)}})},cancel:function(e){confirm($ict.cdI)&&($inv.d.close(),$inv.rReload())}})},error:()=>{t.rC("freeze"),alert($ict.eis)}}))},save:function(){let e=$inv.d.token();if(""===e)return;let t=$inv.d.layout();t.aC("freeze"),$ocms.postXT({url:$ocms.url("inv/dsave"),data:{token:e},success:e=>{$inv.d.tbl().data("invid",e.invid)},error:()=>{alert($ict.eis)},complete:()=>{t.rC("freeze")}})},history:function(){let e=$inv.d.token();""!==e&&$ocms.postXT({url:$ocms.url("inv/dhistory"),data:{token:e},success:e=>{let t=$$.dc("dhist");if((e.history||[]).length<1)$$.dc("note",t).text("Noch keine Änderungen erfasst.");else{let n=$$.tblset({class:"invtbl fullwidth"},t);$$.tr(n.hd).append([$$.th().text("Zeit"),$$.th().text("Feld"),$$.th().text("Alt"),$$.th().text("Neu")]),$.each(e.history,((e,t)=>$$.tr(n.bdy).append([$$.tdc("keep",fdt(t.timestamp)),$$.td().text(t.target),$$.td().text(t.oldValue),$$.td().text(t.newValue)])))}$ocms.dlg(t,{width:800,form:!1})}})},discard:function(){let e=$inv.d.tbl().data("invid")||"";""!==e?!1!==confirm("Alle Änderungen verwerfen und den zuletzt gespeicherten Stand neu laden?")&&($inv.d.close(),$inv.cntInv({id:e})):alert("Es wurde noch kein Zwischenstand gespeichert, der wiederhergestellt werden könnte.")},warnExpiry:function(e){let t=Math.max(1,Math.round((e||0)/60));$fis.notifications.push({severity:"info",title:"Entwurf läuft ab",message:"Der Rechnungsentwurf läuft in etwa "+t+" Minute(n) ab. Bitte zwischenspeichern, sonst gehen die Änderungen verloren."})},closed:function(e){let t=$inv.d.token();$inv.d.tbl().removeData("dtoken"),""!==t&&$fis.draft.release(t),$fis.frm_edit().remove(),$fis.lf(!0),$fis.notifications.push({severity:"error",title:"Entwurf geschlossen",message:"expired"===e?"Der Rechnungsentwurf ist wegen Inaktivität abgelaufen. Nicht gespeicherte Änderungen sind verloren.":"Der Rechnungsentwurf wurde geschlossen."});try{$inv.rReload()}catch(e){}},close:function(){let e=$inv.d.token();""!==e&&($ocms.postXT({url:$ocms.url("inv/dclose"),data:{token:e}}),$fis.draft.release(e)),$inv.d.tbl().removeData("dtoken")}},$inv.cInv2=function(e){let t=$$.dc("rfrm").ldng(1),n=$ocms.dlg(t,{width:1e3});n&&n.ft.rwText($rct.rq1);let i=()=>{$ocms.postXT({url:$ocms.url("req/get"),timeout:60,data:{id:e.id,mode:"r"},success:t=>{t.admin=t.admin||{};let n=$fis.lf(!0).aC("fix").rC("hd");if($fis.frm_edit().IN(),$inv.eM(!0,!0),(t.requests||[]).length<1)n.aC("fix").text($rct.nd);else{$$.dc("lh",n,$rct.mdl);let i=$$.d(),a=$$.ul({class:"rql"}).data({search:e.id,parent:t.admin.parent}).appendTo(n),r={},l=$rcol.req.lbl();$.each(t.requests||[],(function(e,t){let n=$$.li({class:"cli rli"}).data($.extend({},t)).appendTo(a),s=$$.dc("lihd",n).addClass(t.state);!0===booln(t.open,!1)&&s.append($$.sc("cbox").click((()=>{n.tC("checked"),i.find("li").rC("checked"),!0===n.is(".checked")?$inv.rMn(t.open):$inv.eM(!0)}))),s.append([$$.sc("eid",t.ExternalId),$$.sc("nme",t.Name)]),$$.dc("lidt",n).append([$$.dc("rqs").append([$$.s(l.State+": "),$$.s($rct.sts[t.State||"-"])]),$$.dc("ivn").append([$$.s(l.InvoiceId+": "),$$.s(t.InvoiceId||"- -")]),$$.dc("wda").append([$$.s(l.WorkDoneAt+": "),$$.s(fdt(t.WorkDoneAt,"dd.MM.yyyy"))])]),r[t.Id]=n})),(t.inv||[]).length>0&&($$.dc("lh",n,$rct.invs),i=$$.ul({class:"ivl"}).appendTo(n),$.each(t.inv||[],((e,t)=>{let n=$$.li({class:"cli ili"}).data($.extend({},t)).appendTo(i),r=$$.dc("lihd",n).addClass(t.invstatus);!1===booln(t.isFinal,!0)?r.append($$.sc("cbox").click((()=>{""!==(t.Id||"")&&(n.tC("checked").siblings().rC("checked"),a.find("li").rC("checked"),!0===n.is(".checked")?$inv.iMnr(t):$inv.eM(!0))}))):["","dft"].indexOf(t.invstatus)<0&&r.append($$.sc("dli").click((function(){$inv.disp(t.Id,"inv")}))),r.append($$.sc("nme",t.DocumentName||t.Id)),$$.dc("lidt",n).append([$$.dc("wda").append([$$.s(fdt(t.DateCreated,"dd.MM.yyyy"))]),$$.d().text($ict.iSt[t.invstatus]||t.invstatus)])})))}},complete:()=>{n&&n.c.trigger("modal_close")}})};$ocms.postXT({url:$ocms.url("req/pget"),timeout:90,data:{id:e.id},success:e=>{n&&n.ft.rwText($rct.rq2),i()},error:()=>{confirm($rct.rq1f)?(n&&n.ft.rwText($rct.rq2),i()):n&&n.c.trigger("modal_close")}})},$inv.ccInv=function(e){let t=(e.data||{}).typ||"r",n=$fis.lf(),i=n.children("ul.rql"),a=i.data("parent"),r=[];if(i.find("li.rli.checked").each((function(){r.push($(this).data("Id"))})),r.length<1)return void alert($rct.dnS);if("i"===t&&r.length>1)return void alert($rct.dII);let l=$fis.frm_edit(),s=$$.dc("invoice_layout",l).append($$.dc("btn sprev").click($inv.sprev)),d=$fis.cf().width()>s.width()+n.width()+20;n.tC("fix",d).tC("hd",!d),$inv.eM(!1,!0);let c=$$.dc("rfrm").ldng(1),o=$ocms.dlg(c,{width:1e3});o.ft.rwText($rct.rq2),$ocms.postXT({url:$ocms.url("req/iget"),timeout:60,data:{id:a,mode:"ful",typ:t,sel:r.join(",")},success:e=>{let t=$$.dc("srq",s),n=$$.tblset({class:"invi"},t);n.bdy.remove(),n.ft=$$[0]("tfoot"),e.admin=e.admin||{},e.admin.p13b=bool(e.admin.p13b||"",!0===((e.inv||{}).InvoiceOptions||"").split(",").includes("§13b")),n.tbl.data($.extend({new:{},sms:{},itm:{}},{admin:e.admin,companies:e.companies,locations:e.locations}));let i=$$.tr(n.hd).aC("shd").append([$$.th().aC("aux")]);$rct.invHR.forEach((e=>$$.th(i,e))),n.tbl.on("fds.inv",$inv.invSumUpdate),$.each(e.requests||[],(function(t,i){if(0!==(i.Id||0)){let t=$inv.worknotes(i);i.text="i"===e.admin.type?$rct.req+jine([i.ExternalId,i.Name],": ").eine(" ",""):jine([jine([fdt(i.WorkDoneAt,"dd.MM.yy"),i.ExternalId]," - "+$rct.req+" "),t.ne(i.Name)],": \n");let a=$$.tbody(n.tbl).data($.extend({},i));$inv.rendersrq.call(a)}}));let a=$$.tr($$.tbody(n.tbl),{class:"placeholder"}).data({net_val:0,vat_val:0,svcnet_val:0,svcvat_val:0,net:0});$inv.rrw.call(a),n.ft.appendTo(n.tbl);let r,l,d=e.admin||{},c=(e,t,i,a,r)=>{let l=$$.dc("inpfrm",s).aC(e).append("string"==typeof a?$$.dc("ahd",a):a>0?$$.dc("ahd",$rct.frm[i]):null),d=$$.dc("content",l).rwText(t);$$.dc("axf",l).append($$.dc("ibtn edit").data("dialog",$rct.frm[i]).append(gi("pencil")).click($.extend({t:d,nme:i,change:e=>{n.tbl.data("new")[i]=e}},r),$inv.eHtml)),n.tbl.data("new")[i]=t};c("tfrm",d.invoicetitle,"invoicetitle",0,null),c("adrfrm",d.invoiceaddress,"invoiceaddress",0,null),c("locfrm","","loc",1,{list:deepCopy(e.locations),lbl:"ref",property:"address"}),c("emailfrm",d.invoiceemail,"invoiceemail",0,null),$$.dc("sndfrm",s).append($$.dc("content").text(d.sender)),d.provisionend&&(l=d.provisionstart?$rct.provP:$rct.provD,r=d.provisionstart?fdt(d.provisionstart,"dd.MM.yyyy")+" - "+fdt(d.provisionend,"dd.MM.yyyy"):fdt(d.provisionend,"dd.MM.yyyy")),c("admfrm",r,"provisionperiod",l,1),n.tbl.data("new").CustomValues=d.CustomValues||"",$$.dc("inpfrm ctpfrm",s).text(jObj(d.CustomValues,"contactName")),n.tbl.children("tbody").each($inv.bdysort),n.tbl.trigger("fds.inv"),$inv.eM(!1,!0,"iss,p13b,setm,ctp")},complete:()=>{o.c.trigger("modal_close")}})},$inv.ccStInv=function(e){let t=e.data||{},n=$fis.lf(),i=t.id,a=$$.dc("invoice_layout",$fis.frm_edit()).append($$.dc("btn sprev").click($inv.sprev)),r=$fis.cf().width()>a.width()+n.width()+20;n.tC("fix",r).tC("hd",!r),$inv.eM(!1,!0);let l=$$.dc("rfrm").ldng(1),s=$ocms.dlg(l,{width:1e3});s.ft.rwText($ict.iq1),$ocms.postXT({url:$ocms.url("inv/pget"),timeout:90,data:{id:t.id},success:e=>{s&&s.ft.rwText($ict.iq2),$ocms.postXT({url:$ocms.url("inv/icget"),timeout:60,data:{id:i},success:e=>{let t=$$.dc("srq",a),n=$$.tblset({class:"invi"},t);n.bdy.remove(),n.ft=$$[0]("tfoot"),e.admin=e.admin||{},e.admin.p13b=bool(e.admin.p13b||"",!0===((e.inv||{}).InvoiceOptions||"").split(",").includes("§13b")),n.tbl.data($.extend({new:{},sms:{},itm:{}},{admin:e.admin,companies:e.companies,locations:e.locations}));let i=$$.tr(n.hd).aC("shd").append([$$.th().aC("aux")]);$rct.invHR.forEach((e=>$$.th(i,e))),n.tbl.on("fds.inv",$inv.invSumUpdate),$.each(e.requests||[],(function(t,i){if(0!==(i.Id||0)){let t=$inv.worknotes(i);i.text="i"===e.admin.type?$rct.req+jine([i.ExternalId,i.Name],": ").eine(" ",""):jine([fdt(i.WorkDoneAt,"dd.MM.yy")+t.ne(i.Name)],": ");let a=$$.tbody(n.tbl).data($.extend({},i));$inv.rendersrq.call(a)}}));let r=$$.tr($$.tbody(n.tbl),{class:"placeholder"}).data({net_val:0,vat_val:0,svcnet_val:0,svcvat_val:0,net:0});$inv.rrw.call(r),n.ft.appendTo(n.tbl);let l,s,d=e.admin||{},c=(e,t,i,r,l)=>{let s=$$.dc("inpfrm",a).aC(e).append("string"==typeof r?$$.dc("ahd",r):r>0?$$.dc("ahd",$rct.frm[i]):null),d=$$.dc("content",s).rwText(t);$$.dc("axf",s).append($$.dc("ibtn edit").data("dialog",$rct.frm[i]).append(gi("pencil")).click($.extend({t:d,nme:i,change:e=>{n.tbl.data("new")[i]=e}},l),$inv.eHtml)),n.tbl.data("new")[i]=t};c("tfrm",d.invoicetitle,"invoicetitle",0,null),c("adrfrm",d.invoiceaddress,"invoiceaddress",0,null),c("locfrm",d.provisionlocation,"loc",1,{list:deepCopy(e.locations),lbl:"ref",property:"address"}),c("emailfrm",d.invoiceemail,"invoiceemail",0,null),$$.dc("sndfrm",a).append($$.dc("content").text(d.sender)),d.provisionend&&(s=d.provisionstart?$rct.provP:$rct.provD,l=d.provisionstart?fdt(d.provisionstart,"dd.MM.yyyy")+" - "+fdt(d.provisionend,"dd.MM.yyyy"):fdt(d.provisionend,"dd.MM.yyyy")),c("admfrm",l,"provisionperiod",s,1),n.tbl.data("new").CustomValues=d.CustomValues||"",$$.dc("inpfrm ctpfrm",a).text(jObj(d.CustomValues,"contactName")),n.tbl.children("tbody").each($inv.bdysort),n.tbl.trigger("fds.inv")},complete:()=>{s.c.trigger("modal_close")}})},error:()=>{s&&s.c.trigger("modal_close")}})},$inv.clCntInv=function(e){let t=$fis.lf(!1),n=[];t.find("li.ili.checked").each((function(){n.push($(this).data("Id"))})),1===n.length&&$inv.cntInv({id:n[0]})},$inv.cntInv=function(e){e=e||{};$fis.lf(!1).rC("fix").aC("hd");let t=$$.dc("invoice_layout",$fis.frm_edit()).append($$.dc("btn sprev").click($inv.sedit));$inv.eM(!1,!0);let n=$$.dc("rfrm").ldng(1),i=$ocms.dlg(n,{width:1e3});i.ft.rwText($rct.rq2),$ocms.postXT({url:$ocms.url("inv/get"),timeout:60,data:{id:e.id},success:e=>{e.admin=e.admin||{};let n=e.inv||{},i=$$.dc("srq",t),a=$$.tblset({class:"invi"},i);a.bdy.remove(),a.ft=$$[0]("tfoot"),a.tbl.data($.extend({invid:n.Id,new:{},sms:{},itm:{},bai:[]},e));let r=$$.tr(a.hd).aC("shd").append([$$.th().aC("aux")]);$rct.invHR.forEach((e=>$$.th(r,e))),a.tbl.on("fds.inv",$inv.invSumUpdate),$.each(e.req||[],(function(e,t){let n=$$.tbody(a.tbl).data($.extend({},t));$inv.rendersrq.call(n)}));let l=$$.tr($$.tbody(a.tbl),{class:"placeholder"}).data({net_val:0,vat_val:0,svcnet_val:0,svcvat_val:0,net:0});$inv.rrw.call(l),a.ft.appendTo(a.tbl);let s=(e,n,i,r,l)=>{let s=$$.dc("inpfrm",t).aC(e).append("string"==typeof r?$$.dc("ahd",r):r>0?$$.dc("ahd",$rct.frm[i]):null),d=$$.dc("content",s).rwText(n);$$.dc("axf",s).append($$.dc("ibtn edit").data("dialog",$rct.frm[i]).append(gi("pencil")).click($.extend({t:d,nme:i,change:e=>{a.tbl.data("new")[i]=e}},l),$inv.eHtml)),a.tbl.data("new")[i]=n};s("tfrm",n.InvoiceTitle,"invoicetitle",0,null),s("adrfrm",n.SendToAddress,"invoiceaddress",0,null),s("locfrm",n.ProvisionLocation,"loc",1,null),s("emailfrm",n.SendToEmail,"invoiceemail",0,null),$$.dc("sndfrm",t).append($$.dc("content").text(e.admin.sender)),s("admfrm",n.ProvisionPeriod,"provisionperiod",!0===(n.ProvisionPeriod||"").includes("-")?$rct.provP:$rct.provD,1),a.tbl.data("new").CustomValues=n.CustomValues||"",$$.dc("inpfrm ctpfrm",t).text(jObj(n.CustomValues,"contactName")),a.tbl.children("tbody").each($inv.bdysort),a.tbl.trigger("fds.inv"),$inv.eM(!1,!0,"iss,p13b,setm,ctp")},complete:()=>{i.c.trigger("modal_close")}})},$inv.cSt=function(e){e=e||{};let t=$fis.lf(),n=$$.dc("invoice_layout",$fis.frm_edit()).append($$.dc("btn sprev").click($inv.sedit)),i=$fis.cf().width()>n.width()+t.width()+20;t.tC("fix",i).tC("hd",!i),$inv.eM(!1,!0);let a=$$.dc("rfrm").ldng(1),r=$ocms.dlg(a,{width:1e3});r.ft.rwText($ict.iq1),$ocms.postXT({url:$ocms.url("inv/pget"),data:{id:e.id},success:t=>{r&&r.ft.rwText($ict.iq2),$ocms.postXT({url:$ocms.url("inv/storno"),data:{id:e.id,mode:e.mode},success:e=>{e.admin=e.admin||{},e.admin.p13b=bool(e.admin.p13b||"",!0===((e.inv||{}).InvoiceOptions||"").split(",").includes("§13b"));let t=e.inv||{},i=$$.dc("srq",n),a=$$.tblset({class:"invi"},i);a.bdy.remove(),a.ft=$$[0]("tfoot"),a.tbl.data($.extend({invid:t.Id,new:{},sms:{},itm:{},bai:[]},e));let r=$$.tr(a.hd).aC("shd").append([$$.th().aC("aux")]);$rct.invHR.forEach((e=>$$.th(r,e))),a.tbl.on("fds.inv",$inv.invSumUpdate),$.each(e.req||[],(function(e,t){let n=$$.tbody(a.tbl).data($.extend({},t));$inv.rendersrq.call(n)}));let l=$$.tr($$.tbody(a.tbl),{class:"placeholder"}).data({net_val:0,vat_val:0,svcnet_val:0,svcvat_val:0,net:0});$inv.rrw.call(l),a.ft.appendTo(a.tbl);let s=(e,t,i,r,l)=>{let s=$$.dc("inpfrm",n).aC(e).append("string"==typeof r?$$.dc("ahd",r):r>0?$$.dc("ahd",$rct.frm[i]):null),d=$$.dc("content",s).rwText(t);$$.dc("axf",s).append($$.dc("ibtn edit").data("dialog",$rct.frm[i]).append(gi("pencil")).click($.extend({t:d,nme:i,change:e=>{a.tbl.data("new")[i]=e}},l),$inv.eHtml)),a.tbl.data("new")[i]=t};s("tfrm",t.InvoiceTitle,"invoicetitle",0,null),s("adrfrm",t.SendToAddress,"invoiceaddress",0,null),s("locfrm",t.ProvisionLocation,"loc",1,null),s("emailfrm",t.SendToEmail,"invoiceemail",0,null),$$.dc("sndfrm",n).append($$.dc("content").text(e.admin.sender)),s("admfrm",t.ProvisionPeriod,"provisionperiod",!0===(t.ProvisionPeriod||"").includes("-")?$rct.provP:$rct.provD,1),a.tbl.data("new").CustomValues=t.CustomValues||"",$$.dc("inpfrm ctpfrm",n).text(jObj(t.CustomValues,"contactName")),a.tbl.children("tbody").each($inv.bdysort),a.tbl.trigger("fds.inv")},complete:()=>{r.c.trigger("modal_close")}})},error:()=>{r&&r.c.trigger("modal_close")}})},$inv.eHtml=function(e){let t=$(this),n=e.data instanceof jQuery?e.data:e.data.t,i=["invoiceemail","provisionperiod","invoicetitle"].includes(e.data.nme),a=i?[{name:"txt",label:"Text",type:"text",value:n.text()}]:[{name:"txt",label:"Text",type:"html",value:n.html(),tinymce:!0,attr:{style:"height: 300px"}}],r=e.data.change||null,l={title:t.data("dialog")||"",success:function(t){i?n.text(t.txt||""):n.html(t.txt),"function"==typeof r&&r(t.txt),$inv.d.syncField(e.data.nme,i?t.txt||"":t.txt)},tinymce:{valid_elements:"br",hidemenu:!0,hidetoolbar:!0}};if(Array.isArray(e.data.list)){let t=$$.dc("lstfrm");$.each(e.data.list,((n,i)=>{let a=$$.dc("li",t).append(""!==(e.data.lbl||"")?$$.dc("lbl").rwText(i[e.data.lbl]):null);$$.dc("adr",a).rwText(i[e.data.property]).data("val",i[e.data.property]).click((function(){let e=$(this),t=e.closest(".modal-body").find(':input[name="txt"]');t.is(".tinymce")?tinymce.get(t.attr("id")).setContent($$.s().rwText(e.data("val")).html()):"TEXTAREA"===t.prop("tagName")?t.val(e.data("val")).change():t.rwText(e.data("val"))}))})),l.addcontent=t}$ocms.dlgform(a,l)},$inv.setVat=function(e){$(this);let t=e.data,n=prompt($rct.rqV);n&&(n=parseFloat(n.replace("%","")),n>1&&(n*=.01),!1===isNaN(n)&&(t.siblings(".itm").each((function(){let e=$(this).data();e.vat=fnum(n,{style:"percent"}).replace(" ",""),(e.net_val||0)>0&&(e.vat_val=e.net_val*n),(e.svcnet_val||0)>0&&(e.svcvat_val=e.svcnet_val*n)})),$inv.t_fds_inv()))},$inv.inRow=function(e){let t=$(this),n=e.data,i={},a=$rcol.itm.clone(["SortOrder","NameOrNumber","Type","quantityhours","UnitString","net","svcnet_val","svcvat_val","net_val","vat_val","vat","Note"]),r="N"+(65536*(1+Math.random())||0).toString(16).substr(6),l=$$.tr({id:"itm_"+r.toString(),class:"itm"});$ocms.dlgform(a,{title:t.data("dialog")||"",success:function(e){l.data($.extend({Id:r},i,e)),$inv.rrw.call(l),l.insertAfter(n),$inv.t_fds_inv()},typedvalues:!0})},$inv.eRow=function(e){let t=$(this),n=e.data,i=n.data()||{},a=["SortOrder","NameOrNumber","Type","quantityhours","UnitString","net","svcnet_val","svcvat_val","net_val","vat_val","vat","Note"];i.id||""!==(i.Type||"")||a.unshift("Type");let r=$rcol.itm.clone(a).applyValues(i);r.set("Type","hidden","type"),$inv.eRw.call(t,n,i,r)},$inv.eRw=function(e,t,n){let i=$(this);$ocms.dlgform(n,{title:i.data("dialog")||"",success:function(n){let i={};""===(t.Id||"")&&(i.Id="N"+(65536*(1+Math.random())||0).toString(16).substr(6),e.attr("id","itm_"+i.Id.toString())),i.quantity=((n.quantityhours||"").toString()+" "+(n.UnitString||"").toString()).trimEnd(),e.data($.extend({},t,n,i)),console.debug("eRw success %o",e.data()),$inv.rrw.call(e),$inv.t_fds_inv()},typedvalues:!0})},$inv.bdysort=(e,t)=>{$(t).Sortable({dragItem:!1,dragHandleClass:"ico",parentident:"tr",onend:()=>{$inv.t_fds_inv()}})},$inv.rrw=function(){let e=$(this),t=e.data(),n={},i=e.is(".placeholder"),a=e.is(".hidenote"),r=e=>$$.d().append(e).html(),l=[$$.dc("ibtn insb",{title:$rct.iRb}).append(gi("indent-left")).click(e,$inv.inRow)];!1===i&&(l.unshift($$.dc("ibtn edit",{title:$rct.cP}).append(gi("pencil")).click(e,$inv.eRow)),l.push($$.dc("ibtn del",{title:$rct.dR}).append(gi("trash")).click((function(t){confirm($rct.cD)&&(e.remove(),$inv.t_fds_inv())}))));let s=$$.dc("axf").append(l);!0===i?n={id:"",typ:"placeholder"}:!0===e.is(".itm.osum")?n={invrqid:t.InvRqId,id:"osum"+e.index(),typ:"osum",p:"",q:null,t:r(t.tbl.tbl),tt:null,v:null,vt:t.net_val,vs:t.svcnet_val,vat:t.vat,vv:t.vat_val,vsv:t.svcvat_val,det:!1}:(n={invrqid:t.InvRqId,id:t.Id||"",typ:t.Type||"other",p:"",q:null,t:"",tt:null,v:null,vt:t.net_val,vs:t.svcnet_val,vat:t.vat,vv:t.vat_val,vsv:t.svcvat_val,det:""!==(t.Note||"")&&!1===a},$$.dc("ibtn ico move",s,{title:$rct.mR}),n.p=t.position||t.SortOrder||"",""===n.id?n.t="":["Text","Title"].includes(n.typ)&&0===(t.net_val||0)?n.t=t.htmltext||("#"!==(t.NameOrNumber||"").substr(0,1)?r($$[0]("p").text(t.NameOrNumber)):"")+(t.Note||""):(n.tt=n.det?"":$$.s(t.Note||"").text(),n.q=t.quantity||fnum(t.quantityhours)+" "+(t.UnitString||""),n.t=t.htmltext||(n.det?r($$.s(t.NameOrNumber||""))+r($$.dc("desc").html(t.Note)):r($$.s(t.NameOrNumber||""))),n.v=t.net,n.vt=t.net_val)),""!==(t.Note||"")&&$$.dc("ibtn add",s).append(gi("object-align-left")).click((function(t){$inv.rrw.call(e.tC("hidenote"))}));let d=[$$.tdc("aux").append(s),$$.tdc("keep").text(n.p)];""===n.id?d.push($$.td(e,{colspan:4}).append(n.t)):(Array.prototype.push.apply(d,n.q?[$$.tdc("keep").text(n.q)]:[]),Array.prototype.push.apply(d,[$$.tdc("txt",{colspan:n.q?1:2,title:n.tt}).append(n.t),$$.tdc("currency").text(fnum(n.v,$rct.cst)),$$.tdc("currency inetval").text(fnum(n.vt,$rct.cst)).attr("title",$rct.svcPart+": "+fnum(n.vs,$rct.cst))])),e.empty().attr("class",i?"placeholder":"itm").aC(n.Typ).tC("hidenote",a).append(d),t.co=n},$inv.invSumUpdate=function(){let e=$(this),t=e.children("tfoot").empty(),n=bool((e.data().admin||{}).p13b||"",!1);e.nextAll(".fnote").remove();let i={ttn:0,ttb:0,ttvat:0,tscn:0,tscvat:0,vat:{},itmnet:{}},a=[],r=(e,n,i)=>$$.tdc("currency",$$.tr(t,{class:i||"tsum"}).append([$$.tdc("aux"),$$.td({colspan:4}).text(e)]),fnum(n,$rct.cst)),l=t=>$$.dc("fnote").insertAfter(e).rwText(t),s=e.children("tbody");s.each(((e,t)=>{let n=$(t),r=n.data()||{},l=[],s=[],d=null,c=0,o=n.find("tr.itm"),u=0;n.tC("empty",o.length<1),o.each(((e,t)=>{let n=$(t).data()||{};!function(e,t,n){t.tscn+=e.svcnet_val||0,t.tscvat+=e.svcvat_val||0,t.ttn+=e.net_val||0,t.ttvat+=e.vat_val||0,t.ttb+=(e.net_val||0)+(e.vat_val||0),""!==(e.vat||"")&&(t.vat[e.vat]=(t.vat[e.vat]||0)+(e.vat_val||0))}(n,i,r.Id),c+=n.net_val||0,l.push(n.co);let a=$inv.itemToContract(n);"set"===a.type&&""!==a.id?d=a.id:null!==d&&""!==(a.id||"")&&(a.setId=d),s.push(a),(void 0===n.SortOrder||null===n.SortOrder?-1:n.SortOrder)>-1&&(!1===["text","title"].includes((n.Type||"other").toLowerCase())&&u++,n.SortOrder=0,n.position=u,$inv.rrw.call(t))})),n.find("tr.isum > td.isumval").text(fnum(c,$rct.cst)),a.push({Id:r.Id,nme:r.Name,text:r.text,itm:l,items:s,netval:c})}));let d=e.find("tbody:not(.empty)").length;s.find("tr.isum").tC("hidden",d<2),r("Netto",i.ttn),!1===n?$.each(i.vat,((e,t)=>{r($rct.vat+" "+e,t,"tvat")})):i.ttb=i.ttn,r("Summe",i.ttb);let c=e.data().admin.type;"i"===c?(l($rct.note2),l($rct.note4)):"c"===c?l($rct.note2):(l(string($rct.note3,[fnum((i.tscn+i.tscvat)*(e.data().admin.tax_servicerefund||0),$rct.cst)])).aC("ntax"),l($rct.note2),l(string($rct.note1,[fnum(i.tscn+i.tscvat,$rct.cst),fnum(i.tscn,$rct.cst),fnum(i.tscvat,$rct.cst)]))),!0===n&&l($rct.note13b),e.data("sms",i),e.data("bai",a),""===(e.data("dtoken")||"")&&!1===bool(e.data("dseeding"),!1)&&null!=(e.data("admin")||{}).type&&(e.data("dseeding",!0),$inv.d.seed($.extend($inv.invcPayload(e.data()),{invid:e.data("invid")||""})))},$inv.worknotes=function(e){let t="";return e.steps.forEach(((e,n)=>{let i;try{i=JSON.parse(e.Data||{}).fields||[]}catch(e){console.debug(e),i=[]}!0!==Array.isArray(i||"")&&(i="object"==typeof i&&!0===Array.isArray(i.field||"")?i.field:[]),i.forEach(((e,n)=>{"Ausgeführte Arbeiten"===e.name&&(t=e.result||"")}))})),t},$inv.rendersrq=function(){let e=$(this).empty(),t=e.is(".onesum"),n=e.data(),i=$$.tr(e,{id:"srq"+n.Id}).aC("title nosort"),a=($rcol.itm.lbl(),$$.dc("axf").appendTo($$.tdc("aux",i)));$$.dc("ibtn osum",a,{title:$rct.combP}).append(gi("euro")).click((function(t){e.tC("onesum"),$inv.rendersrq.call(e),$inv.t_fds_inv()})),$$.dc("ibtn setvat",a,{title:$rct.sV}).append(gi("gbp")).click(i,$inv.setVat),$$.dc("ibtn insb",a,{title:$rct.iRb}).append(gi("indent-left")).click(i,$inv.inRow);let r,l=$$.sc("text",n.text),s=($$.td(i,{colspan:t?4:5}).append(l),["net_val","vat_val","svcnet_val","svcvat_val","net"]);if($$.dc("ibtn edit",a).data("dialog",$rcol.req.lbl().Name).append(gi("pencil")).click({t:l,change:e=>{n.text=e,$inv.t_fds_inv()}},$inv.eHtml),t&&($$.tdc("currency isumval",i),r={Id:n.Id.toString()+"_osum",net_val:0,vat_val:0,svcnet_val:0,svcvat_val:0,net:0},r.tbl=$$.tblset({class:"stbl"})),$.each(n.items||[],((n,i)=>{let a,l={Id:i.Id,net_val:i.net_val||0,vat_val:i.vat_val||0,svcnet_val:0,svcvat_val:0,net:i.net||0,Note:i.Note||""};if("service"===i.Type.toLowerCase())l.svcnet_val=i.net_val||0,l.svcvat_val=i.vat_val||0;t?(a=$$.tr(r.tbl.bdy,{id:"itm"+i.Id,class:"sitm"}).aC(i.Type),"Text"===i.Type||"Title"===i.Type?$$.td(a,{colspan:2}).html(i.htmltext||i.Note):($$.tdc("keep",a).text(i.quantity||((i.quantityhours||0)>0?fnum(i.quantityhours)+(i.UnitString||"").eine(" ",""):"")),i.htmltext?$$.tdc("txt",a).html(i.htmltext):$$.tdc("txt",a).text(i.NameOrNumber).attr("title",i.Note)),$.each(s,((e,t)=>{r[t]+=l[t]})),a.data(l)):($.extend(l,i),a=$$.tr(e,{id:"itm"+i.Id,class:"itm"}),a.data(l),$inv.rrw.call(a))})),t){let t=$$.tr(e,{id:"itmsq"+n.Id,class:"itm osum"}).data(r);$inv.rrw.call(t)}else{let t=$$.tr(e).aC("isum nosort");$$.tdc("aux",t),$$.td(t,{colspan:4}).text($rct.iSum),$$.tdc("currency isumval",t)}},$inv.t_fds_inv=()=>{let e=$("div.invoice_layout table.invi");e.trigger("fds.inv"),""!==(e.data("dtoken")||"")&&$inv.d.syncChanged(e)},$inv.sedit=()=>{$inv.sprev(!0)},$inv.jdisp=function(e){e.stopPropagation(),e.data.id&&$inv.disp(e.data.id,e.data.typ||"")},$inv.disp=(e,t)=>{let n="";switch(t){case"inv":n="inv/rdoc";break;case"rem":n="rem/rdoc"}""!==n&&$ocms.postXT({url:$ocms.url(n),data:{id:e||"",typ:"img"},success:e=>{let t=$$.dc("imagecollection pdfpreview"),n=Math.round(.88*vh());e.id;$.each(e.img||[],(function(e,i){$$.dc("pdfp",t).append($$.img(i).css("max-height",(n-rpx(6)).toString()+"px"))})),$ocms.dlg(t,{size:[n,Math.round(.88*vw())],zindex_min:50,form:!1,exclusive:!1})}})},$inv.jdbn=function(e){$ocms.postXT({url:$ocms.url("inv/rdocn"),data:{name:e.data.id||"",typ:"img"},success:e=>{let t=$$.dc("imagecollection pdfpreview"),n=Math.round(.88*vh());e.id;$.each(e.img||[],(function(e,i){$$.dc("pdfp",t).append($$.img(i).css("max-height",(n-rpx(6)).toString()+"px"))})),$ocms.dlg(t,{size:[n,Math.round(.88*vw())],zindex:50,form:!1})}})},$inv.sp13b=()=>{var e=$("div.invoice_layout").find("table.invi"),t=e.data();t.admin.p13b=!0,!1===(t.inv.InvoiceOptions||"").split(",").includes("§13b")&&(t.inv.InvoiceOptions+=",§13b"),e.trigger("fds.inv"),$inv.d.sync({Target:"p13b",Value:t.admin.p13b})},$inv.itemToContract=function(e){let t=((e=e||{}).Type||"").toString().toLowerCase(),n={id:(e.Id||"").toString(),type:t,title:"",desc:"",qty:"",price_net:"",total_net:e.net_val||0,vat:e.vat||""};var i;return e.co&&"osum"===e.co.typ?(n.desc=e.co.t||"",n.total_net=e.net_val||0):["text","title"].includes(t)&&0===(e.net_val||0)?(n.desc=e.htmltext||("#"!==(e.NameOrNumber||"").substr(0,1)?(i=$$[0]("p").text(e.NameOrNumber||""),$$.d().append(i).html()):"")+(e.Note||""),n.total_net=""):(e.htmltext?n.desc=e.htmltext:(n.title=e.NameOrNumber||"",n.desc=e.Note||""),n.qty=e.quantity||(0!==(e.quantityhours||0)?fnum(e.quantityhours)+(e.UnitString?" "+e.UnitString:""):""),n.price_net=e.net||0,n.total_net=e.net_val||0),n},$inv.ssetmode=()=>{let e=$("div.invoice_layout").find("table.invi").data();e.admin=e.admin||{};let t,n=e.admin.setmode||"setprice",i=e=>$$.dc("btn",$ict.setmo[e]).tC("selected",n===e).click((()=>{t.c.trigger("modal_close"),$inv.setSetmode(e)})),a=$$.dc("choicefrm").append([i("setprice"),i("itemprices"),i("setonly")]);t=$ocms.dlg(a,{width:800})},$inv.setSetmode=e=>{let t=$("div.invoice_layout").find("table.invi").data();t.admin=t.admin||{},t.admin.setmode=e,t.inv=t.inv||{};let n=(t.inv.InvoiceOptions||"").split(",").filter((e=>""!==e&&0!==e.indexOf("setmode:")));e&&"setprice"!==e&&n.push("setmode:"+e),t.inv.InvoiceOptions=n.join(","),$inv.d.sync({Target:"setmode",Value:e})},$inv.sctp=()=>{let e=$invcol.ctp;$ocms.dlgform(e,{title:$ict.ctp,success:function(e){var t=$("div.invoice_layout"),n=t.find("table.invi").data();let i={};void 0!==n.new&&"{"===(n.new.CustomValues||"").substr(0,1)&&(i=JSON.parse(n.inv.CustomValues)),i.contactName=e.name,i.contactEmail=e.email,n.new.CustomValues=JSON.stringify(i),t.find(".ctpfrm").text(ne(e.name,e.email)),$inv.d.sync({Target:"contact",Value:{name:e.name,email:e.email}})},typedvalues:!0})},$inv.invcPayload=function(e){let t=(e=e||{}).sms||{},n=$.extend({},e.new),i=$.extend({},e.admin);return n.total_net=t.ttn||0,n.total_gross=t.ttb||0,n.title=null!=n.invoicetitle?n.invoicetitle:n.title||"",n.provisionlocation=null!=n.loc?n.loc:n.provisionlocation||"",n.paymentterm=null!=i.paymentterms?i.paymentterms:n.paymentterm||"",i.customerid=null!=i.customerid?i.customerid:i.CustomerId,{admin:i,req:e.bai,sms:e.sms,new:n}},$inv.ssave=()=>{$inv.d.save()},$inv.sprev=e=>{$inv.d.preview()},$inv.rReload=()=>{try{let e=$("#listframe ul.rql:first").data();$inv.cInv2({id:e.search})}catch(e){}},$inv.quantChange=function(e){let t=$(this).closest("form"),n={},i=e=>parseFloat(e.toString().replace("%","").replace(",",".")),a=e=>e.toFixed(2);t.find(":input").each(((e,t)=>{n[$(t).attr("name")]=$(t)}));let r=parseInt(n.quantityhours.val()||"0"),l=i(n.net.val()||"0"),s=.01*i(n.vat.val());r>0&&l>0&&(n.net_val.val(a(r*l)),n.vat_val.val(a(r*l*s)),["Service"].includes(n.Type.val())&&(n.svcnet_val.val(a(r*l)),n.svcvat_val.val(a(r*l*s))))},$inv.storno=function(e,t){let n,i=$$.dc("choicefrm").append([$$.dc("btn","Storno ohne Details").click({id:e,mode:"simple"},(e=>{n.c.trigger("modal_close"),$inv.cSt(e.data)})),$$.dc("btn","Storno mit neuer Rechnung").click({id:e},(e=>{n.c.trigger("modal_close"),$inv.ccStInv(e)})),$$.dc("btn","Storno mit best. Rechnung").tC("inactive",!1===bool(t,!1)).click({id:e,mode:"copy"},(e=>{!0===bool(t,!1)&&(n.c.trigger("modal_close"),$inv.cSt(e.data))}))]);n=$ocms.dlg(i,{width:1e3})},$inv.credit=function(e,t){let n,i=$$.dc("choicefrm").append([$$.dc("btn","Gutschrift").click({id:e,mode:"credit"},(e=>{n.c.trigger("modal_close"),$inv.cSt(e.data)}))]);n=$ocms.dlg(i,{width:1e3})},$inv.setPyd=function(e){confirm($ict.cpyd)&&$ocms.postXT({url:$ocms.url("inv/setpyd"),timeout:60,data:{id:e},success:e=>{alert($ict.relm)},error:()=>{alert($t.f1)}})},$inv.setUpd=function(e){confirm($ict.cupd)&&$ocms.postXT({url:$ocms.url("inv/setupd"),timeout:60,data:{id:e},success:e=>{alert($ict.relm)},error:()=>{alert($t.f1)}})},$inv.resendRem=function(e){e.stopPropagation(),e.data.id&&confirm(string($ict.remresc,[e.data.name]))&&$ocms.postXT({url:$ocms.url("rem/resend"),timeout:60,data:{id:e.data.id},success:t=>{alert(string($ict.remresr,[e.data.name]))},error:()=>{alert($t.f1)}})},$inv.dspRem=function(e){let t=$$.dc("rfrm").ldng(1),n=$ocms.dlg(t,{width:1e3});n.ft.rwText($rct.rq2),$ocms.postXT({url:$ocms.url("inv/getrem"),timeout:60,data:{id:e,drafts:!1},success:e=>{n.ft.empty();let i=$$.tblset({class:"invtbl"},t.empty()),a=$invcol.rem2,r=$$.tr(i.hd);$$.th(r);$.each(a.fields||[],((e,t)=>{$$.th(r).text(t.label)}));let l=!1;$.each(e,((e,t)=>{l=!l;let n=$$.tr(i.bdy).tC("alt",l),r=$$.td(n);n.click((function(){n.tC("selected").siblings().rC("selected")})),!0===bool(t.hasFile,!1)&&($$.dc("idl ilbtn",r,{title:$ict.dl+"\n"+t.DocumentName}).append(gi("save-file","ico")).click({id:t.Id},$inv.downloadrem),$$.dc("idl ilbtn",r,{title:$ict.remdsp+"\n"+t.DocumentName}).append(gi("eye-open","ico")).click({id:t.Id,typ:"rem"},$inv.jdisp),$$.dc("idl ilbtn",r,{title:$ict.remres+"\n"+t.DocumentName}).append(gi("refresh","ico")).click({id:t.Id,typ:"rem",name:t.DocumentName},$inv.resendRem)),$.each(a.fields||[],((e,i)=>{let a=$$.td(n).aC(i.dtype),r=t[i.name];if("function"==typeof i.dfnc)i.dfnc.call(a,r,t);else switch(i.type||""){case"date":a.text(fdt(t[i.name],"dd.MM.yy"));break;case"datetime":a.text(fdt(t[i.name]));break;case"html":a.append($$.dc("ctw").html(r)),a.append($$.dc("ttip").html(r));break;default:a.text(t[i.name])}if("InvoiceId"===(i.name||""))a.aC("keep");switch(typeof i.title){case"function":i.title.call(a,t);break;case"string":a.attr("title",cs.title)}}))}))},error:()=>{t.empty(),n.ft.rwText($t.f1)},complete:()=>{t.ldng(0)}})},$inv.ccRem=function(e,t){$(this);$ocms.postXT({url:$ocms.url("rem/lrem"),timeout:60,data:{id:e},success:n=>{let i=$invcol.rid.clone();i.applyValues(n.ov);let a=$$.dc("ac"),r=$$.tblset({class:"fullgrid fullwidth"},a);if((n.lst||[]).length>0){$$.d({style:"margin: 1.5rem 0 1rem 0;font-size: 110%;text-decoration: underline;"}).prependTo(a).text($ict.rovlh);let e=$$.tr(r.hd);$ict.rovl.forEach(((t,n)=>$$.th(e,t))),$.each(n.lst,((e,t)=>{$$.tr(r.bdy).append([$$.tdc("keep",t.subject),$$.tdc("currency",fnum(t.amount,$rct.cst)),$$.tdc("currency",fnum(t.amount_payed,$rct.cst)),$$.tdc("keep",fdt(t.DateFinalized,"dd.MM.yy"))])}))}else $$.td($$.tr(r.bdy),$ict.nd);$ocms.dlgform(i,{addcontent:a,title:string($ict.remdt,[t||"?"]),success:function(t){$inv.ccRem_s2(e,t)},typedvalues:!0})}})},$inv.rRemRw=function(e){let t=$(this),n=e.rm||{};t.empty().data({invoiceid:n.invoiceid,invoicedate:n.invoicedate,amount:n.amount,amount_payed:n.amount_payed});let i=$$.dc("axf").append($$.dc("ibtn edit",{title:$rct.cP}).append(gi("pencil")).click(t,$inv.eRowR));t.append([$$.tdc("aux").append(i),$$.tdc("keep",n.invoiceid),$$.tdc("keep",fdt(n.invoicedate,"dd.MM.yy")),$$.tdc("currency",fnum(n.amount,$rct.cst)),$$.tdc("currency",fnum(n.amount_payed,$rct.cst)),$$.tdc("currency",fnum(n.amount-n.amount_payed,$rct.cst))])},$inv.eRowR=function(e){let t=$(this),n=e.data,i=n.data()||{},a=$invcol.rem.clone().applyValues(i);$ocms.dlgform(a,{title:t.data("dialog")||"",success:function(e){let i=t.closest("table"),a=i.data();$.extend(a.rm,e),i.data(a),$inv.rRemRw.call(n,a)},typedvalues:!0})},$inv.ccRem_s2=function(e,t){$fis.lf(!1).rC("fix").aC("hd");let n=$$.dc("invoice_layout",$fis.frm_edit()).append($$.dc("btn sprev").click($inv.rprev));$inv.eM(!1,!0);$$.dc("rfrm").ldng(1);$ocms.postXT({url:$ocms.url("rem/get"),timeout:60,data:$.extend({id:e},t),success:e=>{let t=e.rm||{},i=$$.dc("srq",n);$ict.remt[t.type].forEach((e=>$$[0]("p").rwText(e).appendTo(i)));let a=$$.tblset({class:"invi"},i);a.ft=$$[0]("tfoot"),a.tbl.data($.extend({invid:t.invid,new:{}},e));let r=$$.tr(a.hd).aC("shd").append([$$.th().aC("aux")]);$ict.remHR.forEach((e=>$$.th(r,e))),$inv.rRemRw.call($$.tr(a.bdy),a.tbl.data()),a.ft.appendTo(a.tbl),$ict.remt2[t.type].forEach((e=>$$[0]("p").rwText(e).appendTo(i)));let l=(e,t,i,r,l)=>{let s=$$.dc("inpfrm",n).aC(e).append("string"==typeof r?$$.dc("ahd",r):r>0?$$.dc("ahd",$rct.frm[i]):null),d=$$.dc("content",s).rwText(t);$$.dc("axf",s).append($$.dc("ibtn edit").data("dialog",$rct.frm[i]).append(gi("pencil")).click($.extend({t:d,nme:i,change:e=>{a.tbl.data("new")[i]=e}},l),$inv.eHtml)),a.tbl.data("new")[i]=t};l("tfrm",t.subject,"subject",0,null),l("adrfrm",t.invoiceaddress,"invoiceaddress",0,null),l("emailfrm",t.invoiceemail,"invoiceemail",0,null),$$.dc("sndfrm",n).append($$.dc("content").text(t.sender)),a.tbl.children("tbody").each($inv.bdysort),a.tbl.trigger("fds.inv")},complete:()=>{}})},$inv.rprev=()=>{var e=$("div.invoice_layout"),t=e.find("table.invi"),n=t.data();$.extend(n.new,t.find("tbody > tr:first").data()),e.aC("freeze"),!1!==$fis.ValidateEmail(n.new.invoiceemail||"")||!1!==bool(confirm($ict.ivE+$ict.ivEc),!1)?$ocms.postXT({url:$ocms.url("rem/prep"),data:{remc:JSON.stringify({rem:n.rm,new:n.new}),id:n.invid||""},success:t=>{e.rC("freeze");let n=$$.dc("imagecollection pdfpreview"),i=Math.round(.88*vh()),a=t.id;$.each(t.img||[],(function(e,t){$$.dc("pdfp",n).append($$.img(t).css("max-height",(i-rpx(6)).toString()+"px"))})),$ocms.dlg(n,{size:[i,Math.round(.88*vw())],zindex:50,form:!1,button:$ict.remd,confirm:function(e){let t=$(this);$ocms.postXT({url:$ocms.url("rem/conf"),data:{id:a},success:()=>{t.trigger("modal_close"),window.open($ocms.url("rem/idoc")+"?id="+a,"_blank"),$ocms.init("req"),$inv.rReload()},error:()=>{alert($t.f1),t.trigger("modal_close")}})},cancel:function(e){$(this);confirm($ict.cdI)&&$ocms.postXT({url:$ocms.url("rem/del"),data:{id:a}}),$inv.rReload()}})}}):e.rC("freeze")},$inv.sis=e=>{confirm($ict.sisc)&&$ocms.postXT({url:$ocms.url("inv/sis"),data:{id:e||""},success:e=>{}})},$inv.srs=e=>{confirm($ict.srsc)&&$ocms.postXT({url:$ocms.url("rem/srs"),data:{id:e||""},success:e=>{}})},$inv.mfrrel=e=>{$("#contentframe").ldng(),$ocms.postXT({url:$ocms.url("inv/mfrrel"),data:{id:e||""},success:e=>{$inv.rerenderinv()},complete:()=>{$("#contentframe").ldng(0)}})}; \ No newline at end of file diff --git a/Fuchs/wwwroot/web/fis.js b/Fuchs/wwwroot/web/fis.js index f7955e7..8654a22 100644 --- a/Fuchs/wwwroot/web/fis.js +++ b/Fuchs/wwwroot/web/fis.js @@ -2533,7 +2533,8 @@ if (!Element.prototype.closest) { this._dragging = false; this._dragHandleClass = this._options.dragHandleClass || ''; this._parentident = this._options.parentident || ''; - this._swapdone = typeof this._options.swapdone === "function" ? this._options._swapdone : null; + this._swapdone = typeof this._options.swapdone === "function" ? this._options.swapdone : null; + this._onend = typeof this._options.onend === "function" ? this._options.onend : null; this._container.setAttribute("data-is-sortable", 1); this._container.classList.add("sortable"); @@ -2683,10 +2684,17 @@ if (!Element.prototype.closest) { } }, - // on item release/drop + // on item release/drop _onRelease: function (e) { + // Was THIS list mid-drag? (mouseup fires on every instance's window listener.) + var wasDragging = this._dragging === true && this._clickItem !== null; this._dragging = false; this._trashDragItem(); + // Fire a single "drag finished" callback so callers can commit the new order once, + // reliably, on drop — rather than relying on the per-hover _swapdone during the drag. + if (wasDragging && typeof this._onend === 'function') { + this._onend(); + } }, // on item drag/move diff --git a/Fuchs/wwwroot/web/fis.min.js b/Fuchs/wwwroot/web/fis.min.js index b3cb91c..9b88169 100644 --- a/Fuchs/wwwroot/web/fis.min.js +++ b/Fuchs/wwwroot/web/fis.min.js @@ -1,4 +1,4 @@ -var t,e,$t={lng:"de-DE",dn:["So","Mo","Di","Mi","Do","Fr","Sa"],mn:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],ma:["Jan","Feb","Mrz","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],datepattern:"(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}",datetimepattern:"(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}\\s([0-5][0-9]):([0-5][0-9])",dateplaceholder:"dd.MM.yyyy",datetimeplaceholder:"dd.MM.yyyy HH:mm",dateformat:"dd.MM.yyyy",datetimeformat:"dd.MM.yyyy HH:mm",f1:"Der Server hat einen Fehler gemeldet: \n",f2:"Bitte versuchen Sie es erneut.",m0:"Diese Internet-Seite benötigt einen html5-kompatiblen Browser.",m0b:"Unterstützt werden bspw: Internet Explorer ab Version 10, Firefox ab Version 31, Chrome ab Version 31, Safari ab Version 7, Opera ab Version 27",m1:"Dieser Datensatz ist momentan von jemand anderem zur Bearbeitung gesperrt.",m2:"Diese Funktion ist zur Zeit nicht verfügbar",t1:"Eingabe erforderlich.",t2:"Eingabe ist nicht erforderlich.",true:"Ja",false:"Nein",alert:"Hinweis",confirm:"Bestätigen",open:"Öffnen","not implemented":"Diese Funktion in zur Zeit noch nicht verfügbar.",l0:"Anmeldung",l1:"Email / Anmeldename",l2:"Email-Adresse / Anmeldename",l3:"Passwort",l4:"Benutzer",l5:"Wird vom System ermittelt...",l6:"Anmelden",l7:"Passwort vergessen?",l7a:'Die "Passwort vergessen"-Funktion läuft in zwei Schritten ab:\n \nIm ersten Schritt wird eine SMS mit einem Code an die hinterlegte Mobilfunk-Nummer versandt.\nIm zweiten Schritt geben Sie bitte diesen Code in das Formular ein und übermitteln es erneut.\n \nIn beiden Schritten wird aus Sicherheitsgründen kein Fehler angezeigt und auch dann ein erfolgreicher Versand bestätigt, wenn die Kombination aus Email-Adresse und Nachname nicht gefunden wurde und/oder der code falsch ist.',l8:"Keinen Account?",l9:"Anmeldenamen der Email-Adresse wurde nicht erkannt.",l10:"Nachname",l11:"Email-Adresse",l12:"Passwort zusenden",l13:"Das Passwort wurde erfolgreich verschickt",l14:"Das Passwort konnte nicht verschickt werden",l15:"Sie sind nicht berechtigt, diese Funktion auszuführen.",l16:"Sie müssen zunächst einen Account angeben.",l17:"Die Kombination aus Anmeldenamen und Passwort konnte nicht bestätigt werden.",l18:"Es gibt ein Problem mit dem Formular.\nEs kann momentan nicht verarbeitet und versendet werden.",name:"Name",submit:"Senden",cancel:"Abbrechen",noop:"Diese Funktion is noch nicht verfügar."};t=self,e=()=>(()=>{var t={d:(e,n)=>{for(var i in n)t.o(n,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:n[i]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),t.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"t",{value:!0})};var e,n={};t.r(n),t.d(n,{AbortError:()=>r,DefaultHttpClient:()=>D,HttpClient:()=>h,HttpError:()=>i,HttpResponse:()=>d,HttpTransportType:()=>U,HubConnection:()=>O,HubConnectionBuilder:()=>tt,HubConnectionState:()=>j,JsonHubProtocol:()=>K,LogLevel:()=>e,MessageType:()=>N,NullLogger:()=>p,Subject:()=>q,TimeoutError:()=>o,TransferFormat:()=>B,VERSION:()=>f});class i extends Error{constructor(t,e){const n=new.target.prototype;super(`${t}: Status code '${e}'`),this.statusCode=e,this.__proto__=n}}class o extends Error{constructor(t="A timeout occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class r extends Error{constructor(t="An abort occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class s extends Error{constructor(t,e){const n=new.target.prototype;super(t),this.transport=e,this.errorType="UnsupportedTransportError",this.__proto__=n}}class a extends Error{constructor(t,e){const n=new.target.prototype;super(t),this.transport=e,this.errorType="DisabledTransportError",this.__proto__=n}}class c extends Error{constructor(t,e){const n=new.target.prototype;super(t),this.transport=e,this.errorType="FailedToStartTransportError",this.__proto__=n}}class l extends Error{constructor(t){const e=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=e}}class u extends Error{constructor(t,e){const n=new.target.prototype;super(t),this.innerErrors=e,this.__proto__=n}}class d{constructor(t,e,n){this.statusCode=t,this.statusText=e,this.content=n}}class h{get(t,e){return this.send({...e,method:"GET",url:t})}post(t,e){return this.send({...e,method:"POST",url:t})}delete(t,e){return this.send({...e,method:"DELETE",url:t})}getCookieString(t){return""}}!function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Information=2]="Information",t[t.Warning=3]="Warning",t[t.Error=4]="Error",t[t.Critical=5]="Critical",t[t.None=6]="None"}(e||(e={}));class p{constructor(){}log(t,e){}}p.instance=new p;const f="10.0.0";class m{static isRequired(t,e){if(null==t)throw new Error(`The '${e}' argument is required.`)}static isNotEmpty(t,e){if(!t||t.match(/^\s*$/))throw new Error(`The '${e}' argument should not be empty.`)}static isIn(t,e,n){if(!(t in e))throw new Error(`Unknown ${n} value: ${t}.`)}}class g{static get isBrowser(){return!g.isNode&&"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return!g.isNode&&"object"==typeof self&&"importScripts"in self}static get isReactNative(){return!g.isNode&&"object"==typeof window&&void 0===window.document}static get isNode(){return"undefined"!=typeof process&&process.release&&"node"===process.release.name}}function y(t,e){let n="";return v(t)?(n=`Binary data of length ${t.byteLength}`,e&&(n+=`. Content: '${function(t){const e=new Uint8Array(t);let n="";return e.forEach((t=>{n+=`0x${t<16?"0":""}${t.toString(16)} `})),n.substring(0,n.length-1)}(t)}'`)):"string"==typeof t&&(n=`String data of length ${t.length}`,e&&(n+=`. Content: '${t}'`)),n}function v(t){return t&&"undefined"!=typeof ArrayBuffer&&(t instanceof ArrayBuffer||t.constructor&&"ArrayBuffer"===t.constructor.name)}async function b(t,n,i,o,r,s){const a={},[c,l]=C();a[c]=l,t.log(e.Trace,`(${n} transport) sending data. ${y(r,s.logMessageContent)}.`);const u=v(r)?"arraybuffer":"text",d=await i.post(o,{content:r,headers:{...a,...s.headers},responseType:u,timeout:s.timeout,withCredentials:s.withCredentials});t.log(e.Trace,`(${n} transport) request complete. Response status: ${d.statusCode}.`)}class ${constructor(t,e){this.i=t,this.h=e}dispose(){const t=this.i.observers.indexOf(this.h);t>-1&&this.i.observers.splice(t,1),0===this.i.observers.length&&this.i.cancelCallback&&this.i.cancelCallback().catch((t=>{}))}}class w{constructor(t){this.l=t,this.out=console}log(t,n){if(t>=this.l){const i=`[${(new Date).toISOString()}] ${e[t]}: ${n}`;switch(t){case e.Critical:case e.Error:this.out.error(i);break;case e.Warning:this.out.warn(i);break;case e.Information:this.out.info(i);break;default:this.out.log(i)}}}}function C(){let t="X-SignalR-User-Agent";return g.isNode&&(t="User-Agent"),[t,S(f,x(),g.isNode?"NodeJS":"Browser",T())]}function S(t,e,n,i){let o="Microsoft SignalR/";const r=t.split(".");return o+=`${r[0]}.${r[1]}`,o+=` (${t}; `,o+=e&&""!==e?`${e}; `:"Unknown OS; ",o+=`${n}`,o+=i?`; ${i}`:"; Unknown Runtime Version",o+=")",o}function x(){if(!g.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function T(){if(g.isNode)return process.versions.node}function _(t){return t.stack?t.stack:t.message?t.message:`${t}`}class E extends h{constructor(e){if(super(),this.u=e,"undefined"==typeof fetch||g.isNode){const t=require;this.p=new(t("tough-cookie").CookieJar),"undefined"==typeof fetch?this.m=t("node-fetch"):this.m=fetch,this.m=t("fetch-cookie")(this.m,this.p)}else this.m=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==t.g)return t.g;throw new Error("could not find global")}());if("undefined"==typeof AbortController){const t=require;this.v=t("abort-controller")}else this.v=AbortController}async send(t){if(t.abortSignal&&t.abortSignal.aborted)throw new r;if(!t.method)throw new Error("No method defined.");if(!t.url)throw new Error("No url defined.");const n=new this.v;let s;t.abortSignal&&(t.abortSignal.onabort=()=>{n.abort(),s=new r});let a,c=null;if(t.timeout){const i=t.timeout;c=setTimeout((()=>{n.abort(),this.u.log(e.Warning,"Timeout from HTTP request."),s=new o}),i)}""===t.content&&(t.content=void 0),t.content&&(t.headers=t.headers||{},v(t.content)?t.headers["Content-Type"]="application/octet-stream":t.headers["Content-Type"]="text/plain;charset=UTF-8");try{a=await this.m(t.url,{body:t.content,cache:"no-cache",credentials:!0===t.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...t.headers},method:t.method,mode:"cors",redirect:"follow",signal:n.signal})}catch(t){if(s)throw s;throw this.u.log(e.Warning,`Error from HTTP request. ${t}.`),t}finally{c&&clearTimeout(c),t.abortSignal&&(t.abortSignal.onabort=null)}if(!a.ok){const t=await k(a,"text");throw new i(t||a.statusText,a.status)}const l=k(a,t.responseType),u=await l;return new d(a.status,a.statusText,u)}getCookieString(t){let e="";return g.isNode&&this.p&&this.p.getCookies(t,((t,n)=>e=n.join("; "))),e}}function k(t,e){let n;switch(e){case"arraybuffer":n=t.arrayBuffer();break;case"text":default:n=t.text();break;case"blob":case"document":case"json":throw new Error(`${e} is not supported.`)}return n}class I extends h{constructor(t){super(),this.u=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new r):t.method?t.url?new Promise(((n,s)=>{const a=new XMLHttpRequest;a.open(t.method,t.url,!0),a.withCredentials=void 0===t.withCredentials||t.withCredentials,a.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===t.content&&(t.content=void 0),t.content&&(v(t.content)?a.setRequestHeader("Content-Type","application/octet-stream"):a.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const c=t.headers;c&&Object.keys(c).forEach((t=>{a.setRequestHeader(t,c[t])})),t.responseType&&(a.responseType=t.responseType),t.abortSignal&&(t.abortSignal.onabort=()=>{a.abort(),s(new r)}),t.timeout&&(a.timeout=t.timeout),a.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),a.status>=200&&a.status<300?n(new d(a.status,a.statusText,a.response||a.responseText)):s(new i(a.response||a.responseText||a.statusText,a.status))},a.onerror=()=>{this.u.log(e.Warning,`Error from HTTP request. ${a.status}: ${a.statusText}.`),s(new i(a.statusText,a.status))},a.ontimeout=()=>{this.u.log(e.Warning,"Timeout from HTTP request."),s(new o)},a.send(t.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class D extends h{constructor(t){if(super(),"undefined"!=typeof fetch||g.isNode)this.$=new E(t);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this.$=new I(t)}}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new r):t.method?t.url?this.$.send(t):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(t){return this.$.getCookieString(t)}}class A{static write(t){return`${t}${A.RecordSeparator}`}static parse(t){if(t[t.length-1]!==A.RecordSeparator)throw new Error("Message is incomplete.");const e=t.split(A.RecordSeparator);return e.pop(),e}}A.RecordSeparatorCode=30,A.RecordSeparator=String.fromCharCode(A.RecordSeparatorCode);class P{writeHandshakeRequest(t){return A.write(JSON.stringify(t))}parseHandshakeResponse(t){let e,n;if(v(t)){const i=new Uint8Array(t),o=i.indexOf(A.RecordSeparatorCode);if(-1===o)throw new Error("Message is incomplete.");const r=o+1;e=String.fromCharCode.apply(null,Array.prototype.slice.call(i.slice(0,r))),n=i.byteLength>r?i.slice(r).buffer:null}else{const i=t,o=i.indexOf(A.RecordSeparator);if(-1===o)throw new Error("Message is incomplete.");const r=o+1;e=i.substring(0,r),n=i.length>r?i.substring(r):null}const i=A.parse(e),o=JSON.parse(i[0]);if(o.type)throw new Error("Expected a handshake response from the server.");return[n,o]}}var N,j;!function(t){t[t.Invocation=1]="Invocation",t[t.StreamItem=2]="StreamItem",t[t.Completion=3]="Completion",t[t.StreamInvocation=4]="StreamInvocation",t[t.CancelInvocation=5]="CancelInvocation",t[t.Ping=6]="Ping",t[t.Close=7]="Close",t[t.Ack=8]="Ack",t[t.Sequence=9]="Sequence"}(N||(N={}));class q{constructor(){this.observers=[]}next(t){for(const e of this.observers)e.next(t)}error(t){for(const e of this.observers)e.error&&e.error(t)}complete(){for(const t of this.observers)t.complete&&t.complete()}subscribe(t){return this.observers.push(t),new $(this,t)}}class M{constructor(t,e,n){this.C=1e5,this.S=[],this.k=0,this.P=!1,this.T=1,this.I=0,this._=0,this.H=!1,this.D=t,this.R=e,this.C=n}async A(t){const e=this.D.writeMessage(t);let n=Promise.resolve();if(this.U(t)){this.k++;let t=()=>{},i=()=>{};v(e)?this._+=e.byteLength:this._+=e.length,this._>=this.C&&(n=new Promise(((e,n)=>{t=e,i=n}))),this.S.push(new R(e,this.k,t,i))}try{this.H||await this.R.send(e)}catch{this.L()}await n}N(t){let e=-1;for(let n=0;nthis.T?this.R.stop(new Error("Sequence ID greater than amount of messages we've received.")):this.T=t.sequenceId}L(){this.H=!0,this.P=!0}async B(){const t=0!==this.S.length?this.S[0].q:this.k+1;await this.R.send(this.D.writeMessage({type:N.Sequence,sequenceId:t}));const e=this.S;for(const t of e)await this.R.send(t.M);this.H=!1}X(t){null!=t||(t=new Error("Unable to reconnect to server."));for(const e of this.S)e.J(t)}U(t){switch(t.type){case N.Invocation:case N.StreamItem:case N.Completion:case N.StreamInvocation:case N.CancelInvocation:return!0;case N.Close:case N.Sequence:case N.Ping:case N.Ack:return!1}}O(){void 0===this.V&&(this.V=setTimeout((async()=>{try{this.H||await this.R.send(this.D.writeMessage({type:N.Ack,sequenceId:this.I}))}catch{}clearTimeout(this.V),this.V=void 0}),1e3))}}class R{constructor(t,e,n,i){this.M=t,this.q=e,this.j=n,this.J=i}}!function(t){t.Disconnected="Disconnected",t.Connecting="Connecting",t.Connected="Connected",t.Disconnecting="Disconnecting",t.Reconnecting="Reconnecting"}(j||(j={}));class O{static create(t,e,n,i,o,r,s){return new O(t,e,n,i,o,r,s)}constructor(t,n,i,o,r,s,a){this.K=0,this.G=()=>{this.u.log(e.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},m.isRequired(t,"connection"),m.isRequired(n,"logger"),m.isRequired(i,"protocol"),this.serverTimeoutInMilliseconds=null!=r?r:3e4,this.keepAliveIntervalInMilliseconds=null!=s?s:15e3,this.Y=null!=a?a:1e5,this.u=n,this.D=i,this.connection=t,this.Z=o,this.tt=new P,this.connection.onreceive=t=>this.et(t),this.connection.onclose=t=>this.st(t),this.it={},this.nt={},this.rt=[],this.ot=[],this.ht=[],this.ct=0,this.lt=!1,this.ut=j.Disconnected,this.dt=!1,this.ft=this.D.writeMessage({type:N.Ping})}get state(){return this.ut}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(t){if(this.ut!==j.Disconnected&&this.ut!==j.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!t)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=t}start(){return this.wt=this.gt(),this.wt}async gt(){if(this.ut!==j.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this.ut=j.Connecting,this.u.log(e.Debug,"Starting HubConnection.");try{await this.yt(),g.isBrowser&&window.document.addEventListener("freeze",this.G),this.ut=j.Connected,this.dt=!0,this.u.log(e.Debug,"HubConnection connected successfully.")}catch(t){return this.ut=j.Disconnected,this.u.log(e.Debug,`HubConnection failed to start successfully because of error '${t}'.`),Promise.reject(t)}}async yt(){this.vt=void 0,this.lt=!1;const t=new Promise(((t,e)=>{this.bt=t,this.Et=e}));await this.connection.start(this.D.transferFormat);try{let n=this.D.version;this.connection.features.reconnect||(n=1);const i={protocol:this.D.name,version:n};if(this.u.log(e.Debug,"Sending handshake request."),await this.$t(this.tt.writeHandshakeRequest(i)),this.u.log(e.Information,`Using HubProtocol '${this.D.name}'.`),this.Ct(),this.St(),this.kt(),await t,this.vt)throw this.vt;!!this.connection.features.reconnect&&(this.Pt=new M(this.D,this.connection,this.Y),this.connection.features.disconnected=this.Pt.L.bind(this.Pt),this.connection.features.resend=()=>{if(this.Pt)return this.Pt.B()}),this.connection.features.inherentKeepAlive||await this.$t(this.ft)}catch(t){throw this.u.log(e.Debug,`Hub handshake failed with error '${t}' during start(). Stopping HubConnection.`),this.Ct(),this.Tt(),await this.connection.stop(t),t}}async stop(){const t=this.wt;this.connection.features.reconnect=!1,this.It=this._t(),await this.It;try{await t}catch(t){}}_t(t){if(this.ut===j.Disconnected)return this.u.log(e.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this.ut===j.Disconnecting)return this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this.It;const n=this.ut;return this.ut=j.Disconnecting,this.u.log(e.Debug,"Stopping HubConnection."),this.Ht?(this.u.log(e.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this.Ht),this.Ht=void 0,this.Dt(),Promise.resolve()):(n===j.Connected&&this.Rt(),this.Ct(),this.Tt(),this.vt=t||new r("The connection was stopped before the hub handshake could complete."),this.connection.stop(t))}async Rt(){try{await this.xt(this.At())}catch{}}stream(t,...e){const[n,i]=this.Ut(e),o=this.Lt(t,e,i);let r;const s=new q;return s.cancelCallback=()=>{const t=this.Nt(o.invocationId);return delete this.it[o.invocationId],r.then((()=>this.xt(t)))},this.it[o.invocationId]=(t,e)=>{e?s.error(e):t&&(t.type===N.Completion?t.error?s.error(new Error(t.error)):s.complete():s.next(t.item))},r=this.xt(o).catch((t=>{s.error(t),delete this.it[o.invocationId]})),this.qt(n,r),s}$t(t){return this.kt(),this.connection.send(t)}xt(t){return this.Pt?this.Pt.A(t):this.$t(this.D.writeMessage(t))}send(t,...e){const[n,i]=this.Ut(e),o=this.xt(this.Mt(t,e,!0,i));return this.qt(n,o),o}invoke(t,...e){const[n,i]=this.Ut(e),o=this.Mt(t,e,!1,i);return new Promise(((t,e)=>{this.it[o.invocationId]=(n,i)=>{i?e(i):n&&(n.type===N.Completion?n.error?e(new Error(n.error)):t(n.result):e(new Error(`Unexpected message type: ${n.type}`)))};const i=this.xt(o).catch((t=>{e(t),delete this.it[o.invocationId]}));this.qt(n,i)}))}on(t,e){t&&e&&(t=t.toLowerCase(),this.nt[t]||(this.nt[t]=[]),-1===this.nt[t].indexOf(e)&&this.nt[t].push(e))}off(t,e){if(!t)return;t=t.toLowerCase();const n=this.nt[t];if(n)if(e){const i=n.indexOf(e);-1!==i&&(n.splice(i,1),0===n.length&&delete this.nt[t])}else delete this.nt[t]}onclose(t){t&&this.rt.push(t)}onreconnecting(t){t&&this.ot.push(t)}onreconnected(t){t&&this.ht.push(t)}et(t){if(this.Ct(),this.lt||(t=this.jt(t),this.lt=!0),t){const n=this.D.parseMessages(t,this.u);for(const i of n)if(!this.Pt||this.Pt.W(i))switch(i.type){case N.Invocation:this.Wt(i).catch((t=>{this.u.log(e.Error,`Invoke client method threw error: ${_(t)}`)}));break;case N.StreamItem:case N.Completion:{const n=this.it[i.invocationId];if(n){i.type===N.Completion&&delete this.it[i.invocationId];try{n(i)}catch(t){this.u.log(e.Error,`Stream callback threw error: ${_(t)}`)}}break}case N.Ping:break;case N.Close:{this.u.log(e.Information,"Close message received from server.");const t=i.error?new Error("Server returned an error on close: "+i.error):void 0;!0===i.allowReconnect?this.connection.stop(t):this.It=this._t(t);break}case N.Ack:this.Pt&&this.Pt.N(i);break;case N.Sequence:this.Pt&&this.Pt.F(i);break;default:this.u.log(e.Warning,`Invalid message type: ${i.type}.`)}}this.St()}jt(t){let n,i;try{[i,n]=this.tt.parseHandshakeResponse(t)}catch(t){const n="Error parsing handshake response: "+t;this.u.log(e.Error,n);const i=new Error(n);throw this.Et(i),i}if(n.error){const t="Server returned handshake error: "+n.error;this.u.log(e.Error,t);const i=new Error(t);throw this.Et(i),i}return this.u.log(e.Debug,"Server handshake complete."),this.bt(),i}kt(){this.connection.features.inherentKeepAlive||(this.K=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this.Tt())}St(){if(!this.connection.features||!this.connection.features.inherentKeepAlive){this.Ot=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds);let t=this.K-(new Date).getTime();if(t<0)return void(this.ut===j.Connected&&this.Ft());void 0===this.Bt&&(t<0&&(t=0),this.Bt=setTimeout((async()=>{this.ut===j.Connected&&await this.Ft()}),t))}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async Wt(t){const n=t.target.toLowerCase(),i=this.nt[n];if(!i)return this.u.log(e.Warning,`No client method with the name '${n}' found.`),void(t.invocationId&&(this.u.log(e.Warning,`No result given for '${n}' method and invocation ID '${t.invocationId}'.`),await this.xt(this.Xt(t.invocationId,"Client didn't provide a result.",null))));const o=i.slice(),r=!!t.invocationId;let s,a,c;for(const i of o)try{const o=s;s=await i.apply(this,t.arguments),r&&s&&o&&(this.u.log(e.Error,`Multiple results provided for '${n}'. Sending error to server.`),c=this.Xt(t.invocationId,"Client provided multiple results.",null)),a=void 0}catch(t){a=t,this.u.log(e.Error,`A callback for the method '${n}' threw error '${t}'.`)}c?await this.xt(c):r?(a?c=this.Xt(t.invocationId,`${a}`,null):void 0!==s?c=this.Xt(t.invocationId,null,s):(this.u.log(e.Warning,`No result given for '${n}' method and invocation ID '${t.invocationId}'.`),c=this.Xt(t.invocationId,"Client didn't provide a result.",null)),await this.xt(c)):s&&this.u.log(e.Error,`Result given for '${n}' method but server is not expecting a result.`)}st(t){this.u.log(e.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this.ut}.`),this.vt=this.vt||t||new r("The underlying connection was closed before the hub handshake could complete."),this.bt&&this.bt(),this.Jt(t||new Error("Invocation canceled due to the underlying connection being closed.")),this.Ct(),this.Tt(),this.ut===j.Disconnecting?this.Dt(t):this.ut===j.Connected&&this.Z?this.zt(t):this.ut===j.Connected&&this.Dt(t)}Dt(t){if(this.dt){this.ut=j.Disconnected,this.dt=!1,this.Pt&&(this.Pt.X(null!=t?t:new Error("Connection closed.")),this.Pt=void 0),g.isBrowser&&window.document.removeEventListener("freeze",this.G);try{this.rt.forEach((e=>e.apply(this,[t])))}catch(n){this.u.log(e.Error,`An onclose callback called with error '${t}' threw error '${n}'.`)}}}async zt(t){const n=Date.now();let i=0,o=void 0!==t?t:new Error("Attempting to reconnect due to a unknown error."),r=this.Vt(i,0,o);if(null===r)return this.u.log(e.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this.Dt(t);if(this.ut=j.Reconnecting,t?this.u.log(e.Information,`Connection reconnecting because of error '${t}'.`):this.u.log(e.Information,"Connection reconnecting."),0!==this.ot.length){try{this.ot.forEach((e=>e.apply(this,[t])))}catch(n){this.u.log(e.Error,`An onreconnecting callback called with error '${t}' threw error '${n}'.`)}if(this.ut!==j.Reconnecting)return void this.u.log(e.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this.u.log(e.Information,`Reconnect attempt number ${i+1} will start in ${r} ms.`),await new Promise((t=>{this.Ht=setTimeout(t,r)})),this.Ht=void 0,this.ut!==j.Reconnecting)return void this.u.log(e.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this.yt(),this.ut=j.Connected,this.u.log(e.Information,"HubConnection reconnected successfully."),0!==this.ht.length)try{this.ht.forEach((t=>t.apply(this,[this.connection.connectionId])))}catch(t){this.u.log(e.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${t}'.`)}return}catch(t){if(this.u.log(e.Information,`Reconnect attempt failed because of error '${t}'.`),this.ut!==j.Reconnecting)return this.u.log(e.Debug,`Connection moved to the '${this.ut}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this.ut===j.Disconnecting&&this.Dt());i++,o=t instanceof Error?t:new Error(t.toString()),r=this.Vt(i,Date.now()-n,o)}}this.u.log(e.Information,`Reconnect retries have been exhausted after ${Date.now()-n} ms and ${i} failed attempts. Connection disconnecting.`),this.Dt()}Vt(t,n,i){try{return this.Z.nextRetryDelayInMilliseconds({elapsedMilliseconds:n,previousRetryCount:t,retryReason:i})}catch(i){return this.u.log(e.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${n}) threw error '${i}'.`),null}}Jt(t){const n=this.it;this.it={},Object.keys(n).forEach((i=>{const o=n[i];try{o(null,t)}catch(n){this.u.log(e.Error,`Stream 'error' callback called with '${t}' threw error: ${_(n)}`)}}))}Tt(){this.Bt&&(clearTimeout(this.Bt),this.Bt=void 0)}Ct(){this.Ot&&clearTimeout(this.Ot)}Mt(t,e,n,i){if(n)return 0!==i.length?{target:t,arguments:e,streamIds:i,type:N.Invocation}:{target:t,arguments:e,type:N.Invocation};{const n=this.ct;return this.ct++,0!==i.length?{target:t,arguments:e,invocationId:n.toString(),streamIds:i,type:N.Invocation}:{target:t,arguments:e,invocationId:n.toString(),type:N.Invocation}}}qt(t,e){if(0!==t.length){e||(e=Promise.resolve());for(const n in t)t[n].subscribe({complete:()=>{e=e.then((()=>this.xt(this.Xt(n))))},error:t=>{let i;i=t instanceof Error?t.message:t&&t.toString?t.toString():"Unknown error",e=e.then((()=>this.xt(this.Xt(n,i))))},next:t=>{e=e.then((()=>this.xt(this.Kt(n,t))))}})}}Ut(t){const e=[],n=[];for(let i=0;i0)&&(e=!1,this.te=await this.Zt()),this.ee(t);const n=await this.Yt.send(t);return e&&401===n.statusCode&&this.Zt?(this.te=await this.Zt(),this.ee(t),await this.Yt.send(t)):n}ee(t){t.headers||(t.headers={}),this.te?t.headers[z.Authorization]=`Bearer ${this.te}`:this.Zt&&t.headers[z.Authorization]&&delete t.headers[z.Authorization]}getCookieString(t){return this.Yt.getCookieString(t)}}var U,B;!function(t){t[t.None=0]="None",t[t.WebSockets=1]="WebSockets",t[t.ServerSentEvents=2]="ServerSentEvents",t[t.LongPolling=4]="LongPolling"}(U||(U={})),function(t){t[t.Text=1]="Text",t[t.Binary=2]="Binary"}(B||(B={}));class W{constructor(){this.se=!1,this.onabort=null}abort(){this.se||(this.se=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this.se}}class X{get pollAborted(){return this.ie.aborted}constructor(t,e,n){this.$=t,this.u=e,this.ie=new W,this.ne=n,this.re=!1,this.onreceive=null,this.onclose=null}async connect(t,n){if(m.isRequired(t,"url"),m.isRequired(n,"transferFormat"),m.isIn(n,B,"transferFormat"),this.oe=t,this.u.log(e.Trace,"(LongPolling transport) Connecting."),n===B.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[o,r]=C(),s={[o]:r,...this.ne.headers},a={abortSignal:this.ie.signal,headers:s,timeout:1e5,withCredentials:this.ne.withCredentials};n===B.Binary&&(a.responseType="arraybuffer");const c=`${t}&_=${Date.now()}`;this.u.log(e.Trace,`(LongPolling transport) polling: ${c}.`);const l=await this.$.get(c,a);200!==l.statusCode?(this.u.log(e.Error,`(LongPolling transport) Unexpected response code: ${l.statusCode}.`),this.he=new i(l.statusText||"",l.statusCode),this.re=!1):this.re=!0,this.ce=this.ae(this.oe,a)}async ae(t,n){try{for(;this.re;)try{const o=`${t}&_=${Date.now()}`;this.u.log(e.Trace,`(LongPolling transport) polling: ${o}.`);const r=await this.$.get(o,n);204===r.statusCode?(this.u.log(e.Information,"(LongPolling transport) Poll terminated by server."),this.re=!1):200!==r.statusCode?(this.u.log(e.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this.he=new i(r.statusText||"",r.statusCode),this.re=!1):r.content?(this.u.log(e.Trace,`(LongPolling transport) data received. ${y(r.content,this.ne.logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this.u.log(e.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(t){this.re?t instanceof o?this.u.log(e.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this.he=t,this.re=!1):this.u.log(e.Trace,`(LongPolling transport) Poll errored after shutdown: ${t.message}`)}}finally{this.u.log(e.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this.le()}}async send(t){return this.re?b(this.u,"LongPolling",this.$,this.oe,t,this.ne):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this.u.log(e.Trace,"(LongPolling transport) Stopping polling."),this.re=!1,this.ie.abort();try{await this.ce,this.u.log(e.Trace,`(LongPolling transport) sending DELETE request to ${this.oe}.`);const t={},[n,o]=C();t[n]=o;const r={headers:{...t,...this.ne.headers},timeout:this.ne.timeout,withCredentials:this.ne.withCredentials};let s;try{await this.$.delete(this.oe,r)}catch(t){s=t}s?s instanceof i&&(404===s.statusCode?this.u.log(e.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this.u.log(e.Trace,`(LongPolling transport) Error sending a DELETE request: ${s}`)):this.u.log(e.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this.u.log(e.Trace,"(LongPolling transport) Stop finished."),this.le()}}le(){if(this.onclose){let t="(LongPolling transport) Firing onclose event.";this.he&&(t+=" Error: "+this.he),this.u.log(e.Trace,t),this.onclose(this.he)}}}class V{constructor(t,e,n,i){this.$=t,this.te=e,this.u=n,this.ne=i,this.onreceive=null,this.onclose=null}async connect(t,n){return m.isRequired(t,"url"),m.isRequired(n,"transferFormat"),m.isIn(n,B,"transferFormat"),this.u.log(e.Trace,"(SSE transport) Connecting."),this.oe=t,this.te&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this.te)}`),new Promise(((i,o)=>{let r,s=!1;if(n===B.Text){if(g.isBrowser||g.isWebWorker)r=new this.ne.EventSource(t,{withCredentials:this.ne.withCredentials});else{const e=this.$.getCookieString(t),n={};n.Cookie=e;const[i,o]=C();n[i]=o,r=new this.ne.EventSource(t,{withCredentials:this.ne.withCredentials,headers:{...n,...this.ne.headers}})}try{r.onmessage=t=>{if(this.onreceive)try{this.u.log(e.Trace,`(SSE transport) data received. ${y(t.data,this.ne.logMessageContent)}.`),this.onreceive(t.data)}catch(t){return void this.ue(t)}},r.onerror=t=>{s?this.ue():o(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this.u.log(e.Information,`SSE connected to ${this.oe}`),this.de=r,s=!0,i()}}catch(t){return void o(t)}}else o(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(t){return this.de?b(this.u,"SSE",this.$,this.oe,t,this.ne):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this.ue(),Promise.resolve()}ue(t){this.de&&(this.de.close(),this.de=void 0,this.onclose&&this.onclose(t))}}class J{constructor(t,e,n,i,o,r){this.u=n,this.Zt=e,this.fe=i,this.pe=o,this.$=t,this.onreceive=null,this.onclose=null,this.we=r}async connect(t,n){let i;return m.isRequired(t,"url"),m.isRequired(n,"transferFormat"),m.isIn(n,B,"transferFormat"),this.u.log(e.Trace,"(WebSockets transport) Connecting."),this.Zt&&(i=await this.Zt()),new Promise(((o,r)=>{let s;t=t.replace(/^http/,"ws");const a=this.$.getCookieString(t);let c=!1;if(g.isNode||g.isReactNative){const e={},[n,o]=C();e[n]=o,i&&(e[z.Authorization]=`Bearer ${i}`),a&&(e[z.Cookie]=a),s=new this.pe(t,void 0,{headers:{...e,...this.we}})}else i&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(i)}`);s||(s=new this.pe(t)),n===B.Binary&&(s.binaryType="arraybuffer"),s.onopen=n=>{this.u.log(e.Information,`WebSocket connected to ${t}.`),this.ge=s,c=!0,o()},s.onerror=t=>{let n=null;n="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"There was an error with the transport",this.u.log(e.Information,`(WebSockets transport) ${n}.`)},s.onmessage=t=>{if(this.u.log(e.Trace,`(WebSockets transport) data received. ${y(t.data,this.fe)}.`),this.onreceive)try{this.onreceive(t.data)}catch(t){return void this.ue(t)}},s.onclose=t=>{if(c)this.ue(t);else{let e=null;e="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(e))}}}))}send(t){return this.ge&&this.ge.readyState===this.pe.OPEN?(this.u.log(e.Trace,`(WebSockets transport) sending data. ${y(t,this.fe)}.`),this.ge.send(t),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this.ge&&this.ue(void 0),Promise.resolve()}ue(t){this.ge&&(this.ge.onclose=()=>{},this.ge.onmessage=()=>{},this.ge.onerror=()=>{},this.ge.close(),this.ge=void 0),this.u.log(e.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this.me(t)||!1!==t.wasClean&&1e3===t.code?t instanceof Error?this.onclose(t):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason||"no reason given"}).`)))}me(t){return t&&"boolean"==typeof t.wasClean&&"number"==typeof t.code}}class Z{constructor(t,n={}){var i;if(this.ye=()=>{},this.features={},this.ve=1,m.isRequired(t,"url"),this.u=void 0===(i=n.logger)?new w(e.Information):null===i?p.instance:void 0!==i.log?i:new w(i),this.baseUrl=this.be(t),(n=n||{}).logMessageContent=void 0!==n.logMessageContent&&n.logMessageContent,"boolean"!=typeof n.withCredentials&&void 0!==n.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");n.withCredentials=void 0===n.withCredentials||n.withCredentials,n.timeout=void 0===n.timeout?1e5:n.timeout;let o=null,r=null;if(g.isNode){const t=require;o=t("ws"),r=t("eventsource")}g.isNode||"undefined"==typeof WebSocket||n.WebSocket?g.isNode&&!n.WebSocket&&o&&(n.WebSocket=o):n.WebSocket=WebSocket,g.isNode||"undefined"==typeof EventSource||n.EventSource?g.isNode&&!n.EventSource&&void 0!==r&&(n.EventSource=r):n.EventSource=EventSource,this.$=new F(n.httpClient||new D(this.u),n.accessTokenFactory),this.ut="Disconnected",this.dt=!1,this.ne=n,this.onreceive=null,this.onclose=null}async start(t){if(t=t||B.Binary,m.isIn(t,B,"transferFormat"),this.u.log(e.Debug,`Starting connection with transfer format '${B[t]}'.`),"Disconnected"!==this.ut)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this.ut="Connecting",this.Ee=this.yt(t),await this.Ee,"Disconnecting"===this.ut){const t="Failed to start the HttpConnection before stop() was called.";return this.u.log(e.Error,t),await this.It,Promise.reject(new r(t))}if("Connected"!==this.ut){const t="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this.u.log(e.Error,t),Promise.reject(new r(t))}this.dt=!0}send(t){return"Connected"!==this.ut?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this.$e||(this.$e=new Y(this.transport)),this.$e.send(t))}async stop(t){return"Disconnected"===this.ut?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this.ut?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this.It):(this.ut="Disconnecting",this.It=new Promise((t=>{this.ye=t})),await this._t(t),void await this.It)}async _t(t){this.Ce=t;try{await this.Ee}catch(t){}if(this.transport){try{await this.transport.stop()}catch(t){this.u.log(e.Error,`HttpConnection.transport.stop() threw error '${t}'.`),this.Se()}this.transport=void 0}else this.u.log(e.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async yt(t){let n=this.baseUrl;this.Zt=this.ne.accessTokenFactory,this.$.Zt=this.Zt;try{if(this.ne.skipNegotiation){if(this.ne.transport!==U.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this.ke(U.WebSockets),await this.Pe(n,t)}else{let e=null,i=0;do{if(e=await this.Te(n),"Disconnecting"===this.ut||"Disconnected"===this.ut)throw new r("The connection was stopped during negotiation.");if(e.error)throw new Error(e.error);if(e.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(e.url&&(n=e.url),e.accessToken){const t=e.accessToken;this.Zt=()=>t,this.$.te=t,this.$.Zt=void 0}i++}while(e.url&&i<100);if(100===i&&e.url)throw new Error("Negotiate redirection limit exceeded.");await this.Ie(n,this.ne.transport,e,t)}this.transport instanceof X&&(this.features.inherentKeepAlive=!0),"Connecting"===this.ut&&(this.u.log(e.Debug,"The HttpConnection connected successfully."),this.ut="Connected")}catch(t){return this.u.log(e.Error,"Failed to start the connection: "+t),this.ut="Disconnected",this.transport=void 0,this.ye(),Promise.reject(t)}}async Te(t){const n={},[o,r]=C();n[o]=r;const s=this._e(t);this.u.log(e.Debug,`Sending negotiation request: ${s}.`);try{const t=await this.$.post(s,{content:"",headers:{...n,...this.ne.headers},timeout:this.ne.timeout,withCredentials:this.ne.withCredentials});if(200!==t.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${t.statusCode}'`));const e=JSON.parse(t.content);return(!e.negotiateVersion||e.negotiateVersion<1)&&(e.connectionToken=e.connectionId),e.useStatefulReconnect&&!0!==this.ne.He?Promise.reject(new l("Client didn't negotiate Stateful Reconnect but the server did.")):e}catch(t){let n="Failed to complete negotiation with the server: "+t;return t instanceof i&&404===t.statusCode&&(n+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this.u.log(e.Error,n),Promise.reject(new l(n))}}De(t,e){return e?t+(-1===t.indexOf("?")?"?":"&")+`id=${e}`:t}async Ie(t,n,i,o){let s=this.De(t,i.connectionToken);if(this.Re(n))return this.u.log(e.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=n,await this.Pe(s,o),void(this.connectionId=i.connectionId);const a=[],l=i.availableTransports||[];let d=i;for(const i of l){const l=this.xe(i,n,o,!0===(null==d?void 0:d.useStatefulReconnect));if(l instanceof Error)a.push(`${i.transport} failed:`),a.push(l);else if(this.Re(l)){if(this.transport=l,!d){try{d=await this.Te(t)}catch(t){return Promise.reject(t)}s=this.De(t,d.connectionToken)}try{return await this.Pe(s,o),void(this.connectionId=d.connectionId)}catch(t){if(this.u.log(e.Error,`Failed to start the transport '${i.transport}': ${t}`),d=void 0,a.push(new c(`${i.transport} failed: ${t}`,U[i.transport])),"Connecting"!==this.ut){const t="Failed to select transport before stop() was called.";return this.u.log(e.Debug,t),Promise.reject(new r(t))}}}}return a.length>0?Promise.reject(new u(`Unable to connect to the server with any of the available transports. ${a.join(" ")}`,a)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}ke(t){switch(t){case U.WebSockets:if(!this.ne.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new J(this.$,this.Zt,this.u,this.ne.logMessageContent,this.ne.WebSocket,this.ne.headers||{});case U.ServerSentEvents:if(!this.ne.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new V(this.$,this.$.te,this.u,this.ne);case U.LongPolling:return new X(this.$,this.u,this.ne);default:throw new Error(`Unknown transport: ${t}.`)}}Pe(t,e){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async n=>{let i=!1;if(this.features.reconnect){try{this.features.disconnected(),await this.transport.connect(t,e),await this.features.resend()}catch{i=!0}i&&this.Se(n)}else this.Se(n)}:this.transport.onclose=t=>this.Se(t),this.transport.connect(t,e)}xe(t,n,i,o){const r=U[t.transport];if(null==r)return this.u.log(e.Debug,`Skipping transport '${t.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`);if(!function(t,e){return!t||!!(e&t)}(n,r))return this.u.log(e.Debug,`Skipping transport '${U[r]}' because it was disabled by the client.`),new a(`'${U[r]}' is disabled by the client.`,r);if(!(t.transferFormats.map((t=>B[t])).indexOf(i)>=0))return this.u.log(e.Debug,`Skipping transport '${U[r]}' because it does not support the requested transfer format '${B[i]}'.`),new Error(`'${U[r]}' does not support ${B[i]}.`);if(r===U.WebSockets&&!this.ne.WebSocket||r===U.ServerSentEvents&&!this.ne.EventSource)return this.u.log(e.Debug,`Skipping transport '${U[r]}' because it is not supported in your environment.'`),new s(`'${U[r]}' is not supported in your environment.`,r);this.u.log(e.Debug,`Selecting transport '${U[r]}'.`);try{return this.features.reconnect=r===U.WebSockets?o:void 0,this.ke(r)}catch(t){return t}}Re(t){return t&&"object"==typeof t&&"connect"in t}Se(t){if(this.u.log(e.Debug,`HttpConnection.stopConnection(${t}) called while in state ${this.ut}.`),this.transport=void 0,t=this.Ce||t,this.Ce=void 0,"Disconnected"!==this.ut){if("Connecting"===this.ut)throw this.u.log(e.Warning,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this.ut&&this.ye(),t?this.u.log(e.Error,`Connection disconnected with error '${t}'.`):this.u.log(e.Information,"Connection disconnected."),this.$e&&(this.$e.stop().catch((t=>{this.u.log(e.Error,`TransportSendQueue.stop() threw error '${t}'.`)})),this.$e=void 0),this.connectionId=void 0,this.ut="Disconnected",this.dt){this.dt=!1;try{this.onclose&&this.onclose(t)}catch(n){this.u.log(e.Error,`HttpConnection.onclose(${t}) threw error '${n}'.`)}}}else this.u.log(e.Debug,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`)}be(t){if(0===t.lastIndexOf("https://",0)||0===t.lastIndexOf("http://",0))return t;if(!g.isBrowser)throw new Error(`Cannot resolve '${t}'.`);const n=window.document.createElement("a");return n.href=t,this.u.log(e.Information,`Normalizing '${t}' to '${n.href}'.`),n.href}_e(t){const e=new URL(t);e.pathname.endsWith("/")?e.pathname+="negotiate":e.pathname+="/negotiate";const n=new URLSearchParams(e.searchParams);return n.has("negotiateVersion")||n.append("negotiateVersion",this.ve.toString()),n.has("useStatefulReconnect")?"true"===n.get("useStatefulReconnect")&&(this.ne.He=!0):!0===this.ne.He&&n.append("useStatefulReconnect","true"),e.search=n.toString(),e.toString()}}class Y{constructor(t){this.Ae=t,this.Ue=[],this.Le=!0,this.Ne=new Q,this.qe=new Q,this.Me=this.je()}send(t){return this.We(t),this.qe||(this.qe=new Q),this.qe.promise}stop(){return this.Le=!1,this.Ne.resolve(),this.Me}We(t){if(this.Ue.length&&typeof this.Ue[0]!=typeof t)throw new Error(`Expected data to be of type ${typeof this.Ue} but was of type ${typeof t}`);this.Ue.push(t),this.Ne.resolve()}async je(){for(;;){if(await this.Ne.promise,!this.Le){this.qe&&this.qe.reject("Connection stopped.");break}this.Ne=new Q;const t=this.qe;this.qe=void 0;const e="string"==typeof this.Ue[0]?this.Ue.join(""):Y.Oe(this.Ue);this.Ue.length=0;try{await this.Ae.send(e),t.resolve()}catch(e){t.reject(e)}}}static Oe(t){const e=t.map((t=>t.byteLength)).reduce(((t,e)=>t+e)),n=new Uint8Array(e);let i=0;for(const e of t)n.set(new Uint8Array(e),i),i+=e.byteLength;return n.buffer}}class Q{constructor(){this.promise=new Promise(((t,e)=>[this.j,this.Fe]=[t,e]))}resolve(){this.j()}reject(t){this.Fe(t)}}class K{constructor(){this.name="json",this.version=2,this.transferFormat=B.Text}parseMessages(t,n){if("string"!=typeof t)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!t)return[];null===n&&(n=p.instance);const i=A.parse(t),o=[];for(const t of i){const i=JSON.parse(t);if("number"!=typeof i.type)throw new Error("Invalid payload.");switch(i.type){case N.Invocation:this.U(i);break;case N.StreamItem:this.Be(i);break;case N.Completion:this.Xe(i);break;case N.Ping:case N.Close:break;case N.Ack:this.Je(i);break;case N.Sequence:this.ze(i);break;default:n.log(e.Information,"Unknown message type '"+i.type+"' ignored.");continue}o.push(i)}return o}writeMessage(t){return A.write(JSON.stringify(t))}U(t){this.Ve(t.target,"Invalid payload for Invocation message."),void 0!==t.invocationId&&this.Ve(t.invocationId,"Invalid payload for Invocation message.")}Be(t){if(this.Ve(t.invocationId,"Invalid payload for StreamItem message."),void 0===t.item)throw new Error("Invalid payload for StreamItem message.")}Xe(t){if(t.result&&t.error)throw new Error("Invalid payload for Completion message.");!t.result&&t.error&&this.Ve(t.error,"Invalid payload for Completion message."),this.Ve(t.invocationId,"Invalid payload for Completion message.")}Je(t){if("number"!=typeof t.sequenceId)throw new Error("Invalid SequenceId for Ack message.")}ze(t){if("number"!=typeof t.sequenceId)throw new Error("Invalid SequenceId for Sequence message.")}Ve(t,e){if("string"!=typeof t||""===t)throw new Error(e)}}const G={trace:e.Trace,debug:e.Debug,info:e.Information,information:e.Information,warn:e.Warning,warning:e.Warning,error:e.Error,critical:e.Critical,none:e.None};class tt{configureLogging(t){if(m.isRequired(t,"logging"),void 0!==t.log)this.logger=t;else if("string"==typeof t){const e=function(t){const e=G[t.toLowerCase()];if(void 0!==e)return e;throw new Error(`Unknown log level: ${t}`)}(t);this.logger=new w(e)}else this.logger=new w(t);return this}withUrl(t,e){return m.isRequired(t,"url"),m.isNotEmpty(t,"url"),this.url=t,this.httpConnectionOptions="object"==typeof e?{...this.httpConnectionOptions,...e}:{...this.httpConnectionOptions,transport:e},this}withHubProtocol(t){return m.isRequired(t,"protocol"),this.protocol=t,this}withAutomaticReconnect(t){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return t?Array.isArray(t)?this.reconnectPolicy=new L(t):this.reconnectPolicy=t:this.reconnectPolicy=new L,this}withServerTimeout(t){return m.isRequired(t,"milliseconds"),this.Ke=t,this}withKeepAliveInterval(t){return m.isRequired(t,"milliseconds"),this.Ge=t,this}withStatefulReconnect(t){return void 0===this.httpConnectionOptions&&(this.httpConnectionOptions={}),this.httpConnectionOptions.He=!0,this.Y=null==t?void 0:t.bufferSize,this}build(){const t=this.httpConnectionOptions||{};if(void 0===t.logger&&(t.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const e=new Z(this.url,t);return O.create(e,this.logger||p.instance,this.protocol||new K,this.reconnectPolicy,this.Ke,this.Ge,this.Y)}}return Uint8Array.prototype.indexOf||Object.defineProperty(Uint8Array.prototype,"indexOf",{value:Array.prototype.indexOf,writable:!0}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:function(t,e){return new Uint8Array(Array.prototype.slice.call(this,t,e))},writable:!0}),Uint8Array.prototype.forEach||Object.defineProperty(Uint8Array.prototype,"forEach",{value:Array.prototype.forEach,writable:!0}),n})(),"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.signalR=e():t.signalR=e(),$.extend($t,{t1:"Eingabe erforderlich",t2:"Bitte überprüfen Sie Ihre Eingaben im Formular.",b0:"Erstellt",b1:"Zuletzt geändert",b2:"von",t12:"Der Server hat einen Fehler zurückgegeben. Bitte versuchen Sie es erneut.",t17:"Eine Email mit einem Aktivierungs-Link wurde an deine Adresse versandt.",t18:"Ein Account mit deinem Namen existiert bereits. Dennoch erstellen?",t19:"Einträge sind entweder unngültig oder zu kurz.",t20:"Der Server hat einen Fehler gemeldet. Bitte versuch es erneut.",t21:"Der Zugang wurde nicht gefunden.",t30a:"Als erledigt markieren.",t30b:"Als unerledigt markieren.",t55:"Ein Email mit einem Aktivierungs-Link wurde an Ihre Adresse versandt.",t56:"Ein Zugang für diesen Namen besteht bereits. Trotzdem erstellen?",t57:"Ein bestehender Zugang wurde für diese Serie registriert.",t60:"Bitte geben Sie Email-Adresse an, die Sie hier hinterlegt haben.",t61:"Ihr Passwort wurde erfolgreich versandt.",t62:"Die angegebene Email-Adresse stimmt nicht mit der hier hinterlegten überein.",ov:"Persönliche Übersicht"});var $v={}; +var t,e,$t={lng:"de-DE",dn:["So","Mo","Di","Mi","Do","Fr","Sa"],mn:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],ma:["Jan","Feb","Mrz","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],datepattern:"(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}",datetimepattern:"(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}\\s([0-5][0-9]):([0-5][0-9])",dateplaceholder:"dd.MM.yyyy",datetimeplaceholder:"dd.MM.yyyy HH:mm",dateformat:"dd.MM.yyyy",datetimeformat:"dd.MM.yyyy HH:mm",f1:"Der Server hat einen Fehler gemeldet: \n",f2:"Bitte versuchen Sie es erneut.",m0:"Diese Internet-Seite benötigt einen html5-kompatiblen Browser.",m0b:"Unterstützt werden bspw: Internet Explorer ab Version 10, Firefox ab Version 31, Chrome ab Version 31, Safari ab Version 7, Opera ab Version 27",m1:"Dieser Datensatz ist momentan von jemand anderem zur Bearbeitung gesperrt.",m2:"Diese Funktion ist zur Zeit nicht verfügbar",t1:"Eingabe erforderlich.",t2:"Eingabe ist nicht erforderlich.",true:"Ja",false:"Nein",alert:"Hinweis",confirm:"Bestätigen",open:"Öffnen","not implemented":"Diese Funktion in zur Zeit noch nicht verfügbar.",l0:"Anmeldung",l1:"Email / Anmeldename",l2:"Email-Adresse / Anmeldename",l3:"Passwort",l4:"Benutzer",l5:"Wird vom System ermittelt...",l6:"Anmelden",l7:"Passwort vergessen?",l7a:'Die "Passwort vergessen"-Funktion läuft in zwei Schritten ab:\n \nIm ersten Schritt wird eine SMS mit einem Code an die hinterlegte Mobilfunk-Nummer versandt.\nIm zweiten Schritt geben Sie bitte diesen Code in das Formular ein und übermitteln es erneut.\n \nIn beiden Schritten wird aus Sicherheitsgründen kein Fehler angezeigt und auch dann ein erfolgreicher Versand bestätigt, wenn die Kombination aus Email-Adresse und Nachname nicht gefunden wurde und/oder der code falsch ist.',l8:"Keinen Account?",l9:"Anmeldenamen der Email-Adresse wurde nicht erkannt.",l10:"Nachname",l11:"Email-Adresse",l12:"Passwort zusenden",l13:"Das Passwort wurde erfolgreich verschickt",l14:"Das Passwort konnte nicht verschickt werden",l15:"Sie sind nicht berechtigt, diese Funktion auszuführen.",l16:"Sie müssen zunächst einen Account angeben.",l17:"Die Kombination aus Anmeldenamen und Passwort konnte nicht bestätigt werden.",l18:"Es gibt ein Problem mit dem Formular.\nEs kann momentan nicht verarbeitet und versendet werden.",name:"Name",submit:"Senden",cancel:"Abbrechen",noop:"Diese Funktion is noch nicht verfügar."};t=self,e=()=>(()=>{var t={d:(e,n)=>{for(var i in n)t.o(n,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:n[i]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),t.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"t",{value:!0})};var e,n={};t.r(n),t.d(n,{AbortError:()=>r,DefaultHttpClient:()=>D,HttpClient:()=>h,HttpError:()=>i,HttpResponse:()=>d,HttpTransportType:()=>U,HubConnection:()=>O,HubConnectionBuilder:()=>tt,HubConnectionState:()=>j,JsonHubProtocol:()=>K,LogLevel:()=>e,MessageType:()=>N,NullLogger:()=>p,Subject:()=>q,TimeoutError:()=>o,TransferFormat:()=>B,VERSION:()=>f});class i extends Error{constructor(t,e){const n=new.target.prototype;super(`${t}: Status code '${e}'`),this.statusCode=e,this.__proto__=n}}class o extends Error{constructor(t="A timeout occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class r extends Error{constructor(t="An abort occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class s extends Error{constructor(t,e){const n=new.target.prototype;super(t),this.transport=e,this.errorType="UnsupportedTransportError",this.__proto__=n}}class a extends Error{constructor(t,e){const n=new.target.prototype;super(t),this.transport=e,this.errorType="DisabledTransportError",this.__proto__=n}}class c extends Error{constructor(t,e){const n=new.target.prototype;super(t),this.transport=e,this.errorType="FailedToStartTransportError",this.__proto__=n}}class l extends Error{constructor(t){const e=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=e}}class u extends Error{constructor(t,e){const n=new.target.prototype;super(t),this.innerErrors=e,this.__proto__=n}}class d{constructor(t,e,n){this.statusCode=t,this.statusText=e,this.content=n}}class h{get(t,e){return this.send({...e,method:"GET",url:t})}post(t,e){return this.send({...e,method:"POST",url:t})}delete(t,e){return this.send({...e,method:"DELETE",url:t})}getCookieString(t){return""}}!function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Information=2]="Information",t[t.Warning=3]="Warning",t[t.Error=4]="Error",t[t.Critical=5]="Critical",t[t.None=6]="None"}(e||(e={}));class p{constructor(){}log(t,e){}}p.instance=new p;const f="10.0.0";class m{static isRequired(t,e){if(null==t)throw new Error(`The '${e}' argument is required.`)}static isNotEmpty(t,e){if(!t||t.match(/^\s*$/))throw new Error(`The '${e}' argument should not be empty.`)}static isIn(t,e,n){if(!(t in e))throw new Error(`Unknown ${n} value: ${t}.`)}}class g{static get isBrowser(){return!g.isNode&&"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return!g.isNode&&"object"==typeof self&&"importScripts"in self}static get isReactNative(){return!g.isNode&&"object"==typeof window&&void 0===window.document}static get isNode(){return"undefined"!=typeof process&&process.release&&"node"===process.release.name}}function y(t,e){let n="";return v(t)?(n=`Binary data of length ${t.byteLength}`,e&&(n+=`. Content: '${function(t){const e=new Uint8Array(t);let n="";return e.forEach((t=>{n+=`0x${t<16?"0":""}${t.toString(16)} `})),n.substring(0,n.length-1)}(t)}'`)):"string"==typeof t&&(n=`String data of length ${t.length}`,e&&(n+=`. Content: '${t}'`)),n}function v(t){return t&&"undefined"!=typeof ArrayBuffer&&(t instanceof ArrayBuffer||t.constructor&&"ArrayBuffer"===t.constructor.name)}async function b(t,n,i,o,r,s){const a={},[c,l]=C();a[c]=l,t.log(e.Trace,`(${n} transport) sending data. ${y(r,s.logMessageContent)}.`);const u=v(r)?"arraybuffer":"text",d=await i.post(o,{content:r,headers:{...a,...s.headers},responseType:u,timeout:s.timeout,withCredentials:s.withCredentials});t.log(e.Trace,`(${n} transport) request complete. Response status: ${d.statusCode}.`)}class ${constructor(t,e){this.i=t,this.h=e}dispose(){const t=this.i.observers.indexOf(this.h);t>-1&&this.i.observers.splice(t,1),0===this.i.observers.length&&this.i.cancelCallback&&this.i.cancelCallback().catch((t=>{}))}}class w{constructor(t){this.l=t,this.out=console}log(t,n){if(t>=this.l){const i=`[${(new Date).toISOString()}] ${e[t]}: ${n}`;switch(t){case e.Critical:case e.Error:this.out.error(i);break;case e.Warning:this.out.warn(i);break;case e.Information:this.out.info(i);break;default:this.out.log(i)}}}}function C(){let t="X-SignalR-User-Agent";return g.isNode&&(t="User-Agent"),[t,S(f,x(),g.isNode?"NodeJS":"Browser",_())]}function S(t,e,n,i){let o="Microsoft SignalR/";const r=t.split(".");return o+=`${r[0]}.${r[1]}`,o+=` (${t}; `,o+=e&&""!==e?`${e}; `:"Unknown OS; ",o+=`${n}`,o+=i?`; ${i}`:"; Unknown Runtime Version",o+=")",o}function x(){if(!g.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function _(){if(g.isNode)return process.versions.node}function T(t){return t.stack?t.stack:t.message?t.message:`${t}`}class E extends h{constructor(e){if(super(),this.u=e,"undefined"==typeof fetch||g.isNode){const t=require;this.p=new(t("tough-cookie").CookieJar),"undefined"==typeof fetch?this.m=t("node-fetch"):this.m=fetch,this.m=t("fetch-cookie")(this.m,this.p)}else this.m=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==t.g)return t.g;throw new Error("could not find global")}());if("undefined"==typeof AbortController){const t=require;this.v=t("abort-controller")}else this.v=AbortController}async send(t){if(t.abortSignal&&t.abortSignal.aborted)throw new r;if(!t.method)throw new Error("No method defined.");if(!t.url)throw new Error("No url defined.");const n=new this.v;let s;t.abortSignal&&(t.abortSignal.onabort=()=>{n.abort(),s=new r});let a,c=null;if(t.timeout){const i=t.timeout;c=setTimeout((()=>{n.abort(),this.u.log(e.Warning,"Timeout from HTTP request."),s=new o}),i)}""===t.content&&(t.content=void 0),t.content&&(t.headers=t.headers||{},v(t.content)?t.headers["Content-Type"]="application/octet-stream":t.headers["Content-Type"]="text/plain;charset=UTF-8");try{a=await this.m(t.url,{body:t.content,cache:"no-cache",credentials:!0===t.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...t.headers},method:t.method,mode:"cors",redirect:"follow",signal:n.signal})}catch(t){if(s)throw s;throw this.u.log(e.Warning,`Error from HTTP request. ${t}.`),t}finally{c&&clearTimeout(c),t.abortSignal&&(t.abortSignal.onabort=null)}if(!a.ok){const t=await k(a,"text");throw new i(t||a.statusText,a.status)}const l=k(a,t.responseType),u=await l;return new d(a.status,a.statusText,u)}getCookieString(t){let e="";return g.isNode&&this.p&&this.p.getCookies(t,((t,n)=>e=n.join("; "))),e}}function k(t,e){let n;switch(e){case"arraybuffer":n=t.arrayBuffer();break;case"text":default:n=t.text();break;case"blob":case"document":case"json":throw new Error(`${e} is not supported.`)}return n}class I extends h{constructor(t){super(),this.u=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new r):t.method?t.url?new Promise(((n,s)=>{const a=new XMLHttpRequest;a.open(t.method,t.url,!0),a.withCredentials=void 0===t.withCredentials||t.withCredentials,a.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===t.content&&(t.content=void 0),t.content&&(v(t.content)?a.setRequestHeader("Content-Type","application/octet-stream"):a.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const c=t.headers;c&&Object.keys(c).forEach((t=>{a.setRequestHeader(t,c[t])})),t.responseType&&(a.responseType=t.responseType),t.abortSignal&&(t.abortSignal.onabort=()=>{a.abort(),s(new r)}),t.timeout&&(a.timeout=t.timeout),a.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),a.status>=200&&a.status<300?n(new d(a.status,a.statusText,a.response||a.responseText)):s(new i(a.response||a.responseText||a.statusText,a.status))},a.onerror=()=>{this.u.log(e.Warning,`Error from HTTP request. ${a.status}: ${a.statusText}.`),s(new i(a.statusText,a.status))},a.ontimeout=()=>{this.u.log(e.Warning,"Timeout from HTTP request."),s(new o)},a.send(t.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class D extends h{constructor(t){if(super(),"undefined"!=typeof fetch||g.isNode)this.$=new E(t);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this.$=new I(t)}}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new r):t.method?t.url?this.$.send(t):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(t){return this.$.getCookieString(t)}}class A{static write(t){return`${t}${A.RecordSeparator}`}static parse(t){if(t[t.length-1]!==A.RecordSeparator)throw new Error("Message is incomplete.");const e=t.split(A.RecordSeparator);return e.pop(),e}}A.RecordSeparatorCode=30,A.RecordSeparator=String.fromCharCode(A.RecordSeparatorCode);class P{writeHandshakeRequest(t){return A.write(JSON.stringify(t))}parseHandshakeResponse(t){let e,n;if(v(t)){const i=new Uint8Array(t),o=i.indexOf(A.RecordSeparatorCode);if(-1===o)throw new Error("Message is incomplete.");const r=o+1;e=String.fromCharCode.apply(null,Array.prototype.slice.call(i.slice(0,r))),n=i.byteLength>r?i.slice(r).buffer:null}else{const i=t,o=i.indexOf(A.RecordSeparator);if(-1===o)throw new Error("Message is incomplete.");const r=o+1;e=i.substring(0,r),n=i.length>r?i.substring(r):null}const i=A.parse(e),o=JSON.parse(i[0]);if(o.type)throw new Error("Expected a handshake response from the server.");return[n,o]}}var N,j;!function(t){t[t.Invocation=1]="Invocation",t[t.StreamItem=2]="StreamItem",t[t.Completion=3]="Completion",t[t.StreamInvocation=4]="StreamInvocation",t[t.CancelInvocation=5]="CancelInvocation",t[t.Ping=6]="Ping",t[t.Close=7]="Close",t[t.Ack=8]="Ack",t[t.Sequence=9]="Sequence"}(N||(N={}));class q{constructor(){this.observers=[]}next(t){for(const e of this.observers)e.next(t)}error(t){for(const e of this.observers)e.error&&e.error(t)}complete(){for(const t of this.observers)t.complete&&t.complete()}subscribe(t){return this.observers.push(t),new $(this,t)}}class M{constructor(t,e,n){this.C=1e5,this.S=[],this.k=0,this.P=!1,this.T=1,this.I=0,this._=0,this.H=!1,this.D=t,this.R=e,this.C=n}async A(t){const e=this.D.writeMessage(t);let n=Promise.resolve();if(this.U(t)){this.k++;let t=()=>{},i=()=>{};v(e)?this._+=e.byteLength:this._+=e.length,this._>=this.C&&(n=new Promise(((e,n)=>{t=e,i=n}))),this.S.push(new R(e,this.k,t,i))}try{this.H||await this.R.send(e)}catch{this.L()}await n}N(t){let e=-1;for(let n=0;nthis.T?this.R.stop(new Error("Sequence ID greater than amount of messages we've received.")):this.T=t.sequenceId}L(){this.H=!0,this.P=!0}async B(){const t=0!==this.S.length?this.S[0].q:this.k+1;await this.R.send(this.D.writeMessage({type:N.Sequence,sequenceId:t}));const e=this.S;for(const t of e)await this.R.send(t.M);this.H=!1}X(t){null!=t||(t=new Error("Unable to reconnect to server."));for(const e of this.S)e.J(t)}U(t){switch(t.type){case N.Invocation:case N.StreamItem:case N.Completion:case N.StreamInvocation:case N.CancelInvocation:return!0;case N.Close:case N.Sequence:case N.Ping:case N.Ack:return!1}}O(){void 0===this.V&&(this.V=setTimeout((async()=>{try{this.H||await this.R.send(this.D.writeMessage({type:N.Ack,sequenceId:this.I}))}catch{}clearTimeout(this.V),this.V=void 0}),1e3))}}class R{constructor(t,e,n,i){this.M=t,this.q=e,this.j=n,this.J=i}}!function(t){t.Disconnected="Disconnected",t.Connecting="Connecting",t.Connected="Connected",t.Disconnecting="Disconnecting",t.Reconnecting="Reconnecting"}(j||(j={}));class O{static create(t,e,n,i,o,r,s){return new O(t,e,n,i,o,r,s)}constructor(t,n,i,o,r,s,a){this.K=0,this.G=()=>{this.u.log(e.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},m.isRequired(t,"connection"),m.isRequired(n,"logger"),m.isRequired(i,"protocol"),this.serverTimeoutInMilliseconds=null!=r?r:3e4,this.keepAliveIntervalInMilliseconds=null!=s?s:15e3,this.Y=null!=a?a:1e5,this.u=n,this.D=i,this.connection=t,this.Z=o,this.tt=new P,this.connection.onreceive=t=>this.et(t),this.connection.onclose=t=>this.st(t),this.it={},this.nt={},this.rt=[],this.ot=[],this.ht=[],this.ct=0,this.lt=!1,this.ut=j.Disconnected,this.dt=!1,this.ft=this.D.writeMessage({type:N.Ping})}get state(){return this.ut}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(t){if(this.ut!==j.Disconnected&&this.ut!==j.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!t)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=t}start(){return this.wt=this.gt(),this.wt}async gt(){if(this.ut!==j.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this.ut=j.Connecting,this.u.log(e.Debug,"Starting HubConnection.");try{await this.yt(),g.isBrowser&&window.document.addEventListener("freeze",this.G),this.ut=j.Connected,this.dt=!0,this.u.log(e.Debug,"HubConnection connected successfully.")}catch(t){return this.ut=j.Disconnected,this.u.log(e.Debug,`HubConnection failed to start successfully because of error '${t}'.`),Promise.reject(t)}}async yt(){this.vt=void 0,this.lt=!1;const t=new Promise(((t,e)=>{this.bt=t,this.Et=e}));await this.connection.start(this.D.transferFormat);try{let n=this.D.version;this.connection.features.reconnect||(n=1);const i={protocol:this.D.name,version:n};if(this.u.log(e.Debug,"Sending handshake request."),await this.$t(this.tt.writeHandshakeRequest(i)),this.u.log(e.Information,`Using HubProtocol '${this.D.name}'.`),this.Ct(),this.St(),this.kt(),await t,this.vt)throw this.vt;!!this.connection.features.reconnect&&(this.Pt=new M(this.D,this.connection,this.Y),this.connection.features.disconnected=this.Pt.L.bind(this.Pt),this.connection.features.resend=()=>{if(this.Pt)return this.Pt.B()}),this.connection.features.inherentKeepAlive||await this.$t(this.ft)}catch(t){throw this.u.log(e.Debug,`Hub handshake failed with error '${t}' during start(). Stopping HubConnection.`),this.Ct(),this.Tt(),await this.connection.stop(t),t}}async stop(){const t=this.wt;this.connection.features.reconnect=!1,this.It=this._t(),await this.It;try{await t}catch(t){}}_t(t){if(this.ut===j.Disconnected)return this.u.log(e.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this.ut===j.Disconnecting)return this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this.It;const n=this.ut;return this.ut=j.Disconnecting,this.u.log(e.Debug,"Stopping HubConnection."),this.Ht?(this.u.log(e.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this.Ht),this.Ht=void 0,this.Dt(),Promise.resolve()):(n===j.Connected&&this.Rt(),this.Ct(),this.Tt(),this.vt=t||new r("The connection was stopped before the hub handshake could complete."),this.connection.stop(t))}async Rt(){try{await this.xt(this.At())}catch{}}stream(t,...e){const[n,i]=this.Ut(e),o=this.Lt(t,e,i);let r;const s=new q;return s.cancelCallback=()=>{const t=this.Nt(o.invocationId);return delete this.it[o.invocationId],r.then((()=>this.xt(t)))},this.it[o.invocationId]=(t,e)=>{e?s.error(e):t&&(t.type===N.Completion?t.error?s.error(new Error(t.error)):s.complete():s.next(t.item))},r=this.xt(o).catch((t=>{s.error(t),delete this.it[o.invocationId]})),this.qt(n,r),s}$t(t){return this.kt(),this.connection.send(t)}xt(t){return this.Pt?this.Pt.A(t):this.$t(this.D.writeMessage(t))}send(t,...e){const[n,i]=this.Ut(e),o=this.xt(this.Mt(t,e,!0,i));return this.qt(n,o),o}invoke(t,...e){const[n,i]=this.Ut(e),o=this.Mt(t,e,!1,i);return new Promise(((t,e)=>{this.it[o.invocationId]=(n,i)=>{i?e(i):n&&(n.type===N.Completion?n.error?e(new Error(n.error)):t(n.result):e(new Error(`Unexpected message type: ${n.type}`)))};const i=this.xt(o).catch((t=>{e(t),delete this.it[o.invocationId]}));this.qt(n,i)}))}on(t,e){t&&e&&(t=t.toLowerCase(),this.nt[t]||(this.nt[t]=[]),-1===this.nt[t].indexOf(e)&&this.nt[t].push(e))}off(t,e){if(!t)return;t=t.toLowerCase();const n=this.nt[t];if(n)if(e){const i=n.indexOf(e);-1!==i&&(n.splice(i,1),0===n.length&&delete this.nt[t])}else delete this.nt[t]}onclose(t){t&&this.rt.push(t)}onreconnecting(t){t&&this.ot.push(t)}onreconnected(t){t&&this.ht.push(t)}et(t){if(this.Ct(),this.lt||(t=this.jt(t),this.lt=!0),t){const n=this.D.parseMessages(t,this.u);for(const i of n)if(!this.Pt||this.Pt.W(i))switch(i.type){case N.Invocation:this.Wt(i).catch((t=>{this.u.log(e.Error,`Invoke client method threw error: ${T(t)}`)}));break;case N.StreamItem:case N.Completion:{const n=this.it[i.invocationId];if(n){i.type===N.Completion&&delete this.it[i.invocationId];try{n(i)}catch(t){this.u.log(e.Error,`Stream callback threw error: ${T(t)}`)}}break}case N.Ping:break;case N.Close:{this.u.log(e.Information,"Close message received from server.");const t=i.error?new Error("Server returned an error on close: "+i.error):void 0;!0===i.allowReconnect?this.connection.stop(t):this.It=this._t(t);break}case N.Ack:this.Pt&&this.Pt.N(i);break;case N.Sequence:this.Pt&&this.Pt.F(i);break;default:this.u.log(e.Warning,`Invalid message type: ${i.type}.`)}}this.St()}jt(t){let n,i;try{[i,n]=this.tt.parseHandshakeResponse(t)}catch(t){const n="Error parsing handshake response: "+t;this.u.log(e.Error,n);const i=new Error(n);throw this.Et(i),i}if(n.error){const t="Server returned handshake error: "+n.error;this.u.log(e.Error,t);const i=new Error(t);throw this.Et(i),i}return this.u.log(e.Debug,"Server handshake complete."),this.bt(),i}kt(){this.connection.features.inherentKeepAlive||(this.K=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this.Tt())}St(){if(!this.connection.features||!this.connection.features.inherentKeepAlive){this.Ot=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds);let t=this.K-(new Date).getTime();if(t<0)return void(this.ut===j.Connected&&this.Ft());void 0===this.Bt&&(t<0&&(t=0),this.Bt=setTimeout((async()=>{this.ut===j.Connected&&await this.Ft()}),t))}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async Wt(t){const n=t.target.toLowerCase(),i=this.nt[n];if(!i)return this.u.log(e.Warning,`No client method with the name '${n}' found.`),void(t.invocationId&&(this.u.log(e.Warning,`No result given for '${n}' method and invocation ID '${t.invocationId}'.`),await this.xt(this.Xt(t.invocationId,"Client didn't provide a result.",null))));const o=i.slice(),r=!!t.invocationId;let s,a,c;for(const i of o)try{const o=s;s=await i.apply(this,t.arguments),r&&s&&o&&(this.u.log(e.Error,`Multiple results provided for '${n}'. Sending error to server.`),c=this.Xt(t.invocationId,"Client provided multiple results.",null)),a=void 0}catch(t){a=t,this.u.log(e.Error,`A callback for the method '${n}' threw error '${t}'.`)}c?await this.xt(c):r?(a?c=this.Xt(t.invocationId,`${a}`,null):void 0!==s?c=this.Xt(t.invocationId,null,s):(this.u.log(e.Warning,`No result given for '${n}' method and invocation ID '${t.invocationId}'.`),c=this.Xt(t.invocationId,"Client didn't provide a result.",null)),await this.xt(c)):s&&this.u.log(e.Error,`Result given for '${n}' method but server is not expecting a result.`)}st(t){this.u.log(e.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this.ut}.`),this.vt=this.vt||t||new r("The underlying connection was closed before the hub handshake could complete."),this.bt&&this.bt(),this.Jt(t||new Error("Invocation canceled due to the underlying connection being closed.")),this.Ct(),this.Tt(),this.ut===j.Disconnecting?this.Dt(t):this.ut===j.Connected&&this.Z?this.zt(t):this.ut===j.Connected&&this.Dt(t)}Dt(t){if(this.dt){this.ut=j.Disconnected,this.dt=!1,this.Pt&&(this.Pt.X(null!=t?t:new Error("Connection closed.")),this.Pt=void 0),g.isBrowser&&window.document.removeEventListener("freeze",this.G);try{this.rt.forEach((e=>e.apply(this,[t])))}catch(n){this.u.log(e.Error,`An onclose callback called with error '${t}' threw error '${n}'.`)}}}async zt(t){const n=Date.now();let i=0,o=void 0!==t?t:new Error("Attempting to reconnect due to a unknown error."),r=this.Vt(i,0,o);if(null===r)return this.u.log(e.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this.Dt(t);if(this.ut=j.Reconnecting,t?this.u.log(e.Information,`Connection reconnecting because of error '${t}'.`):this.u.log(e.Information,"Connection reconnecting."),0!==this.ot.length){try{this.ot.forEach((e=>e.apply(this,[t])))}catch(n){this.u.log(e.Error,`An onreconnecting callback called with error '${t}' threw error '${n}'.`)}if(this.ut!==j.Reconnecting)return void this.u.log(e.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this.u.log(e.Information,`Reconnect attempt number ${i+1} will start in ${r} ms.`),await new Promise((t=>{this.Ht=setTimeout(t,r)})),this.Ht=void 0,this.ut!==j.Reconnecting)return void this.u.log(e.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this.yt(),this.ut=j.Connected,this.u.log(e.Information,"HubConnection reconnected successfully."),0!==this.ht.length)try{this.ht.forEach((t=>t.apply(this,[this.connection.connectionId])))}catch(t){this.u.log(e.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${t}'.`)}return}catch(t){if(this.u.log(e.Information,`Reconnect attempt failed because of error '${t}'.`),this.ut!==j.Reconnecting)return this.u.log(e.Debug,`Connection moved to the '${this.ut}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this.ut===j.Disconnecting&&this.Dt());i++,o=t instanceof Error?t:new Error(t.toString()),r=this.Vt(i,Date.now()-n,o)}}this.u.log(e.Information,`Reconnect retries have been exhausted after ${Date.now()-n} ms and ${i} failed attempts. Connection disconnecting.`),this.Dt()}Vt(t,n,i){try{return this.Z.nextRetryDelayInMilliseconds({elapsedMilliseconds:n,previousRetryCount:t,retryReason:i})}catch(i){return this.u.log(e.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${n}) threw error '${i}'.`),null}}Jt(t){const n=this.it;this.it={},Object.keys(n).forEach((i=>{const o=n[i];try{o(null,t)}catch(n){this.u.log(e.Error,`Stream 'error' callback called with '${t}' threw error: ${T(n)}`)}}))}Tt(){this.Bt&&(clearTimeout(this.Bt),this.Bt=void 0)}Ct(){this.Ot&&clearTimeout(this.Ot)}Mt(t,e,n,i){if(n)return 0!==i.length?{target:t,arguments:e,streamIds:i,type:N.Invocation}:{target:t,arguments:e,type:N.Invocation};{const n=this.ct;return this.ct++,0!==i.length?{target:t,arguments:e,invocationId:n.toString(),streamIds:i,type:N.Invocation}:{target:t,arguments:e,invocationId:n.toString(),type:N.Invocation}}}qt(t,e){if(0!==t.length){e||(e=Promise.resolve());for(const n in t)t[n].subscribe({complete:()=>{e=e.then((()=>this.xt(this.Xt(n))))},error:t=>{let i;i=t instanceof Error?t.message:t&&t.toString?t.toString():"Unknown error",e=e.then((()=>this.xt(this.Xt(n,i))))},next:t=>{e=e.then((()=>this.xt(this.Kt(n,t))))}})}}Ut(t){const e=[],n=[];for(let i=0;i0)&&(e=!1,this.te=await this.Zt()),this.ee(t);const n=await this.Yt.send(t);return e&&401===n.statusCode&&this.Zt?(this.te=await this.Zt(),this.ee(t),await this.Yt.send(t)):n}ee(t){t.headers||(t.headers={}),this.te?t.headers[z.Authorization]=`Bearer ${this.te}`:this.Zt&&t.headers[z.Authorization]&&delete t.headers[z.Authorization]}getCookieString(t){return this.Yt.getCookieString(t)}}var U,B;!function(t){t[t.None=0]="None",t[t.WebSockets=1]="WebSockets",t[t.ServerSentEvents=2]="ServerSentEvents",t[t.LongPolling=4]="LongPolling"}(U||(U={})),function(t){t[t.Text=1]="Text",t[t.Binary=2]="Binary"}(B||(B={}));class W{constructor(){this.se=!1,this.onabort=null}abort(){this.se||(this.se=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this.se}}class X{get pollAborted(){return this.ie.aborted}constructor(t,e,n){this.$=t,this.u=e,this.ie=new W,this.ne=n,this.re=!1,this.onreceive=null,this.onclose=null}async connect(t,n){if(m.isRequired(t,"url"),m.isRequired(n,"transferFormat"),m.isIn(n,B,"transferFormat"),this.oe=t,this.u.log(e.Trace,"(LongPolling transport) Connecting."),n===B.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[o,r]=C(),s={[o]:r,...this.ne.headers},a={abortSignal:this.ie.signal,headers:s,timeout:1e5,withCredentials:this.ne.withCredentials};n===B.Binary&&(a.responseType="arraybuffer");const c=`${t}&_=${Date.now()}`;this.u.log(e.Trace,`(LongPolling transport) polling: ${c}.`);const l=await this.$.get(c,a);200!==l.statusCode?(this.u.log(e.Error,`(LongPolling transport) Unexpected response code: ${l.statusCode}.`),this.he=new i(l.statusText||"",l.statusCode),this.re=!1):this.re=!0,this.ce=this.ae(this.oe,a)}async ae(t,n){try{for(;this.re;)try{const o=`${t}&_=${Date.now()}`;this.u.log(e.Trace,`(LongPolling transport) polling: ${o}.`);const r=await this.$.get(o,n);204===r.statusCode?(this.u.log(e.Information,"(LongPolling transport) Poll terminated by server."),this.re=!1):200!==r.statusCode?(this.u.log(e.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this.he=new i(r.statusText||"",r.statusCode),this.re=!1):r.content?(this.u.log(e.Trace,`(LongPolling transport) data received. ${y(r.content,this.ne.logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this.u.log(e.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(t){this.re?t instanceof o?this.u.log(e.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this.he=t,this.re=!1):this.u.log(e.Trace,`(LongPolling transport) Poll errored after shutdown: ${t.message}`)}}finally{this.u.log(e.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this.le()}}async send(t){return this.re?b(this.u,"LongPolling",this.$,this.oe,t,this.ne):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this.u.log(e.Trace,"(LongPolling transport) Stopping polling."),this.re=!1,this.ie.abort();try{await this.ce,this.u.log(e.Trace,`(LongPolling transport) sending DELETE request to ${this.oe}.`);const t={},[n,o]=C();t[n]=o;const r={headers:{...t,...this.ne.headers},timeout:this.ne.timeout,withCredentials:this.ne.withCredentials};let s;try{await this.$.delete(this.oe,r)}catch(t){s=t}s?s instanceof i&&(404===s.statusCode?this.u.log(e.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this.u.log(e.Trace,`(LongPolling transport) Error sending a DELETE request: ${s}`)):this.u.log(e.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this.u.log(e.Trace,"(LongPolling transport) Stop finished."),this.le()}}le(){if(this.onclose){let t="(LongPolling transport) Firing onclose event.";this.he&&(t+=" Error: "+this.he),this.u.log(e.Trace,t),this.onclose(this.he)}}}class V{constructor(t,e,n,i){this.$=t,this.te=e,this.u=n,this.ne=i,this.onreceive=null,this.onclose=null}async connect(t,n){return m.isRequired(t,"url"),m.isRequired(n,"transferFormat"),m.isIn(n,B,"transferFormat"),this.u.log(e.Trace,"(SSE transport) Connecting."),this.oe=t,this.te&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this.te)}`),new Promise(((i,o)=>{let r,s=!1;if(n===B.Text){if(g.isBrowser||g.isWebWorker)r=new this.ne.EventSource(t,{withCredentials:this.ne.withCredentials});else{const e=this.$.getCookieString(t),n={};n.Cookie=e;const[i,o]=C();n[i]=o,r=new this.ne.EventSource(t,{withCredentials:this.ne.withCredentials,headers:{...n,...this.ne.headers}})}try{r.onmessage=t=>{if(this.onreceive)try{this.u.log(e.Trace,`(SSE transport) data received. ${y(t.data,this.ne.logMessageContent)}.`),this.onreceive(t.data)}catch(t){return void this.ue(t)}},r.onerror=t=>{s?this.ue():o(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this.u.log(e.Information,`SSE connected to ${this.oe}`),this.de=r,s=!0,i()}}catch(t){return void o(t)}}else o(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(t){return this.de?b(this.u,"SSE",this.$,this.oe,t,this.ne):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this.ue(),Promise.resolve()}ue(t){this.de&&(this.de.close(),this.de=void 0,this.onclose&&this.onclose(t))}}class J{constructor(t,e,n,i,o,r){this.u=n,this.Zt=e,this.fe=i,this.pe=o,this.$=t,this.onreceive=null,this.onclose=null,this.we=r}async connect(t,n){let i;return m.isRequired(t,"url"),m.isRequired(n,"transferFormat"),m.isIn(n,B,"transferFormat"),this.u.log(e.Trace,"(WebSockets transport) Connecting."),this.Zt&&(i=await this.Zt()),new Promise(((o,r)=>{let s;t=t.replace(/^http/,"ws");const a=this.$.getCookieString(t);let c=!1;if(g.isNode||g.isReactNative){const e={},[n,o]=C();e[n]=o,i&&(e[z.Authorization]=`Bearer ${i}`),a&&(e[z.Cookie]=a),s=new this.pe(t,void 0,{headers:{...e,...this.we}})}else i&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(i)}`);s||(s=new this.pe(t)),n===B.Binary&&(s.binaryType="arraybuffer"),s.onopen=n=>{this.u.log(e.Information,`WebSocket connected to ${t}.`),this.ge=s,c=!0,o()},s.onerror=t=>{let n=null;n="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"There was an error with the transport",this.u.log(e.Information,`(WebSockets transport) ${n}.`)},s.onmessage=t=>{if(this.u.log(e.Trace,`(WebSockets transport) data received. ${y(t.data,this.fe)}.`),this.onreceive)try{this.onreceive(t.data)}catch(t){return void this.ue(t)}},s.onclose=t=>{if(c)this.ue(t);else{let e=null;e="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(e))}}}))}send(t){return this.ge&&this.ge.readyState===this.pe.OPEN?(this.u.log(e.Trace,`(WebSockets transport) sending data. ${y(t,this.fe)}.`),this.ge.send(t),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this.ge&&this.ue(void 0),Promise.resolve()}ue(t){this.ge&&(this.ge.onclose=()=>{},this.ge.onmessage=()=>{},this.ge.onerror=()=>{},this.ge.close(),this.ge=void 0),this.u.log(e.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this.me(t)||!1!==t.wasClean&&1e3===t.code?t instanceof Error?this.onclose(t):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason||"no reason given"}).`)))}me(t){return t&&"boolean"==typeof t.wasClean&&"number"==typeof t.code}}class Z{constructor(t,n={}){var i;if(this.ye=()=>{},this.features={},this.ve=1,m.isRequired(t,"url"),this.u=void 0===(i=n.logger)?new w(e.Information):null===i?p.instance:void 0!==i.log?i:new w(i),this.baseUrl=this.be(t),(n=n||{}).logMessageContent=void 0!==n.logMessageContent&&n.logMessageContent,"boolean"!=typeof n.withCredentials&&void 0!==n.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");n.withCredentials=void 0===n.withCredentials||n.withCredentials,n.timeout=void 0===n.timeout?1e5:n.timeout;let o=null,r=null;if(g.isNode){const t=require;o=t("ws"),r=t("eventsource")}g.isNode||"undefined"==typeof WebSocket||n.WebSocket?g.isNode&&!n.WebSocket&&o&&(n.WebSocket=o):n.WebSocket=WebSocket,g.isNode||"undefined"==typeof EventSource||n.EventSource?g.isNode&&!n.EventSource&&void 0!==r&&(n.EventSource=r):n.EventSource=EventSource,this.$=new F(n.httpClient||new D(this.u),n.accessTokenFactory),this.ut="Disconnected",this.dt=!1,this.ne=n,this.onreceive=null,this.onclose=null}async start(t){if(t=t||B.Binary,m.isIn(t,B,"transferFormat"),this.u.log(e.Debug,`Starting connection with transfer format '${B[t]}'.`),"Disconnected"!==this.ut)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this.ut="Connecting",this.Ee=this.yt(t),await this.Ee,"Disconnecting"===this.ut){const t="Failed to start the HttpConnection before stop() was called.";return this.u.log(e.Error,t),await this.It,Promise.reject(new r(t))}if("Connected"!==this.ut){const t="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this.u.log(e.Error,t),Promise.reject(new r(t))}this.dt=!0}send(t){return"Connected"!==this.ut?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this.$e||(this.$e=new Y(this.transport)),this.$e.send(t))}async stop(t){return"Disconnected"===this.ut?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this.ut?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this.It):(this.ut="Disconnecting",this.It=new Promise((t=>{this.ye=t})),await this._t(t),void await this.It)}async _t(t){this.Ce=t;try{await this.Ee}catch(t){}if(this.transport){try{await this.transport.stop()}catch(t){this.u.log(e.Error,`HttpConnection.transport.stop() threw error '${t}'.`),this.Se()}this.transport=void 0}else this.u.log(e.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async yt(t){let n=this.baseUrl;this.Zt=this.ne.accessTokenFactory,this.$.Zt=this.Zt;try{if(this.ne.skipNegotiation){if(this.ne.transport!==U.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this.ke(U.WebSockets),await this.Pe(n,t)}else{let e=null,i=0;do{if(e=await this.Te(n),"Disconnecting"===this.ut||"Disconnected"===this.ut)throw new r("The connection was stopped during negotiation.");if(e.error)throw new Error(e.error);if(e.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(e.url&&(n=e.url),e.accessToken){const t=e.accessToken;this.Zt=()=>t,this.$.te=t,this.$.Zt=void 0}i++}while(e.url&&i<100);if(100===i&&e.url)throw new Error("Negotiate redirection limit exceeded.");await this.Ie(n,this.ne.transport,e,t)}this.transport instanceof X&&(this.features.inherentKeepAlive=!0),"Connecting"===this.ut&&(this.u.log(e.Debug,"The HttpConnection connected successfully."),this.ut="Connected")}catch(t){return this.u.log(e.Error,"Failed to start the connection: "+t),this.ut="Disconnected",this.transport=void 0,this.ye(),Promise.reject(t)}}async Te(t){const n={},[o,r]=C();n[o]=r;const s=this._e(t);this.u.log(e.Debug,`Sending negotiation request: ${s}.`);try{const t=await this.$.post(s,{content:"",headers:{...n,...this.ne.headers},timeout:this.ne.timeout,withCredentials:this.ne.withCredentials});if(200!==t.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${t.statusCode}'`));const e=JSON.parse(t.content);return(!e.negotiateVersion||e.negotiateVersion<1)&&(e.connectionToken=e.connectionId),e.useStatefulReconnect&&!0!==this.ne.He?Promise.reject(new l("Client didn't negotiate Stateful Reconnect but the server did.")):e}catch(t){let n="Failed to complete negotiation with the server: "+t;return t instanceof i&&404===t.statusCode&&(n+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this.u.log(e.Error,n),Promise.reject(new l(n))}}De(t,e){return e?t+(-1===t.indexOf("?")?"?":"&")+`id=${e}`:t}async Ie(t,n,i,o){let s=this.De(t,i.connectionToken);if(this.Re(n))return this.u.log(e.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=n,await this.Pe(s,o),void(this.connectionId=i.connectionId);const a=[],l=i.availableTransports||[];let d=i;for(const i of l){const l=this.xe(i,n,o,!0===(null==d?void 0:d.useStatefulReconnect));if(l instanceof Error)a.push(`${i.transport} failed:`),a.push(l);else if(this.Re(l)){if(this.transport=l,!d){try{d=await this.Te(t)}catch(t){return Promise.reject(t)}s=this.De(t,d.connectionToken)}try{return await this.Pe(s,o),void(this.connectionId=d.connectionId)}catch(t){if(this.u.log(e.Error,`Failed to start the transport '${i.transport}': ${t}`),d=void 0,a.push(new c(`${i.transport} failed: ${t}`,U[i.transport])),"Connecting"!==this.ut){const t="Failed to select transport before stop() was called.";return this.u.log(e.Debug,t),Promise.reject(new r(t))}}}}return a.length>0?Promise.reject(new u(`Unable to connect to the server with any of the available transports. ${a.join(" ")}`,a)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}ke(t){switch(t){case U.WebSockets:if(!this.ne.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new J(this.$,this.Zt,this.u,this.ne.logMessageContent,this.ne.WebSocket,this.ne.headers||{});case U.ServerSentEvents:if(!this.ne.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new V(this.$,this.$.te,this.u,this.ne);case U.LongPolling:return new X(this.$,this.u,this.ne);default:throw new Error(`Unknown transport: ${t}.`)}}Pe(t,e){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async n=>{let i=!1;if(this.features.reconnect){try{this.features.disconnected(),await this.transport.connect(t,e),await this.features.resend()}catch{i=!0}i&&this.Se(n)}else this.Se(n)}:this.transport.onclose=t=>this.Se(t),this.transport.connect(t,e)}xe(t,n,i,o){const r=U[t.transport];if(null==r)return this.u.log(e.Debug,`Skipping transport '${t.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`);if(!function(t,e){return!t||!!(e&t)}(n,r))return this.u.log(e.Debug,`Skipping transport '${U[r]}' because it was disabled by the client.`),new a(`'${U[r]}' is disabled by the client.`,r);if(!(t.transferFormats.map((t=>B[t])).indexOf(i)>=0))return this.u.log(e.Debug,`Skipping transport '${U[r]}' because it does not support the requested transfer format '${B[i]}'.`),new Error(`'${U[r]}' does not support ${B[i]}.`);if(r===U.WebSockets&&!this.ne.WebSocket||r===U.ServerSentEvents&&!this.ne.EventSource)return this.u.log(e.Debug,`Skipping transport '${U[r]}' because it is not supported in your environment.'`),new s(`'${U[r]}' is not supported in your environment.`,r);this.u.log(e.Debug,`Selecting transport '${U[r]}'.`);try{return this.features.reconnect=r===U.WebSockets?o:void 0,this.ke(r)}catch(t){return t}}Re(t){return t&&"object"==typeof t&&"connect"in t}Se(t){if(this.u.log(e.Debug,`HttpConnection.stopConnection(${t}) called while in state ${this.ut}.`),this.transport=void 0,t=this.Ce||t,this.Ce=void 0,"Disconnected"!==this.ut){if("Connecting"===this.ut)throw this.u.log(e.Warning,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this.ut&&this.ye(),t?this.u.log(e.Error,`Connection disconnected with error '${t}'.`):this.u.log(e.Information,"Connection disconnected."),this.$e&&(this.$e.stop().catch((t=>{this.u.log(e.Error,`TransportSendQueue.stop() threw error '${t}'.`)})),this.$e=void 0),this.connectionId=void 0,this.ut="Disconnected",this.dt){this.dt=!1;try{this.onclose&&this.onclose(t)}catch(n){this.u.log(e.Error,`HttpConnection.onclose(${t}) threw error '${n}'.`)}}}else this.u.log(e.Debug,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`)}be(t){if(0===t.lastIndexOf("https://",0)||0===t.lastIndexOf("http://",0))return t;if(!g.isBrowser)throw new Error(`Cannot resolve '${t}'.`);const n=window.document.createElement("a");return n.href=t,this.u.log(e.Information,`Normalizing '${t}' to '${n.href}'.`),n.href}_e(t){const e=new URL(t);e.pathname.endsWith("/")?e.pathname+="negotiate":e.pathname+="/negotiate";const n=new URLSearchParams(e.searchParams);return n.has("negotiateVersion")||n.append("negotiateVersion",this.ve.toString()),n.has("useStatefulReconnect")?"true"===n.get("useStatefulReconnect")&&(this.ne.He=!0):!0===this.ne.He&&n.append("useStatefulReconnect","true"),e.search=n.toString(),e.toString()}}class Y{constructor(t){this.Ae=t,this.Ue=[],this.Le=!0,this.Ne=new Q,this.qe=new Q,this.Me=this.je()}send(t){return this.We(t),this.qe||(this.qe=new Q),this.qe.promise}stop(){return this.Le=!1,this.Ne.resolve(),this.Me}We(t){if(this.Ue.length&&typeof this.Ue[0]!=typeof t)throw new Error(`Expected data to be of type ${typeof this.Ue} but was of type ${typeof t}`);this.Ue.push(t),this.Ne.resolve()}async je(){for(;;){if(await this.Ne.promise,!this.Le){this.qe&&this.qe.reject("Connection stopped.");break}this.Ne=new Q;const t=this.qe;this.qe=void 0;const e="string"==typeof this.Ue[0]?this.Ue.join(""):Y.Oe(this.Ue);this.Ue.length=0;try{await this.Ae.send(e),t.resolve()}catch(e){t.reject(e)}}}static Oe(t){const e=t.map((t=>t.byteLength)).reduce(((t,e)=>t+e)),n=new Uint8Array(e);let i=0;for(const e of t)n.set(new Uint8Array(e),i),i+=e.byteLength;return n.buffer}}class Q{constructor(){this.promise=new Promise(((t,e)=>[this.j,this.Fe]=[t,e]))}resolve(){this.j()}reject(t){this.Fe(t)}}class K{constructor(){this.name="json",this.version=2,this.transferFormat=B.Text}parseMessages(t,n){if("string"!=typeof t)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!t)return[];null===n&&(n=p.instance);const i=A.parse(t),o=[];for(const t of i){const i=JSON.parse(t);if("number"!=typeof i.type)throw new Error("Invalid payload.");switch(i.type){case N.Invocation:this.U(i);break;case N.StreamItem:this.Be(i);break;case N.Completion:this.Xe(i);break;case N.Ping:case N.Close:break;case N.Ack:this.Je(i);break;case N.Sequence:this.ze(i);break;default:n.log(e.Information,"Unknown message type '"+i.type+"' ignored.");continue}o.push(i)}return o}writeMessage(t){return A.write(JSON.stringify(t))}U(t){this.Ve(t.target,"Invalid payload for Invocation message."),void 0!==t.invocationId&&this.Ve(t.invocationId,"Invalid payload for Invocation message.")}Be(t){if(this.Ve(t.invocationId,"Invalid payload for StreamItem message."),void 0===t.item)throw new Error("Invalid payload for StreamItem message.")}Xe(t){if(t.result&&t.error)throw new Error("Invalid payload for Completion message.");!t.result&&t.error&&this.Ve(t.error,"Invalid payload for Completion message."),this.Ve(t.invocationId,"Invalid payload for Completion message.")}Je(t){if("number"!=typeof t.sequenceId)throw new Error("Invalid SequenceId for Ack message.")}ze(t){if("number"!=typeof t.sequenceId)throw new Error("Invalid SequenceId for Sequence message.")}Ve(t,e){if("string"!=typeof t||""===t)throw new Error(e)}}const G={trace:e.Trace,debug:e.Debug,info:e.Information,information:e.Information,warn:e.Warning,warning:e.Warning,error:e.Error,critical:e.Critical,none:e.None};class tt{configureLogging(t){if(m.isRequired(t,"logging"),void 0!==t.log)this.logger=t;else if("string"==typeof t){const e=function(t){const e=G[t.toLowerCase()];if(void 0!==e)return e;throw new Error(`Unknown log level: ${t}`)}(t);this.logger=new w(e)}else this.logger=new w(t);return this}withUrl(t,e){return m.isRequired(t,"url"),m.isNotEmpty(t,"url"),this.url=t,this.httpConnectionOptions="object"==typeof e?{...this.httpConnectionOptions,...e}:{...this.httpConnectionOptions,transport:e},this}withHubProtocol(t){return m.isRequired(t,"protocol"),this.protocol=t,this}withAutomaticReconnect(t){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return t?Array.isArray(t)?this.reconnectPolicy=new L(t):this.reconnectPolicy=t:this.reconnectPolicy=new L,this}withServerTimeout(t){return m.isRequired(t,"milliseconds"),this.Ke=t,this}withKeepAliveInterval(t){return m.isRequired(t,"milliseconds"),this.Ge=t,this}withStatefulReconnect(t){return void 0===this.httpConnectionOptions&&(this.httpConnectionOptions={}),this.httpConnectionOptions.He=!0,this.Y=null==t?void 0:t.bufferSize,this}build(){const t=this.httpConnectionOptions||{};if(void 0===t.logger&&(t.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const e=new Z(this.url,t);return O.create(e,this.logger||p.instance,this.protocol||new K,this.reconnectPolicy,this.Ke,this.Ge,this.Y)}}return Uint8Array.prototype.indexOf||Object.defineProperty(Uint8Array.prototype,"indexOf",{value:Array.prototype.indexOf,writable:!0}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:function(t,e){return new Uint8Array(Array.prototype.slice.call(this,t,e))},writable:!0}),Uint8Array.prototype.forEach||Object.defineProperty(Uint8Array.prototype,"forEach",{value:Array.prototype.forEach,writable:!0}),n})(),"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.signalR=e():t.signalR=e(),$.extend($t,{t1:"Eingabe erforderlich",t2:"Bitte überprüfen Sie Ihre Eingaben im Formular.",b0:"Erstellt",b1:"Zuletzt geändert",b2:"von",t12:"Der Server hat einen Fehler zurückgegeben. Bitte versuchen Sie es erneut.",t17:"Eine Email mit einem Aktivierungs-Link wurde an deine Adresse versandt.",t18:"Ein Account mit deinem Namen existiert bereits. Dennoch erstellen?",t19:"Einträge sind entweder unngültig oder zu kurz.",t20:"Der Server hat einen Fehler gemeldet. Bitte versuch es erneut.",t21:"Der Zugang wurde nicht gefunden.",t30a:"Als erledigt markieren.",t30b:"Als unerledigt markieren.",t55:"Ein Email mit einem Aktivierungs-Link wurde an Ihre Adresse versandt.",t56:"Ein Zugang für diesen Namen besteht bereits. Trotzdem erstellen?",t57:"Ein bestehender Zugang wurde für diese Serie registriert.",t60:"Bitte geben Sie Email-Adresse an, die Sie hier hinterlegt haben.",t61:"Ihr Passwort wurde erfolgreich versandt.",t62:"Die angegebene Email-Adresse stimmt nicht mit der hier hinterlegten überein.",ov:"Persönliche Übersicht"});var $v={}; /*! loadCSS. [c]2020 Filament Group, Inc. MIT License */ /*! onloadCSS. (onload callback for loadCSS) [c]2017 Filament Group, Inc. MIT License */ -function onloadCSS(t,e){e=e||{};let n=function(e){return new Promise(((n,i)=>{t.addEventListener?e.addEventListener("load",newcb):t.attachEvent&&e.attachEvent("onload",newcb),"isApplicationInstalled"in navigator&&"onloadcssdefined"in t&&e.onloadcssdefined(newcb)}))};if(Array.isArray(t)){let i=t.length;Promise.all(t.map(n)).then((function(t){var n=t.reduce(((t,e)=>t+(!0===e?1:0)));!async function(t){!0===t&&"function"==typeof e.success?e.success():!0===t&&"object"==typeof e.success&&e.success instanceof Promise&&await e.success(),e.complete()}(i===n)}))}else n(t)}!function(t){"use strict";var e=function(e,n,i,o){var r,s=t.document,a=s.createElement("link");if(n)r=n;else{var c=(s.body||s.getElementsByTagName("head")[0]).childNodes;r=c[c.length-1]}var l=s.styleSheets;if(o)for(var u in o)o.hasOwnProperty(u)&&a.setAttribute(u,o[u]);a.rel="stylesheet",a.href=e,a.media="only x",function t(e){if(s.body)return e();setTimeout((function(){t(e)}))}((function(){r.parentNode.insertBefore(a,n?r:r.nextSibling)}));var d=function(t){for(var e=a.href,n=l.length;n--;)if(l[n].href===e)return t();setTimeout((function(){d(t)}))};function h(){a.addEventListener&&a.removeEventListener("load",h),a.media=i||"all"}return a.addEventListener&&a.addEventListener("load",h),a.onloadcssdefined=d,d(h),a};"undefined"!=typeof exports?exports.loadCSS=e:t.loadCSS=e}("undefined"!=typeof global?global:this);const isIE=/MSIE\/|Trident/gi.test(window.navigator.userAgent)||void 0!==window.document.documentMode,isfileapi=!!(window.File&&window.FileReader&&window.FileList&&window.Blob);var $ocms={auth:{},no:function(t){t.stopPropagation()},vmin:function(t){var e=$(window).width*(t||1),n=$(window).height*(t||1);return e($ocms.baseurl+"/"+(t||"")).replace(/\/\//,"/"),cexi:null};function deepCopy(t){var e,n,i;if("object"!=typeof t||null===t)return t;for(i in e=Array.isArray(t)?[]:{},t)n=t[i],e[i]=deepCopy(n);return e}function fields_definition(t,e,n){this.label_sng=!0===Array.isArray(t)?"":t||"",this.label_pl=!0===Array.isArray(t)?"":e||"",this.fields=!0===Array.isArray(t)?t:n||[],this.itm=function(t){for(var e=0;e0)for(var n=0;nt||"")).filter(((t,e)=>""!==t)).join(e)}function parseDt(t,e,n){t=(t||"").substr(0,e.length);var i=e,o=t.length>0&&e.split(";").some((function(e){for(var n,o=/[^yMdhms0-9]/gi,r=!0;null!==(n=o.exec(e));)r=r&&e.substr(n.index,1)===t.substr(n.index,1);var s=t.length===e.length&&r;return!0===s&&(i=e),s}));if(!0===o){for(var r,s=[0,0,0,0,0,0,0],a=/(mm{1,2}|dd{1,2}|MM{1,2}|(yy){2,4}|ss{1,2}|hh{1,2})(?!\w)/g;null!==(r=a.exec(i));)s["yMdhms".indexOf(r[0].substr(0,1))]=parseInt(("yy"===r[0]?"20":"")+t.substr(r.index,r[0].length))-("M"===r[0].substr(0,1)?1:0);var c=new(Function.prototype.bind.apply(Date,[null].concat(s)));return"string"==typeof n?fdt(c,n):c}return!1}function bool(t,e){return"boolean"==typeof t?t:"boolean"==typeof e&&e}function booln(t,e){return"boolean"==typeof t?t:"number"==typeof t?1===t:"boolean"==typeof e&&e}Date.prototype.isValid=function(){return!isNaN(this)},Date.prototype.format=function(t){return fdt(this,t)},Date.prototype.addDays=function(t){return this.setDate(this.getDate()+t),this},Date.prototype.isBetween=function(t,e){return this>t&&this section");$(window).scroll((function(e){let n=$(window).scrollTop(),i=$("body");i.toggleClass("unfocus",n>vh()-1.2*t),i.toggleClass("btb",n>.5*vh()-t)}))},$ocms.cf_reset=function(){return $("#contentframe").empty()},function(t){t.fn.scrollTo=function(e){if(t(this).length>0){var n=t(this).offset().top||0;n>0&&t("html, body").animate({scrollTop:n-hh()},2e3)}},t.fn.ldng=function(e){var n=!0;return"boolean"==typeof e?n=e:"number"==typeof e&&(n=e>0),t(this).toggleClass("loading",n)},"function"!=typeof t.noop&&(t.noop=function(){}),t.fn.hasAttr=function(e){var n=t(this).attr(e);return void 0!==n&&!1!==n},t.fn.parseCssPx=function(e){try{return parseFloat(t(this).css(e).replace("px","")||0)}catch(t){return 0}},t.max=function(t,e){return isNaN(t)&&isNaN(e)?null:isNaN(t)&&!isNaN(e)?e:!isNaN(e)&&isNaN(e)||t>=e?t:e},t.min=function(t,e){return isNaN(t)&&isNaN(e)?null:isNaN(t)&&!isNaN(e)?e:!isNaN(e)&&isNaN(e)||t<=e?t:e},t.lim=function(t,e){return isNaN(t)?null:isNaN(e)?t:e<=t?e:t},t.fn.enterKey=function(e){return this.each((function(){t(this).keypress((function(t){"13"===(t.keyCode?t.keyCode:t.which).toString()&&e.call(this,t)}))}))}}(jQuery),$ocms.defaultTimeout=3e4,$ocms.AjaxEX=function(t){var e=this;e.responseText=e.responseText||"";var n=e.getResponseHeader("x-ocms-code")||"";e.internalCode=""!==n&&!1===isNaN(n)?parseInt(n):-1,e.isInternal=e.internalCode>-1,e.internalText=decodeURIComponent((e.getResponseHeader("x-ocms-desc")||"").replace(/\+/g,"%20")||"");var i=e.internalText||t,o=e.internalCode||e.status;e.logtext=i+" ("+o+")"},$ocms.postXTS=function(t){$ocms.postXT.call(this,$.extend(t,{sync:!0}))},$ocms.postXT=function(t){if((t=t||{}).trycount=t.trycount||0,""!==(t.url||"")){t.url=-1!==t.url.indexOf("&yy=")?t.url:t.url.indexOf("?")>-1?t.url+"&yy="+(new Date).getTime():t.url+"?yy="+(new Date).getTime();var e=t.context||this;switch(t.context=e,t.retryLimit=t.retryLimit||0,t.timeout=t.timeout||$ocms.defaultTimeout,t.timeout<100&&(t.timeout=1e3*t.timeout),t.data=t.data||{},t.contentType=t.contentType||"multipart/form-data; charset=UTF-8",t.islogin="boolean"==typeof t.islogin&&t.islogin,t.contentType){case"":case"json":t.contentType="application/json; charset=utf-8";break;case"form":t.contentType="application/x-www-form-urlencoded; charset=UTF-8";break;case"multi":t.contentType="multipart/form-data";break;case"text":t.contentType="text/plain; charset=UTF-8"}if(t.form instanceof jQuery?(t.data=t.form.serializeObject(),t.contentType="form-data"):t.lzw instanceof jQuery&&(t.data.lzw=$.ccLZW(t.lzw.serializeAnything(!0)).join(",")),"multipart/form-data"!==t.contentType.substr(0,19)&&"form-data"!==t.contentType.substr(0,9)||t.data instanceof FormData!=!1)t.data instanceof FormData&&(t.contentType=!1,t.processData=!1);else{t.contentType=!1;var n=new FormData;$.each(t.files||[],(function(t,e){n.append("upload_file",e)})),$.each(t.data||{},(function(t,e){n.append(t,e)})),t.data=n,t.processData=!1}var i={type:t.method||"post",url:t.url,data:t.data,processData:"boolean"!=typeof t.processData||t.processData,contentType:t.contentType,cache:t.cache||!1,timeout:t.timeout,beforeSend:function(n){$(t.loading).ldng(),$("body").addClass("ldng"),"function"==typeof t.beforesend&&t.beforesend.apply(e,[n])},success:function(n,i,o){"false"===n||"not authorized"===n?("function"==typeof t.error&&t.error.apply(e,[o,i,n]),"function"==typeof $.status&&$.status(i+" - "+n)):"function"==typeof t.success&&t.success.apply(e,[n,i,o])},error:function(n,i,o){if($ocms.AjaxEX.call(n,i),-1===t.url.indexOf("doc.ashx")||-1!==t.url.indexOf("ftest")){if(401===n.status&&111===n.internalCode&&!1===t.islogin&&"function"==typeof $ocms.login.dlg)$ocms.login.dlg({ajo:t});else if("timeout"===i||302===n.status)return t.tryCount++,t.tryCount<=t.retryLimit?void $ocms.postXT(t):void 0;"function"==typeof t.error?t.error.apply(e,[n,i,o]):"function"==typeof $ocms.failure?$ocms.failure.apply(e,[n]):"function"==typeof $.status&&$.status("Server error: "+i+" - "+o)}},dataType:t.datatype||"json",complete:function(n,i){"function"==typeof t.complete&&t.complete.apply(e,[n,i]),$(t.loading).ldng(0),$("body").removeClass("ldng");let o=$("body > .timer");if(o.length>0){let t=new Date(n.getResponseHeader("ocms_cec")||""),e=new Date(n.getResponseHeader("ocms_cex")||"");if(t.isValid()&&e.isValid()){let n=new Date,i=Math.abs(e-t);n.setMilliseconds(n.getMilliseconds()+i),o.data({cex:n,ctt:i}),$ocms.cex_timer()}}},context:e,async:!0};"boolean"==typeof t.sync&&(i.async=!1===t.sync),!0==("boolean"==typeof t.contentType&&!1===t.contentType)&&(i.contentType=!1),$.ajax(i)}},$ocms.cex_timer=function(){$ocms.cexi||($ocms.cexi=setInterval($ocms.cex_timer,15e3));let t=$("body > .timer"),e=t.data("cex"),n=t.data("ctt"),i=new Date;if(e instanceof Date&&e.isValid()&&"number"==typeof n&&n>0&&e>i){let o=Math.abs(i-e)/n*100;t.css("width",o.toString()+"%"),o<98&&(!$ocms.cex_lp||Math.abs(i-$ocms.cex_lp)>6e5)&&$ocms.postXT({url:$ocms.url("ping"),success:()=>{$ocms.cex_lp=i},timeout:5e3,error:()=>{}})}},$ocms.vbl_send=function(t){var e=t.data||{};if(""!==(e.url||"")){var n=$("#contentframe form:first"),i={url:e.url,data:new FormData,success:function(t){"function"==typeof e.success?e.success(t):"string"==typeof e.success&&alert(e.success)},error:function(t,n,i){"function"==typeof e.error?e.error(i):"string"==typeof e.error&&alert(e.error)},complete:function(){n.ldng(0)}},o=!0;n.find("input").each((function(){var t=$(this),e=t.nza("name"),n=t.val(),r=$(this).prop("required")||!1;if(""!==e){var s=""!==n||!1===r;o=o&&s,!0===s?(i.data.append(e,n),t[0].setCustomValidity("")):""!==$(this).nza("ocms-nvnote")&&t[0].setCustomValidity($(this).nza("ocms-nvnote"))}})),!0===o&&(n.ldng(1),$ocms.postXT.call(this,i))}},function(t){t.fn.nza=function(e,n){var i=t(this).attr(e);return void 0!==i&&!1!==i?i:n||""},t.fn.serializeObject=function(e,n){var i=/\r?\n/g,o=/^(?:submit|button|image|reset|file)$/i,r=/^(?:input|select|textarea|keygen)/i,s=/^(?:checkbox|radio)$/i,a=bool((n=n||{}).typedvalues,!1),c={},l=t(this),u=l.find(':input:not([nosend],[type="file"])').addBack(":input"),d=!0;return t.each(u.not(".tinymce").get(),(function(n,l){var u=t(this),h=this,p=(this.type||"").toLowerCase(),f=u.prop("required")||!1;if(!0===(h.name&&!u.is(":disabled")&&r.test(h.nodeName)&&!o.test(p))){var m=u.val(),g=h.name,y=u.nza("data-format").split(":"),v=u.nza("pattern")||".*";if(!0===s.test(p)&&(m=h.checked?""!==m?m:"true":""),"date"===y[0].substr(0,4)&&y.length>1)"boolean"==typeof(m=parseDt(m,y.slice(1).join(":")))&&(m=null),null===m&&"date"===u.prop("type").substr(0,4)&&!1===isNaN(new Date(u.val()))&&(m=new Date(u.val())),m instanceof Date==!0&&"function"==typeof m.getMonth?!1===a&&(m=fdt(m,"date"===y[0]?"dts":"iso")):m=null;else if("number"===p&&!0===a){let t;t="integer"===y[0]?parseInt(m):parseFloat(m),m=isNaN(t)?m:t}if(!0!==f||""!==(m||"")&&null!==m.match(v)?!0===bool(e,!1)&&h.setCustomValidity(""):(!0===bool(e,!1)&&h.setCustomValidity(u.nza("ocms-nvnote",$ocms.t.inv||"Invalid field")),m=null),null!=m&&"string"==typeof m){let t=c[g];null!=t?Array.isArray(t)?t.push(m.replace(i,"\r\n")):c[g]=[t,m.replace(i,"\r\n")]:c[g]=m.replace(i,"\r\n")}else if(null!=m){let t=c[g];null!=t?Array.isArray(t)?t.push(m):c[g]=[t,m]:c[g]=m}else d=!1}})),u.filter(".tinymce").each((function(e,n){var i=t(this),o=((this.type||"").toLowerCase(),i.prop("required")||!1);try{var r=tinymce.get(t(n).attr("id"));if(r){var s=t(n).attr("name"),a=r.getContent();!1===o||""!==(a||"")?c[s]=a:d=!1}}catch(e){t.noop()}})),l.toggleClass("invalid",!d),d?c:null},t.fn.sendForm=function(e,n,i){var o=t(this);i=i||{};var r={url:e,success:function(t){if(i.response=t,"function"==typeof n)n(t);o.closest("div.modal").remove()},error:function(t,e,n){"function"==typeof i.error?i.error.call(this,t):$ocms.failure.call(this,t)},complete:function(){o.ldng(0),"function"==typeof i.complete&&i.complete.call(this,jqXHR)}},s=o.find('input[type="file"]');r.data=new FormData,s.length>0&&t.each(s[0].files,(function(t,e){r.data.append(t,e),r.data.append("file_lastmodified",$ocms.isodt(e.lastModifiedDate))}));var a=o.serializeObject();t.each(a||{},(function(t,e){r.data.append(t,e)})),o.ldng(),$ocms.postXT.call(this,r)},t.fn.checkValidity=function(){var e=t(this),n=!0;return e.each((function(t,e){n=n&&e.checkValidity()})),n},t.fn.wrap=function(e,n){var i=t(this),o=$$.dc(e).attr(n||{}).insertAfter(i);return i.append(o),o}}(jQuery),$ocms.logout=function(){$ocms.postXT({url:$ocms.url("logout"),complete:function(){window.location.reload()}})},$ocms.login={send:function(t){t.preventDefault();var e=$(this);if(!0===e.find("#dbtn-confirm").hasClass("disabled"))return!1;var n=e.serializeObject();return n.loginaccount=ne(n.loginaccount,$ocms.auth.account||$ocms.auth.requestedaccount||""),n.loginaccount=ne(n.loginaccount,$ocms.auth.account||$ocms.auth.requestedaccount||""),""===ne(n.loginaccount)&&!0===bool($ocms.auth.accountrequired,!0)?(alert($t.l16),!1):($ocms.postXT({url:$ocms.url("login"),data:n,success:function(){window.location.reload()}}),!1)},uichange:function(){let t=$(this),e=t.closest("form"),n=bool($ocms.auth.accountrequired,!0),i=ne(e.find('[name="loginaccount"]').val(),$ocms.auth.account||$ocms.auth.requestedaccount||"");if(""!==i||!1===n){var o=e.find('[name="userlogin"]').empty().val(""),r=e.find('[name="username"]').empty().val(""),s=$("#dlg_userlogin_sel").empty().val(""),a=t.val()||"";if(!1===t.checkValidity()&&""===a)return;var c=t.closest("table").ldng();$ocms.postXT.call(this,{url:$ocms.url("auth"),data:{userinfo:a,account:i||""},success:function(t,e,n){if(1===t.length){var i=t[0];o.val(i.login).change().attr("required","").removeAttr("nosend"),r.val(i.name).change().attr("required","").show(),s.removeAttr("required").attr("nosend","").hide()}else t.length>0?(r.hide().removeAttr("required"),o.removeAttr("required").attr("nosend",""),0===s.length&&(s=$("").attr({name:"userlogin",size:t.length,id:"dlg_userlogin_sel",class:"form-control",required:""}).css({width:"100%","max-width":"100%",padding:"2px"}).insertAfter(r)),$.each(t,(function(t,e){var n=$("").attr({value:e.login,style:"padding-top: 2px; padding-bottom: 5px;","border-bottom":"1px solid #EEE;"}).text(e.name).appendTo(s);t%2==0&&n.css({"background-color":"#F9F9F9"})})),s.attr("required","").removeAttr("nosend")):(s.hide().attr("nosend",""),r.attr("required","").show(),o.attr("required","").removeAttr("nosend"),alert($t.l9))},error:function(t){$ocms.failure.call(this,t)},complete:function(){c.ldng(0)}})}else alert($t.l18)},sendpassword:function(t){var e=$(''),n=e.find(".form-body"),i=null;e.find("form").submit((function(t){t.preventDefault();var o=$(this).serializeObject(!0),r=null===i,s=r?"spwc":"spw";return $ocms.postXT.call(this,{url:$ocms.url(s),data:o,complete:function(){r?(n.append('
Ihnen wurde ein Code per SMS zugesandt.
Bitte tragen Sie den hier ein:
'),i=$('
').appendTo(n)):(alert($t.l13),e.remove())},error:()=>{}}),!1})),e.find(".modal-close").click((function(){e.remove()}));var o=[];$.each($t.l7a.split("\n"),((t,e)=>{Array.prototype.push.apply(o,[$("
"),$("").text(e)])})),e.find(".modal-note").append($('').text($t.alert)).append(o),e.appendTo("body"),setTimeout((function(){$(".modal").find('input[name="lastname"]').focus()}),600)}};var $$={s:function(t){return $("").text(t)},br:function(){return $("
")},sc:function(t,e){return $("").addClass(t).text(e)},td:function(t,e){var n=$("");return t instanceof jQuery==!0?n.appendTo(t):"object"==typeof t?n.attr(t):"string"==typeof t&&n.text(t),"object"==typeof e?n.attr(e):"string"==typeof e&&n.text(e),n},th:function(t,e){var n=$("");return t instanceof jQuery==!0?n.appendTo(t):"object"==typeof t?n.attr(t):"string"==typeof t&&n.text(t),"object"==typeof e?n.attr(e):"string"==typeof e&&n.text(e),n},tdc:function(t,e,n){return $$.td(e,n).addClass(t)},td2:function(t){var e=$('');return"string"===$.type(t)?e.text(t):t instanceof jQuery?e.append(t):"function"==typeof t?t.call(e):e.html(" "),e},td3:function(t){var e=$('');return"string"===$.type(t)?e.text(t):t instanceof jQuery?e.append(t):"function"==typeof t?t.call(e):e.html(" "),e},tdtr:function(t,e){var n=$$.tr().appendTo(e);return t instanceof jQuery==!0||"string"==typeof t?t.appendTo($$.td().appendTo(n)):!0===Array.isArray(t)&&$.each(t,(function(t,e){$(e).appendTo($$.td().appendTo(n))})),n},tr:function(t,e){var n=$("");return t instanceof jQuery==!0?n.appendTo(t):"object"==typeof t&&n.attr(t),"object"==typeof e&&n.attr(e),n},trc:function(t,e){var n=$("").addClass(t);return e instanceof jQuery==!0?n.appendTo(e):"object"==typeof e&&n.attr(e),n},d:function(t){return $("
").attr(t||{})},dc:function(t,e,n,i){var o=$("
").addClass(t);return e instanceof jQuery==!0?o.appendTo(e):"object"==typeof e?o.attr(e):"function"==typeof e?o.click(e):"string"==typeof e&&o.text(e),"string"==typeof n?o.text(n):"object"==typeof n?o.attr(n):"function"==typeof n&&o.click(n),"string"==typeof i?o.text(i):"object"==typeof i?o.attr(i):"function"==typeof i&&o.click(i),o},df:function(t){return $("
 
").attr(t||{})},opt:function(t,e,n){var i=$("");return"string"==typeof t?i.attr("value",t):"object"==typeof t&&i.attr(t),"string"==typeof e?i.text(e):"object"==typeof e&&i.attr(e),"object"==typeof n&&i.attr(n),i},eOpt:function(t){var e=$('');return t&&e.attr("selected","selected"),e},tbl:function(t){return $("
").attr(t||{})},tblc:function(t){return $("
").addClass(t)},thead:function(t){let e=$("");return t instanceof jQuery&&e.prependTo(t),e},tbody:function(t){let e=$("");return t instanceof jQuery&&e.appendTo(t),e},tblset:function(t,e){let n=$$.tbl(t||{});return e instanceof jQuery&&e.append(n),{tbl:n,hd:$$.thead().appendTo(n),bdy:$$.tbody().appendTo(n)}},i:function(t){return $("").attr(t||{})},img:function(t,e){return $("").attr("src",t).attr(e||{})},sel:function(t){return $("").attr(t||{})},btn:function(t){return $("").attr(t||{})},a:function(t){return $("").attr(t||{})},li:function(t){return $("
  • ").attr(t||{})},ul:function(t){return $("
      ").attr(t||{})},nav:function(t){return $("").attr(t||{})},lbl:function(t,e){var n=$("");return"string"==typeof t&&n.text(t),"object"==typeof t?n.attr(t):"object"==typeof e&&n.attr(e),n},txt:function(t){return $("").attr(t||{})},0:function(t,e){return $("<"+t+">").attr(e||{})},bbtn:function(t,e){return $$.btn({type:"button",class:"btn"}).addClass(e).text(t)},svg:t=>$(document.createElementNS("http://www.w3.org/2000/svg",t))};function getMonday(t){var e=(t=new Date(t)).getDay(),n=t.getDate()-e+(0==e?-6:1);return new Date(t.setDate(n))}function $lf(t){var e=void 0===t?null:"number"==typeof t&&1!==t||"boolean"==typeof cl&&!1===t;return $("#listframe").tC("hd",e).is(".hd")}function $nuf(t){if(t&&t.stopPropagation(),!$(this).is(".disabled")){var e=function(t){t.removeClass("vis").find("li.dropdown").removeClass("open").removeClass("vis").attr("aria-expanded","false")},n=$(this).parent("li.dropdown");if(n.length>0){n.tC("open"),navs=!0===n.is(".open")?"true":"false",n.attr("aria-expanded",navs);var i=n.closest("nav");i.find("li.dropdown").not(n.parentsUntil("nav")).not(n).removeClass("open").attr("aria-expanded","false"),!1===n.is(".open")&&n.find("li.dropdown").removeClass("open").attr("aria-expanded","false"),e($("nav").not(i))}else e($("nav"))}}function $tbr(){return $lf(0),$("#topbar").ocmsmenu([])}function $lfr(){return $("#sidebar").empty(),$("#listframe").removeClass("fix").addClass("hd").empty()}function $cfr(){return $tbr(),$("#contentframe").empty()}function jObj(t,e){let n={};if("{"===(t||"").substr(0,1))try{n=JSON.parse(t)}catch(t){n={}}return n[e]||""}function string(t,e){var n,i=t||"";return $.each(e||[],(function(t,e){n=new RegExp("\\{"+t.toString()+"\\}","ig"),i=i.replace(n,e)})),i}function init_tooltip(t){var e=!0===("boolean"==typeof t&&t)&&"mouse";$("[title]").qtip({position:{target:e,adjust:{x:2,y:2},viewport:!0},events:{hidden:$ocms.tooltip_hidden},effect:!1}),$("div.tooltiptext").each((function(){$(this).filter(":not(:empty)").parent().qtip({suppress:!1,content:{text:$(this).clone()},position:{target:e,adjust:{x:2,y:2},viewport:!0},events:{hidden:$ocms.tooltip_hidden}})}))}String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")},String.prototype.left=function(t){if("string"===$.type(t)){var e=this.indexOf(t);return e>0?this.slice(0,e):""}return this.substring(0,t)},String.prototype.right=function(t){if("string"===$.type(t)){var e=this.indexOf(t);return e>0?this.substring(this.length-e):""}return this.substring(this.length-t)},Array.prototype.move=function(t,e){if(e>=this.length)for(var n=e-this.length;1+n--;)this.push(void 0);return this.splice(e,0,this.splice(t,1)[0]),this},function(t){t.fn.appendToIf=function(e,n){var i=t(this),o="function"==typeof n?n(i):n;return!0===("boolean"!=typeof o||o)&&i.appendTo(e),i},t.fn.appendIf=function(e,n){var i=t(this),o="function"==typeof n?n(i):n;return!0===("boolean"!=typeof o||o)&&i.append(e),i},t.fn.rwText=function(e,n,i){var o=t(this).empty();i=t.extend({wrap:!0},i);var r=!0===Array.isArray(e)?e:(null==e?"":String(e)).split("\n");return t.each(r,(function(t,e){""!==(e||"")&&(t>0&&o.append($$.br()),o.append(!0===i.wrap?$$.s(e):e))})),n&&o.attr("title",n),o},t.fn.loadSel=function(e,n,i){if("SELECT"===t(this).prop("tagName").toUpperCase()){var o=t(this);$ocms.postXT.call(this,{url:e,data:n||{},success:function(e){t.each(e,(function(){o.append($$.opt(e.value,e.text))}))},complete:function(){o.ldng(0),"function"==typeof i&&i.call(o)}})}},t.fn.emptyWithEditors=function(e){var n=t(this);return n.find(":input.tinymce").each((function(e,n){try{var i=tinymce.get(t(n).attr("id"));i&&i.remove()}catch(e){t.noop()}})),n.empty()},t.fn.cssValue=function(t){if(this.length>0){var e=this.css(t)||"";if(""===e)return 0;var n=/(^[\d\.]*)(\D{1,3}$)/gi.exec(e);return null!==n?"rem"===n[2]?$ocms.rpx(parseFloat(n[1])):parseFloat(n[1]):!1===isNaN(e)?parseFloat(e):0}return 0},t.fn.veryInnerHeight=function(){let e=e=>t(this).cssValue(e);return t(this).innerHeight()-e("padding-top")-e("padding-bottom")},t.fn.veryInnerWidth=function(){let e=e=>t(this).cssValue(e);return t(this).innerWidth()-e("padding-left")-e("padding-right")},t.fn.marginWidth=function(){let e=e=>t(this).cssValue(e);return e("margin-left")+e("margin-right")},t.fn.marginHeight=function(){let e=e=>t(this).cssValue(e);return e("margin-top")+e("margin-bottom")},t.inArrayRegEx=function(e,n,i){var o="regexp"===t.type(e)?e:new RegExp(e);if(!n)return-1;for(var r=i=i||0;r7){i=e.split(","),o=(n||(t<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(",");var c=a(i[0].slice(4)),l=a(i[1]),u=a(i[2]);return"rgb("+(s((a(o[0].slice(4))-c)*r)+c)+","+(s((a(o[1])-l)*r)+l)+","+(s((a(o[2])-u)*r)+u)+")"}var d=(i=a(e.slice(1),16))>>16,h=i>>8&255,p=255&i;return"#"+(16777216+65536*(s((((o=a((n||(t<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(s(((o>>8&255)-h)*r)+h)+(s(((255&o)-p)*r)+p)).toString(16).slice(1)},t.fn.IN=function(e){return t(this).fadeIn(400,e),t(this)},t.fn.OUT=function(e){return t(this).fadeOut(400,e),t(this)},t.fn.tooltip=function(e,n){var i=!0===("boolean"==typeof e&&e)&&"mouse",o="boolean"==typeof n&&n,r=t(this);return r.each((function(){var e=o?t(this).find(".tooltiptext"):t(this).children(".tooltiptext");t(e).length>0?e.each((function(){var e=t(this);t(this).filter(":not(:empty)").parent().qtip({suppress:!1,content:{text:e.clone()},position:{target:i,adjust:{x:2,y:2},viewport:!0},events:{hidden:$ocms.tooltip_hidden},show:{effect:!1},hide:{effect:!1}}),e.remove()})):t(this).qtip({position:{target:i,adjust:{x:2,y:2},viewport:!0},events:{hidden:$ocms.tooltip_hidden},effect:!1})})),r},t.fn.rC=function(e){return t(this).removeClass(e)},t.fn.aC=function(e){return t(this).addClass(e)},t.fn.tC=function(e,n){return t(this).toggleClass(e,n)}}(jQuery),function(t){t.fn.ocmsmenu=function(e,n){var i=t(this);return $ocms.menu.call(i,e,n),i},t.fn.activatemenu=function(){var e=t(this).filter("nav");return e.find("a").not(".on").addClass("on").click($nuf),e.find(".nav-btn").not(".on").addClass("on").click((function(e){e.stopPropagation();var n=t(this);t(n.attr("data-target")).tC(n.attr("data-toggle"))})),e}}(jQuery);class ObjectArray extends Array{isEmpty(){return 0===this[0].length}static get[Symbol.species](){return Array}filter(t){return"function"==typeof t?new ObjectArray(this[0].filter(t)):this}remove(t){if("function"!=typeof t)return this;{let e=this[0].findIndex(t);for(;e>-1;)this[0].splice(e),e=this[0].findIndex(t)}}sortBy(t){return"function"==typeof t&&this[0].sort(t),this}sortString(t){return this[0].sort(((e,n)=>{let i=(e[t]||"").toString().toUpperCase(),o=(n[t]||"").toString().toUpperCase();return console.debug(i.localeCompare(o)),i.localeCompare(o)})),this}sortNum(t){return this[0].sort(((e,n)=>{let i=e[t],o=n[t];return!0===isNaN(o)&&!1===isNaN(i)||io?1:0})),this}sum(t){return this[0].reduce(((e,n)=>e+(!0===isNaN(n[t])?0:n[t])),0)}groupBy(t){return this[0].reduce((function(e,n){let i=n[t];return e[i]||(e[i]=[]),e[i].push(n),e}),{})}each(t){if("function"==typeof t){let e=!1;this[0].forEach(((n,i,o)=>{if(!1===e){let r=t(n,i,o);"boolean"==typeof r&&!1===r&&(e=!0)}}))}}get toArray(){return this[0]}}class NumArray extends Array{sum(){return this.reduce(((t,e)=>t+e))}first(){return this[0]}last(){return this[this.length-1]}average(){return this.sum()/this.length}range(){let t=this.map((t=>t)).sort();return{min:t[0],max:t[this.length-1]}}static get[Symbol.species](){return Array}}$ocms.ocmsmenu=[{lbl:"",id:"m_home",ico:"glyphicon glyphicon-home",fnc:"init:home"},{fnc:"separator"}],function(t){t.multline=function(t){let e=t.split("\n"),n=$$.d();return $.each(e,((t,e)=>{n.append($$.s(e))})),n.html()},t.tooltip_hidden=function(t,e){$(this).remove(),e.rendered=!1},t.isJSONDateString=function(t){return"string"==typeof t&&/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?)?$/.test(t)},t.failure=function(e){11110===(e.internalCode||-1)?t.login.dlg():alert($t.f1+"\n"+(e.internalText||""))},t.getScript=function(e,n){var i=[],o=[],r=function(t){return"string"==typeof t&&""!==(t||"")},s=function(t,e){!0===bool(e.condition,!0)&&(""!==(e.script||"")&&o.push({url:e.script,module:e.module||""}),!0===r(e.css||"")?i.push(e.css):!0===Array.isArray(e.css)&&Array.prototype.push.apply(i,e.css.filter(r)))};!0===r(e||"")?o.push(e):!0===Array.isArray(e)?$.each(e,s):"object"==typeof e&&""!==(e.script||"")&&s(0,e);let a=[];$.each(i,(function(t,e){""!==(e||"")&&a.push(loadCSS(e))}));let c=o.map((function(e,n){let i=e.url,r=e.module||"";if(""===r){let t=new Promise((function(t,e){try{!async function(){$.ajax({url:i,dataType:"script",success:function(){t(o)},error:function(){e(o)},timeout:3e4})}()}catch(t){console.debug(t.message+"%o",t)}}));return t}return t.loadmodule(r,i,e.alias)}));Promise.all(c).then(n)},t.loadmodule=function(e,n,i){let o=new Promise((function(o,r){!async function(){try{let s=(n.startsWith("/")||n.startsWith(".")?"":"/")+n;import(s).then((n=>{t[e]=n[i||"default"],o(e)})).catch((t=>{console.debug(t.message+"%o",t),r(e)}))}catch(t){console.debug(t.message+"%o",t)}}()}));return o},t.ocms_auth=function(e,n,i,o){!1===$.isPlainObject(t.auth.modules)&&(t.auth.modules={});var r=0;t.auth.modules[e+(i||"")]?((r=t.auth.modules[e+(i||"")])<2&&(i||"")===auth.guid&&(r=2),r>=(n||0)&&o(false)):t.postXT({url:t.url("auth"),data:{module:e,person_guid:i||""},success:function(s){r=s[e],t.auth.modules[e+(i||"")]=r,r<2&&(i||"")===t.auth.person_guid&&(r=2),r>=(n||0)&&o(false)},error:function(e){t.failure.call(this,e)}})},t.auth.locale="de",t.ocms_prepauth=function(e,n,i){t.postXT({url:t.url("auth"),data:{fn:"csv",modules:e,person_guid:n||""},success:function(e){t.ocms_regauth(e)},error:function(e){t.failure.call(this,e)},complete:function(){i()}})},t.ocms_regauth=function(t){$.each(t||{},(function(t,e){auth.modules[t]=parseInt(e)}))},t.init=function(e){var n="string"==typeof e?e:(e.data||{}).fn||"";""!==n&&("home"===n?($cfr(),$lfr(),$("#topbar").ocmsmenu([],!0),$("#activemodule").text($t.ov),t.ov.call($("#contentframe"))):($cfr(),$lfr(),$("#topbar").ocmsmenu([]),t.postXT({url:t.url(n+"/auth"),success:function(e){void 0===t[n]&&(t[n]={}),t[n].auth=e,e.manage>0&&t.getScript({module:n,script:["web/imdl",n,t.auth.locale||"de","js"].join("."),css:["web/imdl",n,"css"].join("."),condition:"function"!=typeof t[n].init2},(function(){t[n].init2()}))},error:function(){$("#contentframe").empty()}})))},t.menuarray=function(t){this.array=[],this.sep=function(){this.length>0&&"separator"!==this.array[array.length-1].fnc&&this.push({fnc:"separator"})},this.push=function(t){return void 0===t?null:(!0===Array.isArray(t)?Array.prototype.push.apply(this.array,t):"object"==typeof t&&this.array.push(t),t)},this.unshift=function(t){return void 0===t?null:(!0===Array.isArray(t)?Array.prototype.unshift.apply(this.array,t):"object"==typeof t&&this.array.unshift(t),t)},this.push(t)},t.menu=function(e,n){e=e||[];var i=$(this).removeClass("vis");if(!0===bool(n,!0)&&!1===i.is("#mainmenu")&&i.empty(),!1===bool(n,!1)&&i.is("#sidebar,#topbar")&&(e.unshift({id:"sbctrl",glyph:"glyphicon-th-list",aclass:"fbtn",fnc:function(){$lf()}}),$lf(0)),0===(e||[]).length)i.empty().addClass("hd");else{i.removeClass("hd");var o=!0===i.is("nav")?i:i.children("nav");1!==o.length&&(o=$("").tC("nv",i.is("#sidebar")).tC("ctxt",i.is("#topbar")).appendTo(i));var r,s=$$.ul().appendTo(o),a=function(t,e){var n=$(this).addClass("dropdown submenu");t.append($$.sc("caret dd")).addClass("dds dropdown-toggle").attr({"aria-expanded":"false"}),""!==(e.ico||"")&&t.prepend($$.sc("ico "+e.ico));var i=$$.ul({class:"dropdown-menu",role:"menu"}).appendTo(n);$.each(e.itm||[],(function(t,e){r.call(i,e)}))},c=function(t){$(this).tC("disabled","boolean"==typeof t.disabled?t.disabled:"string"==typeof t.disabled&&"subs"===t.disabled&&0===(t.itm||[]).length)};r=function(e){var n,i=$$.li({id:e.id}).attr(e.attr||{}).addClass(e.lclass).appendTo($(this)),o="string"==typeof e.fnc&&""!==e.fnc?e.fnc.split(":")[0]:"";""!==o&&"init"!==o?i.attr("role",o).appendIf($$.s(e.lbl),""!==ne(e.lbl)):(n=$$.a({class:"on",role:"button"}).addClass(e.aclass).appendTo(i).append($$.s(e.lbl)),c.call(n,e),(e.itm||[]).length>0&&a.call(i,n,e),n.click($nuf),"function"==typeof e.fnc?n.click(e.data||{},e.fnc):"init"===o&&n.click($.extend({},e.data||{},{fn:e.fnc.split(":")[1]}),t.init))},$.each(e,(function(e,n){var i,o=$$.li({id:n.id}).attr(n.attr||{}).addClass(n.lclass),a="string"==typeof n.fnc&&""!==n.fnc?n.fnc.split(":")[0]:"";if(""!==a&&"init"!==a)o.attr("role",a).appendIf($$.s(n.lbl),""!==ne(n.lbl));else{if(i=$$.a({class:"on",role:"button"}).addClass(n.aclass).appendTo(o),c.call(i,n),""!==(n.lbl||"")&&i.append($$.s(n.lbl)),""!==(n.ico||"")&&i.prepend($$.sc("ico "+n.ico)),""!==(n.glyph||"")&&i.prepend($$.sc("glyphicon "+n.glyph)),(n.itm||[]).length>0){o.addClass("dropdown"),i.append($$.sc("caret dd")).addClass("dds dropdown-toggle").attr({"aria-expanded":"false"});var l=$$.ul({class:"dropdown-menu",role:"menu"}).appendTo(o);$.each(n.itm||[],(function(t,e){r.call(l,e)}))}(n.sel||[]).length>0||(i.click($nuf),"function"==typeof n.fnc?i.click(n.data||{},n.fnc):"init"===a&&i.click($.extend({},n.data||{},{fn:n.fnc.split(":")[1]}),t.init))}o.appendTo(s)})),o.activatemenu()}},t.easytbl=(t,e)=>{e=e||{};let n=$$.tbl().addClass(e.class).css("border-collapse","collapse"),i=($$.tbody(n),!0===bool(e.frame,!1)?{padding:"5px",border:"1px solid #727272"}:{});if(!0===Array.isArray(e.header)){let t=$$.thead(n);$.each(e.header,((n,o)=>$$.th(t).css(e.cellcss||i).rwText(o)))}else if(!0===bool(e.header,!1)&&(t||[]).length>0){let o=$$.thead(n);$.each(Object.keys(t[0]),((t,n)=>$$.th(o).css(e.cellcss||i).rwText(n)))}return $.each(t||[],((t,o)=>{let r=$$.tr();$.each(o,((t,n)=>{n=n||"";let o=$$.td(r).css(e.cellcss||i);n instanceof jQuery?o.append(n):"string"==typeof n&&("<"===n.substring(0,1)?o.append(n):o.text(n))})),n.append(r)})),n},t.dlgtbl=(e,n,i)=>{i=i||{};let o=t.easytbl(e,i);t.dlg(o,$.extend({title:n},i))},t.dlg=function(t,n){n=n||{};let i=$("body > .modal").length>0,o=t=>typeof n[t],r=t=>"function"===o(t);if(!0===bool(n.exclusive,!0)&&!0===i)return void alert($t.dbldlg||"Es ist bereits ein Dialog geöffnet");let s=$$.dc("modal",$("body")),a=$$.dc("modal-dialog",s);!1===isNaN(n.zindex)?s.css("zIndex",n.zindex):!0===i&&s.css("zIndex",parseInt($("body > .modal:last").cssValue("zIndex"))+200),!1===isNaN(n.zindex_min)&&s.cssValue("zIndex")').appendTo(d)),""!==ne(n.title)&&(c=$$.dc("modal-header",d),$("

      ").text(n.title).appendTo(c));let p=$$.dc("modal-body",d),f=$$.dc("modal-footer",d);t instanceof jQuery==!0&&p.append(t);let m=function(t){t&&"function"==typeof t.stopPropagation&&t.stopPropagation(),a.removeClass("in"),!0===r("closing")&&n.closing.call(d),p.hide().emptyWithEditors(),s.remove(),!0===r("close")&&n.close.call(d)};if(d.find(":input[required]").length>0&&($$.dc("note_required",f).append($$.sc("ind_required","*")).append($$.s($t.t1||"Eingabe erforderlich")),$$.dc("note_invalid",f).append($$.s($t.t2||"Bitte überprüfen Sie Ihre Eingaben im Formular."))),!0===r("cancel")){$$.bbtn(n.cancelbutton||"Abbrechen","cancel").attr({type:"button",role:"cancel"}).appendTo(f).click((function(t){n.cancel.call(d,t);t.stopPropagation(),m()}))}if(!0===r("confirm")){let t=$$.bbtn(n.button||"OK","confirm").attr({type:!0===bool(n.form,!1)?"submit":"button",role:"confirm"}).appendTo(f);!0===h?(d.submit((function(t){try{n.confirm.call(d,t)}finally{t.preventDefault()}return!1})),d.on("modal_submit",(function(){n.confirm.call(d,e)}))):(t.click((function(t){n.confirm.call(d,t);t.stopPropagation()})),d.on("modal_submit",(function(){t.click()})))}else!0===h&&d.submit((function(t){return t.preventDefault(),!1}));return d.on("modal_close",(function(){m()})),l.click(m),!0===r("opening")&&n.opening.call(d),a.addClass("in"),ne(n.mode).indexOf("maxbody")>-1&&p.css("min-height",(u.height()-c.outerHeight()-f.outerHeight()).toString()+"px"),!0===r("open")&&n.open.call(d),{hd:c,bdy:p,ft:f,ct:u,dlg:a,c:d}},t.mform=function(e){let n=$$.dc("form-body"),i=Array.isArray(e)?e:e instanceof fields_definition?e.fields:[];return $.each(i||[],(function(e,i){let o=i.type||"";if("ignore"===o)return!0;let r=$$.dc("form-group",n),s=i.id||"dlg_"+(i.name||"")+("html"===i.type?"_"+(65536*(1+Math.random())||0).toString(16).substr(9):""),a=$$.lbl(i.label||i.name,{for:s}).appendTo($$.dc("form-itm",r)),c=$$.dc("form-itm",r),l=$$.i({id:s,name:i.name,placeholder:i.placeholder,type:i.type});switch(o){case"email":i.pattern=ne(i.pattern,"[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$");break;case"url":i.pattern=ne(i.pattern,"https?://.+");break;case"number":i.pattern=ne(i.pattern,"[-+]?[0-9]*[.,]?[0-9]*"),l.attr("step",i.precision||"any"),l.attr("data-format","float");break;case"integer":case"int":i.pattern=ne(i.pattern,"[-+]?[0-9]*"),l.attr("type","number"),l.attr("data-format","integer");break;case"date":if(""!==ne(i.pattern,$t.datepattern)&&(i.pattern=ne(i.pattern,"("+$t.datepattern+")|([0-9]{4}.(0[1-9]|1[012]).(0[1-9]|1[0-9]|2[0-9]|3[01]))")),""!==ne(i.placeholder,$t.dateplaceholder)&&l.attr("placeholder",ne(i.placeholder,$t.dateplaceholder)),"string"==typeof i.value){var u=i.value.substr(0,10);i.value="date"!==l.prop("type")?fdt(u+"T00:00:00",ne(i.dateformat,$t.dateformat)):u}l.attr("data-format","date:"+ne(i.dateformat,$t.dateformat)+";yyyy-MM-dd");break;case"datetime":l.attr("type","datetime-local"),""!==ne(i.pattern,$t.datetimepattern)&&(i.pattern=ne(i.pattern,"("+$t.datetimepattern+")|([0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])\\s([0-5][0-9]):([0-5][0-9]))")),""!==ne(i.placeholder,$t.datetimeplaceholder)&&l.attr("placeholder",ne(i.placeholder,$t.datetimeplaceholder)),"string"==typeof i.value&&"T"===i.value.substr(10,1)&&(i.value="datetime"!==l.prop("type").substr(0,8)?fdt(i.value,ne(i.datetimeformat,$t.datetimeformat)):i.value),l.attr("data-format","datetime:"+ne(i.datetimeformat,$t.datetimeformat)+";yyyy-MM-dd HH:mm:ss");break;case"hidden":r.addClass("hd");break;case"html":case"text":l=$$.txt({id:s,name:i.name,placeholder:i.placeholder,type:i.type}),l.tC("tinymce","html"===i.type);break;case"bool":case"boolean":i.url=[{value:"true",label:($t||{}).true||"Yes"},{value:"false",label:($t||{}).false||"No"}],"boolean"==typeof i.value&&(i.value=i.value?"true":"false");case"select":l=$$.sel({id:s,name:i.name,type:i.type}),!1===bool(i.required,!1)&&$$.eOpt().appendTo(l);try{var d=function(t){!0===Array.isArray(t)&&$.each(t,(function(t,e){"string"==typeof e?$$.opt(e,e).appendTo(l):!0===Array.isArray(e)?$$.opt(e[0],e[1]).appendTo(l):"object"==typeof e&&$$.opt(e.value,e.label||e.text).appendTo(l)}))};!0===Array.isArray(i.url)?d(i.url):"function"==typeof i.url?i.url.call(l):"string"==typeof i.url&&t.postXT({url:i.url,success:d})}catch(t){$.noop()}break;default:""!==ne(i["max-length"])&&l.attr("max-length",i["max-length"])}""!==ne(i.pattern)&&l.attr("pattern",i.pattern),l.val(i.value).change(),l.change((function(){$(this)[0].setCustomValidity("")})),l.addClass("form-control").prop("required",bool(i.required,!1)).prop("readonly",bool(i.readonly,!1)).appendTo(c),!0===bool(i.required,!1)&&a.append($$.sc("ind_required","*")),"object"==typeof i.attr&&l.attr(i.attr),"object"==typeof i.prop&&l.prop(i.prop),"string"==typeof i.class&&l.addClass(i.class),"function"==typeof i.change&&(l.change(i.change),!0===bool(i.applychange,!1)&&void 0!==i.value&&l.change()),""!==(i.note||"")&&$$.dc("form-note",c).rwText(i.note),"function"==typeof i.complete&&i.complete.call(l)})),n},t.initMCE=function(t,e){t=$(t),e=e||{};try{let n={target:t[0],inline:!1,width:e.width||"100%",statusbar:!1,document_base_url:window.location.origin+"/",content_style:"ph:before {content: '«'; color: #BBB; font-style:italic; } ph:after {content: '»'; color: #BBB; font-style:italic; } ph { color: #AAA; font-style:italic; }",relative_urls:!1,remove_script_host:!1};!0===bool(e.hidemenu,!1)&&(n.menubar=!1,n.menu={}),!0===bool(e.hidetoolbar,!1)&&(n.toolbar=!1),$.extend(n,e||{}),tinymce.init(n)}catch(t){alert(t.message)}},t.dlgform=function(e,n){n=n||{};let i,o=$$.dc("frm").append(t.mform(e||[]).addClass("stacked"));n.addcontent instanceof jQuery&&o.append(n.addcontent),"function"==typeof n.submit?i=n.submit:"function"==typeof n.success&&(i=function(e){var i=$(this).ldng(1),o=$.extend({loginaccount:t.auth.account||""},i.serializeObject(bool(n.checkvalidity,!0),{typedvalues:bool(n.typedvalues,!1)}));""!==(n.url||"")?t.postXT({url:n.url,data:o,success:function(t){n.success.call(this,t),i.trigger("modal_close")},error:function(){alert($t.l17)},complete:function(){i.ldng(0)},timeout:6e4}):(n.success.call(this,o),i.trigger("modal_close"))});let r={form:!0,title:n.title||"",button:n.button||$t.submit,confirm:i,size:n.size||[500,600],open:function(){let e=$(this).find(".tinymce");e.length>0&&t.initMCE(e,n.tinymce||{})}};return t.dlg.call(this,o,r)},t.login.dlg=function(e){e=e||{};let n=[{name:"userinfo",label:$t.l1,type:"string",value:t.auth.login,change:t.login.uichange,required:!0},{name:"userlogin",type:"hidden",required:!0,value:t.auth.login},{name:"username",type:"string",label:$t.l4,required:!0,readonly:!0,placeholder:$t.l5,value:t.auth.fullname_rev},{name:"userpass",type:"password",label:$t.l3,required:!0,placeholder:$t.l3}];""===(t.auth.account||"")&&n.unshift({id:"dlg_loginaccount",name:"loginaccount",type:"string",required:!0,value:t.auth.account});let i=$$.dc("frm").append(t.mform(n).addClass("stacked")),o=t.dlg.call(this,i,{form:!0,title:$t.l0,button:$t.submit,confirm:function(n){var i=$(this).ldng(1),o=$.extend({loginaccount:t.auth.account||""},i.serializeObject());t.postXT({url:"/vt/login",data:o,success:function(n){""!==((n||{}).login||"")&&(i.trigger("modal_close"),t.auth=n,"object"==typeof e.ajo&&(e.ajo.islogin,$.ajax(e.ajo)))},error:function(){alert($t.l17)},complete:function(){i.ldng(0)},timeout:6e4})},size:[500,600]}),r=$$.dc("modal-content").css("height","auto").attr("novalidate","true").append($$.dc("modal-header").appendIf($("

      ").text(t.auth.accountname),""!==(t.auth.accountname||"")).append($("

      Vereinsmanager

      ")));o.dlg.prepend(r)},t.addNoEntryInfo=function(t){$(this).append($$.dc("noentryinfo").text(t||$t.t11))}}($ocms),Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(t){var e=this;do{if(Element.prototype.matches.call(e,t))return e;e=e.parentElement||e.parentNode}while(null!==e&&1===e.nodeType);return null}),function(t,e){var n,i;"object"==typeof window&&(window[t]=(n=function(t){var e=window,n=document.body,i=document.documentElement,o=Math.max(0,e.pageXOffset||i.scrollLeft||n.scrollLeft||0)-(i.clientLeft||0),r=Math.max(0,e.pageYOffset||i.scrollTop||n.scrollTop||0)-(i.clientTop||0);return{x:t?Math.max(0,t.pageX||t.clientX||0)-o:0,y:t?Math.max(0,t.pageY||t.clientY||0)-r:0}},(i=function(t,e){t&&t instanceof Element&&(this._container=t,this._options=e||{},this._clickItem=null,this._dragItem=null,this._showDragItem="boolean"!=typeof this._options.dragItem||!1!==this._options.dragItem,this._hovItem=null,this._sortLists=[],this._click={},this._dragging=!1,this._dragHandleClass=this._options.dragHandleClass||"",this._parentident=this._options.parentident||"",this._swapdone="function"==typeof this._options.swapdone?this._options._swapdone:null,this._container.setAttribute("data-is-sortable",1),this._container.classList.add("sortable"),this._container.style.position="static",window.addEventListener("mousedown",this._onPress.bind(this),!0),window.addEventListener("touchstart",this._onPress.bind(this),!0),window.addEventListener("mouseup",this._onRelease.bind(this),!0),window.addEventListener("touchend",this._onRelease.bind(this),!0),window.addEventListener("mousemove",this._onMove.bind(this),!0),window.addEventListener("touchmove",this._onMove.bind(this),!0))}).prototype={constructor:i,toArray:function(t){t=t||"id";for(var e=[],n="",i=0;ii.left&&ei.top&&n-1)&&e.className.indexOf("nosort")<0)&&(t.preventDefault(),this._dragging=!0,this._click=n(t),this._makeDragItem(e),this._onMove(t),!0)}t&&!1===e.call(this,t.target)&&""!==this._parentident&&t.target.closest(this._parentident)&&e.call(this,t.target.closest(this._parentident))},_onRelease:function(t){this._dragging=!1,this._trashDragItem()},_onMove:function(t){if(this._dragItem&&this._dragging){t.preventDefault();var e=n(t),i=this._container;!0===this._showDragItem&&this._moveItem(this._dragItem,e.x-this._click.x,e.y-this._click.y);for(var o=0;o0?a.mousedown(c).addClass("dctrl"):s.mousedown(c).addClass("dctrl"),t(this)}}(jQuery),$(document).ready((function(){$("html").click((function(t){$nuf()})),$("#listframe").click((function(t){t.stopPropagation(),$nuf()})),$("#mainmenu").ocmsmenu($ocms.ocmsmenu),$("#mainmenu").activatemenu()})),$.extend($t,{m_inv:"Rechnungen",m_req:"Aufträge",m_rep:"Berichte",m_todo:"ToDos",m_bcd:"BankBuchungen",rsp:"Passwort ändern",pnm:"Die Passwörter stimmen nicht überein",cps:"Das neue Passwort wurde gespeichert.",pwr:"Bitte wählen Sie ein starkes Passwort (min 8 Zeichen, davon jeweils min 2 Zahlen, kleine und große Buchstaben, Sonderzeichen sind optional).",smsc:"Sie beötigen für diese Funktion einen SMS-Code.\nSoll dieser nun versandt werden?",wdc:"Doppelt klicken, um die Box zu aktualisieren.",wdg:{}}),$t.rspf={sms:"Der SMS-Code konnte nicht bestätigt werden",valid:"Das alte Passwort ist nicht korrekt",requirements:"Das Passwort entspricht nicht den Anforderungen.\n"+$t.pwr},$fd={rsp:new fields_definition("","",[{name:"opw",label:"aktuelles Passwort",type:"password",required:!0,attr:{"auto-complete":"current-password"}},{name:"npw",label:"neues Passwort",type:"password",required:!0,pattern:"(.{6,})",attr:{"auto-complete":"new-password"}},{name:"npwc",label:"neues Passwort (Bestätigung)",type:"password",required:!0,attr:{"auto-complete":"new-password"},note:$t.pwr},{name:"code",label:"SMS-Code",type:"string",required:!0,attr:{"auto-complete":"one-time-code"}}])},$ocms.init=function(t){var e="string"==typeof t?t:(t.data||{}).fn||"";""!==e&&("home"===e?($cfr(),$lfr(),$("#topbar").ocmsmenu([],!0),$("#activemodule").text($t.ov),$fis.ov()):($cfr(),$lfr(),$("#topbar").ocmsmenu([]),$ocms.postXT({url:$ocms.url(e+"/auth"),success:function(t){void 0===$ocms[e]&&($ocms[e]={}),$ocms[e].auth=t,t.manage>0&&$ocms.getScript({module:e,script:["/web/fis",e,$ocms.auth.locale||"de","js"].join("."),css:["/web/fis",e,"css"].join("."),condition:"function"!=typeof $ocms[e].init2},(function(){$ocms[e].init2()}))},error:function(){$("#contentframe").empty()}})))};var $fis={auth:{},db:function(){$("#mainmenu_activemodule").text($t.ov);let t=$(this).empty(),e=$$.d({id:"dashboard_frame"}).appendTo(t);$ocms.postXT({url:$ocms.url("wdg/my"),success:function(t){$.each(t,(function(t,n){var i=$$.dc("wdg_frame",e,{"data-wdg":n}).ldng(1);$ocms.wdg.call(i,{wdg:n})}))},loading:e})},ValidateEmail:function(t){return!!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(t)},cf:t=>{let e=$("#contentframe");return!0===bool(t,!1)&&e.empty().rC("hd"),e},lf:t=>{let e=$("#listframe");return!0===bool(t,!1)&&e.empty().aC("hd").rC("fix"),e},frm_edit:function(t){let e=$fis.cf(!1),n=e.children(".cfrm"),i=e.children(".edit_frm");return n.length<1?n=$$.dc("cfrm hd").prependTo(e):!0===bool(t,!1)&&n.empty(),i.length<1&&(i=$$.dc("edit_frm").insertAfter(n)),i.empty()},frm_list:function(t,e){let n=$fis.cf(!1),i=n.children(".cfrm"),o=n.children(".list_frm");return i.length<1?i=$$.dc("cfrm hd").prependTo(n):!0===bool(t,!1)&&i.empty(),!0===bool(e,!1)&&n.children(".edit_frm").remove(),o.length<1&&(o=$$.dc("list_frm").appendTo(n)),o.empty()},lfm:()=>{let t=$fis.lf(!1),e=t.children(".lfrm");return e.length<1&&(e=$$.dc("lfrm").prependTo(t)),e},getAuth:(t,e)=>new Promise(((n,i)=>{$fis.auth[t]&&!1===bool(e,!1)?n($fis.auth[t]||-1):$ocms.postXT({url:$ocms.url("auth"),data:{module:t},success:e=>{$fis.auth[t]=e.auth||-1,n($fis.auth[t]||-1)},error:()=>{i()}})})),prepAuth:t=>new Promise(((e,n)=>{$ocms.postXT({url:$ocms.url("auth"),data:{module:t,array:1},success:t=>{$.extend($fis.auth,t||{})},complete:()=>{e()}})})),isAuth:(t,e)=>($fis.auth[t]||-1)>=(e||1),resetPass:function(t,e){confirm($t.smsc)&&($ocms.postXT({url:$ocms.url("account/sms"),data:{fn:"pwc"}}),$ocms.dlgform($fd.rsp.clone(),{title:$t.rsp||"",submit:function(t){var e=$(this).ldng(1),n=$.extend({loginaccount:$ocms.auth.account||""},e.serializeObject(!0,{typedvalues:!0}));(n.npw||"")!==(n.npwc||"")?e.find('input[name="npw"]:first')[0].setCustomValidity($t.pnm):$ocms.postXT({url:$ocms.url("account/changepassword"),data:n,success:function(t){alert($t.cps),e.trigger("modal_close")},error:function(t){alert($t.rspf[t.getResponseHeader("x-ocms-std")])},complete:function(){e.ldng(0)},timeout:6e4})}}))},wdg:function(t){let e=$(this).empty();$ocms.postXT({url:$ocms.url("wdg/one"),data:{short_name:t.wdg},timeout:9e4,success:function(n,i,o){let r=t.wdg,s=n[r];if(!s)return void e.ldng(0);let a=$.inArrayRegEx("dblwidth",s.rendering_options)>-1,c=$.inArrayRegEx("tiny",s.rendering_options)>-1;e.toggleClass("dbl",a&&!c).toggleClass("tny",c);$$.dc("wdg_hd",e,{title:ne(s.description,$t.wdc)}).toggleClass("dbl",a).text(ne(s.name,t.wdg)).dblclick((function(t){t.stopPropagation(),$fis.wdg.call(e,{wdg:r})}));let l=$$.dc("wdg_cnt",e).toggleClass("dbl",a).hide(),u=$.inArrayRegEx("bgcolor",s.rendering_options);switch(u>-1&&l.css("backgroundColor",s.rendering_options[u].toString().right(":")),s.type){case"table":var d=$$.tblset({},l),h=$$.tr().appendTo(d.hd),p=$t.wdg[r.indexOf("wdg_ev_")>=0?"wdg_ev_":r]||{};$.each(s.columns,(function(t,e){var n=p[e]?p[e].label:e;$$.th().text(n).appendTo(h)})),$.each(s.data,(function(t,e){var n=$$.tr().appendTo(d.bdy);$.each(s.columns,(function(t,i){var o=$$.td().appendTo(n);e[i]instanceof Date||!0===$ocms.isJSONDateString(e[i])?o.text(fdt(e[i],$t.dateformat)):o.rwText(e[i])}))})),$.inArray("firstrow_bold",s.rendering_options)>-1&&h.nextAll("tr:first").css("font-weight","bold");break;case"ind":$$.dc("ind",l).addClass("sts_"+(s.data.status||"")).append([$$.dc("ind").text(s.data.value),$$.lbl(s.data.label)]);break;case"image_url":l.css("background","url('"+s.url+"') no-repeat center center transparent");break;case"image_base64":l.css("background","url('data:image/png;base64,"+s.image+"') no-repeat center center transparent");break;case"html":if(l.html(s.html),$.inArray("reload_10min",s.rendering_options)>-1){var f=l.find("iframe");setTimeout((function(){f.attr("src",(function(t,e){return e}))}),6e5)}}$.inArray("reload_30min",s.rendering_options)>-1&&"html"!==s.type&&setTimeout((function(){$fis.wdg.call(e,{wdg:r})}),18e5),l.slideDown(150)},error:function(t){e.slideUp(150),$fis.failure.call(this,t)},complete:function(){e.ldng(0)}})},ov:function(){$fis.lf(!0);let t=$("#contentframe").empty(),e=$$.d({id:"dashboard_frame"}).appendTo(t);$ocms.postXT({url:$ocms.url("wdg/my"),success:function(t){$.each(t,(function(t,n){var i=$$.dc("wdg_frame",e,{"data-wdg":n}).ldng(1);$fis.wdg.call(i,{wdg:n})}))},loading:e})}};$fis.notifications={connection:null,init:function(){"undefined"!=typeof signalR&&null===this.connection&&$ocms.auth.useraccount_id&&(this.ensureFrame(),this.connection=(new signalR.HubConnectionBuilder).withUrl("/notifications").withAutomaticReconnect().build(),this.connection.on("notification",(t=>{this.push(t)})),this.connection.onclose((()=>{console.warn("Notification connection closed; retrying in 5s."),this.connection=null,setTimeout((()=>this.init()),5e3)})),this.start())},start:function(){this.connection.start().catch((t=>{console.warn("Notification connection failed to start; retrying in 5s.",t),this.connection=null,setTimeout((()=>this.init()),5e3)}))},ensureFrame:function(){$("#notification_frame").length<1&&$("
      ",{id:"notification_frame"}).appendTo($("footer:first").length?"footer:first":"body")},push:function(t){this.ensureFrame(),t=t||{};let e=$("
      ",{class:"notification_item"}).addClass((t.severity||"info").toLowerCase()).append($("
      '),n=e.find(".form-body"),i=null;e.find("form").submit((function(t){t.preventDefault();var o=$(this).serializeObject(!0),r=null===i,s=r?"spwc":"spw";return $ocms.postXT.call(this,{url:$ocms.url(s),data:o,complete:function(){r?(n.append('
      Ihnen wurde ein Code per SMS zugesandt.
      Bitte tragen Sie den hier ein:
      '),i=$('
      ').appendTo(n)):(alert($t.l13),e.remove())},error:()=>{}}),!1})),e.find(".modal-close").click((function(){e.remove()}));var o=[];$.each($t.l7a.split("\n"),((t,e)=>{Array.prototype.push.apply(o,[$("
      "),$("").text(e)])})),e.find(".modal-note").append($('').text($t.alert)).append(o),e.appendTo("body"),setTimeout((function(){$(".modal").find('input[name="lastname"]').focus()}),600)}};var $$={s:function(t){return $("").text(t)},br:function(){return $("
      ")},sc:function(t,e){return $("").addClass(t).text(e)},td:function(t,e){var n=$("");return t instanceof jQuery==!0?n.appendTo(t):"object"==typeof t?n.attr(t):"string"==typeof t&&n.text(t),"object"==typeof e?n.attr(e):"string"==typeof e&&n.text(e),n},th:function(t,e){var n=$("");return t instanceof jQuery==!0?n.appendTo(t):"object"==typeof t?n.attr(t):"string"==typeof t&&n.text(t),"object"==typeof e?n.attr(e):"string"==typeof e&&n.text(e),n},tdc:function(t,e,n){return $$.td(e,n).addClass(t)},td2:function(t){var e=$('');return"string"===$.type(t)?e.text(t):t instanceof jQuery?e.append(t):"function"==typeof t?t.call(e):e.html(" "),e},td3:function(t){var e=$('');return"string"===$.type(t)?e.text(t):t instanceof jQuery?e.append(t):"function"==typeof t?t.call(e):e.html(" "),e},tdtr:function(t,e){var n=$$.tr().appendTo(e);return t instanceof jQuery==!0||"string"==typeof t?t.appendTo($$.td().appendTo(n)):!0===Array.isArray(t)&&$.each(t,(function(t,e){$(e).appendTo($$.td().appendTo(n))})),n},tr:function(t,e){var n=$("");return t instanceof jQuery==!0?n.appendTo(t):"object"==typeof t&&n.attr(t),"object"==typeof e&&n.attr(e),n},trc:function(t,e){var n=$("").addClass(t);return e instanceof jQuery==!0?n.appendTo(e):"object"==typeof e&&n.attr(e),n},d:function(t){return $("
      ").attr(t||{})},dc:function(t,e,n,i){var o=$("
      ").addClass(t);return e instanceof jQuery==!0?o.appendTo(e):"object"==typeof e?o.attr(e):"function"==typeof e?o.click(e):"string"==typeof e&&o.text(e),"string"==typeof n?o.text(n):"object"==typeof n?o.attr(n):"function"==typeof n&&o.click(n),"string"==typeof i?o.text(i):"object"==typeof i?o.attr(i):"function"==typeof i&&o.click(i),o},df:function(t){return $("
       
      ").attr(t||{})},opt:function(t,e,n){var i=$("");return"string"==typeof t?i.attr("value",t):"object"==typeof t&&i.attr(t),"string"==typeof e?i.text(e):"object"==typeof e&&i.attr(e),"object"==typeof n&&i.attr(n),i},eOpt:function(t){var e=$('');return t&&e.attr("selected","selected"),e},tbl:function(t){return $("
      ").attr(t||{})},tblc:function(t){return $("
      ").addClass(t)},thead:function(t){let e=$("");return t instanceof jQuery&&e.prependTo(t),e},tbody:function(t){let e=$("");return t instanceof jQuery&&e.appendTo(t),e},tblset:function(t,e){let n=$$.tbl(t||{});return e instanceof jQuery&&e.append(n),{tbl:n,hd:$$.thead().appendTo(n),bdy:$$.tbody().appendTo(n)}},i:function(t){return $("").attr(t||{})},img:function(t,e){return $("").attr("src",t).attr(e||{})},sel:function(t){return $("").attr(t||{})},btn:function(t){return $("").attr(t||{})},a:function(t){return $("").attr(t||{})},li:function(t){return $("
    • ").attr(t||{})},ul:function(t){return $("
        ").attr(t||{})},nav:function(t){return $("").attr(t||{})},lbl:function(t,e){var n=$("");return"string"==typeof t&&n.text(t),"object"==typeof t?n.attr(t):"object"==typeof e&&n.attr(e),n},txt:function(t){return $("").attr(t||{})},0:function(t,e){return $("<"+t+">").attr(e||{})},bbtn:function(t,e){return $$.btn({type:"button",class:"btn"}).addClass(e).text(t)},svg:t=>$(document.createElementNS("http://www.w3.org/2000/svg",t))};function getMonday(t){var e=(t=new Date(t)).getDay(),n=t.getDate()-e+(0==e?-6:1);return new Date(t.setDate(n))}function $lf(t){var e=void 0===t?null:"number"==typeof t&&1!==t||"boolean"==typeof cl&&!1===t;return $("#listframe").tC("hd",e).is(".hd")}function $nuf(t){if(t&&t.stopPropagation(),!$(this).is(".disabled")){var e=function(t){t.removeClass("vis").find("li.dropdown").removeClass("open").removeClass("vis").attr("aria-expanded","false")},n=$(this).parent("li.dropdown");if(n.length>0){n.tC("open"),navs=!0===n.is(".open")?"true":"false",n.attr("aria-expanded",navs);var i=n.closest("nav");i.find("li.dropdown").not(n.parentsUntil("nav")).not(n).removeClass("open").attr("aria-expanded","false"),!1===n.is(".open")&&n.find("li.dropdown").removeClass("open").attr("aria-expanded","false"),e($("nav").not(i))}else e($("nav"))}}function $tbr(){return $lf(0),$("#topbar").ocmsmenu([])}function $lfr(){return $("#sidebar").empty(),$("#listframe").removeClass("fix").addClass("hd").empty()}function $cfr(){return $tbr(),$("#contentframe").empty()}function jObj(t,e){let n={};if("{"===(t||"").substr(0,1))try{n=JSON.parse(t)}catch(t){n={}}return n[e]||""}function string(t,e){var n,i=t||"";return $.each(e||[],(function(t,e){n=new RegExp("\\{"+t.toString()+"\\}","ig"),i=i.replace(n,e)})),i}function init_tooltip(t){var e=!0===("boolean"==typeof t&&t)&&"mouse";$("[title]").qtip({position:{target:e,adjust:{x:2,y:2},viewport:!0},events:{hidden:$ocms.tooltip_hidden},effect:!1}),$("div.tooltiptext").each((function(){$(this).filter(":not(:empty)").parent().qtip({suppress:!1,content:{text:$(this).clone()},position:{target:e,adjust:{x:2,y:2},viewport:!0},events:{hidden:$ocms.tooltip_hidden}})}))}String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")},String.prototype.left=function(t){if("string"===$.type(t)){var e=this.indexOf(t);return e>0?this.slice(0,e):""}return this.substring(0,t)},String.prototype.right=function(t){if("string"===$.type(t)){var e=this.indexOf(t);return e>0?this.substring(this.length-e):""}return this.substring(this.length-t)},Array.prototype.move=function(t,e){if(e>=this.length)for(var n=e-this.length;1+n--;)this.push(void 0);return this.splice(e,0,this.splice(t,1)[0]),this},function(t){t.fn.appendToIf=function(e,n){var i=t(this),o="function"==typeof n?n(i):n;return!0===("boolean"!=typeof o||o)&&i.appendTo(e),i},t.fn.appendIf=function(e,n){var i=t(this),o="function"==typeof n?n(i):n;return!0===("boolean"!=typeof o||o)&&i.append(e),i},t.fn.rwText=function(e,n,i){var o=t(this).empty();i=t.extend({wrap:!0},i);var r=!0===Array.isArray(e)?e:(null==e?"":String(e)).split("\n");return t.each(r,(function(t,e){""!==(e||"")&&(t>0&&o.append($$.br()),o.append(!0===i.wrap?$$.s(e):e))})),n&&o.attr("title",n),o},t.fn.loadSel=function(e,n,i){if("SELECT"===t(this).prop("tagName").toUpperCase()){var o=t(this);$ocms.postXT.call(this,{url:e,data:n||{},success:function(e){t.each(e,(function(){o.append($$.opt(e.value,e.text))}))},complete:function(){o.ldng(0),"function"==typeof i&&i.call(o)}})}},t.fn.emptyWithEditors=function(e){var n=t(this);return n.find(":input.tinymce").each((function(e,n){try{var i=tinymce.get(t(n).attr("id"));i&&i.remove()}catch(e){t.noop()}})),n.empty()},t.fn.cssValue=function(t){if(this.length>0){var e=this.css(t)||"";if(""===e)return 0;var n=/(^[\d\.]*)(\D{1,3}$)/gi.exec(e);return null!==n?"rem"===n[2]?$ocms.rpx(parseFloat(n[1])):parseFloat(n[1]):!1===isNaN(e)?parseFloat(e):0}return 0},t.fn.veryInnerHeight=function(){let e=e=>t(this).cssValue(e);return t(this).innerHeight()-e("padding-top")-e("padding-bottom")},t.fn.veryInnerWidth=function(){let e=e=>t(this).cssValue(e);return t(this).innerWidth()-e("padding-left")-e("padding-right")},t.fn.marginWidth=function(){let e=e=>t(this).cssValue(e);return e("margin-left")+e("margin-right")},t.fn.marginHeight=function(){let e=e=>t(this).cssValue(e);return e("margin-top")+e("margin-bottom")},t.inArrayRegEx=function(e,n,i){var o="regexp"===t.type(e)?e:new RegExp(e);if(!n)return-1;for(var r=i=i||0;r7){i=e.split(","),o=(n||(t<0?"rgb(0,0,0)":"rgb(255,255,255)")).split(",");var c=a(i[0].slice(4)),l=a(i[1]),u=a(i[2]);return"rgb("+(s((a(o[0].slice(4))-c)*r)+c)+","+(s((a(o[1])-l)*r)+l)+","+(s((a(o[2])-u)*r)+u)+")"}var d=(i=a(e.slice(1),16))>>16,h=i>>8&255,p=255&i;return"#"+(16777216+65536*(s((((o=a((n||(t<0?"#000000":"#FFFFFF")).slice(1),16))>>16)-d)*r)+d)+256*(s(((o>>8&255)-h)*r)+h)+(s(((255&o)-p)*r)+p)).toString(16).slice(1)},t.fn.IN=function(e){return t(this).fadeIn(400,e),t(this)},t.fn.OUT=function(e){return t(this).fadeOut(400,e),t(this)},t.fn.tooltip=function(e,n){var i=!0===("boolean"==typeof e&&e)&&"mouse",o="boolean"==typeof n&&n,r=t(this);return r.each((function(){var e=o?t(this).find(".tooltiptext"):t(this).children(".tooltiptext");t(e).length>0?e.each((function(){var e=t(this);t(this).filter(":not(:empty)").parent().qtip({suppress:!1,content:{text:e.clone()},position:{target:i,adjust:{x:2,y:2},viewport:!0},events:{hidden:$ocms.tooltip_hidden},show:{effect:!1},hide:{effect:!1}}),e.remove()})):t(this).qtip({position:{target:i,adjust:{x:2,y:2},viewport:!0},events:{hidden:$ocms.tooltip_hidden},effect:!1})})),r},t.fn.rC=function(e){return t(this).removeClass(e)},t.fn.aC=function(e){return t(this).addClass(e)},t.fn.tC=function(e,n){return t(this).toggleClass(e,n)}}(jQuery),function(t){t.fn.ocmsmenu=function(e,n){var i=t(this);return $ocms.menu.call(i,e,n),i},t.fn.activatemenu=function(){var e=t(this).filter("nav");return e.find("a").not(".on").addClass("on").click($nuf),e.find(".nav-btn").not(".on").addClass("on").click((function(e){e.stopPropagation();var n=t(this);t(n.attr("data-target")).tC(n.attr("data-toggle"))})),e}}(jQuery);class ObjectArray extends Array{isEmpty(){return 0===this[0].length}static get[Symbol.species](){return Array}filter(t){return"function"==typeof t?new ObjectArray(this[0].filter(t)):this}remove(t){if("function"!=typeof t)return this;{let e=this[0].findIndex(t);for(;e>-1;)this[0].splice(e),e=this[0].findIndex(t)}}sortBy(t){return"function"==typeof t&&this[0].sort(t),this}sortString(t){return this[0].sort(((e,n)=>{let i=(e[t]||"").toString().toUpperCase(),o=(n[t]||"").toString().toUpperCase();return console.debug(i.localeCompare(o)),i.localeCompare(o)})),this}sortNum(t){return this[0].sort(((e,n)=>{let i=e[t],o=n[t];return!0===isNaN(o)&&!1===isNaN(i)||io?1:0})),this}sum(t){return this[0].reduce(((e,n)=>e+(!0===isNaN(n[t])?0:n[t])),0)}groupBy(t){return this[0].reduce((function(e,n){let i=n[t];return e[i]||(e[i]=[]),e[i].push(n),e}),{})}each(t){if("function"==typeof t){let e=!1;this[0].forEach(((n,i,o)=>{if(!1===e){let r=t(n,i,o);"boolean"==typeof r&&!1===r&&(e=!0)}}))}}get toArray(){return this[0]}}class NumArray extends Array{sum(){return this.reduce(((t,e)=>t+e))}first(){return this[0]}last(){return this[this.length-1]}average(){return this.sum()/this.length}range(){let t=this.map((t=>t)).sort();return{min:t[0],max:t[this.length-1]}}static get[Symbol.species](){return Array}}$ocms.ocmsmenu=[{lbl:"",id:"m_home",ico:"glyphicon glyphicon-home",fnc:"init:home"},{fnc:"separator"}],function(t){t.multline=function(t){let e=t.split("\n"),n=$$.d();return $.each(e,((t,e)=>{n.append($$.s(e))})),n.html()},t.tooltip_hidden=function(t,e){$(this).remove(),e.rendered=!1},t.isJSONDateString=function(t){return"string"==typeof t&&/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?)?$/.test(t)},t.failure=function(e){11110===(e.internalCode||-1)?t.login.dlg():alert($t.f1+"\n"+(e.internalText||""))},t.getScript=function(e,n){var i=[],o=[],r=function(t){return"string"==typeof t&&""!==(t||"")},s=function(t,e){!0===bool(e.condition,!0)&&(""!==(e.script||"")&&o.push({url:e.script,module:e.module||""}),!0===r(e.css||"")?i.push(e.css):!0===Array.isArray(e.css)&&Array.prototype.push.apply(i,e.css.filter(r)))};!0===r(e||"")?o.push(e):!0===Array.isArray(e)?$.each(e,s):"object"==typeof e&&""!==(e.script||"")&&s(0,e);let a=[];$.each(i,(function(t,e){""!==(e||"")&&a.push(loadCSS(e))}));let c=o.map((function(e,n){let i=e.url,r=e.module||"";if(""===r){let t=new Promise((function(t,e){try{!async function(){$.ajax({url:i,dataType:"script",success:function(){t(o)},error:function(){e(o)},timeout:3e4})}()}catch(t){console.debug(t.message+"%o",t)}}));return t}return t.loadmodule(r,i,e.alias)}));Promise.all(c).then(n)},t.loadmodule=function(e,n,i){let o=new Promise((function(o,r){!async function(){try{let s=(n.startsWith("/")||n.startsWith(".")?"":"/")+n;import(s).then((n=>{t[e]=n[i||"default"],o(e)})).catch((t=>{console.debug(t.message+"%o",t),r(e)}))}catch(t){console.debug(t.message+"%o",t)}}()}));return o},t.ocms_auth=function(e,n,i,o){!1===$.isPlainObject(t.auth.modules)&&(t.auth.modules={});var r=0;t.auth.modules[e+(i||"")]?((r=t.auth.modules[e+(i||"")])<2&&(i||"")===auth.guid&&(r=2),r>=(n||0)&&o(false)):t.postXT({url:t.url("auth"),data:{module:e,person_guid:i||""},success:function(s){r=s[e],t.auth.modules[e+(i||"")]=r,r<2&&(i||"")===t.auth.person_guid&&(r=2),r>=(n||0)&&o(false)},error:function(e){t.failure.call(this,e)}})},t.auth.locale="de",t.ocms_prepauth=function(e,n,i){t.postXT({url:t.url("auth"),data:{fn:"csv",modules:e,person_guid:n||""},success:function(e){t.ocms_regauth(e)},error:function(e){t.failure.call(this,e)},complete:function(){i()}})},t.ocms_regauth=function(t){$.each(t||{},(function(t,e){auth.modules[t]=parseInt(e)}))},t.init=function(e){var n="string"==typeof e?e:(e.data||{}).fn||"";""!==n&&("home"===n?($cfr(),$lfr(),$("#topbar").ocmsmenu([],!0),$("#activemodule").text($t.ov),t.ov.call($("#contentframe"))):($cfr(),$lfr(),$("#topbar").ocmsmenu([]),t.postXT({url:t.url(n+"/auth"),success:function(e){void 0===t[n]&&(t[n]={}),t[n].auth=e,e.manage>0&&t.getScript({module:n,script:["web/imdl",n,t.auth.locale||"de","js"].join("."),css:["web/imdl",n,"css"].join("."),condition:"function"!=typeof t[n].init2},(function(){t[n].init2()}))},error:function(){$("#contentframe").empty()}})))},t.menuarray=function(t){this.array=[],this.sep=function(){this.length>0&&"separator"!==this.array[array.length-1].fnc&&this.push({fnc:"separator"})},this.push=function(t){return void 0===t?null:(!0===Array.isArray(t)?Array.prototype.push.apply(this.array,t):"object"==typeof t&&this.array.push(t),t)},this.unshift=function(t){return void 0===t?null:(!0===Array.isArray(t)?Array.prototype.unshift.apply(this.array,t):"object"==typeof t&&this.array.unshift(t),t)},this.push(t)},t.menu=function(e,n){e=e||[];var i=$(this).removeClass("vis");if(!0===bool(n,!0)&&!1===i.is("#mainmenu")&&i.empty(),!1===bool(n,!1)&&i.is("#sidebar,#topbar")&&(e.unshift({id:"sbctrl",glyph:"glyphicon-th-list",aclass:"fbtn",fnc:function(){$lf()}}),$lf(0)),0===(e||[]).length)i.empty().addClass("hd");else{i.removeClass("hd");var o=!0===i.is("nav")?i:i.children("nav");1!==o.length&&(o=$("").tC("nv",i.is("#sidebar")).tC("ctxt",i.is("#topbar")).appendTo(i));var r,s=$$.ul().appendTo(o),a=function(t,e){var n=$(this).addClass("dropdown submenu");t.append($$.sc("caret dd")).addClass("dds dropdown-toggle").attr({"aria-expanded":"false"}),""!==(e.ico||"")&&t.prepend($$.sc("ico "+e.ico));var i=$$.ul({class:"dropdown-menu",role:"menu"}).appendTo(n);$.each(e.itm||[],(function(t,e){r.call(i,e)}))},c=function(t){$(this).tC("disabled","boolean"==typeof t.disabled?t.disabled:"string"==typeof t.disabled&&"subs"===t.disabled&&0===(t.itm||[]).length)};r=function(e){var n,i=$$.li({id:e.id}).attr(e.attr||{}).addClass(e.lclass).appendTo($(this)),o="string"==typeof e.fnc&&""!==e.fnc?e.fnc.split(":")[0]:"";""!==o&&"init"!==o?i.attr("role",o).appendIf($$.s(e.lbl),""!==ne(e.lbl)):(n=$$.a({class:"on",role:"button"}).addClass(e.aclass).appendTo(i).append($$.s(e.lbl)),c.call(n,e),(e.itm||[]).length>0&&a.call(i,n,e),n.click($nuf),"function"==typeof e.fnc?n.click(e.data||{},e.fnc):"init"===o&&n.click($.extend({},e.data||{},{fn:e.fnc.split(":")[1]}),t.init))},$.each(e,(function(e,n){var i,o=$$.li({id:n.id}).attr(n.attr||{}).addClass(n.lclass),a="string"==typeof n.fnc&&""!==n.fnc?n.fnc.split(":")[0]:"";if(""!==a&&"init"!==a)o.attr("role",a).appendIf($$.s(n.lbl),""!==ne(n.lbl));else{if(i=$$.a({class:"on",role:"button"}).addClass(n.aclass).appendTo(o),c.call(i,n),""!==(n.lbl||"")&&i.append($$.s(n.lbl)),""!==(n.ico||"")&&i.prepend($$.sc("ico "+n.ico)),""!==(n.glyph||"")&&i.prepend($$.sc("glyphicon "+n.glyph)),(n.itm||[]).length>0){o.addClass("dropdown"),i.append($$.sc("caret dd")).addClass("dds dropdown-toggle").attr({"aria-expanded":"false"});var l=$$.ul({class:"dropdown-menu",role:"menu"}).appendTo(o);$.each(n.itm||[],(function(t,e){r.call(l,e)}))}(n.sel||[]).length>0||(i.click($nuf),"function"==typeof n.fnc?i.click(n.data||{},n.fnc):"init"===a&&i.click($.extend({},n.data||{},{fn:n.fnc.split(":")[1]}),t.init))}o.appendTo(s)})),o.activatemenu()}},t.easytbl=(t,e)=>{e=e||{};let n=$$.tbl().addClass(e.class).css("border-collapse","collapse"),i=($$.tbody(n),!0===bool(e.frame,!1)?{padding:"5px",border:"1px solid #727272"}:{});if(!0===Array.isArray(e.header)){let t=$$.thead(n);$.each(e.header,((n,o)=>$$.th(t).css(e.cellcss||i).rwText(o)))}else if(!0===bool(e.header,!1)&&(t||[]).length>0){let o=$$.thead(n);$.each(Object.keys(t[0]),((t,n)=>$$.th(o).css(e.cellcss||i).rwText(n)))}return $.each(t||[],((t,o)=>{let r=$$.tr();$.each(o,((t,n)=>{n=n||"";let o=$$.td(r).css(e.cellcss||i);n instanceof jQuery?o.append(n):"string"==typeof n&&("<"===n.substring(0,1)?o.append(n):o.text(n))})),n.append(r)})),n},t.dlgtbl=(e,n,i)=>{i=i||{};let o=t.easytbl(e,i);t.dlg(o,$.extend({title:n},i))},t.dlg=function(t,n){n=n||{};let i=$("body > .modal").length>0,o=t=>typeof n[t],r=t=>"function"===o(t);if(!0===bool(n.exclusive,!0)&&!0===i)return void alert($t.dbldlg||"Es ist bereits ein Dialog geöffnet");let s=$$.dc("modal",$("body")),a=$$.dc("modal-dialog",s);!1===isNaN(n.zindex)?s.css("zIndex",n.zindex):!0===i&&s.css("zIndex",parseInt($("body > .modal:last").cssValue("zIndex"))+200),!1===isNaN(n.zindex_min)&&s.cssValue("zIndex")').appendTo(d)),""!==ne(n.title)&&(c=$$.dc("modal-header",d),$("

        ").text(n.title).appendTo(c));let p=$$.dc("modal-body",d),f=$$.dc("modal-footer",d);t instanceof jQuery==!0&&p.append(t);let m=function(t){t&&"function"==typeof t.stopPropagation&&t.stopPropagation(),a.removeClass("in"),!0===r("closing")&&n.closing.call(d),p.hide().emptyWithEditors(),s.remove(),!0===r("close")&&n.close.call(d)};if(d.find(":input[required]").length>0&&($$.dc("note_required",f).append($$.sc("ind_required","*")).append($$.s($t.t1||"Eingabe erforderlich")),$$.dc("note_invalid",f).append($$.s($t.t2||"Bitte überprüfen Sie Ihre Eingaben im Formular."))),!0===r("cancel")){$$.bbtn(n.cancelbutton||"Abbrechen","cancel").attr({type:"button",role:"cancel"}).appendTo(f).click((function(t){n.cancel.call(d,t);t.stopPropagation(),m()}))}if(!0===r("confirm")){let t=$$.bbtn(n.button||"OK","confirm").attr({type:!0===bool(n.form,!1)?"submit":"button",role:"confirm"}).appendTo(f);!0===h?(d.submit((function(t){try{n.confirm.call(d,t)}finally{t.preventDefault()}return!1})),d.on("modal_submit",(function(){n.confirm.call(d,e)}))):(t.click((function(t){n.confirm.call(d,t);t.stopPropagation()})),d.on("modal_submit",(function(){t.click()})))}else!0===h&&d.submit((function(t){return t.preventDefault(),!1}));return d.on("modal_close",(function(){m()})),l.click(m),!0===r("opening")&&n.opening.call(d),a.addClass("in"),ne(n.mode).indexOf("maxbody")>-1&&p.css("min-height",(u.height()-c.outerHeight()-f.outerHeight()).toString()+"px"),!0===r("open")&&n.open.call(d),{hd:c,bdy:p,ft:f,ct:u,dlg:a,c:d}},t.mform=function(e){let n=$$.dc("form-body"),i=Array.isArray(e)?e:e instanceof fields_definition?e.fields:[];return $.each(i||[],(function(e,i){let o=i.type||"";if("ignore"===o)return!0;let r=$$.dc("form-group",n),s=i.id||"dlg_"+(i.name||"")+("html"===i.type?"_"+(65536*(1+Math.random())||0).toString(16).substr(9):""),a=$$.lbl(i.label||i.name,{for:s}).appendTo($$.dc("form-itm",r)),c=$$.dc("form-itm",r),l=$$.i({id:s,name:i.name,placeholder:i.placeholder,type:i.type});switch(o){case"email":i.pattern=ne(i.pattern,"[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$");break;case"url":i.pattern=ne(i.pattern,"https?://.+");break;case"number":i.pattern=ne(i.pattern,"[-+]?[0-9]*[.,]?[0-9]*"),l.attr("step",i.precision||"any"),l.attr("data-format","float");break;case"integer":case"int":i.pattern=ne(i.pattern,"[-+]?[0-9]*"),l.attr("type","number"),l.attr("data-format","integer");break;case"date":if(""!==ne(i.pattern,$t.datepattern)&&(i.pattern=ne(i.pattern,"("+$t.datepattern+")|([0-9]{4}.(0[1-9]|1[012]).(0[1-9]|1[0-9]|2[0-9]|3[01]))")),""!==ne(i.placeholder,$t.dateplaceholder)&&l.attr("placeholder",ne(i.placeholder,$t.dateplaceholder)),"string"==typeof i.value){var u=i.value.substr(0,10);i.value="date"!==l.prop("type")?fdt(u+"T00:00:00",ne(i.dateformat,$t.dateformat)):u}l.attr("data-format","date:"+ne(i.dateformat,$t.dateformat)+";yyyy-MM-dd");break;case"datetime":l.attr("type","datetime-local"),""!==ne(i.pattern,$t.datetimepattern)&&(i.pattern=ne(i.pattern,"("+$t.datetimepattern+")|([0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])\\s([0-5][0-9]):([0-5][0-9]))")),""!==ne(i.placeholder,$t.datetimeplaceholder)&&l.attr("placeholder",ne(i.placeholder,$t.datetimeplaceholder)),"string"==typeof i.value&&"T"===i.value.substr(10,1)&&(i.value="datetime"!==l.prop("type").substr(0,8)?fdt(i.value,ne(i.datetimeformat,$t.datetimeformat)):i.value),l.attr("data-format","datetime:"+ne(i.datetimeformat,$t.datetimeformat)+";yyyy-MM-dd HH:mm:ss");break;case"hidden":r.addClass("hd");break;case"html":case"text":l=$$.txt({id:s,name:i.name,placeholder:i.placeholder,type:i.type}),l.tC("tinymce","html"===i.type);break;case"bool":case"boolean":i.url=[{value:"true",label:($t||{}).true||"Yes"},{value:"false",label:($t||{}).false||"No"}],"boolean"==typeof i.value&&(i.value=i.value?"true":"false");case"select":l=$$.sel({id:s,name:i.name,type:i.type}),!1===bool(i.required,!1)&&$$.eOpt().appendTo(l);try{var d=function(t){!0===Array.isArray(t)&&$.each(t,(function(t,e){"string"==typeof e?$$.opt(e,e).appendTo(l):!0===Array.isArray(e)?$$.opt(e[0],e[1]).appendTo(l):"object"==typeof e&&$$.opt(e.value,e.label||e.text).appendTo(l)}))};!0===Array.isArray(i.url)?d(i.url):"function"==typeof i.url?i.url.call(l):"string"==typeof i.url&&t.postXT({url:i.url,success:d})}catch(t){$.noop()}break;default:""!==ne(i["max-length"])&&l.attr("max-length",i["max-length"])}""!==ne(i.pattern)&&l.attr("pattern",i.pattern),l.val(i.value).change(),l.change((function(){$(this)[0].setCustomValidity("")})),l.addClass("form-control").prop("required",bool(i.required,!1)).prop("readonly",bool(i.readonly,!1)).appendTo(c),!0===bool(i.required,!1)&&a.append($$.sc("ind_required","*")),"object"==typeof i.attr&&l.attr(i.attr),"object"==typeof i.prop&&l.prop(i.prop),"string"==typeof i.class&&l.addClass(i.class),"function"==typeof i.change&&(l.change(i.change),!0===bool(i.applychange,!1)&&void 0!==i.value&&l.change()),""!==(i.note||"")&&$$.dc("form-note",c).rwText(i.note),"function"==typeof i.complete&&i.complete.call(l)})),n},t.initMCE=function(t,e){t=$(t),e=e||{};try{let n={target:t[0],inline:!1,width:e.width||"100%",statusbar:!1,document_base_url:window.location.origin+"/",content_style:"ph:before {content: '«'; color: #BBB; font-style:italic; } ph:after {content: '»'; color: #BBB; font-style:italic; } ph { color: #AAA; font-style:italic; }",relative_urls:!1,remove_script_host:!1};!0===bool(e.hidemenu,!1)&&(n.menubar=!1,n.menu={}),!0===bool(e.hidetoolbar,!1)&&(n.toolbar=!1),$.extend(n,e||{}),tinymce.init(n)}catch(t){alert(t.message)}},t.dlgform=function(e,n){n=n||{};let i,o=$$.dc("frm").append(t.mform(e||[]).addClass("stacked"));n.addcontent instanceof jQuery&&o.append(n.addcontent),"function"==typeof n.submit?i=n.submit:"function"==typeof n.success&&(i=function(e){var i=$(this).ldng(1),o=$.extend({loginaccount:t.auth.account||""},i.serializeObject(bool(n.checkvalidity,!0),{typedvalues:bool(n.typedvalues,!1)}));""!==(n.url||"")?t.postXT({url:n.url,data:o,success:function(t){n.success.call(this,t),i.trigger("modal_close")},error:function(){alert($t.l17)},complete:function(){i.ldng(0)},timeout:6e4}):(n.success.call(this,o),i.trigger("modal_close"))});let r={form:!0,title:n.title||"",button:n.button||$t.submit,confirm:i,size:n.size||[500,600],open:function(){let e=$(this).find(".tinymce");e.length>0&&t.initMCE(e,n.tinymce||{})}};return t.dlg.call(this,o,r)},t.login.dlg=function(e){e=e||{};let n=[{name:"userinfo",label:$t.l1,type:"string",value:t.auth.login,change:t.login.uichange,required:!0},{name:"userlogin",type:"hidden",required:!0,value:t.auth.login},{name:"username",type:"string",label:$t.l4,required:!0,readonly:!0,placeholder:$t.l5,value:t.auth.fullname_rev},{name:"userpass",type:"password",label:$t.l3,required:!0,placeholder:$t.l3}];""===(t.auth.account||"")&&n.unshift({id:"dlg_loginaccount",name:"loginaccount",type:"string",required:!0,value:t.auth.account});let i=$$.dc("frm").append(t.mform(n).addClass("stacked")),o=t.dlg.call(this,i,{form:!0,title:$t.l0,button:$t.submit,confirm:function(n){var i=$(this).ldng(1),o=$.extend({loginaccount:t.auth.account||""},i.serializeObject());t.postXT({url:"/vt/login",data:o,success:function(n){""!==((n||{}).login||"")&&(i.trigger("modal_close"),t.auth=n,"object"==typeof e.ajo&&(e.ajo.islogin,$.ajax(e.ajo)))},error:function(){alert($t.l17)},complete:function(){i.ldng(0)},timeout:6e4})},size:[500,600]}),r=$$.dc("modal-content").css("height","auto").attr("novalidate","true").append($$.dc("modal-header").appendIf($("

        ").text(t.auth.accountname),""!==(t.auth.accountname||"")).append($("

        Vereinsmanager

        ")));o.dlg.prepend(r)},t.addNoEntryInfo=function(t){$(this).append($$.dc("noentryinfo").text(t||$t.t11))}}($ocms),Element.prototype.matches||(Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector),Element.prototype.closest||(Element.prototype.closest=function(t){var e=this;do{if(Element.prototype.matches.call(e,t))return e;e=e.parentElement||e.parentNode}while(null!==e&&1===e.nodeType);return null}),function(t,e){var n,i;"object"==typeof window&&(window[t]=(n=function(t){var e=window,n=document.body,i=document.documentElement,o=Math.max(0,e.pageXOffset||i.scrollLeft||n.scrollLeft||0)-(i.clientLeft||0),r=Math.max(0,e.pageYOffset||i.scrollTop||n.scrollTop||0)-(i.clientTop||0);return{x:t?Math.max(0,t.pageX||t.clientX||0)-o:0,y:t?Math.max(0,t.pageY||t.clientY||0)-r:0}},(i=function(t,e){t&&t instanceof Element&&(this._container=t,this._options=e||{},this._clickItem=null,this._dragItem=null,this._showDragItem="boolean"!=typeof this._options.dragItem||!1!==this._options.dragItem,this._hovItem=null,this._sortLists=[],this._click={},this._dragging=!1,this._dragHandleClass=this._options.dragHandleClass||"",this._parentident=this._options.parentident||"",this._swapdone="function"==typeof this._options.swapdone?this._options.swapdone:null,this._onend="function"==typeof this._options.onend?this._options.onend:null,this._container.setAttribute("data-is-sortable",1),this._container.classList.add("sortable"),this._container.style.position="static",window.addEventListener("mousedown",this._onPress.bind(this),!0),window.addEventListener("touchstart",this._onPress.bind(this),!0),window.addEventListener("mouseup",this._onRelease.bind(this),!0),window.addEventListener("touchend",this._onRelease.bind(this),!0),window.addEventListener("mousemove",this._onMove.bind(this),!0),window.addEventListener("touchmove",this._onMove.bind(this),!0))}).prototype={constructor:i,toArray:function(t){t=t||"id";for(var e=[],n="",i=0;ii.left&&ei.top&&n-1)&&e.className.indexOf("nosort")<0)&&(t.preventDefault(),this._dragging=!0,this._click=n(t),this._makeDragItem(e),this._onMove(t),!0)}t&&!1===e.call(this,t.target)&&""!==this._parentident&&t.target.closest(this._parentident)&&e.call(this,t.target.closest(this._parentident))},_onRelease:function(t){var e=!0===this._dragging&&null!==this._clickItem;this._dragging=!1,this._trashDragItem(),e&&"function"==typeof this._onend&&this._onend()},_onMove:function(t){if(this._dragItem&&this._dragging){t.preventDefault();var e=n(t),i=this._container;!0===this._showDragItem&&this._moveItem(this._dragItem,e.x-this._click.x,e.y-this._click.y);for(var o=0;o0?a.mousedown(c).addClass("dctrl"):s.mousedown(c).addClass("dctrl"),t(this)}}(jQuery),$(document).ready((function(){$("html").click((function(t){$nuf()})),$("#listframe").click((function(t){t.stopPropagation(),$nuf()})),$("#mainmenu").ocmsmenu($ocms.ocmsmenu),$("#mainmenu").activatemenu()})),$.extend($t,{m_inv:"Rechnungen",m_req:"Aufträge",m_rep:"Berichte",m_todo:"ToDos",m_bcd:"BankBuchungen",rsp:"Passwort ändern",pnm:"Die Passwörter stimmen nicht überein",cps:"Das neue Passwort wurde gespeichert.",pwr:"Bitte wählen Sie ein starkes Passwort (min 8 Zeichen, davon jeweils min 2 Zahlen, kleine und große Buchstaben, Sonderzeichen sind optional).",smsc:"Sie beötigen für diese Funktion einen SMS-Code.\nSoll dieser nun versandt werden?",wdc:"Doppelt klicken, um die Box zu aktualisieren.",wdg:{}}),$t.rspf={sms:"Der SMS-Code konnte nicht bestätigt werden",valid:"Das alte Passwort ist nicht korrekt",requirements:"Das Passwort entspricht nicht den Anforderungen.\n"+$t.pwr},$fd={rsp:new fields_definition("","",[{name:"opw",label:"aktuelles Passwort",type:"password",required:!0,attr:{"auto-complete":"current-password"}},{name:"npw",label:"neues Passwort",type:"password",required:!0,pattern:"(.{6,})",attr:{"auto-complete":"new-password"}},{name:"npwc",label:"neues Passwort (Bestätigung)",type:"password",required:!0,attr:{"auto-complete":"new-password"},note:$t.pwr},{name:"code",label:"SMS-Code",type:"string",required:!0,attr:{"auto-complete":"one-time-code"}}])},$ocms.init=function(t){var e="string"==typeof t?t:(t.data||{}).fn||"";""!==e&&("home"===e?($cfr(),$lfr(),$("#topbar").ocmsmenu([],!0),$("#activemodule").text($t.ov),$fis.ov()):($cfr(),$lfr(),$("#topbar").ocmsmenu([]),$ocms.postXT({url:$ocms.url(e+"/auth"),success:function(t){void 0===$ocms[e]&&($ocms[e]={}),$ocms[e].auth=t,t.manage>0&&$ocms.getScript({module:e,script:["/web/fis",e,$ocms.auth.locale||"de","js"].join("."),css:["/web/fis",e,"css"].join("."),condition:"function"!=typeof $ocms[e].init2},(function(){$ocms[e].init2()}))},error:function(){$("#contentframe").empty()}})))};var $fis={auth:{},db:function(){$("#mainmenu_activemodule").text($t.ov);let t=$(this).empty(),e=$$.d({id:"dashboard_frame"}).appendTo(t);$ocms.postXT({url:$ocms.url("wdg/my"),success:function(t){$.each(t,(function(t,n){var i=$$.dc("wdg_frame",e,{"data-wdg":n}).ldng(1);$ocms.wdg.call(i,{wdg:n})}))},loading:e})},ValidateEmail:function(t){return!!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(t)},cf:t=>{let e=$("#contentframe");return!0===bool(t,!1)&&e.empty().rC("hd"),e},lf:t=>{let e=$("#listframe");return!0===bool(t,!1)&&e.empty().aC("hd").rC("fix"),e},frm_edit:function(t){let e=$fis.cf(!1),n=e.children(".cfrm"),i=e.children(".edit_frm");return n.length<1?n=$$.dc("cfrm hd").prependTo(e):!0===bool(t,!1)&&n.empty(),i.length<1&&(i=$$.dc("edit_frm").insertAfter(n)),i.empty()},frm_list:function(t,e){let n=$fis.cf(!1),i=n.children(".cfrm"),o=n.children(".list_frm");return i.length<1?i=$$.dc("cfrm hd").prependTo(n):!0===bool(t,!1)&&i.empty(),!0===bool(e,!1)&&n.children(".edit_frm").remove(),o.length<1&&(o=$$.dc("list_frm").appendTo(n)),o.empty()},lfm:()=>{let t=$fis.lf(!1),e=t.children(".lfrm");return e.length<1&&(e=$$.dc("lfrm").prependTo(t)),e},getAuth:(t,e)=>new Promise(((n,i)=>{$fis.auth[t]&&!1===bool(e,!1)?n($fis.auth[t]||-1):$ocms.postXT({url:$ocms.url("auth"),data:{module:t},success:e=>{$fis.auth[t]=e.auth||-1,n($fis.auth[t]||-1)},error:()=>{i()}})})),prepAuth:t=>new Promise(((e,n)=>{$ocms.postXT({url:$ocms.url("auth"),data:{module:t,array:1},success:t=>{$.extend($fis.auth,t||{})},complete:()=>{e()}})})),isAuth:(t,e)=>($fis.auth[t]||-1)>=(e||1),resetPass:function(t,e){confirm($t.smsc)&&($ocms.postXT({url:$ocms.url("account/sms"),data:{fn:"pwc"}}),$ocms.dlgform($fd.rsp.clone(),{title:$t.rsp||"",submit:function(t){var e=$(this).ldng(1),n=$.extend({loginaccount:$ocms.auth.account||""},e.serializeObject(!0,{typedvalues:!0}));(n.npw||"")!==(n.npwc||"")?e.find('input[name="npw"]:first')[0].setCustomValidity($t.pnm):$ocms.postXT({url:$ocms.url("account/changepassword"),data:n,success:function(t){alert($t.cps),e.trigger("modal_close")},error:function(t){alert($t.rspf[t.getResponseHeader("x-ocms-std")])},complete:function(){e.ldng(0)},timeout:6e4})}}))},wdg:function(t){let e=$(this).empty();$ocms.postXT({url:$ocms.url("wdg/one"),data:{short_name:t.wdg},timeout:9e4,success:function(n,i,o){let r=t.wdg,s=n[r];if(!s)return void e.ldng(0);let a=$.inArrayRegEx("dblwidth",s.rendering_options)>-1,c=$.inArrayRegEx("tiny",s.rendering_options)>-1;e.toggleClass("dbl",a&&!c).toggleClass("tny",c);$$.dc("wdg_hd",e,{title:ne(s.description,$t.wdc)}).toggleClass("dbl",a).text(ne(s.name,t.wdg)).dblclick((function(t){t.stopPropagation(),$fis.wdg.call(e,{wdg:r})}));let l=$$.dc("wdg_cnt",e).toggleClass("dbl",a).hide(),u=$.inArrayRegEx("bgcolor",s.rendering_options);switch(u>-1&&l.css("backgroundColor",s.rendering_options[u].toString().right(":")),s.type){case"table":var d=$$.tblset({},l),h=$$.tr().appendTo(d.hd),p=$t.wdg[r.indexOf("wdg_ev_")>=0?"wdg_ev_":r]||{};$.each(s.columns,(function(t,e){var n=p[e]?p[e].label:e;$$.th().text(n).appendTo(h)})),$.each(s.data,(function(t,e){var n=$$.tr().appendTo(d.bdy);$.each(s.columns,(function(t,i){var o=$$.td().appendTo(n);e[i]instanceof Date||!0===$ocms.isJSONDateString(e[i])?o.text(fdt(e[i],$t.dateformat)):o.rwText(e[i])}))})),$.inArray("firstrow_bold",s.rendering_options)>-1&&h.nextAll("tr:first").css("font-weight","bold");break;case"ind":$$.dc("ind",l).addClass("sts_"+(s.data.status||"")).append([$$.dc("ind").text(s.data.value),$$.lbl(s.data.label)]);break;case"image_url":l.css("background","url('"+s.url+"') no-repeat center center transparent");break;case"image_base64":l.css("background","url('data:image/png;base64,"+s.image+"') no-repeat center center transparent");break;case"html":if(l.html(s.html),$.inArray("reload_10min",s.rendering_options)>-1){var f=l.find("iframe");setTimeout((function(){f.attr("src",(function(t,e){return e}))}),6e5)}}$.inArray("reload_30min",s.rendering_options)>-1&&"html"!==s.type&&setTimeout((function(){$fis.wdg.call(e,{wdg:r})}),18e5),l.slideDown(150)},error:function(t){e.slideUp(150),$fis.failure.call(this,t)},complete:function(){e.ldng(0)}})},ov:function(){$fis.lf(!0);let t=$("#contentframe").empty(),e=$$.d({id:"dashboard_frame"}).appendTo(t);$ocms.postXT({url:$ocms.url("wdg/my"),success:function(t){$.each(t,(function(t,n){var i=$$.dc("wdg_frame",e,{"data-wdg":n}).ldng(1);$fis.wdg.call(i,{wdg:n})}))},loading:e})}};$fis.notifications={connection:null,init:function(){"undefined"!=typeof signalR&&null===this.connection&&$ocms.auth.useraccount_id&&(this.ensureFrame(),this.connection=(new signalR.HubConnectionBuilder).withUrl("/notifications").withAutomaticReconnect().build(),this.connection.on("notification",(t=>{this.push(t)})),this.connection.onclose((()=>{console.warn("Notification connection closed; retrying in 5s."),this.connection=null,setTimeout((()=>this.init()),5e3)})),this.start())},start:function(){this.connection.start().catch((t=>{console.warn("Notification connection failed to start; retrying in 5s.",t),this.connection=null,setTimeout((()=>this.init()),5e3)}))},ensureFrame:function(){$("#notification_frame").length<1&&$("
        ",{id:"notification_frame"}).appendTo($("footer:first").length?"footer:first":"body")},push:function(t){this.ensureFrame(),t=t||{};let e=$("
        ",{class:"notification_item"}).addClass((t.severity||"info").toLowerCase()).append($("