$inv.cInv = function (ev) { let tr = $(this).closest('tr'); ev.stopPropagation(); if (tr.is('.selected') === false) { return; } else if ($fis.isAuth('fds_inv', 2) === false) { return; } $inv.cInv2({ id: ev.data.id }); }; $inv.rMn = (o) => { let m = [{ lbl: $ict.req, itm: [] }]; if (bool(o, false) === true && $fis.isAuth('fds_inv', 2) === true) { Array.prototype.push.apply(m[0].itm, [ { lbl: $rct.crI, fnc: $inv.ccInv, data: { typ: 'r' } } , { lbl: $rct.crII, fnc: $inv.ccInv, data: { typ: 'i' } } ]); } m.push({ lbl: $ict.rel, fnc: $inv.rReload }); return $('#topbar').ocmsmenu(m); }; $inv.iMnr = (ix) => { let f = booln(ix.isFinal, true), id = ix.Id, fds = booln(ix.fds, false); let m = [ { glyph: 'glyphicon-menu-left', fnc: () => { $fis.frm_edit().remove(); } }, { lbl: $ict.inv, itm: [] }, { lbl: $ict.rem, itm: [] } ]; if (f === false && $fis.isAuth('fds_inv', 2) === true) { m[1].itm.push({ lbl: $ict.ced, fnc: $inv.clCntInv }); } else if ($fis.isAuth('fds_inv', 1) === true) { m[1].itm.push({ lbl: $ict.dsp, fnc: () => $inv.disp(id, 'inv') }) } if (fds === true && f === true && $fis.isAuth('fds_inv', 2) === true) { m[1].itm.push({ lbl: $ict.storno, fnc: () => $inv.storno(id, fds) }); m[1].itm.push({ lbl: $ict.credit, fnc: () => $inv.credit(id, fds) }); } if (f === true && $fis.isAuth('fds_reminder', 2) === true) { m[2].itm.push({ lbl: $ict.remd, fnc: () => $inv.ccRem(id, ix.InvoiceId) }); m[2].itm.push({ lbl: $ict.remlst, fnc: () => $inv.dspRem(id) }); } if (f === true && $fis.isAuth('fds_reminder', 2) === true && booln(ix.IsSent, false) === false) { m[2].itm.push({ lbl: $ict.srs, fnc: () => $inv.srs(id) }); } m.push({ lbl: $ict.rel, fnc: $inv.rReload }); return $('#topbar').ocmsmenu(m); }; $inv.iMn = (ix) => { let f = booln(ix.isFinal, true), id = ix.Id, fds = booln(ix.fds, false); let m = [{ glyph: 'glyphicon-menu-left', fnc: () => { $fis.frm_edit().remove(); } }, { lbl: $ict.inv, itm: [] }, { lbl: $ict.rem, itm: [] } ]; if (f === false && $fis.isAuth('fds_inv', 2) === true) { m[1].itm.push({ lbl: $ict.ced, fnc: () => { $inv.cntInv({ id: id }); } }); } else if ( $fis.isAuth('fds_inv', 1) === true) { m[1].itm.push({ lbl: $ict.dsp, fnc: () => $inv.disp(id, 'inv') }) } if ($fis.isAuth('fds_inv', 2) === true) { m[1].itm.push({ lbl: $ict.storno, fnc: () => $inv.storno(id, fds) }) m[1].itm.push({ lbl: $ict.credit, fnc: () => $inv.credit(id, fds) }); } if (f === true && booln(ix.IsPayed, false) === false) { if ($fis.isAuth('fds_reminder', 2) === true) { m[2].itm.push({ lbl: $ict.remd, fnc: () => $inv.ccRem(id, ix.InvoiceId) }); } if ($fis.isAuth('fds_inv', 2) === true) { m[1].itm.push({ lbl: $ict.setpyd, fnc: () => $inv.setPyd(id) }); } } else if (f === true && booln(ix.IsPayed, false) === true && (ix.PaymentStatus || '') === 'm') { if ($fis.isAuth('fds_inv', 2) === true) { m[1].itm.push({ lbl: $ict.setupd, fnc: () => $inv.setUpd(id) }); } } if ($fis.isAuth('fds_reminder', 2) === true) { m[2].itm.push({ lbl: $ict.remlst, fnc: () => $inv.dspRem(id) }); } if (f === true && $fis.isAuth('fds_inv', 2) === true && booln(ix.IsSent, false) === false) { m[1].itm.push({ lbl: $ict.sis, fnc: () => $inv.sis(id) }); } if (fds === false) { m[1].itm.push({ lbl: $ict.mfr, fnc: () => $inv.mfrrel(id) }); } return $('#topbar').ocmsmenu(m); } /* Menu option CSV builder. 'setm' (Set-Preisanzeige) is always offered: since ADR 0019 the two modes convert every still-unconverted SET (not the whole invoice), so running them again after the user has added or re-assigned a set converts just that one — and is a plain no-op when there is nothing left to convert. The legacy admin.setmode flag no longer gates the entry. */ $inv.emOpt = () => 'iss,p13b,ctp,setst,setm'; $inv.eM = (r, re, opt) => { let m = []; if (booln(r, false) === true || booln(re, false) === true) { m.push({ glyph: 'glyphicon-menu-left', fnc: () => { $fis.lf(true); $fis.frm_edit().remove(); } }); } if ((opt || '').split(',').includes('iss') === true) { m.push({ lbl: $ict.iss, fnc: $inv.ssave }); } if ((opt || '').split(',').includes('ctp') === true) { m.push({ lbl: $ict.ctp, fnc: $inv.sctp }); } if ((opt || '').split(',').includes('p13b') === true) { m.push({ lbl: $ict.p13b, fnc: $inv.sp13b }); } if ((opt || '').split(',').includes('setm') === true) { m.push({ lbl: $ict.setm, fnc: $inv.ssetmode }); } if ((opt || '').split(',').includes('setst') === true) { /* user-defined set structure dialog (ADR 0016) */ m.push({ lbl: $ict.setst, fnc: () => $inv.sets.open() }); } if ((opt || '').split(',').includes('iss') === true) { /* backend-authoritative draft (ADR 0006) */ m.push({ lbl: 'Änderungshistorie', fnc: () => $inv.d.history() }); m.push({ lbl: 'Änderungen verwerfen', fnc: () => $inv.d.discard() }); } if (booln(r, false) === true) { m.push({ lbl: $ict.rel, fnc: $inv.rReload }); } return $('#topbar').ocmsmenu(m); /* empty Array => empty menu */ }; /* ── PDF preview failure handling (shared by every image-preview call) ──────── A preview render can legitimately take longer than the 30s postXT default (Spire rasterises every page), and postXT swallows a timeout silently — the user would sit in front of a frozen editor with no message. So previews get a longer timeout and one handler that always tells the user something: the server's description header when it sent one (the backend logs the failure and puts the reason there), a timeout hint when the request timed out, the generic text otherwise. */ /* Milliseconds. postXT only treats values below 100 as seconds — 120 would be 120 ms. */ $inv.pdfPreviewTimeout = 120000; $inv.pdfPreviewFailed = function (jqXHR, textStatus) { if ((jqXHR || {}).internalCode === 11110) { $ocms.login.dlg(); return; } let desc = ((jqXHR || {}).internalText || '').trim(); if (desc === '' && textStatus === 'timeout') { desc = $ict.pvto; } if (desc === '' && (jqXHR || {}).status === 410) { desc = $ict.pvgone; } alert(($ict.pvf || $t.f1) + (desc !== '' ? '\n' + desc : '')); }; /* postXT never calls `error` for a timeout (it returns early), so the timeout is only observable from `complete`; this builds the complete handler for a preview call. `wait`, if given, is the "please wait" popup from `$inv.pdfWaitDlg` — it must close on every outcome (success, error, timeout), so `complete` is the only place that reliably covers all three. */ $inv.pdfPreviewComplete = function (layout, wait) { return (jqXHR, textStatus) => { if (wait) { wait.c.trigger('modal_close'); } if (layout) { layout.rC('freeze'); } if (textStatus === 'timeout') { $inv.pdfPreviewFailed(jqXHR, textStatus); } }; }; /* A preview render can take anywhere from a couple of seconds to the full 120s timeout (a cold miss regenerates + stores the PDF before rasterising it, ADR 0025); postXT's generic `body.ldng` class has no CSS behind it, so nothing tells the user the click was received. Same popup the MFR data fetch shows (see $inv.cInv2): spinner frame in a modal with the explanation in the footer. Non-exclusive so it can sit on top of an open editor. */ $inv.pdfWaitDlg = function () { let o = $ocms.dlg($$.dc('rfrm').ldng(1), { exclusive: false, zindex_min: 50 }); if (o) { o.ft.rwText($ict.pvw); } return o; }; /* ── Backend-authoritative draft editing controller (ADR 0006/0007) ─────────── The server holds the truth for an invoice draft in an in-memory session; this object seeds it, sends single edits as deltas, and renders the totals footer + validation from the authoritative server state. It is invoice-only: reminders never obtain a token (invSumUpdate, the seed trigger, is only bound for invoices), so they keep the legacy stateless flow untouched. */ $inv.d = { tbl: () => $('div.invoice_layout table.invi'), layout: () => $('div.invoice_layout'), token: function () { return $inv.d.tbl().data('dtoken') || ''; }, /* Hash each assembled block so only genuinely-changed blocks are sent as deltas. */ hashes: function () { let bai = $inv.d.tbl().data('bai') || [], h = {}; $.each(bai, (i, b) => { h[(b.Id || '').toString()] = JSON.stringify(b); }); return h; }, /* Seed the authoritative server session from the assembled editor payload. Called once from invSumUpdate on open; thereafter the backend is the source of truth. The in-flight ajax promise is stashed on 'dseedpromise' so a delta sent (e.g. via a context-menu action) before seeding has actually completed can wait for the token instead of silently no-op'ing (see $inv.d.sync). */ seed: function (payload) { let l = $inv.d.layout(); l.aC('freeze'); let p = $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()).data('dorder', $inv.d.order()); $fis.draft.bind(r.token, { onReady: () => $inv.d.refresh(), onExpiring: (s) => $inv.d.warnExpiry(s), onClosed: (reason) => $inv.d.closed(reason) }); $inv.d.refresh(); }, error: () => { l.rC('freeze'); }, complete: () => { $inv.d.tbl().removeData('dseeding').removeData('dseedpromise'); } }); $inv.d.tbl().data('dseedpromise', p); return p; }, /* Re-fetch the authoritative state and render the totals footer + validation from it. */ refresh: function (cb) { let t = $inv.d.token(); if (t === '') { return; } $ocms.postXT({ url: $ocms.url('inv/dstate'), data: { token: t }, success: (state) => { $inv.d.applyState(state); if (typeof cb === 'function') { cb(state); } }, error: (xhr) => { if (xhr && xhr.status === 410) { $inv.d.closed('expired'); } }, complete: () => { $inv.d.layout().rC('freeze'); } }); }, applyState: function (state) { let tbl = $inv.d.tbl(); if (tbl.length < 1) { return; } /* Concurrent refreshes (one per flushed block plus one for a follow-up delta such as item.setprice, and SignalR draftReady on top) can have their dstate responses arrive out of order. Applying a response older than the version already rendered would silently roll back a just-applied server-side mutation (e.g. a set-price conversion reverting to its pre-conversion 0/individually-priced state) — so stale responses are dropped here instead of rendered. */ let curVer = tbl.data('dver'); if (typeof curVer === 'number' && typeof state.version === 'number' && state.version < curVer) { return; } tbl.data('dver', state.version).data('serverSums', state.sums).data('dstate', state); $inv.d.footer(tbl, state.sums || {}, state.admin || {}); $inv.d.notes(state.notes || []); $inv.d.validation(state.validation || []); $inv.d.applyItems(tbl, state.req || []); $inv.d.applySetDisplay(tbl, state.setDisplay || {}); if ($inv.sets && $inv.sets.isOpen()) { $inv.sets.render(state); } /* the set-structure dialog is a view of the same state (ADR 0016) */ $inv.eM(false, true, $inv.emOpt()); }, /* Renders the backend-authoritative notice paragraphs (ADR: notice texts are backend-authoritative) exactly as FuchsPdf.BuildInvoiceNotes emits them for the PDF, so the online editor always shows precisely what will be printed. */ notes: function (notes) { let frm = $inv.d.layout(); if (frm.length < 1) { return; } let box = frm.children('.dnotes'); if (box.length < 1) { box = $$.dc('dnotes'); frm.append(box); } box.empty(); (notes || []).forEach((n) => $$.dc('dnote').aC(n.style || 'InvoiceNotes').text(n.text)); }, /* 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. */ /* Reconciles each block's rendered rows against the authoritative server line list (`req[].itm`, the co shape). The server may not only change a line's values but also ADD lines (e.g. a set/text line created in the structure dialog) and REMOVE lines (a set's members under "Nur Set mit Preis"/block.setonly), and reorder them — the browser never computes any of that (ADR 0006/0008/0019), it just mirrors the server. For each server line: patch/insert the matching row, preserving null price fields verbatim (null = empty cell, kept distinct from 0). Rows the server no longer lists are removed; order follows the server. Position numbers, net/VAT and the set-row emphasis all come from rrw off the mirrored data. */ applyItems: function (tbl, req) { let val = (x) => (x === undefined ? null : x); // JSON null stays null; absent -> null (req || []).forEach((b) => { if (!b) { return; } let bid = (b.Id || '').toString(); if (bid === '') { return; } let bdy = tbl.children('tbody').filter((i, e) => (($(e).data() || {}).Id || '').toString() === bid).first(); if (bdy.length < 1) { return; } let itms = b.itm || [], serverIds = {}; let title = bdy.find('tr.title').first(); let prev = title.length ? title : null; itms.forEach((co) => { let id = (co.id || '').toString(); if (id === '') { return; } serverIds[id] = true; let rw = bdy.find('#itm' + id).first(), isNew = rw.length < 1; if (isNew) { rw = $$.tr(bdy, { id: 'itm' + id, class: 'itm' }); } let dta = rw.data() || {}; let changed = isNew || (dta.Type || '') !== (co.typ || '') || dta.net !== val(co.v) || dta.net_val !== val(co.vt) || dta.vat_val !== val(co.vv) || dta.svcnet_val !== val(co.vs) || dta.svcvat_val !== val(co.vsv) || (dta.position || '') !== (co.p != null ? co.p : '') || (dta.lvl || 0) !== (co.lvl || 0) || (dta.SetItmId || null) !== (co.SetItmId != null ? co.SetItmId : null); $.extend(dta, { Id: id, Type: co.typ, net: val(co.v), net_val: val(co.vt), vat_val: val(co.vv), svcnet_val: val(co.vs), svcvat_val: val(co.vsv), vat: co.vat, position: (co.p != null ? co.p : ''), SetItmId: (co.SetItmId != null ? co.SetItmId : null), lvl: (co.lvl || 0) /* nesting depth (ADR 0016) — rendered as an indent */ }); if (isNew) { $.extend(dta, { htmltext: co.t, quantity: co.q }); } // text only for server-created rows (e.g. the set row) rw.data(dta); if (prev) { if (rw.prev()[0] !== prev[0]) { rw.insertAfter(prev); } } // keep server order, but don't churn already-ordered rows else if (bdy.children().first()[0] !== rw[0]) { bdy.prepend(rw); } prev = rw; if (changed) { $inv.rrw.call(rw); } }); bdy.find('tr.itm').each((i, tr) => { let id = (($(tr).data() || {}).Id || '').toString(); if (id !== '' && !serverIds[id]) { $(tr).remove(); } // dropped server-side (block.setonly) }); }); }, /* Applies the backend-authoritative set-pricing display flags (see BuildSetDisplay / InvoiceSetPricing) onto the rendered rows: blanks the price/total cells for lines the server says should show no price (set members in SetPrice/SetOnly mode), and emphasises the set header line — so the online editor always shows exactly what the PDF will print, without duplicating the pricing rules client-side. Rows not present in the map (no set in that block, or standalone items) are left untouched. */ applySetDisplay: function (tbl, setDisplay) { tbl.find('tr.itm').each((i, tr) => { let rw = $(tr), dta = rw.data() || {}, id = (dta.Id || '').toString(); if (id === '' || !Object.prototype.hasOwnProperty.call(setDisplay, id)) { return; } let flags = setDisplay[id] || {}; rw.tC('sethdr', bool(flags.h, false)); if (bool(flags.p, true) === false) { rw.find('td.currency').text(''); } }); }, /* Send one change to the server; the draftReady signal and this success both refresh. Returns the underlying ajax promise so callers that must not race a follow-up delta against this one (e.g. $inv.toSetPrice after a flush) can chain on it. If the initial seeding (inv/dopen) is still in flight (no token yet, but a 'dseedpromise' is pending), the delta previously vanished silently — the user saw no network activity at all when clicking a context-menu action right after opening the editor. Now the delta waits for the seed to finish and retries against the freshly issued token instead of being dropped. */ sync: function (delta) { let t = $inv.d.token(); if (t === '') { let seeding = $inv.d.tbl().data('dseedpromise'); if (seeding) { return $.when(seeding).then(() => $inv.d.sync(delta)); } return $.when(); } $inv.d.layout().aC('freeze'); return $ocms.postXT({ url: $ocms.url('inv/dpatch'), data: { token: t, delta: JSON.stringify(delta) }, success: () => { $inv.d.refresh(); }, 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. 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. No early return on an empty token here: sync() itself waits for an in-flight seed (dseedpromise) instead of silently dropping the delta, so edits made in the brief window before seeding completes are not lost. */ syncChanged: function (tbl) { let bai = tbl.data('bai') || [], prev = tbl.data('dhashes') || {}, next = {}, changed = [], removed = [], pending = []; $.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); } }); let order = $inv.d.order(), prevOrder = tbl.data('dorder') || []; tbl.data('dhashes', next).data('dorder', order); changed.forEach((b) => pending.push($inv.d.sync({ Target: 'block.replace', Ref: (b.Id || '').toString(), Value: b }))); removed.forEach((id) => pending.push($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(',')) { pending.push($inv.d.sync({ Target: 'block.order', Value: order })); } /* $.when(...pending) so a caller (e.g. toSetPrice) can wait until every flushed block has actually reached the server before sending a further delta that depends on it — otherwise a delayed block.replace carrying pre-conversion values can land after and silently overwrite a just-applied server-side mutation (e.g. item.setprice). */ return $.when.apply($, pending).promise(); }, /* Map an inline recipient field to its delta target and send it. No token-guard here for the same reason as syncChanged: sync() waits for an in-flight seed instead of dropping the edit. */ syncField: function (nme, val) { let map = { invoicetitle: 'title', invoiceaddress: 'address', invoiceemail: 'email', invoiceemailcc: 'emailcc', loc: 'provisionlocation', provisionlocation: 'provisionlocation', provisionperiod: 'provisionperiod' }; let target = map[nme]; if (!target) { return; } $inv.d.sync({ Target: target, Value: val }); }, /* Render the totals footer from the server sums (port of invSumUpdate's footer half). */ footer: function (tbl, sums, admin) { let ft = tbl.children('tfoot').empty(); tbl.nextAll('.fnote').remove(); let p13b = bool(admin.p13b, false); let rwcy = (lbl, val, cls) => $$.tdc('currency', $$.tr(ft, { class: cls || 'tsum' }).append([$$.tdc('aux'), $$.td({ colspan: 4 }).text(lbl)]), fnum(val, $rct.cst)); let fn = (t) => $$.dc('fnote').insertAfter(tbl).rwText(t); rwcy('Netto', sums.total_net || 0); if (p13b === false) { $.each(sums.vat || {}, (rate, amt) => rwcy($rct.vat + ' ' + rate + '%', amt, 'tvat')); } rwcy('Summe', sums.total_gross || 0); let itype = (admin.type || ''); if (itype === 'i') { fn($rct.note2); fn($rct.note4); } else if (itype === 'c') { fn($rct.note2); } else { fn(string($rct.note3, [fnum(((sums.service_net || 0) + (sums.service_vat || 0)) * (admin.tax_servicerefund || 0), $rct.cst)])).aC('ntax'); fn($rct.note2); fn(string($rct.note1, [fnum((sums.service_net || 0) + (sums.service_vat || 0), $rct.cst), fnum(sums.service_net || 0, $rct.cst), fnum(sums.service_vat || 0, $rct.cst)])); } if (p13b === true) { fn($rct.note13b); } }, validation: function (msgs) { let frm = $('div.invoice_layout'); if (frm.length < 1) { return; } let box = frm.children('.dvalidation'); if (box.length < 1) { box = $$.dc('dvalidation'); frm.prepend(box); } box.empty().tC('hidden', (msgs || []).length < 1); $.each(msgs || [], (i, m) => $$.dc('dvmsg', box).aC(m.severity).text(m.message)); }, /* PDF preview straight from the cache; confirm = flush + finalise, cancel = discard. */ preview: function () { let t = $inv.d.token(); if (t === '') { return; } let l = $inv.d.layout(); let email = ($inv.d.tbl().data('new') || {}).invoiceemail || ''; if ($fis.ValidateEmail(email) === false) { if (bool(confirm($ict.ivE + $ict.ivEc), false) === false) { return; } } l.aC('freeze'); $ocms.postXT({ url: $ocms.url('inv/dpreview'), data: { token: t }, timeout: $inv.pdfPreviewTimeout, success: (response) => { l.rC('freeze'); let c = $$.dc('imagecollection pdfpreview'), vhr = Math.round(vh() * 0.88), total = response.total; if (total > 10) { $$.dc('note warn', c).text($ict.tpe); } /* Admin-only (fds_inv > 2, decided server-side): date the invoice to the last working day of the previous month, offered only until an invoice has been created in the new month (ADR 0032). */ let bdChk = null; if ((response.backdate || '') !== '') { let bdRow = $('').addClass('backdate').attr('title', $ict.bdTT).appendTo(c); bdChk = $('').appendTo(bdRow); $$.s(string($ict.bdLbl, [response.backdate.split('-').reverse().join('.')])).appendTo(bdRow); } $.each(response.img || [], (ii, img) => { $$.dc('pdfp', c).append($$.img(img).css('max-height', (vhr - rpx(6)).toString() + 'px')); }); for (let ic = (response.img || []).length + 1; ic <= total; ic++) { $$.dc('pdfp ph', c).append($$.dc('note', $ict.pna)); } $ocms.dlg(c, { size: [vhr, Math.round(vw() * 0.88)], zindex: 50, form: false, button: $rct.crI, confirm: function (e) { let ct = $(this); l.aC('freeze'); $ocms.postXT({ url: $ocms.url('inv/dsave'), data: { token: t }, success: (sv) => { $ocms.postXT({ url: $ocms.url('req/sconf'), data: { id: sv.invid, backdate: (bdChk && bdChk.is(':checked')) ? 1 : 0 }, success: (cresp) => { ct.trigger('modal_close'); if (cresp.hasFile === true) { window.open($ocms.url('req/idoc') + '?id=' + sv.invid, '_blank'); } $inv.d.close(); $ocms.init('req'); $inv.rReload(); }, error: () => { alert($t.f1); ct.trigger('modal_close'); }, complete: () => { l.rC('freeze'); } }); }, error: () => { l.rC('freeze'); alert($ict.eis); } }); }, cancel: function (e) { if (confirm($ict.cdI)) { $inv.d.close(); $inv.rReload(); } } }); }, error: $inv.pdfPreviewFailed, complete: $inv.pdfPreviewComplete(l) }); }, /* Zwischenspeichern: flush the cache to the DB (no re-upload); stay in the editor. */ save: function () { let t = $inv.d.token(); if (t === '') { return; } let l = $inv.d.layout(); l.aC('freeze'); $ocms.postXT({ url: $ocms.url('inv/dsave'), data: { token: t }, success: (r) => { $inv.d.tbl().data('invid', r.invid); }, error: () => { alert($ict.eis); }, complete: () => { l.rC('freeze'); } }); }, history: function () { let t = $inv.d.token(); if (t === '') { return; } $ocms.postXT({ url: $ocms.url('inv/dhistory'), data: { token: t }, success: (r) => { let c = $$.dc('dhist'); if ((r.history || []).length < 1) { $$.dc('note', c).text('Noch keine Änderungen erfasst.'); } else { let ts = $$.tblset({ class: 'invtbl fullwidth' }, c); $$.tr(ts.hd).append([$$.th().text('Zeit'), $$.th().text('Feld'), $$.th().text('Alt'), $$.th().text('Neu')]); $.each(r.history, (i, h) => $$.tr(ts.bdy).append([$$.tdc('keep', fdt(h.timestamp)), $$.td().text(h.target), $$.td().text(h.oldValue), $$.td().text(h.newValue)])); } $ocms.dlg(c, { width: 800, form: false }); } }); }, discard: function () { let invid = $inv.d.tbl().data('invid') || ''; if (invid === '') { alert('Es wurde noch kein Zwischenstand gespeichert, der wiederhergestellt werden könnte.'); return; } if (confirm('Alle Änderungen verwerfen und den zuletzt gespeicherten Stand neu laden?') === false) { return; } $inv.d.close(); $inv.cntInv({ id: invid }); }, warnExpiry: function (secondsLeft) { let mins = Math.max(1, Math.round((secondsLeft || 0) / 60)); $fis.notifications.push({ severity: 'info', title: 'Entwurf läuft ab', message: 'Der Rechnungsentwurf läuft in etwa ' + mins + ' Minute(n) ab. Bitte zwischenspeichern, sonst gehen die Änderungen verloren.' }); }, closed: function (reason) { let t = $inv.d.token(); $inv.d.tbl().removeData('dtoken'); if (t !== '') { $fis.draft.release(t); } $fis.frm_edit().remove(); $fis.lf(true); $fis.notifications.push({ severity: 'error', title: 'Entwurf geschlossen', message: reason === 'expired' ? 'Der Rechnungsentwurf ist wegen Inaktivität abgelaufen. Nicht gespeicherte Änderungen sind verloren.' : 'Der Rechnungsentwurf wurde geschlossen.' }); try { $inv.rReload(); } catch (e) { } }, close: function () { let t = $inv.d.token(); if (t !== '') { $ocms.postXT({ url: $ocms.url('inv/dclose'), data: { token: t } }); $fis.draft.release(t); } $inv.d.tbl().removeData('dtoken'); } }; /* ── Backend-authoritative reminder draft editing (ADR 0006/0007) ───────────── The reminder mirror of $inv.d: the server holds the truth for a reminder draft in an in-memory session; this object seeds it (rem/dopen), sends single edits as deltas (rem/dpatch), and renders the open-amount footer + validation from the authoritative server state (rem/dstate). Preview renders straight from the cache (rem/dpreview); confirm flushes (rem/dsave) then finalises + emails (rem/conf). It coexists with $inv.d on the same DOM: each keys off its own token (rdtoken vs dtoken), so the shared inline editor safely no-ops for the mode that is not active. */ $inv.rd = { tbl: () => $('div.invoice_layout table.invi'), layout: () => $('div.invoice_layout'), token: function () { return $inv.rd.tbl().data('rdtoken') || ''; }, /* Seed the authoritative server session from the assembled reminder editor payload. */ seed: function (payload) { let l = $inv.rd.layout(); l.aC('freeze'); $ocms.postXT({ url: $ocms.url('rem/dopen'), data: { payload: JSON.stringify(payload) }, success: (r) => { $inv.rd.tbl().data('rdtoken', r.token).data('rdver', r.version); $fis.draft.bind(r.token, { onReady: () => $inv.rd.refresh(), onExpiring: (s) => $inv.rd.warnExpiry(s), onClosed: (reason) => $inv.rd.closed(reason) }); $inv.rd.refresh(); }, error: () => { l.rC('freeze'); } }); }, /* Re-fetch the authoritative state and render the open-amount footer + validation from it. */ refresh: function (cb) { let t = $inv.rd.token(); if (t === '') { return; } $ocms.postXT({ url: $ocms.url('rem/dstate'), data: { token: t }, success: (state) => { $inv.rd.applyState(state); if (typeof cb === 'function') { cb(state); } }, error: (xhr) => { if (xhr && xhr.status === 410) { $inv.rd.closed('expired'); } }, complete: () => { $inv.rd.layout().rC('freeze'); } }); }, applyState: function (state) { let tbl = $inv.rd.tbl(); if (tbl.length < 1) { return; } /* See $inv.d.applyState — drop stale/out-of-order dstate responses so an older refresh can never roll back a newer one's totals/validation. */ let curVer = tbl.data('rdver'); if (typeof curVer === 'number' && typeof state.version === 'number' && state.version < curVer) { return; } tbl.data('rdver', state.version).data('serverSums', state.sums).data('remid', state.remid || ''); $inv.rd.footer(tbl, state.sums || {}); $inv.rd.notes(state.notes || {}); $inv.rd.validation(state.validation || []); }, /* Renders the backend-authoritative intro/closing notice paragraphs (ADR: notice texts are backend-authoritative) exactly as FuchsPdf.BuildReminderNotes emits them for the PDF, so the online editor always shows precisely what will be printed. */ notes: function (notes) { let frm = $inv.rd.layout(); if (frm.length < 1) { return; } let rq = frm.find('.srq'); if (rq.length < 1) { return; } rq.children('.dnote').remove(); let intro = (notes || {}).intro || [], first = rq.children().first(); intro.slice().reverse().forEach((t) => { let p = $$[0]('p').aC('dnote intro').rwText(t); if (first.length) { p.insertBefore(first); } else { p.appendTo(rq); } }); ((notes || {}).closing || []).forEach((t) => $$[0]('p').aC('dnote closing').rwText(t).appendTo(rq)); }, /* Send one change to the server; the draftReady signal and this success both refresh. */ sync: function (delta) { let t = $inv.rd.token(); if (t === '') { return; } $inv.rd.layout().aC('freeze'); $ocms.postXT({ url: $ocms.url('rem/dpatch'), data: { token: t, delta: JSON.stringify(delta) }, success: () => { $inv.rd.refresh(); }, error: (xhr) => { $inv.rd.layout().rC('freeze'); if (xhr && xhr.status === 410) { $inv.rd.closed('expired'); } } }); }, /* Map an inline recipient field to its delta target and send it. */ syncField: function (nme, val) { if ($inv.rd.token() === '') { return; } let map = { subject: 'subject', invoiceaddress: 'address', invoiceemail: 'email', text: 'text' }; let target = map[nme]; if (!target) { return; } $inv.rd.sync({ Target: target, Value: val }); }, /* Amount / amount-paid come from the item-row dialog; send both as their own deltas. */ syncAmount: function (amount, amount_payed) { if ($inv.rd.token() === '') { return; } $inv.rd.sync({ Target: 'amount', Value: (amount != null ? amount : 0).toString() }); $inv.rd.sync({ Target: 'amount_payed', Value: (amount_payed != null ? amount_payed : 0).toString() }); }, /* Render the open-amount footer from the server sums. Detail rows ($inv.rRemRw) have 6 columns (aux, invoiceid, date, amount, amount_payed, open); span the label over the 4 columns between aux and the open-amount column so the total lands in the same last column as the per-invoice open amounts. */ footer: function (tbl, sums) { let ft = tbl.children('tfoot').empty(); let tr = $$.tr(ft, { class: 'tsum' }).append([$$.tdc('aux'), $$.td({ colspan: 4 }).text('Offener Betrag')]); $$.tdc('currency', tr, fnum(sums.amount_open || 0, $rct.cst)); }, validation: function (msgs) { let frm = $inv.rd.layout(); if (frm.length < 1) { return; } let box = frm.children('.dvalidation'); if (box.length < 1) { box = $$.dc('dvalidation'); frm.prepend(box); } box.empty().tC('hidden', (msgs || []).length < 1); $.each(msgs || [], (i, m) => $$.dc('dvmsg', box).aC(m.severity).text(m.message)); }, /* PDF preview straight from the cache; confirm = flush + finalise + email, cancel = discard. */ preview: function () { let t = $inv.rd.token(); if (t === '') { return; } let l = $inv.rd.layout(); let email = (($inv.rd.tbl().data('new') || {}).invoiceemail) || ''; if ($fis.ValidateEmail(email) === false) { if (bool(confirm($ict.ivE + $ict.ivEc), false) === false) { return; } } l.aC('freeze'); $ocms.postXT({ url: $ocms.url('rem/dpreview'), data: { token: t }, timeout: $inv.pdfPreviewTimeout, success: (response) => { l.rC('freeze'); let c = $$.dc('imagecollection pdfpreview'), vhr = Math.round(vh() * 0.88); $.each(response.img || [], (ii, img) => { $$.dc('pdfp', c).append($$.img(img).css('max-height', (vhr - rpx(6)).toString() + 'px')); }); $ocms.dlg(c, { size: [vhr, Math.round(vw() * 0.88)], zindex: 50, form: false, button: $ict.remd, confirm: function (e) { let ct = $(this); l.aC('freeze'); $ocms.postXT({ url: $ocms.url('rem/dsave'), data: { token: t }, success: (sv) => { $ocms.postXT({ url: $ocms.url('rem/conf'), data: { id: sv.remid }, success: () => { ct.trigger('modal_close'); window.open($ocms.url('rem/idoc') + '?id=' + sv.remid, '_blank'); $inv.rd.close(); $ocms.init('req'); $inv.rReload(); }, error: () => { alert($t.f1); ct.trigger('modal_close'); }, complete: () => { l.rC('freeze'); } }); }, error: () => { l.rC('freeze'); alert($t.f1); } }); }, cancel: function (e) { if (confirm($ict.cdI)) { $inv.rd.close(); $inv.rReload(); } } }); }, error: $inv.pdfPreviewFailed, complete: $inv.pdfPreviewComplete(l) }); }, /* Zwischenspeichern: flush the cache to the DB (no re-upload); stay in the editor. */ save: function () { let t = $inv.rd.token(); if (t === '') { return; } let l = $inv.rd.layout(); l.aC('freeze'); $ocms.postXT({ url: $ocms.url('rem/dsave'), data: { token: t }, success: (r) => { $inv.rd.tbl().data('remid', r.remid); }, error: () => { alert($t.f1); }, complete: () => { l.rC('freeze'); } }); }, history: function () { let t = $inv.rd.token(); if (t === '') { return; } $ocms.postXT({ url: $ocms.url('rem/dhistory'), data: { token: t }, success: (r) => { let c = $$.dc('dhist'); if ((r.history || []).length < 1) { $$.dc('note', c).text('Noch keine Änderungen erfasst.'); } else { let ts = $$.tblset({ class: 'invtbl fullwidth' }, c); $$.tr(ts.hd).append([$$.th().text('Zeit'), $$.th().text('Feld'), $$.th().text('Alt'), $$.th().text('Neu')]); $.each(r.history, (i, h) => $$.tr(ts.bdy).append([$$.tdc('keep', fdt(h.timestamp)), $$.td().text(h.target), $$.td().text(h.oldValue), $$.td().text(h.newValue)])); } $ocms.dlg(c, { width: 800, form: false }); } }); }, warnExpiry: function (secondsLeft) { let mins = Math.max(1, Math.round((secondsLeft || 0) / 60)); $fis.notifications.push({ severity: 'info', title: 'Entwurf läuft ab', message: 'Der Mahnentwurf läuft in etwa ' + mins + ' Minute(n) ab. Bitte zwischenspeichern, sonst gehen die Änderungen verloren.' }); }, closed: function (reason) { let t = $inv.rd.token(); $inv.rd.tbl().removeData('rdtoken'); if (t !== '') { $fis.draft.release(t); } $fis.frm_edit().remove(); $fis.lf(true); $fis.notifications.push({ severity: 'error', title: 'Entwurf geschlossen', message: reason === 'expired' ? 'Der Mahnentwurf ist wegen Inaktivität abgelaufen. Nicht gespeicherte Änderungen sind verloren.' : 'Der Mahnentwurf wurde geschlossen.' }); try { $inv.rReload(); } catch (e) { } }, close: function () { let t = $inv.rd.token(); if (t !== '') { $ocms.postXT({ url: $ocms.url('rem/dclose'), data: { token: t } }); $fis.draft.release(t); } $inv.rd.tbl().removeData('rdtoken'); } }; $inv.cInv2 = function (data) { let fr = $$.dc('rfrm').ldng(1); let o = $ocms.dlg(fr, { width: 1000 }); if (o) { o.ft.rwText($rct.rq1); } let mainfnc = () => { $ocms.postXT({ url: $ocms.url('req/get'), timeout: 60, data: { id: data.id, mode: 'r' }, success: (response) => { //console.debug(response); response.admin = response.admin || {}; let lf = $fis.lf(true).aC('fix').rC('hd'); $fis.frm_edit().IN(); $inv.eM(true, true); if ((response.requests || []).length < 1) { lf.aC('fix').text($rct.nd); } else { $$.dc('lh', lf, $rct.mdl); let iv = $$.d(), rq = $$.ul({ class: 'rql' }).data({ search: data.id, parent: response.admin.parent }).appendTo(lf), rqa = {}, cl = $rcol.req.lbl(); $.each(response.requests || [], function (ri, rx) { let rli = $$.li({ class: 'cli rli' }).data($.extend({}, rx)).appendTo(rq); let lihd = $$.dc('lihd', rli).addClass(rx.state); if (booln(rx.open, false) === true) { lihd.append($$.sc('cbox').click(() => { rli.tC('checked'); iv.find('li').rC('checked'); if (rli.is('.checked') === true) { $inv.rMn(rx.open); } else { $inv.eM(true); } })); } lihd.append([$$.sc('eid', rx.ExternalId), $$.sc('nme', rx.Name)]); $$.dc('lidt', rli).append([$$.dc('rqs').append([$$.s(cl.State + ': '), $$.s($rct.sts[rx.State || '-'])]), $$.dc('ivn').append([$$.s(cl.InvoiceId + ': '), $$.s(rx.InvoiceId || '- -')]), $$.dc('wda').append([$$.s(cl.WorkDoneAt + ': '), $$.s(fdt(rx.WorkDoneAt, 'dd.MM.yyyy'))])]); rqa[rx.Id] = rli; }); if ((response.inv || []).length > 0) { $$.dc('lh', lf, $rct.invs); iv = $$.ul({ class: 'ivl' }).appendTo(lf); /* first assignment to iv is fake, just to prevent issues */ $.each(response.inv || [], (ii, ix) => { let ili = $$.li({ class: 'cli ili' }).data($.extend({}, ix)).appendTo(iv); let lihd = $$.dc('lihd', ili).addClass(ix.invstatus); if (booln(ix.isFinal, true) === false) { lihd.append($$.sc('cbox').click(() => { if ((ix.Id || '') !== '') { ili.tC('checked').siblings().rC('checked'); rq.find('li').rC('checked'); if (ili.is('.checked') === true) { $inv.iMnr(ix); } else { $inv.eM(true); /* empty menu */ } } })); } else if (['', 'dft'].indexOf(ix.invstatus) < 0) { lihd.append($$.sc('dli').click(function () { $inv.disp(ix.Id, 'inv'); })); } lihd.append($$.sc('nme', ix.DocumentName || ix.Id)); $$.dc('lidt', ili).append([$$.dc('wda').append([$$.s(fdt(ix.InvoiceDate || ix.DateCreated, 'dd.MM.yyyy'))]), $$.d().text($ict.iSt[ix.invstatus] || ix.invstatus)]); }); } } }, complete: () => { if (o) { o.c.trigger('modal_close'); } } }); }; $ocms.postXT({ url: $ocms.url('req/pget'), timeout: 90, data: { id: data.id }, success: (r1) => { if (o) { o.ft.rwText($rct.rq2); } mainfnc(); }, error: () => { if (confirm($rct.rq1f)) { if (o) { o.ft.rwText($rct.rq2); } mainfnc(); } else { if (o) { o.c.trigger('modal_close'); } } } }); }; $inv.ccInv = function (ev) { //normale rechnung let data = ev.data || {}, typ = data.typ || 'r'; let lf = $fis.lf(), rql = lf.children('ul.rql'), parent = rql.data('parent'); let selli = []; rql.find('li.rli.checked').each(function () { selli.push($(this).data('Id')); }); if (selli.length < 1) { // abort if none selected alert($rct.dnS); return; }else if (typ === 'i' && selli.length > 1) { // abort if intermediate invoice and several selected alert($rct.dII); return; } let edf = $fis.frm_edit(), frm = $$.dc('invoice_layout', edf).append($$.dc('btn sprev').click($inv.sprev)); let ww = $fis.cf().width() > (frm.width() + lf.width() + 20); lf.tC('fix', ww).tC('hd', !ww); $inv.eM(false, true); let fr = $$.dc('rfrm').ldng(1); let o = $ocms.dlg(fr, { width: 1000 }); o.ft.rwText($rct.rq2); $ocms.postXT({ url: $ocms.url('req/iget'), timeout: 60, data: { id: parent, mode: 'ful', typ: typ, sel: selli.join(',') }, success: (response) => { //console.debug(response); let rq = $$.dc('srq', frm); let rif = $$.tblset({ class: 'invi' }, rq); rif.bdy.remove(); rif.ft = $$[0]('tfoot'); response.admin = response.admin || {}; response.admin.p13b = bool(response.admin.p13b || '', (((response.inv || {}).InvoiceOptions || '').split(',').includes('§13b') === true)); rif.tbl.data($.extend({ new: {}, sms: {}, itm: {} }, { admin: response.admin, companies: response.companies, locations: response.locations })); let thr = $$.tr(rif.hd).aC('shd').append([$$.th().aC('aux')]); /* header row for items */ $rct.invHR.forEach(h => $$.th(thr, h)); rif.tbl.on('fds.inv', $inv.invSumUpdate); $.each(response.requests || [], function (ri, rx) { let srqid = rx.Id || 0; if (srqid !== 0) { let worknotes = $inv.worknotes(rx); rx.text = response.admin.type === 'i' ? ($rct.req + (jine([rx.ExternalId, rx.Name], ': ').eine(' ', ''))) : (jine([jine([fdt(rx.WorkDoneAt, 'dd.MM.yy'), rx.ExternalId], ' - ' + $rct.req + ' '), worknotes.ne(rx.Name)], ': \n')); let bdy = $$.tbody(rif.tbl).data($.extend({}, rx)); $inv.rendersrq.call(bdy); } }); /* add an empty */ let atr = $$.tr($$.tbody(rif.tbl), { class: 'placeholder' }).data({ net_val: 0, vat_val: 0, svcnet_val: 0, svcvat_val: 0, net: 0 }); $inv.rrw.call(atr); rif.ft.appendTo(rif.tbl); let admin = response.admin || {}, fm = (cls, txt, nme, hd, dta) => { let fr = $$.dc('inpfrm', frm).aC(cls).append(typeof hd === 'string' ? $$.dc('ahd', hd) : (hd > 0 ? $$.dc('ahd', $rct.frm[nme]) : null)), fc = $$.dc('content', fr).rwText(txt); $$.dc('axf', fr).append($$.dc('ibtn edit', { title: $rct.frmTT[nme] || $rct.frm[nme] }).data('dialog', $rct.frm[nme]).append(gi('pencil')).click($.extend({ t: fc, nme: nme, change: (nv) => { rif.tbl.data('new')[nme] = nv; } }, dta), $inv.eHtml)); rif.tbl.data('new')[nme] = txt; }; fm('tfrm', admin.invoicetitle, 'invoicetitle', 0, null); fm('adrfrm', admin.invoiceaddress, 'invoiceaddress', 0, null); fm('locfrm', '', 'loc', 1, { list: deepCopy(response.locations), lbl: 'ref', property: 'address' }); $inv.emailFrm(frm, rif, admin.invoiceemail, admin.invoiceemailcc); $$.dc('sndfrm', frm).append($$.dc('content').text(admin.sender)); let admtxt, admlbl; if (admin.provisionend) { admlbl = admin.provisionstart ? $rct.provP : $rct.provD; admtxt = admin.provisionstart ? (fdt(admin.provisionstart, 'dd.MM.yyyy') + ' - ' + fdt(admin.provisionend, 'dd.MM.yyyy')) : fdt(admin.provisionend, 'dd.MM.yyyy'); } fm('admfrm', admtxt, 'provisionperiod', admlbl, 1, null); rif.tbl.data('new').CustomValues = admin.CustomValues || ''; $$.dc('inpfrm ctpfrm', frm).text(jObj(admin.CustomValues, 'contactName')); //adm = $$.dc('admfrm', frm), admc = $$.dc('content', adm), rif.tbl.children('tbody').each($inv.bdysort); rif.tbl.trigger('fds.inv'); /* trigger calculations */ $inv.eM(false, true, $inv.emOpt()); }, complete: () => { o.c.trigger('modal_close'); } }); }; $inv.ccStInv = function (ev) { // Stornorechnung let data = ev.data || {}; let lf = $fis.lf(), oldinv = data.id; let frm = $$.dc('invoice_layout', $fis.frm_edit()).append($$.dc('btn sprev').click($inv.sprev)); let ww = $fis.cf().width() > (frm.width() + lf.width() + 20); lf.tC('fix', ww).tC('hd', !ww); $inv.eM(false, true); let fr = $$.dc('rfrm').ldng(1); let o = $ocms.dlg(fr, { width: 1000 }); o.ft.rwText($ict.iq1); $ocms.postXT({ url: $ocms.url('inv/pget'), timeout: 90, data: { id: data.id }, success: (response) => { if (o) { o.ft.rwText($ict.iq2); } $ocms.postXT({ url: $ocms.url('inv/icget'), timeout: 60, data: { id: oldinv }, success: (response) => { //console.debug(response); let rq = $$.dc('srq', frm); let rif = $$.tblset({ class: 'invi' }, rq); rif.bdy.remove(); rif.ft = $$[0]('tfoot'); response.admin = response.admin || {}; response.admin.p13b = bool(response.admin.p13b || '', (((response.inv || {}).InvoiceOptions || '').split(',').includes('§13b') === true)); rif.tbl.data($.extend({ new: {}, sms: {}, itm: {} }, { admin: response.admin, companies: response.companies, locations: response.locations })); let thr = $$.tr(rif.hd).aC('shd').append([$$.th().aC('aux')]); /* header row for items */ $rct.invHR.forEach(h => $$.th(thr, h)); rif.tbl.on('fds.inv', $inv.invSumUpdate); $.each(response.requests || [], function (ri, rx) { let srqid = rx.Id || 0; if (srqid !== 0) { let worknotes = $inv.worknotes(rx); rx.text = response.admin.type === 'i' ? ($rct.req + (jine([rx.ExternalId, rx.Name], ': ').eine(' ', ''))) : (jine([fdt(rx.WorkDoneAt, 'dd.MM.yy') + worknotes.ne(rx.Name)], ': ')); let bdy = $$.tbody(rif.tbl).data($.extend({}, rx)); $inv.rendersrq.call(bdy); } }); /* add an empty */ let atr = $$.tr($$.tbody(rif.tbl), { class: 'placeholder' }).data({ net_val: 0, vat_val: 0, svcnet_val: 0, svcvat_val: 0, net: 0 }); $inv.rrw.call(atr); rif.ft.appendTo(rif.tbl); let admin = response.admin || {}, fm = (cls, txt, nme, hd, dta) => { let fr = $$.dc('inpfrm', frm).aC(cls).append(typeof hd === 'string' ? $$.dc('ahd', hd) : (hd > 0 ? $$.dc('ahd', $rct.frm[nme]) : null)), fc = $$.dc('content', fr).rwText(txt); $$.dc('axf', fr).append($$.dc('ibtn edit', { title: $rct.frmTT[nme] || $rct.frm[nme] }).data('dialog', $rct.frm[nme]).append(gi('pencil')).click($.extend({ t: fc, nme: nme, change: (nv) => { rif.tbl.data('new')[nme] = nv; } }, dta), $inv.eHtml)); rif.tbl.data('new')[nme] = txt; }; fm('tfrm', admin.invoicetitle, 'invoicetitle', 0, null); fm('adrfrm', admin.invoiceaddress, 'invoiceaddress', 0, null); fm('locfrm', admin.provisionlocation, 'loc', 1, { list: deepCopy(response.locations), lbl: 'ref', property: 'address' }); $inv.emailFrm(frm, rif, admin.invoiceemail, admin.invoiceemailcc); $$.dc('sndfrm', frm).append($$.dc('content').text(admin.sender)); let admtxt, admlbl; if (admin.provisionend) { admlbl = admin.provisionstart ? $rct.provP : $rct.provD; admtxt = admin.provisionstart ? (fdt(admin.provisionstart, 'dd.MM.yyyy') + ' - ' + fdt(admin.provisionend, 'dd.MM.yyyy')) : fdt(admin.provisionend, 'dd.MM.yyyy'); } fm('admfrm', admtxt, 'provisionperiod', admlbl, 1, null); rif.tbl.data('new').CustomValues = admin.CustomValues || ''; $$.dc('inpfrm ctpfrm', frm).text(jObj(admin.CustomValues, 'contactName')); //adm = $$.dc('admfrm', frm), admc = $$.dc('content', adm), rif.tbl.children('tbody').each($inv.bdysort); rif.tbl.trigger('fds.inv'); /* trigger calculations */ }, error: (xhr) => { alert($t.f1 + (xhr && xhr.status ? xhr.status : '')); }, complete: () => { o.c.trigger('modal_close'); } }); }, error: (xhr) => { if (o) { o.c.trigger('modal_close'); } alert($t.f1 + (xhr && xhr.status ? xhr.status : '')); } }); }; $inv.clCntInv = function (ev) { // click-handler for invoice continuation let lf = $fis.lf(false), selli = []; lf.find('li.ili.checked').each(function () { selli.push($(this).data('Id')); }); if (selli.length === 1) { //$('#contentframe').empty(); $inv.cntInv({ id: selli[0] }); } }; $inv.cntInv = function (data) { //invoice continuation data = data || {}; let lf = $fis.lf(false).rC('fix').aC('hd'), frm = $$.dc('invoice_layout', $fis.frm_edit()).append($$.dc('btn sprev').click($inv.sedit)); $inv.eM(false, true); let fr = $$.dc('rfrm').ldng(1); let o = $ocms.dlg(fr, { width: 1000 }); o.ft.rwText($rct.rq2); $ocms.postXT({ url: $ocms.url('inv/get'), timeout: 60, data: { id: data.id }, success: (response) => { //console.debug(response); response.admin = response.admin || {}; let inv = response.inv || {}; let rq = $$.dc('srq', frm); let rif = $$.tblset({ class: 'invi' }, rq); rif.bdy.remove(); rif.ft = $$[0]('tfoot'); rif.tbl.data($.extend({ invid: inv.Id, new: {}, sms: { }, itm: {}, bai: [] }, response)); let thr = $$.tr(rif.hd).aC('shd').append([$$.th().aC('aux')]); /* header row for items */ $rct.invHR.forEach(h => $$.th(thr, h)); rif.tbl.on('fds.inv', $inv.invSumUpdate); $.each(response.req || [], function (ri, rx) { let bdy = $$.tbody(rif.tbl).data($.extend({}, rx)); $inv.rendersrq.call(bdy); }); /* add an empty */ let atr = $$.tr($$.tbody(rif.tbl), { class: 'placeholder' }).data({ net_val: 0, vat_val: 0, svcnet_val: 0, svcvat_val: 0, net: 0 }); $inv.rrw.call(atr); rif.ft.appendTo(rif.tbl); let fm = (cls, txt, nme, hd, dta) => { let fr = $$.dc('inpfrm', frm).aC(cls).append(typeof hd === 'string' ? $$.dc('ahd', hd) : (hd > 0 ? $$.dc('ahd', $rct.frm[nme]) : null)), fc = $$.dc('content', fr).rwText(txt); $$.dc('axf', fr).append($$.dc('ibtn edit', { title: $rct.frmTT[nme] || $rct.frm[nme] }).data('dialog', $rct.frm[nme]).append(gi('pencil')).click($.extend({ t: fc, nme: nme, change: (nv) => { rif.tbl.data('new')[nme] = nv; } }, dta), $inv.eHtml)); rif.tbl.data('new')[nme] = txt; }; fm('tfrm', inv.InvoiceTitle, 'invoicetitle', 0, null); fm('adrfrm', inv.SendToAddress, 'invoiceaddress', 0, null); fm('locfrm', inv.ProvisionLocation, 'loc', 1, null); $inv.emailFrm(frm, rif, inv.SendToEmail, inv.SendToEmailCc); $$.dc('sndfrm', frm).append($$.dc('content').text(response.admin.sender)); fm('admfrm', inv.ProvisionPeriod, 'provisionperiod', ((inv.ProvisionPeriod || '').includes('-') === true ? $rct.provP : $rct.provD), 1, null); rif.tbl.data('new').CustomValues = inv.CustomValues || ''; $$.dc('inpfrm ctpfrm', frm).text(jObj(inv.CustomValues, 'contactName')); //adm = $$.dc('admfrm', frm), admc = $$.dc('content', adm), rif.tbl.children('tbody').each($inv.bdysort); rif.tbl.trigger('fds.inv'); /* trigger calculations */ $inv.eM(false, true, $inv.emOpt()); }, complete: () => { o.c.trigger('modal_close'); } }); }; $inv.cSt = function (data) { data = data || {}; let lf = $fis.lf(), frm = $$.dc('invoice_layout', $fis.frm_edit()).append($$.dc('btn sprev').click($inv.sedit)); let ww = $fis.cf().width() > (frm.width() + lf.width() + 20); lf.tC('fix', ww).tC('hd', !ww); $inv.eM(false, true); let fr = $$.dc('rfrm').ldng(1); let o = $ocms.dlg(fr, { width: 1000 }); o.ft.rwText($ict.iq1); $ocms.postXT({ url: $ocms.url('inv/pget'), data: { id: data.id }, success: (response) => { if (o) { o.ft.rwText($ict.iq2); } $ocms.postXT({ url: $ocms.url('inv/storno'), data: { id: data.id, mode: data.mode }, success: (response) => { //console.debug(response); response.admin = response.admin || {}; response.admin.p13b = bool(response.admin.p13b || '', (((response.inv || {}).InvoiceOptions || '').split(',').includes('§13b') === true)); let inv = response.inv || {}; let rq = $$.dc('srq', frm); let rif = $$.tblset({ class: 'invi' }, rq); rif.bdy.remove(); rif.ft = $$[0]('tfoot'); rif.tbl.data($.extend({ invid: inv.Id, new: {}, sms: {}, itm: {}, bai: [] }, response)); let thr = $$.tr(rif.hd).aC('shd').append([$$.th().aC('aux')]); /* header row for items */ $rct.invHR.forEach(h => $$.th(thr, h)); rif.tbl.on('fds.inv', $inv.invSumUpdate); $.each(response.req || [], function (ri, rx) { let bdy = $$.tbody(rif.tbl).data($.extend({}, rx)); $inv.rendersrq.call(bdy); }); /* add an empty */ let atr = $$.tr($$.tbody(rif.tbl), { class: 'placeholder' }).data({ net_val: 0, vat_val: 0, svcnet_val: 0, svcvat_val: 0, net: 0 }); $inv.rrw.call(atr); rif.ft.appendTo(rif.tbl); let fm = (cls, txt, nme, hd, dta) => { let fr = $$.dc('inpfrm', frm).aC(cls).append(typeof hd === 'string' ? $$.dc('ahd', hd) : (hd > 0 ? $$.dc('ahd', $rct.frm[nme]) : null)), fc = $$.dc('content', fr).rwText(txt); $$.dc('axf', fr).append($$.dc('ibtn edit', { title: $rct.frmTT[nme] || $rct.frm[nme] }).data('dialog', $rct.frm[nme]).append(gi('pencil')).click($.extend({ t: fc, nme: nme, change: (nv) => { rif.tbl.data('new')[nme] = nv; } }, dta), $inv.eHtml)); rif.tbl.data('new')[nme] = txt; }; fm('tfrm', inv.InvoiceTitle, 'invoicetitle', 0, null); fm('adrfrm', inv.SendToAddress, 'invoiceaddress', 0, null); fm('locfrm', inv.ProvisionLocation, 'loc', 1, null); $inv.emailFrm(frm, rif, inv.SendToEmail, inv.SendToEmailCc); $$.dc('sndfrm', frm).append($$.dc('content').text(response.admin.sender)); fm('admfrm', inv.ProvisionPeriod, 'provisionperiod', ((inv.ProvisionPeriod || '').includes('-') === true ? $rct.provP : $rct.provD), 1, null); rif.tbl.data('new').CustomValues = inv.CustomValues || ''; $$.dc('inpfrm ctpfrm', frm).text(jObj(inv.CustomValues,'contactName')); //adm = $$.dc('admfrm', frm), admc = $$.dc('content', adm), rif.tbl.children('tbody').each($inv.bdysort); rif.tbl.trigger('fds.inv'); /* trigger calculations */ }, error: (xhr) => { alert($t.f1 + (xhr && xhr.status ? xhr.status : '')); }, complete: () => { o.c.trigger('modal_close'); } }); }, error: (xhr) => { if (o) { o.c.trigger('modal_close'); } alert($t.f1 + (xhr && xhr.status ? xhr.status : '')); } }); }; /* Country choices for the structured recipient-address dialog (ISO 3166-1 alpha-2, BT-55). */ $inv.adrCountries = [['DE', 'Deutschland'], ['AT', 'Österreich'], ['CH', 'Schweiz'], ['FR', 'Frankreich'], ['NL', 'Niederlande'], ['BE', 'Belgien'], ['LU', 'Luxemburg'], ['IT', 'Italien'], ['ES', 'Spanien'], ['PL', 'Polen'], ['DK', 'Dänemark'], ['CZ', 'Tschechien'], ['GB', 'Großbritannien'], ['US', 'USA']]; /* Compose the free-text postal block (for the inline display) from the structured address — mirrors the backend InvoiceRecipientAddress.Compose (the VAT id is never part of the block). */ $inv.composeAddress = function (a) { a = a || {}; let lines = []; let push = (v) => { v = ('' + (v || '')).trim(); if (v !== '') lines.push(v); }; push(a.name); if (('' + (a.contact || '')).trim() !== '') push('z.Hd. ' + ('' + a.contact).trim()); push(a.line2 || a.addressLine2); push(a.street); push((('' + (a.postalCode || '')) + ' ' + ('' + (a.city || ''))).trim()); let cc = ('' + (a.countryCode || '')).toUpperCase(); if (cc !== '' && cc !== 'DE') push(cc); return lines.join('\n'); }; /* The structured recipient address currently in effect: the backend keeps it in CustomValues.sendToAddress (survives a draft refresh); new invoices seed it from fds__prepInvoice's invoiceaddressData; otherwise start empty. */ $inv.adrCurrent = function (tbl) { let cv = jObj((tbl.data('new') || {}).CustomValues, 'sendToAddress'); if (typeof cv === 'string' && cv.trim().charAt(0) === '{') { try { cv = JSON.parse(cv); } catch (e) { cv = null; } } if (cv && typeof cv === 'object') return cv; let ad = (tbl.data('admin') || {}).invoiceaddressData; if (typeof ad === 'string' && ad.trim().charAt(0) === '{') { try { return JSON.parse(ad); } catch (e) { } } else if (ad && typeof ad === 'object') { return ad; } return {}; }; /* Structured recipient-address dialog (EN 16931 / DATEV). Posts the address delta as a JSON object; the backend stores it, composes SendToAddress and keeps the PDF unchanged (ADR 0012). B2C stays effortless: the USt-IdNr. is optional (empty = private person). */ $inv.eAddress = function (ev) { let tbl = $inv.d.tbl(), cur = $inv.adrCurrent(tbl); let flds = [ { name: 'name', label: 'Name / Firma', type: 'text', value: cur.name || '', required: true }, { name: 'contact', label: 'z.Hd. (optional)', type: 'text', value: cur.contact || '' }, { name: 'street', label: 'Straße + Nr.', type: 'text', value: cur.street || '' }, { name: 'line2', label: 'Adresszusatz (optional)', type: 'text', value: cur.line2 || cur.addressLine2 || '' }, { name: 'postalCode', label: 'PLZ', type: 'text', value: cur.postalCode || '' }, { name: 'city', label: 'Ort', type: 'text', value: cur.city || '' }, { name: 'countryCode', label: 'Land', type: 'select', url: $inv.adrCountries, value: (cur.countryCode || 'DE') }, { name: 'vatId', label: 'USt-IdNr. (nur bei Firmen)', type: 'text', value: cur.vatId || '' }, { name: 'leitwegId', label: 'Leitweg-ID (nur Behörden / B2G)', type: 'text', value: cur.leitwegId || '' } ]; let hint = $$.dc('adr-conformity').append([ $$.dc('hd').text('Hinweis zur DATEV-/eRechnungs-Konformität'), $$.dc('tx').text('Pflicht: Name, Straße, PLZ, Ort und Land. Die USt-IdNr. nur bei Firmen angeben — ' + 'für eine Rechnung an eine Privatperson einfach leer lassen. Eine Leitweg-ID nur bei ' + 'Behörden (B2G) — dann wird die Rechnung automatisch als XRechnung erzeugt.') ]); $ocms.dlgform(flds, { title: 'Rechnungsempfänger', addcontent: hint, success: function (res) { let a = { name: res.name || '', contact: res.contact || '', line2: res.line2 || '', street: res.street || '', postalCode: res.postalCode || '', city: res.city || '', countryCode: (res.countryCode || 'DE'), vatId: ('' + (res.vatId || '')).trim(), leitwegId: ('' + (res.leitwegId || '')).trim() }; let txt = $inv.composeAddress(a); if (ev.data && ev.data.t) { ev.data.t.rwText(txt); } if (typeof (ev.data || {}).change === 'function') { ev.data.change(txt); } /* Structured delta — the invoice draft backend accepts a JSON object for 'address'. */ $inv.d.sync({ Target: 'address', Value: a }); } }); }; /* Leistungsdatum / -zeitraum: structured German-date entry only (no free text). A single date = Leistungsdatum (BT-72); a from+to date = Leistungszeitraum (BG-14). The composed value is a German dd.MM.yyyy string ("18.06.2026" or "01.06.2026 - 30.06.2026") that the PDF shows and the backend maps to the eRechnung service date/period. */ $inv.provToIso = function (dmy) { let m = ('' + (dmy || '')).match(/(\d{1,2})\.(\d{1,2})\.(\d{4})/); return m ? (m[3] + '-' + ('0' + m[2]).slice(-2) + '-' + ('0' + m[1]).slice(-2)) : ''; }; $inv.eProvisionPeriod = function (ev) { let cur = ('' + (ev.data && ev.data.t ? ev.data.t.text() : '')).trim(); let dates = cur.match(/\d{1,2}\.\d{1,2}\.\d{4}/g) || []; let flds = [ { name: 'von', label: 'Leistungsdatum', type: 'date', value: $inv.provToIso(dates[0] || '') }, { name: 'bis', label: 'Leistungszeitraum – bis (optional)', type: 'date', value: $inv.provToIso(dates[1] || '') } ]; let hint = $$.dc('adr-conformity').append([ $$.dc('hd').text('Leistungsdatum / -zeitraum'), $$.dc('tx').text('Für ein einzelnes Datum nur „Leistungsdatum" ausfüllen; für einen Zeitraum ' + 'zusätzlich das Bis-Datum. Nur strukturierte Datumsauswahl — für die E-Rechnung empfohlen.') ]); $ocms.dlgform(flds, { title: 'Leistungsdatum / -zeitraum', addcontent: hint, success: function (res) { let v = ('' + (res.von || '')).trim(), b = ('' + (res.bis || '')).trim(); let txt = v === '' ? '' : ((b === '' || b === v) ? v : (v + ' - ' + b)); if (ev.data && ev.data.t) { ev.data.t.rwText(txt); } if (typeof (ev.data || {}).change === 'function') { ev.data.change(txt); } $inv.d.sync({ Target: 'provisionperiod', Value: txt }); } }); }; /* Main recipient + CC ("Zusatzempfänger") edited together in one dialog — there is no separate pencil on the CC row, only on the email row (see $inv.emailFrm), which passes both content spans through ev.data.t / ev.data.ccT. */ $inv.eEmail = function (ev) { let flds = [ { name: 'email', label: $rct.frm.invoiceemail, type: 'text', value: (ev.data.t || $$.s()).text() }, { name: 'emailcc', label: $rct.frm.invoiceemailcc, type: 'text', value: (ev.data.ccT || $$.s()).text() } ]; $ocms.dlgform(flds, { title: $rct.frm.invoiceemail, success: function (res) { let email = ('' + (res.email || '')).trim(), cc = ('' + (res.emailcc || '')).trim(); if (ev.data && ev.data.t) { ev.data.t.text(email); } if (ev.data && ev.data.ccT) { ev.data.ccT.text(cc); } if (typeof (ev.data || {}).change === 'function') { ev.data.change(email); } if (typeof (ev.data || {}).changeCc === 'function') { ev.data.changeCc(cc); } /* backend-authoritative: mirror both fields to the server session (see $inv.eHtml's generic path, which this mirrors for a single field). */ $inv.d.syncField('invoiceemail', email); $inv.rd.syncField('invoiceemail', email); $inv.d.syncField('invoiceemailcc', cc); $inv.rd.syncField('invoiceemailcc', cc); } }); }; /* Builds the email + CC ("Zusatzempfänger") header rows together: only the email row gets a pencil, opening the combined $inv.eEmail dialog for both fields (see there). */ $inv.emailFrm = function (frm, rif, email, emailcc) { let ccfr = $$.dc('inpfrm emailccfrm', frm), ccfc = $$.dc('content', ccfr).rwText(emailcc); let efr = $$.dc('inpfrm emailfrm', frm), efc = $$.dc('content', efr).rwText(email); $$.dc('axf', efr).append($$.dc('ibtn edit', { title: $rct.frmTT.invoiceemail }).append(gi('pencil')).click({ t: efc, ccT: ccfc, nme: 'invoiceemail', change: (nv) => { rif.tbl.data('new').invoiceemail = nv; }, changeCc: (nv) => { rif.tbl.data('new').invoiceemailcc = nv; } }, $inv.eHtml)); rif.tbl.data('new').invoiceemail = email; rif.tbl.data('new').invoiceemailcc = emailcc; }; $inv.eHtml = function (ev) { /* The recipient address and the service date/period are edited through structured dialogs whenever an invoice draft is active; reminders (no invoice draft token) keep the plain free-text editor. */ if (ev.data && !(ev.data instanceof jQuery) && $inv.d && typeof $inv.d.token === 'function' && $inv.d.token() !== '') { if (ev.data.nme === 'invoiceaddress') { return $inv.eAddress.call(this, ev); } if (ev.data.nme === 'provisionperiod') { return $inv.eProvisionPeriod.call(this, ev); } } /* The CC/Zusatzempfänger recipient is edited together with the main email, in one dialog — there is no separate pencil on the CC row (see $inv.emailFrm). */ if (ev.data && !(ev.data instanceof jQuery) && ev.data.nme === 'invoiceemail' && ev.data.ccT) { return $inv.eEmail.call(this, ev); } let t = $(this), frmct = ev.data instanceof jQuery ? ev.data : ev.data.t; /* 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', 'invoiceemailcc', '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' } }]; let change = ev.data.change || null; let sets = { title: t.data('dialog') || '', success: function (response) { if (isPlainText) { frmct.text(response.txt || ''); } else { frmct.html(response.txt); } if (typeof change === 'function') { change(response.txt); } /* backend-authoritative: mirror the inline recipient-field edit to the server session. Invoice and reminder editors share this DOM; each syncField no-ops unless its own draft token is present, so only the active mode's session receives the delta. */ $inv.d.syncField(ev.data.nme, isPlainText ? (response.txt || '') : response.txt); $inv.rd.syncField(ev.data.nme, isPlainText ? (response.txt || '') : response.txt); }, tinymce: { valid_elements: 'br', hidemenu: true, hidetoolbar: true } } if (Array.isArray(ev.data.list)) { let optf = $$.dc('lstfrm'); $.each(ev.data.list, (ii, lx) => { let li = $$.dc('li', optf).append((ev.data.lbl || '') !== '' ? $$.dc('lbl').rwText(lx[ev.data.lbl]) : null); $$.dc('adr', li).rwText(lx[ev.data.property]).data('val', lx[ev.data.property]).click(function () { let t = $(this), tgt = t.closest('.modal-body').find(':input[name="txt"]'); if (tgt.is('.tinymce')) { tinymce.get(tgt.attr('id')).setContent($$.s().rwText(t.data('val')).html()); } else if (tgt.prop('tagName') === 'TEXTAREA') { tgt.val(t.data('val')).change(); } else { tgt.rwText(t.data('val')); } }); }); sets.addcontent = optf; } $ocms.dlgform(flds, sets); }; /* No client-side arithmetic (ADR 0006/0008): only the chosen VAT rate is stored on each row; the server (InvoiceDraftCalculator.RecomputeLineValues) recomputes vat_val/svcvat_val from it. */ $inv.setVat = function (ev) { let t = $(this), thisrow = ev.data; let vat = prompt($rct.rqV); if (vat) { vat = parseFloat(vat.replace('%', '')); if (vat > 1) { vat = vat * 0.01; } if (isNaN(vat) === false) { thisrow.siblings('.itm').each(function () { let rwi = $(this), dta = rwi.data(); dta.vat = fnum(vat, { style: 'percent' }).replace(' ', ''); }); $inv.t_fds_inv(); } } }; $inv.inRow = function (ev) { let t = $(this), thisrow = ev.data, dta = {}, flds = $rcol.itm.clone(['SortOrder', 'NameOrNumber', 'Type', 'quantityhours', 'UnitString', 'net', 'svcnet_val', 'svcvat_val', 'net_val', 'vat_val', 'vat', 'Note']); /* fields without values */ let nid = 'N' + (((1 + Math.random()) * 0x10000) || 0).toString(16).substr(6), newrow = $$.tr({ id: 'itm_' + nid.toString(), class: 'itm' }); $ocms.dlgform(flds, { title: t.data('dialog') || '', success: function (response) { newrow.data($.extend({ Id: nid }, dta, response)); $inv.rrw.call(newrow); newrow.insertAfter(thisrow); $inv.t_fds_inv(); }, typedvalues: true }); }; $inv.eRow = function (ev) { let t = $(this), row = ev.data, dta = row.data() || {}, fnme = ['SortOrder', 'NameOrNumber', 'Type', 'quantityhours', 'UnitString', 'net', 'svcnet_val', 'svcvat_val', 'net_val', 'vat_val', 'vat', 'Note']; if (!dta.id && (dta.Type || '') === '') { fnme.unshift('Type'); } let flds = $rcol.itm.clone(fnme).applyValues(dta); flds.set('Type', 'hidden', 'type'); $inv.eRw.call(t, row, dta, flds); }; $inv.eRw = function(row, dta, flds) { let t = $(this); $ocms.dlgform(flds, { title: t.data('dialog') || '', success: function (res) { let d = {} if ((dta.Id || '') === '') { d.Id = 'N' + (((1 + Math.random()) * 0x10000) || 0).toString(16).substr(6); row.attr('id', 'itm_' + d.Id.toString()); } d.quantity = ((res.quantityhours ||'').toString() + ' ' + (res.UnitString || '').toString()).trimEnd(); row.data($.extend({}, dta, res, d)); console.debug('eRw success %o', row.data()); $inv.rrw.call(row); $inv.t_fds_inv(); }, typedvalues: true }); }; /* 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(); } }) } /* Single "Kontext-Button" per row/field, opening a dropdown of the row's edit actions (reuses $ocms.menu, the same mechanism that already drives the toolbar menus — see $inv.eM/$inv.iMn). Calling .ocmsmenu() directly on a